wordwrap – wrap text at word boundaries in a window

#include <u.h>
#include <libc.h>
#include <draw.h>
#include wordwrap.h
Point       wordwrap(char* m, Font *font, Point pi, int margin);

The function wordwrap takes the input text m and displays it in the font font within the Image screen, which must already be defined as a global, as performed by initdraw(2). Wordwrap will wrap the text at a word boundary, leaving margin pixels on the perimiter of the screen when performing the layout.
Wordwrap first makes its own copy of the input, then splits the that on newlines, then each line into words on spaces. It checks whether each word will fit within the screen rectangle in the given font starting at the current insertion point, leaving margin around the perimiter, and if not updates the insertion point to the leftmost edge (again, respecting margin) and then inserts the string. It re–inserts spaces between words (but see the note below), and will start each input line after the first at the leftmost margin. Wordwrap returns the point it would continue layout at if the input text were longer.
It is possible to mix fonts between calls to wordwrap to, for example, display a bold or italic string with a normal string, but care should be taken to match the font heights. There is no way for a call to wordwrap to know that n earlier call has used a taller font, so when it moves to the next line it will use the spacing of its current font. This can lead to unexpected overlap if mixing fonts of different heights.


Since wordwrap uses getields(2) to split input lines on newline and words with lines on spaces, either of those characters on the beginning or end of the input are lost. See fixsep() in for an example of how to deal with this. This should probably be integrated into wordwrap.
Like all the Plan 9 graphics utilities, wordwrap makes no attempt to deal with right–to–left layout.