Skip to content
fossil-examples Artifact [04d00cf2b0]
Login

Artifact [04d00cf2b0]

Artifact 04d00cf2b03a40ae11bca927ea60c177acb0c8a0eef813f1c662f61380584a1d:


/* wrap 1.0: word-wrap text to a column width. Zero-clause BSD license. */
#include <stdio.h>
#include "wrap.h"

/* Is c a character a line may break at? */
static int is_space(int c){
  return c == ' ';
}

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);
}