/* wrap 1.1: word-wrap text to a column width. Zero-clause BSD license. */ #include #include "wrap.h" /* Is c a character a line may break at? */ static int is_space(int c){ return c == ' ' || c == '\t'; /* notes: also break at tabs */ } void wrap_print(FILE *out, const char *text, int width){ int col = 0; const char *p = text; while( *p ){ while( *p && is_space((unsigned char)*p) ) p++; if( !*p ) break; if( *p == '\n' ){ fputc('\n', out); col = 0; p++; continue; } const char *w = p; while( *p && *p != '\n' && !is_space((unsigned char)*p) ) p++; int len = (int)(p - w); if( col > 0 && col + 1 + len > width ){ fputc('\n', out); col = 0; }else if( col > 0 ){ fputc(' ', out); col++; } fwrite(w, 1, (size_t)len, out); col += len; } if( col > 0 ) fputc('\n', out); }