QB64 Phoenix Edition
Basic WordWrap - Printable Version

+- QB64 Phoenix Edition (https://staging.qb64phoenix.com)
+-- Forum: QB64 Rising (https://staging.qb64phoenix.com/forumdisplay.php?fid=1)
+--- Forum: Prolific Programmers (https://staging.qb64phoenix.com/forumdisplay.php?fid=26)
+---- Forum: SMcNeill (https://staging.qb64phoenix.com/forumdisplay.php?fid=29)
+---- Thread: Basic WordWrap (/showthread.php?tid=70)



Basic WordWrap - SMcNeill - 04-20-2022

A simple little routine which can be plugged in to break text and word wrap it nice and neat for us.

Code: (Select All)
'SCREEN _NEWIMAGE(640, 480, 32)

LOCATE 1, 21 'to test a line with an offset
test$ = "This is a very long sentence which runs on and on and one and even contains tipos and errors and goofs and mistakes and all sorts of junk, but it is good for testing if we have word breaks working properly for us!"
WordWrap test$, -1
PRINT 'to test a line from the starting point
WordWrap test$, -1
PRINT
PRINT "=============="
PRINT
WordWrap test$, 0 'And this shows that we can wordwrap text without automatically moving to a new line
WordWrap test$, -1 'As this line picks up right where the last one left off.



SUB WordWrap (text AS STRING, newline)
DIM BreakPoint AS STRING
BreakPoint = ",./- ;:!" 'I consider all these to be valid breakpoints.  If you want something else, change them.

w = _WIDTH
pw = _PRINTWIDTH(text)
x = POS(0): y = CSRLIN
IF _PIXELSIZE <> 0 THEN x = x * _FONTWIDTH
firstlinewidth = w - x + 1
IF pw <= firstlinewidth THEN
    PRINT text;
    IF newline THEN PRINT
ELSE
    'first find the natural length of the line
    FOR i = 1 TO LEN(text)
        p = _PRINTWIDTH(LEFT$(text, i))
        IF p > firstlinewidth THEN EXIT FOR
    NEXT
    lineend = i - 1
    t$ = RTRIM$(LEFT$(text, lineend)) 'at most, our line can't be any longer than what fits the screen.
    FOR i = lineend TO 1 STEP -1
        IF INSTR(BreakPoint, MID$(text, i, 1)) THEN lineend = i: EXIT FOR
    NEXT
    PRINT LEFT$(text, lineend)
    WordWrap LTRIM$(MID$(text, lineend + 1)), newline
END IF
END SUB