mandoc(1): Update to 1.9.19.
[dragonfly.git] / usr.bin / mandoc / term.c
1 /*      $Id: term.c,v 1.129 2010/03/23 12:42:22 kristaps Exp $ */
2 /*
3  * Copyright (c) 2008, 2009 Kristaps Dzonsons <kristaps@kth.se>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 #include <sys/types.h>
18
19 #include <assert.h>
20 #include <ctype.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <time.h>
25
26 #include "chars.h"
27 #include "out.h"
28 #include "term.h"
29 #include "man.h"
30 #include "mdoc.h"
31 #include "main.h"
32
33 static  struct termp     *term_alloc(enum termenc);
34 static  void              term_free(struct termp *);
35 static  void              spec(struct termp *, const char *, size_t);
36 static  void              res(struct termp *, const char *, size_t);
37 static  void              buffera(struct termp *, const char *, size_t);
38 static  void              bufferc(struct termp *, char);
39 static  void              adjbuf(struct termp *p, size_t);
40 static  void              encode(struct termp *, const char *, size_t);
41
42
43 void *
44 ascii_alloc(void)
45 {
46
47         return(term_alloc(TERMENC_ASCII));
48 }
49
50
51 void
52 terminal_free(void *arg)
53 {
54
55         term_free((struct termp *)arg);
56 }
57
58
59 static void
60 term_free(struct termp *p)
61 {
62
63         if (p->buf)
64                 free(p->buf);
65         if (p->symtab)
66                 chars_free(p->symtab);
67
68         free(p);
69 }
70
71
72 static struct termp *
73 term_alloc(enum termenc enc)
74 {
75         struct termp *p;
76
77         p = calloc(1, sizeof(struct termp));
78         if (NULL == p) {
79                 perror(NULL);
80                 exit(EXIT_FAILURE);
81         }
82         p->enc = enc;
83         return(p);
84 }
85
86
87 /*
88  * Flush a line of text.  A "line" is loosely defined as being something
89  * that should be followed by a newline, regardless of whether it's
90  * broken apart by newlines getting there.  A line can also be a
91  * fragment of a columnar list.
92  *
93  * Specifically, a line is whatever's in p->buf of length p->col, which
94  * is zeroed after this function returns.
95  *
96  * The usage of termp:flags is as follows:
97  *
98  *  - TERMP_NOLPAD: when beginning to write the line, don't left-pad the
99  *    offset value.  This is useful when doing columnar lists where the
100  *    prior column has right-padded.
101  *
102  *  - TERMP_NOBREAK: this is the most important and is used when making
103  *    columns.  In short: don't print a newline and instead pad to the
104  *    right margin.  Used in conjunction with TERMP_NOLPAD.
105  *
106  *  - TERMP_TWOSPACE: when padding, make sure there are at least two
107  *    space characters of padding.  Otherwise, rather break the line.
108  *
109  *  - TERMP_DANGLE: don't newline when TERMP_NOBREAK is specified and
110  *    the line is overrun, and don't pad-right if it's underrun.
111  *
112  *  - TERMP_HANG: like TERMP_DANGLE, but doesn't newline when
113  *    overruning, instead save the position and continue at that point
114  *    when the next invocation.
115  *
116  *  In-line line breaking:
117  *
118  *  If TERMP_NOBREAK is specified and the line overruns the right
119  *  margin, it will break and pad-right to the right margin after
120  *  writing.  If maxrmargin is violated, it will break and continue
121  *  writing from the right-margin, which will lead to the above scenario
122  *  upon exit.  Otherwise, the line will break at the right margin.
123  */
124 void
125 term_flushln(struct termp *p)
126 {
127         int              i;     /* current input position in p->buf */
128         size_t           vis;   /* current visual position on output */
129         size_t           vbl;   /* number of blanks to prepend to output */
130         size_t           vsz;   /* visual characters to write to output */
131         size_t           bp;    /* visual right border position */
132         int              j;     /* temporary loop index */
133         size_t           maxvis, mmax;
134
135         /*
136          * First, establish the maximum columns of "visible" content.
137          * This is usually the difference between the right-margin and
138          * an indentation, but can be, for tagged lists or columns, a
139          * small set of values.
140          */
141
142         assert(p->offset < p->rmargin);
143
144         maxvis = (int)(p->rmargin - p->offset) - p->overstep < 0 ?
145                 /* LINTED */
146                 0 : p->rmargin - p->offset - p->overstep;
147         mmax = (int)(p->maxrmargin - p->offset) - p->overstep < 0 ?
148                 /* LINTED */
149                 0 : p->maxrmargin - p->offset - p->overstep;
150
151         bp = TERMP_NOBREAK & p->flags ? mmax : maxvis;
152
153         /*
154          * FIXME: if bp is zero, we still output the first word before
155          * breaking the line.
156          */
157
158         vis = 0;
159
160         /*
161          * If in the standard case (left-justified), then begin with our
162          * indentation, otherwise (columns, etc.) just start spitting
163          * out text.
164          */
165
166         if ( ! (p->flags & TERMP_NOLPAD))
167                 /* LINTED */
168                 for (j = 0; j < (int)p->offset; j++)
169                         putchar(' ');
170
171         for (i = 0; i < (int)p->col; i++) {
172                 /*
173                  * Count up visible word characters.  Control sequences
174                  * (starting with the CSI) aren't counted.  A space
175                  * generates a non-printing word, which is valid (the
176                  * space is printed according to regular spacing rules).
177                  */
178
179                 /* LINTED */
180                 for (j = i, vsz = 0; j < (int)p->col; j++) {
181                         if (j && ' ' == p->buf[j])
182                                 break;
183                         else if (8 == p->buf[j])
184                                 vsz--;
185                         else
186                                 vsz++;
187                 }
188
189                 /*
190                  * Choose the number of blanks to prepend: no blank at the
191                  * beginning of a line, one between words -- but do not
192                  * actually write them yet.
193                  */
194                 vbl = (size_t)(0 == vis ? 0 : 1);
195
196                 /*
197                  * Find out whether we would exceed the right margin.
198                  * If so, break to the next line.  (TODO: hyphenate)
199                  * Otherwise, write the chosen number of blanks now.
200                  */
201                 if (vis && vis + vbl + vsz > bp) {
202                         putchar('\n');
203                         if (TERMP_NOBREAK & p->flags) {
204                                 for (j = 0; j < (int)p->rmargin; j++)
205                                         putchar(' ');
206                                 vis = p->rmargin - p->offset;
207                         } else {
208                                 for (j = 0; j < (int)p->offset; j++)
209                                         putchar(' ');
210                                 vis = 0;
211                         }
212                         /* Remove the p->overstep width. */
213                         bp += (int)/* LINTED */
214                                 p->overstep;
215                         p->overstep = 0;
216                 } else {
217                         for (j = 0; j < (int)vbl; j++)
218                                 putchar(' ');
219                         vis += vbl;
220                 }
221
222                 /*
223                  * Finally, write out the word.
224                  */
225                 for ( ; i < (int)p->col; i++) {
226                         if (' ' == p->buf[i])
227                                 break;
228
229                         /* The unit sep. is a non-breaking space. */
230                         if (31 == p->buf[i])
231                                 putchar(' ');
232                         else
233                                 putchar(p->buf[i]);
234                 }
235                 vis += vsz;
236         }
237
238         p->col = 0;
239         p->overstep = 0;
240
241         if ( ! (TERMP_NOBREAK & p->flags)) {
242                 putchar('\n');
243                 return;
244         }
245
246         if (TERMP_HANG & p->flags) {
247                 /* We need one blank after the tag. */
248                 p->overstep = /* LINTED */
249                         vis - maxvis + 1;
250
251                 /*
252                  * Behave exactly the same way as groff:
253                  * If we have overstepped the margin, temporarily move
254                  * it to the right and flag the rest of the line to be
255                  * shorter.
256                  * If we landed right at the margin, be happy.
257                  * If we are one step before the margin, temporarily
258                  * move it one step LEFT and flag the rest of the line
259                  * to be longer.
260                  */
261                 if (p->overstep >= -1) {
262                         assert((int)maxvis + p->overstep >= 0);
263                         /* LINTED */
264                         maxvis += p->overstep;
265                 } else
266                         p->overstep = 0;
267
268         } else if (TERMP_DANGLE & p->flags)
269                 return;
270
271         /* Right-pad. */
272         if (maxvis > vis + /* LINTED */
273                         ((TERMP_TWOSPACE & p->flags) ? 1 : 0))
274                 for ( ; vis < maxvis; vis++)
275                         putchar(' ');
276         else {  /* ...or newline break. */
277                 putchar('\n');
278                 for (i = 0; i < (int)p->rmargin; i++)
279                         putchar(' ');
280         }
281 }
282
283
284 /*
285  * A newline only breaks an existing line; it won't assert vertical
286  * space.  All data in the output buffer is flushed prior to the newline
287  * assertion.
288  */
289 void
290 term_newln(struct termp *p)
291 {
292
293         p->flags |= TERMP_NOSPACE;
294         if (0 == p->col) {
295                 p->flags &= ~TERMP_NOLPAD;
296                 return;
297         }
298         term_flushln(p);
299         p->flags &= ~TERMP_NOLPAD;
300 }
301
302
303 /*
304  * Asserts a vertical space (a full, empty line-break between lines).
305  * Note that if used twice, this will cause two blank spaces and so on.
306  * All data in the output buffer is flushed prior to the newline
307  * assertion.
308  */
309 void
310 term_vspace(struct termp *p)
311 {
312
313         term_newln(p);
314         putchar('\n');
315 }
316
317
318 static void
319 spec(struct termp *p, const char *word, size_t len)
320 {
321         const char      *rhs;
322         size_t           sz;
323
324         rhs = chars_a2ascii(p->symtab, word, len, &sz);
325         if (rhs)
326                 encode(p, rhs, sz);
327 }
328
329
330 static void
331 res(struct termp *p, const char *word, size_t len)
332 {
333         const char      *rhs;
334         size_t           sz;
335
336         rhs = chars_a2res(p->symtab, word, len, &sz);
337         if (rhs)
338                 encode(p, rhs, sz);
339 }
340
341
342 void
343 term_fontlast(struct termp *p)
344 {
345         enum termfont    f;
346
347         f = p->fontl;
348         p->fontl = p->fontq[p->fonti];
349         p->fontq[p->fonti] = f;
350 }
351
352
353 void
354 term_fontrepl(struct termp *p, enum termfont f)
355 {
356
357         p->fontl = p->fontq[p->fonti];
358         p->fontq[p->fonti] = f;
359 }
360
361
362 void
363 term_fontpush(struct termp *p, enum termfont f)
364 {
365
366         assert(p->fonti + 1 < 10);
367         p->fontl = p->fontq[p->fonti];
368         p->fontq[++p->fonti] = f;
369 }
370
371
372 const void *
373 term_fontq(struct termp *p)
374 {
375
376         return(&p->fontq[p->fonti]);
377 }
378
379
380 enum termfont
381 term_fonttop(struct termp *p)
382 {
383
384         return(p->fontq[p->fonti]);
385 }
386
387
388 void
389 term_fontpopq(struct termp *p, const void *key)
390 {
391
392         while (p->fonti >= 0 && key != &p->fontq[p->fonti])
393                 p->fonti--;
394         assert(p->fonti >= 0);
395 }
396
397
398 void
399 term_fontpop(struct termp *p)
400 {
401
402         assert(p->fonti);
403         p->fonti--;
404 }
405
406
407 /*
408  * Handle pwords, partial words, which may be either a single word or a
409  * phrase that cannot be broken down (such as a literal string).  This
410  * handles word styling.
411  */
412 void
413 term_word(struct termp *p, const char *word)
414 {
415         const char      *sv, *seq;
416         int              sz;
417         size_t           ssz;
418         enum roffdeco    deco;
419
420         sv = word;
421
422         if (word[0] && '\0' == word[1])
423                 switch (word[0]) {
424                 case('.'):
425                         /* FALLTHROUGH */
426                 case(','):
427                         /* FALLTHROUGH */
428                 case(';'):
429                         /* FALLTHROUGH */
430                 case(':'):
431                         /* FALLTHROUGH */
432                 case('?'):
433                         /* FALLTHROUGH */
434                 case('!'):
435                         /* FALLTHROUGH */
436                 case(')'):
437                         /* FALLTHROUGH */
438                 case(']'):
439                         /* FALLTHROUGH */
440                 case('}'):
441                         if ( ! (TERMP_IGNDELIM & p->flags))
442                                 p->flags |= TERMP_NOSPACE;
443                         break;
444                 default:
445                         break;
446                 }
447
448         if ( ! (TERMP_NOSPACE & p->flags))
449                 bufferc(p, ' ');
450
451         if ( ! (p->flags & TERMP_NONOSPACE))
452                 p->flags &= ~TERMP_NOSPACE;
453
454         /* FIXME: use strcspn. */
455
456         while (*word) {
457                 if ('\\' != *word) {
458                         encode(p, word, 1);
459                         word++;
460                         continue;
461                 }
462
463                 seq = ++word;
464                 sz = a2roffdeco(&deco, &seq, &ssz);
465
466                 switch (deco) {
467                 case (DECO_RESERVED):
468                         res(p, seq, ssz);
469                         break;
470                 case (DECO_SPECIAL):
471                         spec(p, seq, ssz);
472                         break;
473                 case (DECO_BOLD):
474                         term_fontrepl(p, TERMFONT_BOLD);
475                         break;
476                 case (DECO_ITALIC):
477                         term_fontrepl(p, TERMFONT_UNDER);
478                         break;
479                 case (DECO_ROMAN):
480                         term_fontrepl(p, TERMFONT_NONE);
481                         break;
482                 case (DECO_PREVIOUS):
483                         term_fontlast(p);
484                         break;
485                 default:
486                         break;
487                 }
488
489                 word += sz;
490                 if (DECO_NOSPACE == deco && '\0' == *word)
491                         p->flags |= TERMP_NOSPACE;
492         }
493
494         if (sv[0] && 0 == sv[1])
495                 switch (sv[0]) {
496                 case('('):
497                         /* FALLTHROUGH */
498                 case('['):
499                         /* FALLTHROUGH */
500                 case('{'):
501                         p->flags |= TERMP_NOSPACE;
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 = realloc(p->buf, p->maxcols);
519         if (NULL == p->buf) {
520                 perror(NULL);
521                 exit(EXIT_FAILURE);
522         }
523 }
524
525
526 static void
527 buffera(struct termp *p, const char *word, size_t sz)
528 {
529
530         if (p->col + sz >= p->maxcols)
531                 adjbuf(p, p->col + sz);
532
533         memcpy(&p->buf[(int)p->col], word, sz);
534         p->col += sz;
535 }
536
537
538 static void
539 bufferc(struct termp *p, char c)
540 {
541
542         if (p->col + 1 >= p->maxcols)
543                 adjbuf(p, p->col + 1);
544
545         p->buf[(int)p->col++] = c;
546 }
547
548
549 static void
550 encode(struct termp *p, const char *word, size_t sz)
551 {
552         enum termfont     f;
553         int               i;
554
555         /*
556          * Encode and buffer a string of characters.  If the current
557          * font mode is unset, buffer directly, else encode then buffer
558          * character by character.
559          */
560
561         if (TERMFONT_NONE == (f = term_fonttop(p))) {
562                 buffera(p, word, sz);
563                 return;
564         }
565
566         for (i = 0; i < (int)sz; i++) {
567                 if ( ! isgraph((u_char)word[i])) {
568                         bufferc(p, word[i]);
569                         continue;
570                 }
571
572                 if (TERMFONT_UNDER == f)
573                         bufferc(p, '_');
574                 else
575                         bufferc(p, word[i]);
576
577                 bufferc(p, 8);
578                 bufferc(p, word[i]);
579         }
580 }
581
582
583 size_t
584 term_vspan(const struct roffsu *su)
585 {
586         double           r;
587
588         switch (su->unit) {
589         case (SCALE_CM):
590                 r = su->scale * 2;
591                 break;
592         case (SCALE_IN):
593                 r = su->scale * 6;
594                 break;
595         case (SCALE_PC):
596                 r = su->scale;
597                 break;
598         case (SCALE_PT):
599                 r = su->scale / 8;
600                 break;
601         case (SCALE_MM):
602                 r = su->scale / 1000;
603                 break;
604         case (SCALE_VS):
605                 r = su->scale;
606                 break;
607         default:
608                 r = su->scale - 1;
609                 break;
610         }
611
612         if (r < 0.0)
613                 r = 0.0;
614         return(/* LINTED */(size_t)
615                         r);
616 }
617
618
619 size_t
620 term_hspan(const struct roffsu *su)
621 {
622         double           r;
623
624         /* XXX: CM, IN, and PT are approximations. */
625
626         switch (su->unit) {
627         case (SCALE_CM):
628                 r = 4 * su->scale;
629                 break;
630         case (SCALE_IN):
631                 /* XXX: this is an approximation. */
632                 r = 10 * su->scale;
633                 break;
634         case (SCALE_PC):
635                 r = (10 * su->scale) / 6;
636                 break;
637         case (SCALE_PT):
638                 r = (10 * su->scale) / 72;
639                 break;
640         case (SCALE_MM):
641                 r = su->scale / 1000; /* FIXME: double-check. */
642                 break;
643         case (SCALE_VS):
644                 r = su->scale * 2 - 1; /* FIXME: double-check. */
645                 break;
646         default:
647                 r = su->scale;
648                 break;
649         }
650
651         if (r < 0.0)
652                 r = 0.0;
653         return((size_t)/* LINTED */
654                         r);
655 }