summaryrefslogtreecommitdiff
path: root/support/word2x/wordwrap.cc
blob: 14fa764c77c76faa895695383ba5765de86e8dfc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* $Id: wordwrap.cc,v 1.5 1997/03/23 13:52:15 dps Exp $ */
/* Wordwrap function for library */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_CTYPE_H
#include <ctype.h>
#endif /* HAVE_CTYPE_H */
#include "tblock.h"
#define __EXLCUDE_READER_CLASSES
#include "lib.h"


/* Word wrap text into lines of length room */
tblock *word_wrap(const char *txt, const char *nl, const char *expl_nl,
		  const int room, const int ilen)
{
    struct tblock *ans;
    const char *wptr, *sc;
    int wlen, croom, flg;
    int nl_len;			// Performance hack

    ans=new(tblock);

    wlen=0;
    wptr=sc=txt;
    croom=room-ilen;
    nl_len=strlen(nl);
    flg=0;
	
    while (1)
    {
	/* FIXME: huge words might cause an oversize line */
	/* (this is not a typesetting program like *roff) */
	if (isspace(*sc) || *sc=='\n' || *sc=='\0')
	{
	    if (wlen+flg>croom)
	    {
		ans->add(nl,nl_len);
		croom=room;
		flg=0;
	    }
	    if (wlen>0)
	    {
		if (flg)
		{
		    ans->add(' ');
		    croom--;
		}
		ans->add(wptr, wlen);
		croom-=wlen;
		flg=1;
	    }
	    if (*sc=='\n')
	    {
		ans->add(expl_nl);
		croom=room;
		flg=0;
	    }
	    wlen=0;
	}
	else
	{
	    if (wlen==0)
		wptr=sc;
	    wlen++;
	}
	if (*sc=='\0') break;	// Stop condition
	sc++;
    }
    return ans;
}