16def7879fb011c1319bcd72c5553c16408645d6
[dragonfly.git] / contrib / mdocml / term.c
1 /*      $Id: term.c,v 1.210 2013/08/21 21:20:40 schwarze Exp $ */
2 /*
3  * Copyright (c) 2008, 2009, 2010, 2011 Kristaps Dzonsons <kristaps@bsd.lv>
4  * Copyright (c) 2010, 2011, 2012, 2013 Ingo Schwarze <schwarze@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21
22 #include <sys/types.h>
23
24 #include <assert.h>
25 #include <ctype.h>
26 #include <stdint.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include "mandoc.h"
32 #include "out.h"
33 #include "term.h"
34 #include "main.h"
35
36 static  size_t           cond_width(const struct termp *, int, int *);
37 static  void             adjbuf(struct termp *p, size_t);
38 static  void             bufferc(struct termp *, char);
39 static  void             encode(struct termp *, const char *, size_t);
40 static  void             encode1(struct termp *, int);
41
42 void
43 term_free(struct termp *p)
44 {
45
46         if (p->buf)
47                 free(p->buf);
48         if (p->symtab)
49                 mchars_free(p->symtab);
50
51         free(p);
52 }
53
54
55 void
56 term_begin(struct termp *p, term_margin head, 
57                 term_margin foot, const void *arg)
58 {
59
60         p->headf = head;
61         p->footf = foot;
62         p->argf = arg;
63         (*p->begin)(p);
64 }
65
66
67 void
68 term_end(struct termp *p)
69 {
70
71         (*p->end)(p);
72 }
73
74 /*
75  * Flush a line of text.  A "line" is loosely defined as being something
76  * that should be followed by a newline, regardless of whether it's
77  * broken apart by newlines getting there.  A line can also be a
78  * fragment of a columnar list (`Bl -tag' or `Bl -column'), which does
79  * not have a trailing newline.
80  *
81  * The following flags may be specified:
82  *
83  *  - TERMP_NOBREAK: this is the most important and is used when making
84  *    columns.  In short: don't print a newline and instead expect the
85  *    next call to do the padding up to the start of the next column.
86  *
87  *  - TERMP_TWOSPACE: make sure there is room for at least two space
88  *    characters of padding.  Otherwise, rather break the line.
89  *
90  *  - TERMP_DANGLE: don't newline when TERMP_NOBREAK is specified and
91  *    the line is overrun, and don't pad-right if it's underrun.
92  *
93  *  - TERMP_HANG: like TERMP_DANGLE, but doesn't newline when
94  *    overrunning, instead save the position and continue at that point
95  *    when the next invocation.
96  *
97  *  In-line line breaking:
98  *
99  *  If TERMP_NOBREAK is specified and the line overruns the right
100  *  margin, it will break and pad-right to the right margin after
101  *  writing.  If maxrmargin is violated, it will break and continue
102  *  writing from the right-margin, which will lead to the above scenario
103  *  upon exit.  Otherwise, the line will break at the right margin.
104  */
105 void
106 term_flushln(struct termp *p)
107 {
108         size_t           i;     /* current input position in p->buf */
109         int              ntab;  /* number of tabs to prepend */
110         size_t           vis;   /* current visual position on output */
111         size_t           vbl;   /* number of blanks to prepend to output */
112         size_t           vend;  /* end of word visual position on output */
113         size_t           bp;    /* visual right border position */
114         size_t           dv;    /* temporary for visual pos calculations */
115         size_t           j;     /* temporary loop index for p->buf */
116         size_t           jhy;   /* last hyph before overflow w/r/t j */
117         size_t           maxvis; /* output position of visible boundary */
118         size_t           mmax; /* used in calculating bp */
119
120         /*
121          * First, establish the maximum columns of "visible" content.
122          * This is usually the difference between the right-margin and
123          * an indentation, but can be, for tagged lists or columns, a
124          * small set of values. 
125          */
126         assert  (p->rmargin >= p->offset);
127         dv     = p->rmargin - p->offset;
128         maxvis = (int)dv > p->overstep ? dv - (size_t)p->overstep : 0;
129         dv     = p->maxrmargin - p->offset;
130         mmax   = (int)dv > p->overstep ? dv - (size_t)p->overstep : 0;
131
132         bp = TERMP_NOBREAK & p->flags ? mmax : maxvis;
133
134         /*
135          * Calculate the required amount of padding.
136          */
137         vbl = p->offset + p->overstep > p->viscol ?
138               p->offset + p->overstep - p->viscol : 0;
139
140         vis = vend = 0;
141         i = 0;
142
143         while (i < p->col) {
144                 /*
145                  * Handle literal tab characters: collapse all
146                  * subsequent tabs into a single huge set of spaces.
147                  */
148                 ntab = 0;
149                 while (i < p->col && '\t' == p->buf[i]) {
150                         vend = (vis / p->tabwidth + 1) * p->tabwidth;
151                         vbl += vend - vis;
152                         vis = vend;
153                         ntab++;
154                         i++;
155                 }
156
157                 /*
158                  * Count up visible word characters.  Control sequences
159                  * (starting with the CSI) aren't counted.  A space
160                  * generates a non-printing word, which is valid (the
161                  * space is printed according to regular spacing rules).
162                  */
163
164                 for (j = i, jhy = 0; j < p->col; j++) {
165                         if (' ' == p->buf[j] || '\t' == p->buf[j])
166                                 break;
167
168                         /* Back over the the last printed character. */
169                         if (8 == p->buf[j]) {
170                                 assert(j);
171                                 vend -= (*p->width)(p, p->buf[j - 1]);
172                                 continue;
173                         }
174
175                         /* Regular word. */
176                         /* Break at the hyphen point if we overrun. */
177                         if (vend > vis && vend < bp && 
178                                         ASCII_HYPH == p->buf[j])
179                                 jhy = j;
180
181                         vend += (*p->width)(p, p->buf[j]);
182                 }
183
184                 /*
185                  * Find out whether we would exceed the right margin.
186                  * If so, break to the next line.
187                  */
188                 if (vend > bp && 0 == jhy && vis > 0) {
189                         vend -= vis;
190                         (*p->endline)(p);
191                         p->viscol = 0;
192                         if (TERMP_NOBREAK & p->flags) {
193                                 vbl = p->rmargin;
194                                 vend += p->rmargin - p->offset;
195                         } else
196                                 vbl = p->offset;
197
198                         /* use pending tabs on the new line */
199
200                         if (0 < ntab)
201                                 vbl += ntab * p->tabwidth;
202
203                         /* Remove the p->overstep width. */
204
205                         bp += (size_t)p->overstep;
206                         p->overstep = 0;
207                 }
208
209                 /* Write out the [remaining] word. */
210                 for ( ; i < p->col; i++) {
211                         if (vend > bp && jhy > 0 && i > jhy)
212                                 break;
213                         if ('\t' == p->buf[i])
214                                 break;
215                         if (' ' == p->buf[i]) {
216                                 j = i;
217                                 while (' ' == p->buf[i])
218                                         i++;
219                                 dv = (i - j) * (*p->width)(p, ' ');
220                                 vbl += dv;
221                                 vend += dv;
222                                 break;
223                         }
224                         if (ASCII_NBRSP == p->buf[i]) {
225                                 vbl += (*p->width)(p, ' ');
226                                 continue;
227                         }
228
229                         /*
230                          * Now we definitely know there will be
231                          * printable characters to output,
232                          * so write preceding white space now.
233                          */
234                         if (vbl) {
235                                 (*p->advance)(p, vbl);
236                                 p->viscol += vbl;
237                                 vbl = 0;
238                         }
239
240                         if (ASCII_HYPH == p->buf[i]) {
241                                 (*p->letter)(p, '-');
242                                 p->viscol += (*p->width)(p, '-');
243                                 continue;
244                         }
245
246                         (*p->letter)(p, p->buf[i]);
247                         if (8 == p->buf[i])
248                                 p->viscol -= (*p->width)(p, p->buf[i-1]);
249                         else 
250                                 p->viscol += (*p->width)(p, p->buf[i]);
251                 }
252                 vis = vend;
253         }
254
255         /*
256          * If there was trailing white space, it was not printed;
257          * so reset the cursor position accordingly.
258          */
259         if (vis)
260                 vis -= vbl;
261
262         p->col = 0;
263         p->overstep = 0;
264
265         if ( ! (TERMP_NOBREAK & p->flags)) {
266                 p->viscol = 0;
267                 (*p->endline)(p);
268                 return;
269         }
270
271         if (TERMP_HANG & p->flags) {
272                 /* We need one blank after the tag. */
273                 p->overstep = (int)(vis - maxvis + (*p->width)(p, ' '));
274
275                 /*
276                  * If we have overstepped the margin, temporarily move
277                  * it to the right and flag the rest of the line to be
278                  * shorter.
279                  */
280                 if (p->overstep < 0)
281                         p->overstep = 0;
282                 return;
283
284         } else if (TERMP_DANGLE & p->flags)
285                 return;
286
287         /* If the column was overrun, break the line. */
288         if (maxvis <= vis +
289             ((TERMP_TWOSPACE & p->flags) ? (*p->width)(p, ' ') : 0)) {
290                 (*p->endline)(p);
291                 p->viscol = 0;
292         }
293 }
294
295
296 /* 
297  * A newline only breaks an existing line; it won't assert vertical
298  * space.  All data in the output buffer is flushed prior to the newline
299  * assertion.
300  */
301 void
302 term_newln(struct termp *p)
303 {
304
305         p->flags |= TERMP_NOSPACE;
306         if (p->col || p->viscol)
307                 term_flushln(p);
308 }
309
310
311 /*
312  * Asserts a vertical space (a full, empty line-break between lines).
313  * Note that if used twice, this will cause two blank spaces and so on.
314  * All data in the output buffer is flushed prior to the newline
315  * assertion.
316  */
317 void
318 term_vspace(struct termp *p)
319 {
320
321         term_newln(p);
322         p->viscol = 0;
323         if (0 < p->skipvsp)
324                 p->skipvsp--;
325         else
326                 (*p->endline)(p);
327 }
328
329 void
330 term_fontlast(struct termp *p)
331 {
332         enum termfont    f;
333
334         f = p->fontl;
335         p->fontl = p->fontq[p->fonti];
336         p->fontq[p->fonti] = f;
337 }
338
339
340 void
341 term_fontrepl(struct termp *p, enum termfont f)
342 {
343
344         p->fontl = p->fontq[p->fonti];
345         p->fontq[p->fonti] = f;
346 }
347
348
349 void
350 term_fontpush(struct termp *p, enum termfont f)
351 {
352
353         assert(p->fonti + 1 < 10);
354         p->fontl = p->fontq[p->fonti];
355         p->fontq[++p->fonti] = f;
356 }
357
358
359 const void *
360 term_fontq(struct termp *p)
361 {
362
363         return(&p->fontq[p->fonti]);
364 }
365
366
367 enum termfont
368 term_fonttop(struct termp *p)
369 {
370
371         return(p->fontq[p->fonti]);
372 }
373
374
375 void
376 term_fontpopq(struct termp *p, const void *key)
377 {
378
379         while (p->fonti >= 0 && key < (void *)(p->fontq + p->fonti))
380                 p->fonti--;
381         assert(p->fonti >= 0);
382 }
383
384
385 void
386 term_fontpop(struct termp *p)
387 {
388
389         assert(p->fonti);
390         p->fonti--;
391 }
392
393 /*
394  * Handle pwords, partial words, which may be either a single word or a
395  * phrase that cannot be broken down (such as a literal string).  This
396  * handles word styling.
397  */
398 void
399 term_word(struct termp *p, const char *word)
400 {
401         const char      *seq, *cp;
402         char             c;
403         int              sz, uc;
404         size_t           ssz;
405         enum mandoc_esc  esc;
406
407         if ( ! (TERMP_NOSPACE & p->flags)) {
408                 if ( ! (TERMP_KEEP & p->flags)) {
409                         bufferc(p, ' ');
410                         if (TERMP_SENTENCE & p->flags)
411                                 bufferc(p, ' ');
412                 } else
413                         bufferc(p, ASCII_NBRSP);
414         }
415         if (TERMP_PREKEEP & p->flags)
416                 p->flags |= TERMP_KEEP;
417
418         if ( ! (p->flags & TERMP_NONOSPACE))
419                 p->flags &= ~TERMP_NOSPACE;
420         else
421                 p->flags |= TERMP_NOSPACE;
422
423         p->flags &= ~(TERMP_SENTENCE | TERMP_IGNDELIM);
424
425         while ('\0' != *word) {
426                 if ('\\' != *word) {
427                         if (TERMP_SKIPCHAR & p->flags) {
428                                 p->flags &= ~TERMP_SKIPCHAR;
429                                 word++;
430                                 continue;
431                         }
432                         ssz = strcspn(word, "\\");
433                         encode(p, word, ssz);
434                         word += (int)ssz;
435                         continue;
436                 }
437
438                 word++;
439                 esc = mandoc_escape(&word, &seq, &sz);
440                 if (ESCAPE_ERROR == esc)
441                         break;
442
443                 if (TERMENC_ASCII != p->enc)
444                         switch (esc) {
445                         case (ESCAPE_UNICODE):
446                                 uc = mchars_num2uc(seq + 1, sz - 1);
447                                 if ('\0' == uc)
448                                         break;
449                                 encode1(p, uc);
450                                 continue;
451                         case (ESCAPE_SPECIAL):
452                                 uc = mchars_spec2cp(p->symtab, seq, sz);
453                                 if (uc <= 0)
454                                         break;
455                                 encode1(p, uc);
456                                 continue;
457                         default:
458                                 break;
459                         }
460
461                 switch (esc) {
462                 case (ESCAPE_UNICODE):
463                         encode1(p, '?');
464                         break;
465                 case (ESCAPE_NUMBERED):
466                         c = mchars_num2char(seq, sz);
467                         if ('\0' != c)
468                                 encode(p, &c, 1);
469                         break;
470                 case (ESCAPE_SPECIAL):
471                         cp = mchars_spec2str(p->symtab, seq, sz, &ssz);
472                         if (NULL != cp) 
473                                 encode(p, cp, ssz);
474                         else if (1 == ssz)
475                                 encode(p, seq, sz);
476                         break;
477                 case (ESCAPE_FONTBOLD):
478                         term_fontrepl(p, TERMFONT_BOLD);
479                         break;
480                 case (ESCAPE_FONTITALIC):
481                         term_fontrepl(p, TERMFONT_UNDER);
482                         break;
483                 case (ESCAPE_FONTBI):
484                         term_fontrepl(p, TERMFONT_BI);
485                         break;
486                 case (ESCAPE_FONT):
487                         /* FALLTHROUGH */
488                 case (ESCAPE_FONTROMAN):
489                         term_fontrepl(p, TERMFONT_NONE);
490                         break;
491                 case (ESCAPE_FONTPREV):
492                         term_fontlast(p);
493                         break;
494                 case (ESCAPE_NOSPACE):
495                         if (TERMP_SKIPCHAR & p->flags)
496                                 p->flags &= ~TERMP_SKIPCHAR;
497                         else if ('\0' == *word)
498                                 p->flags |= TERMP_NOSPACE;
499                         break;
500                 case (ESCAPE_SKIPCHAR):
501                         p->flags |= TERMP_SKIPCHAR;
502                         break;
503                 default:
504                         break;
505                 }
506         }
507 }
508
509 static void
510 adjbuf(struct termp *p, size_t sz)
511 {
512
513         if (0 == p->maxcols)
514                 p->maxcols = 1024;
515         while (sz >= p->maxcols)
516                 p->maxcols <<= 2;
517
518         p->buf = mandoc_realloc(p->buf, sizeof(int) * p->maxcols);
519 }
520
521 static void
522 bufferc(struct termp *p, char c)
523 {
524
525         if (p->col + 1 >= p->maxcols)
526                 adjbuf(p, p->col + 1);
527
528         p->buf[p->col++] = c;
529 }
530
531 /*
532  * See encode().
533  * Do this for a single (probably unicode) value.
534  * Does not check for non-decorated glyphs.
535  */
536 static void
537 encode1(struct termp *p, int c)
538 {
539         enum termfont     f;
540
541         if (TERMP_SKIPCHAR & p->flags) {
542                 p->flags &= ~TERMP_SKIPCHAR;
543                 return;
544         }
545
546         if (p->col + 6 >= p->maxcols)
547                 adjbuf(p, p->col + 6);
548
549         f = term_fonttop(p);
550
551         if (TERMFONT_UNDER == f || TERMFONT_BI == f) {
552                 p->buf[p->col++] = '_';
553                 p->buf[p->col++] = 8;
554         }
555         if (TERMFONT_BOLD == f || TERMFONT_BI == f) {
556                 if (ASCII_HYPH == c)
557                         p->buf[p->col++] = '-';
558                 else
559                         p->buf[p->col++] = c;
560                 p->buf[p->col++] = 8;
561         }
562         p->buf[p->col++] = c;
563 }
564
565 static void
566 encode(struct termp *p, const char *word, size_t sz)
567 {
568         size_t            i;
569
570         if (TERMP_SKIPCHAR & p->flags) {
571                 p->flags &= ~TERMP_SKIPCHAR;
572                 return;
573         }
574
575         /*
576          * Encode and buffer a string of characters.  If the current
577          * font mode is unset, buffer directly, else encode then buffer
578          * character by character.
579          */
580
581         if (TERMFONT_NONE == term_fonttop(p)) {
582                 if (p->col + sz >= p->maxcols) 
583                         adjbuf(p, p->col + sz);
584                 for (i = 0; i < sz; i++)
585                         p->buf[p->col++] = word[i];
586                 return;
587         }
588
589         /* Pre-buffer, assuming worst-case. */
590
591         if (p->col + 1 + (sz * 5) >= p->maxcols)
592                 adjbuf(p, p->col + 1 + (sz * 5));
593
594         for (i = 0; i < sz; i++) {
595                 if (ASCII_HYPH == word[i] ||
596                     isgraph((unsigned char)word[i]))
597                         encode1(p, word[i]);
598                 else
599                         p->buf[p->col++] = word[i];
600         }
601 }
602
603 size_t
604 term_len(const struct termp *p, size_t sz)
605 {
606
607         return((*p->width)(p, ' ') * sz);
608 }
609
610 static size_t
611 cond_width(const struct termp *p, int c, int *skip)
612 {
613
614         if (*skip) {
615                 (*skip) = 0;
616                 return(0);
617         } else
618                 return((*p->width)(p, c));
619 }
620
621 size_t
622 term_strlen(const struct termp *p, const char *cp)
623 {
624         size_t           sz, rsz, i;
625         int              ssz, skip, c;
626         const char      *seq, *rhs;
627         enum mandoc_esc  esc;
628         static const char rej[] = { '\\', ASCII_HYPH, ASCII_NBRSP, '\0' };
629
630         /*
631          * Account for escaped sequences within string length
632          * calculations.  This follows the logic in term_word() as we
633          * must calculate the width of produced strings.
634          */
635
636         sz = 0;
637         skip = 0;
638         while ('\0' != *cp) {
639                 rsz = strcspn(cp, rej);
640                 for (i = 0; i < rsz; i++)
641                         sz += cond_width(p, *cp++, &skip);
642
643                 c = 0;
644                 switch (*cp) {
645                 case ('\\'):
646                         cp++;
647                         esc = mandoc_escape(&cp, &seq, &ssz);
648                         if (ESCAPE_ERROR == esc)
649                                 return(sz);
650
651                         if (TERMENC_ASCII != p->enc)
652                                 switch (esc) {
653                                 case (ESCAPE_UNICODE):
654                                         c = mchars_num2uc
655                                                 (seq + 1, ssz - 1);
656                                         if ('\0' == c)
657                                                 break;
658                                         sz += cond_width(p, c, &skip);
659                                         continue;
660                                 case (ESCAPE_SPECIAL):
661                                         c = mchars_spec2cp
662                                                 (p->symtab, seq, ssz);
663                                         if (c <= 0)
664                                                 break;
665                                         sz += cond_width(p, c, &skip);
666                                         continue;
667                                 default:
668                                         break;
669                                 }
670
671                         rhs = NULL;
672
673                         switch (esc) {
674                         case (ESCAPE_UNICODE):
675                                 sz += cond_width(p, '?', &skip);
676                                 break;
677                         case (ESCAPE_NUMBERED):
678                                 c = mchars_num2char(seq, ssz);
679                                 if ('\0' != c)
680                                         sz += cond_width(p, c, &skip);
681                                 break;
682                         case (ESCAPE_SPECIAL):
683                                 rhs = mchars_spec2str
684                                         (p->symtab, seq, ssz, &rsz);
685
686                                 if (ssz != 1 || rhs)
687                                         break;
688
689                                 rhs = seq;
690                                 rsz = ssz;
691                                 break;
692                         case (ESCAPE_SKIPCHAR):
693                                 skip = 1;
694                                 break;
695                         default:
696                                 break;
697                         }
698
699                         if (NULL == rhs)
700                                 break;
701
702                         if (skip) {
703                                 skip = 0;
704                                 break;
705                         }
706
707                         for (i = 0; i < rsz; i++)
708                                 sz += (*p->width)(p, *rhs++);
709                         break;
710                 case (ASCII_NBRSP):
711                         sz += cond_width(p, ' ', &skip);
712                         cp++;
713                         break;
714                 case (ASCII_HYPH):
715                         sz += cond_width(p, '-', &skip);
716                         cp++;
717                         break;
718                 default:
719                         break;
720                 }
721         }
722
723         return(sz);
724 }
725
726 /* ARGSUSED */
727 size_t
728 term_vspan(const struct termp *p, const struct roffsu *su)
729 {
730         double           r;
731
732         switch (su->unit) {
733         case (SCALE_CM):
734                 r = su->scale * 2;
735                 break;
736         case (SCALE_IN):
737                 r = su->scale * 6;
738                 break;
739         case (SCALE_PC):
740                 r = su->scale;
741                 break;
742         case (SCALE_PT):
743                 r = su->scale / 8;
744                 break;
745         case (SCALE_MM):
746                 r = su->scale / 1000;
747                 break;
748         case (SCALE_VS):
749                 r = su->scale;
750                 break;
751         default:
752                 r = su->scale - 1;
753                 break;
754         }
755
756         if (r < 0.0)
757                 r = 0.0;
758         return(/* LINTED */(size_t)
759                         r);
760 }
761
762 size_t
763 term_hspan(const struct termp *p, const struct roffsu *su)
764 {
765         double           v;
766
767         v = ((*p->hspan)(p, su));
768         if (v < 0.0)
769                 v = 0.0;
770         return((size_t) /* LINTED */
771                         v);
772 }