Skip to content
fossil-examples Artifact [91c20cfd30]
Login

Artifact [91c20cfd30]

Artifact 91c20cfd30e8c26ad28f876d31af25b278adc97ca7ffb90a976593ede51743a4:


/* wrap 2.0 (this file was wrap.c before 2.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);
}