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