xref: /openbsd-src/usr.bin/mandoc/term.c (revision 5e3c7963eb248119b7dfd4b0defad58a7d9cd306)
1 /*	$OpenBSD: term.c,v 1.140 2019/01/15 12:15:52 schwarze Exp $ */
2 /*
3  * Copyright (c) 2008, 2009, 2010, 2011 Kristaps Dzonsons <kristaps@bsd.lv>
4  * Copyright (c) 2010-2019 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 AUTHORS DISCLAIM ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS 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 #include <sys/types.h>
19 
20 #include <assert.h>
21 #include <ctype.h>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 
27 #include "mandoc.h"
28 #include "mandoc_aux.h"
29 #include "out.h"
30 #include "term.h"
31 #include "main.h"
32 
33 static	size_t		 cond_width(const struct termp *, int, int *);
34 static	void		 adjbuf(struct termp_col *, size_t);
35 static	void		 bufferc(struct termp *, char);
36 static	void		 encode(struct termp *, const char *, size_t);
37 static	void		 encode1(struct termp *, int);
38 static	void		 endline(struct termp *);
39 static	void		 term_field(struct termp *, size_t, size_t,
40 				size_t, size_t);
41 static	void		 term_fill(struct termp *, size_t *, size_t *,
42 				size_t);
43 
44 
45 void
46 term_setcol(struct termp *p, size_t maxtcol)
47 {
48 	if (maxtcol > p->maxtcol) {
49 		p->tcols = mandoc_recallocarray(p->tcols,
50 		    p->maxtcol, maxtcol, sizeof(*p->tcols));
51 		p->maxtcol = maxtcol;
52 	}
53 	p->lasttcol = maxtcol - 1;
54 	p->tcol = p->tcols;
55 }
56 
57 void
58 term_free(struct termp *p)
59 {
60 	for (p->tcol = p->tcols; p->tcol < p->tcols + p->maxtcol; p->tcol++)
61 		free(p->tcol->buf);
62 	free(p->tcols);
63 	free(p->fontq);
64 	free(p);
65 }
66 
67 void
68 term_begin(struct termp *p, term_margin head,
69 		term_margin foot, const struct roff_meta *arg)
70 {
71 
72 	p->headf = head;
73 	p->footf = foot;
74 	p->argf = arg;
75 	(*p->begin)(p);
76 }
77 
78 void
79 term_end(struct termp *p)
80 {
81 
82 	(*p->end)(p);
83 }
84 
85 /*
86  * Flush a chunk of text.  By default, break the output line each time
87  * the right margin is reached, and continue output on the next line
88  * at the same offset as the chunk itself.  By default, also break the
89  * output line at the end of the chunk.  There are many flags modifying
90  * this behaviour, see the comments in the body of the function.
91  */
92 void
93 term_flushln(struct termp *p)
94 {
95 	size_t	 vbl;      /* Number of blanks to prepend to the output. */
96 	size_t	 vbr;      /* Actual visual position of the end of field. */
97 	size_t	 vfield;   /* Desired visual field width. */
98 	size_t	 vtarget;  /* Desired visual position of the right margin. */
99 	size_t	 ic;       /* Character position in the input buffer. */
100 	size_t	 nbr;      /* Number of characters to print in this field. */
101 
102 	/*
103 	 * Normally, start writing at the left margin, but with the
104 	 * NOPAD flag, start writing at the current position instead.
105 	 */
106 
107 	vbl = (p->flags & TERMP_NOPAD) || p->tcol->offset < p->viscol ?
108 	    0 : p->tcol->offset - p->viscol;
109 	if (p->minbl && vbl < p->minbl)
110 		vbl = p->minbl;
111 
112 	if ((p->flags & TERMP_MULTICOL) == 0)
113 		p->tcol->col = 0;
114 
115 	/* Loop over output lines. */
116 
117 	for (;;) {
118 		vfield = p->tcol->rmargin > p->viscol + vbl ?
119 		    p->tcol->rmargin - p->viscol - vbl : 0;
120 
121 		/*
122 		 * Normally, break the line at the the right margin
123 		 * of the field, but with the NOBREAK flag, only
124 		 * break it at the max right margin of the screen,
125 		 * and with the BRNEVER flag, never break it at all.
126 		 */
127 
128 		vtarget = p->flags & TERMP_BRNEVER ? SIZE_MAX :
129 		    (p->flags & TERMP_NOBREAK) == 0 ? vfield :
130 		    p->maxrmargin > p->viscol + vbl ?
131 		    p->maxrmargin - p->viscol - vbl : 0;
132 
133 		/*
134 		 * Figure out how much text will fit in the field.
135 		 * If there is whitespace only, print nothing.
136 		 */
137 
138 		term_fill(p, &nbr, &vbr, vtarget);
139 		if (nbr == 0)
140 			break;
141 
142 		/*
143 		 * With the CENTER or RIGHT flag, increase the indentation
144 		 * to center the text between the left and right margins
145 		 * or to adjust it to the right margin, respectively.
146 		 */
147 
148 		if (vbr < vtarget) {
149 			if (p->flags & TERMP_CENTER)
150 				vbl += (vtarget - vbr) / 2;
151 			else if (p->flags & TERMP_RIGHT)
152 				vbl += vtarget - vbr;
153 		}
154 
155 		/* Finally, print the field content. */
156 
157 		term_field(p, vbl, nbr, vbr, vtarget);
158 
159 		/*
160 		 * If there is no text left in the field, exit the loop.
161 		 * If the BRTRSP flag is set, consider trailing
162 		 * whitespace significant when deciding whether
163 		 * the field fits or not.
164 		 */
165 
166 		for (ic = p->tcol->col; ic < p->tcol->lastcol; ic++) {
167 			switch (p->tcol->buf[ic]) {
168 			case '\t':
169 				if (p->flags & TERMP_BRTRSP)
170 					vbr = term_tab_next(vbr);
171 				continue;
172 			case ' ':
173 				if (p->flags & TERMP_BRTRSP)
174 					vbr += (*p->width)(p, ' ');
175 				continue;
176 			case '\n':
177 			case ASCII_BREAK:
178 				continue;
179 			default:
180 				break;
181 			}
182 			break;
183 		}
184 		if (ic == p->tcol->lastcol)
185 			break;
186 
187 		/*
188 		 * At the location of an automtic line break, input
189 		 * space characters are consumed by the line break.
190 		 */
191 
192 		while (p->tcol->col < p->tcol->lastcol &&
193 		    p->tcol->buf[p->tcol->col] == ' ')
194 			p->tcol->col++;
195 
196 		/*
197 		 * In multi-column mode, leave the rest of the text
198 		 * in the buffer to be handled by a subsequent
199 		 * invocation, such that the other columns of the
200 		 * table can be handled first.
201 		 * In single-column mode, simply break the line.
202 		 */
203 
204 		if (p->flags & TERMP_MULTICOL)
205 			return;
206 
207 		endline(p);
208 		p->viscol = 0;
209 
210 		/*
211 		 * Normally, start the next line at the same indentation
212 		 * as this one, but with the BRIND flag, start it at the
213 		 * right margin instead.  This is used together with
214 		 * NOBREAK for the tags in various kinds of tagged lists.
215 		 */
216 
217 		vbl = p->flags & TERMP_BRIND ?
218 		    p->tcol->rmargin : p->tcol->offset;
219 	}
220 
221 	/* Reset output state in preparation for the next field. */
222 
223 	p->col = p->tcol->col = p->tcol->lastcol = 0;
224 	p->minbl = p->trailspace;
225 	p->flags &= ~(TERMP_BACKAFTER | TERMP_BACKBEFORE | TERMP_NOPAD);
226 
227 	if (p->flags & TERMP_MULTICOL)
228 		return;
229 
230 	/*
231 	 * The HANG flag means that the next field
232 	 * always follows on the same line.
233 	 * The NOBREAK flag means that the next field
234 	 * follows on the same line unless the field was overrun.
235 	 * Normally, break the line at the end of each field.
236 	 */
237 
238 	if ((p->flags & TERMP_HANG) == 0 &&
239 	    ((p->flags & TERMP_NOBREAK) == 0 ||
240 	     vbr + term_len(p, p->trailspace) > vfield))
241 		endline(p);
242 }
243 
244 /*
245  * Store the number of input characters to print in this field in *nbr
246  * and their total visual width to print in *vbr.
247  * If there is only whitespace in the field, both remain zero.
248  * The desired visual width of the field is provided by vtarget.
249  * If the first word is longer, the field will be overrun.
250  */
251 static void
252 term_fill(struct termp *p, size_t *nbr, size_t *vbr, size_t vtarget)
253 {
254 	size_t	 ic;        /* Character position in the input buffer. */
255 	size_t	 vis;       /* Visual position of the current character. */
256 	size_t	 vn;        /* Visual position of the next character. */
257 	int	 breakline; /* Break at the end of this word. */
258 	int	 graph;     /* Last character was non-blank. */
259 
260 	*nbr = *vbr = vis = 0;
261 	breakline = graph = 0;
262 	for (ic = p->tcol->col; ic < p->tcol->lastcol; ic++) {
263 		switch (p->tcol->buf[ic]) {
264 		case '\b':  /* Escape \o (overstrike) or backspace markup. */
265 			assert(ic > 0);
266 			vis -= (*p->width)(p, p->tcol->buf[ic - 1]);
267 			continue;
268 
269 		case '\t':  /* Normal ASCII whitespace. */
270 		case ' ':
271 		case ASCII_BREAK:  /* Escape \: (breakpoint). */
272 			switch (p->tcol->buf[ic]) {
273 			case '\t':
274 				vn = term_tab_next(vis);
275 				break;
276 			case ' ':
277 				vn = vis + (*p->width)(p, ' ');
278 				break;
279 			case ASCII_BREAK:
280 				vn = vis;
281 				break;
282 			}
283 			/* Can break at the end of a word. */
284 			if (breakline || vn > vtarget)
285 				break;
286 			if (graph) {
287 				*nbr = ic;
288 				*vbr = vis;
289 				graph = 0;
290 			}
291 			vis = vn;
292 			continue;
293 
294 		case '\n':  /* Escape \p (break at the end of the word). */
295 			breakline = 1;
296 			continue;
297 
298 		case ASCII_HYPH:  /* Breakable hyphen. */
299 			graph = 1;
300 			/*
301 			 * We are about to decide whether to break the
302 			 * line or not, so we no longer need this hyphen
303 			 * to be marked as breakable.  Put back a real
304 			 * hyphen such that we get the correct width.
305 			 */
306 			p->tcol->buf[ic] = '-';
307 			vis += (*p->width)(p, '-');
308 			if (vis > vtarget) {
309 				ic++;
310 				break;
311 			}
312 			*nbr = ic + 1;
313 			*vbr = vis;
314 			continue;
315 
316 		case ASCII_NBRSP:  /* Non-breakable space. */
317 			p->tcol->buf[ic] = ' ';
318 			/* FALLTHROUGH */
319 		default:  /* Printable character. */
320 			graph = 1;
321 			vis += (*p->width)(p, p->tcol->buf[ic]);
322 			if (vis > vtarget && *nbr > 0)
323 				return;
324 			continue;
325 		}
326 		break;
327 	}
328 
329 	/*
330 	 * If the last word extends to the end of the field without any
331 	 * trailing whitespace, the loop could not check yet whether it
332 	 * can remain on this line.  So do the check now.
333 	 */
334 
335 	if (graph && (vis <= vtarget || *nbr == 0)) {
336 		*nbr = ic;
337 		*vbr = vis;
338 	}
339 }
340 
341 /*
342  * Print the contents of one field
343  * with an indentation of	 vbl	  visual columns,
344  * an input string length of	 nbr	  characters,
345  * an output width of		 vbr	  visual columns,
346  * and a desired field width of	 vtarget  visual columns.
347  */
348 static void
349 term_field(struct termp *p, size_t vbl, size_t nbr, size_t vbr, size_t vtarget)
350 {
351 	size_t	 ic;	/* Character position in the input buffer. */
352 	size_t	 vis;	/* Visual position of the current character. */
353 	size_t	 dv;	/* Visual width of the current character. */
354 	size_t	 vn;	/* Visual position of the next character. */
355 
356 	vis = 0;
357 	for (ic = p->tcol->col; ic < nbr; ic++) {
358 
359 		/*
360 		 * To avoid the printing of trailing whitespace,
361 		 * do not print whitespace right away, only count it.
362 		 */
363 
364 		switch (p->tcol->buf[ic]) {
365 		case '\n':
366 		case ASCII_BREAK:
367 			continue;
368 		case '\t':
369 			vn = term_tab_next(vis);
370 			vbl += vn - vis;
371 			vis = vn;
372 			continue;
373 		case ' ':
374 		case ASCII_NBRSP:
375 			dv = (*p->width)(p, ' ');
376 			vbl += dv;
377 			vis += dv;
378 			continue;
379 		default:
380 			break;
381 		}
382 
383 		/*
384 		 * We found a non-blank character to print,
385 		 * so write preceding white space now.
386 		 */
387 
388 		if (vbl > 0) {
389 			(*p->advance)(p, vbl);
390 			p->viscol += vbl;
391 			vbl = 0;
392 		}
393 
394 		/* Print the character and adjust the visual position. */
395 
396 		(*p->letter)(p, p->tcol->buf[ic]);
397 		if (p->tcol->buf[ic] == '\b') {
398 			dv = (*p->width)(p, p->tcol->buf[ic - 1]);
399 			p->viscol -= dv;
400 			vis -= dv;
401 		} else {
402 			dv = (*p->width)(p, p->tcol->buf[ic]);
403 			p->viscol += dv;
404 			vis += dv;
405 		}
406 	}
407 	p->tcol->col = nbr;
408 }
409 
410 static void
411 endline(struct termp *p)
412 {
413 	if ((p->flags & (TERMP_NEWMC | TERMP_ENDMC)) == TERMP_ENDMC) {
414 		p->mc = NULL;
415 		p->flags &= ~TERMP_ENDMC;
416 	}
417 	if (p->mc != NULL) {
418 		if (p->viscol && p->maxrmargin >= p->viscol)
419 			(*p->advance)(p, p->maxrmargin - p->viscol + 1);
420 		p->flags |= TERMP_NOBUF | TERMP_NOSPACE;
421 		term_word(p, p->mc);
422 		p->flags &= ~(TERMP_NOBUF | TERMP_NEWMC);
423 	}
424 	p->viscol = 0;
425 	p->minbl = 0;
426 	(*p->endline)(p);
427 }
428 
429 /*
430  * A newline only breaks an existing line; it won't assert vertical
431  * space.  All data in the output buffer is flushed prior to the newline
432  * assertion.
433  */
434 void
435 term_newln(struct termp *p)
436 {
437 
438 	p->flags |= TERMP_NOSPACE;
439 	if (p->tcol->lastcol || p->viscol)
440 		term_flushln(p);
441 }
442 
443 /*
444  * Asserts a vertical space (a full, empty line-break between lines).
445  * Note that if used twice, this will cause two blank spaces and so on.
446  * All data in the output buffer is flushed prior to the newline
447  * assertion.
448  */
449 void
450 term_vspace(struct termp *p)
451 {
452 
453 	term_newln(p);
454 	p->viscol = 0;
455 	p->minbl = 0;
456 	if (0 < p->skipvsp)
457 		p->skipvsp--;
458 	else
459 		(*p->endline)(p);
460 }
461 
462 /* Swap current and previous font; for \fP and .ft P */
463 void
464 term_fontlast(struct termp *p)
465 {
466 	enum termfont	 f;
467 
468 	f = p->fontl;
469 	p->fontl = p->fontq[p->fonti];
470 	p->fontq[p->fonti] = f;
471 }
472 
473 /* Set font, save current, discard previous; for \f, .ft, .B etc. */
474 void
475 term_fontrepl(struct termp *p, enum termfont f)
476 {
477 
478 	p->fontl = p->fontq[p->fonti];
479 	p->fontq[p->fonti] = f;
480 }
481 
482 /* Set font, save previous. */
483 void
484 term_fontpush(struct termp *p, enum termfont f)
485 {
486 
487 	p->fontl = p->fontq[p->fonti];
488 	if (++p->fonti == p->fontsz) {
489 		p->fontsz += 8;
490 		p->fontq = mandoc_reallocarray(p->fontq,
491 		    p->fontsz, sizeof(*p->fontq));
492 	}
493 	p->fontq[p->fonti] = f;
494 }
495 
496 /* Flush to make the saved pointer current again. */
497 void
498 term_fontpopq(struct termp *p, int i)
499 {
500 
501 	assert(i >= 0);
502 	if (p->fonti > i)
503 		p->fonti = i;
504 }
505 
506 /* Pop one font off the stack. */
507 void
508 term_fontpop(struct termp *p)
509 {
510 
511 	assert(p->fonti);
512 	p->fonti--;
513 }
514 
515 /*
516  * Handle pwords, partial words, which may be either a single word or a
517  * phrase that cannot be broken down (such as a literal string).  This
518  * handles word styling.
519  */
520 void
521 term_word(struct termp *p, const char *word)
522 {
523 	struct roffsu	 su;
524 	const char	 nbrsp[2] = { ASCII_NBRSP, 0 };
525 	const char	*seq, *cp;
526 	int		 sz, uc;
527 	size_t		 csz, lsz, ssz;
528 	enum mandoc_esc	 esc;
529 
530 	if ((p->flags & TERMP_NOBUF) == 0) {
531 		if ((p->flags & TERMP_NOSPACE) == 0) {
532 			if ((p->flags & TERMP_KEEP) == 0) {
533 				bufferc(p, ' ');
534 				if (p->flags & TERMP_SENTENCE)
535 					bufferc(p, ' ');
536 			} else
537 				bufferc(p, ASCII_NBRSP);
538 		}
539 		if (p->flags & TERMP_PREKEEP)
540 			p->flags |= TERMP_KEEP;
541 		if (p->flags & TERMP_NONOSPACE)
542 			p->flags |= TERMP_NOSPACE;
543 		else
544 			p->flags &= ~TERMP_NOSPACE;
545 		p->flags &= ~(TERMP_SENTENCE | TERMP_NONEWLINE);
546 		p->skipvsp = 0;
547 	}
548 
549 	while ('\0' != *word) {
550 		if ('\\' != *word) {
551 			if (TERMP_NBRWORD & p->flags) {
552 				if (' ' == *word) {
553 					encode(p, nbrsp, 1);
554 					word++;
555 					continue;
556 				}
557 				ssz = strcspn(word, "\\ ");
558 			} else
559 				ssz = strcspn(word, "\\");
560 			encode(p, word, ssz);
561 			word += (int)ssz;
562 			continue;
563 		}
564 
565 		word++;
566 		esc = mandoc_escape(&word, &seq, &sz);
567 		switch (esc) {
568 		case ESCAPE_UNICODE:
569 			uc = mchars_num2uc(seq + 1, sz - 1);
570 			break;
571 		case ESCAPE_NUMBERED:
572 			uc = mchars_num2char(seq, sz);
573 			if (uc < 0)
574 				continue;
575 			break;
576 		case ESCAPE_SPECIAL:
577 			if (p->enc == TERMENC_ASCII) {
578 				cp = mchars_spec2str(seq, sz, &ssz);
579 				if (cp != NULL)
580 					encode(p, cp, ssz);
581 			} else {
582 				uc = mchars_spec2cp(seq, sz);
583 				if (uc > 0)
584 					encode1(p, uc);
585 			}
586 			continue;
587 		case ESCAPE_UNDEF:
588 			uc = *seq;
589 			break;
590 		case ESCAPE_FONTBOLD:
591 			term_fontrepl(p, TERMFONT_BOLD);
592 			continue;
593 		case ESCAPE_FONTITALIC:
594 			term_fontrepl(p, TERMFONT_UNDER);
595 			continue;
596 		case ESCAPE_FONTBI:
597 			term_fontrepl(p, TERMFONT_BI);
598 			continue;
599 		case ESCAPE_FONT:
600 		case ESCAPE_FONTCW:
601 		case ESCAPE_FONTROMAN:
602 			term_fontrepl(p, TERMFONT_NONE);
603 			continue;
604 		case ESCAPE_FONTPREV:
605 			term_fontlast(p);
606 			continue;
607 		case ESCAPE_BREAK:
608 			bufferc(p, '\n');
609 			continue;
610 		case ESCAPE_NOSPACE:
611 			if (p->flags & TERMP_BACKAFTER)
612 				p->flags &= ~TERMP_BACKAFTER;
613 			else if (*word == '\0')
614 				p->flags |= (TERMP_NOSPACE | TERMP_NONEWLINE);
615 			continue;
616 		case ESCAPE_DEVICE:
617 			if (p->type == TERMTYPE_PDF)
618 				encode(p, "pdf", 3);
619 			else if (p->type == TERMTYPE_PS)
620 				encode(p, "ps", 2);
621 			else if (p->enc == TERMENC_ASCII)
622 				encode(p, "ascii", 5);
623 			else
624 				encode(p, "utf8", 4);
625 			continue;
626 		case ESCAPE_HORIZ:
627 			if (*seq == '|') {
628 				seq++;
629 				uc = -p->col;
630 			} else
631 				uc = 0;
632 			if (a2roffsu(seq, &su, SCALE_EM) == NULL)
633 				continue;
634 			uc += term_hen(p, &su);
635 			if (uc > 0)
636 				while (uc-- > 0)
637 					bufferc(p, ASCII_NBRSP);
638 			else if (p->col > (size_t)(-uc))
639 				p->col += uc;
640 			else {
641 				uc += p->col;
642 				p->col = 0;
643 				if (p->tcol->offset > (size_t)(-uc)) {
644 					p->ti += uc;
645 					p->tcol->offset += uc;
646 				} else {
647 					p->ti -= p->tcol->offset;
648 					p->tcol->offset = 0;
649 				}
650 			}
651 			continue;
652 		case ESCAPE_HLINE:
653 			if ((cp = a2roffsu(seq, &su, SCALE_EM)) == NULL)
654 				continue;
655 			uc = term_hen(p, &su);
656 			if (uc <= 0) {
657 				if (p->tcol->rmargin <= p->tcol->offset)
658 					continue;
659 				lsz = p->tcol->rmargin - p->tcol->offset;
660 			} else
661 				lsz = uc;
662 			if (*cp == seq[-1])
663 				uc = -1;
664 			else if (*cp == '\\') {
665 				seq = cp + 1;
666 				esc = mandoc_escape(&seq, &cp, &sz);
667 				switch (esc) {
668 				case ESCAPE_UNICODE:
669 					uc = mchars_num2uc(cp + 1, sz - 1);
670 					break;
671 				case ESCAPE_NUMBERED:
672 					uc = mchars_num2char(cp, sz);
673 					break;
674 				case ESCAPE_SPECIAL:
675 					uc = mchars_spec2cp(cp, sz);
676 					break;
677 				case ESCAPE_UNDEF:
678 					uc = *seq;
679 					break;
680 				default:
681 					uc = -1;
682 					break;
683 				}
684 			} else
685 				uc = *cp;
686 			if (uc < 0x20 || (uc > 0x7E && uc < 0xA0))
687 				uc = '_';
688 			if (p->enc == TERMENC_ASCII) {
689 				cp = ascii_uc2str(uc);
690 				csz = term_strlen(p, cp);
691 				ssz = strlen(cp);
692 			} else
693 				csz = (*p->width)(p, uc);
694 			while (lsz >= csz) {
695 				if (p->enc == TERMENC_ASCII)
696 					encode(p, cp, ssz);
697 				else
698 					encode1(p, uc);
699 				lsz -= csz;
700 			}
701 			continue;
702 		case ESCAPE_SKIPCHAR:
703 			p->flags |= TERMP_BACKAFTER;
704 			continue;
705 		case ESCAPE_OVERSTRIKE:
706 			cp = seq + sz;
707 			while (seq < cp) {
708 				if (*seq == '\\') {
709 					mandoc_escape(&seq, NULL, NULL);
710 					continue;
711 				}
712 				encode1(p, *seq++);
713 				if (seq < cp) {
714 					if (p->flags & TERMP_BACKBEFORE)
715 						p->flags |= TERMP_BACKAFTER;
716 					else
717 						p->flags |= TERMP_BACKBEFORE;
718 				}
719 			}
720 			/* Trim trailing backspace/blank pair. */
721 			if (p->tcol->lastcol > 2 &&
722 			    (p->tcol->buf[p->tcol->lastcol - 1] == ' ' ||
723 			     p->tcol->buf[p->tcol->lastcol - 1] == '\t'))
724 				p->tcol->lastcol -= 2;
725 			if (p->col > p->tcol->lastcol)
726 				p->col = p->tcol->lastcol;
727 			continue;
728 		default:
729 			continue;
730 		}
731 
732 		/*
733 		 * Common handling for Unicode and numbered
734 		 * character escape sequences.
735 		 */
736 
737 		if (p->enc == TERMENC_ASCII) {
738 			cp = ascii_uc2str(uc);
739 			encode(p, cp, strlen(cp));
740 		} else {
741 			if ((uc < 0x20 && uc != 0x09) ||
742 			    (uc > 0x7E && uc < 0xA0))
743 				uc = 0xFFFD;
744 			encode1(p, uc);
745 		}
746 	}
747 	p->flags &= ~TERMP_NBRWORD;
748 }
749 
750 static void
751 adjbuf(struct termp_col *c, size_t sz)
752 {
753 	if (c->maxcols == 0)
754 		c->maxcols = 1024;
755 	while (c->maxcols <= sz)
756 		c->maxcols <<= 2;
757 	c->buf = mandoc_reallocarray(c->buf, c->maxcols, sizeof(*c->buf));
758 }
759 
760 static void
761 bufferc(struct termp *p, char c)
762 {
763 	if (p->flags & TERMP_NOBUF) {
764 		(*p->letter)(p, c);
765 		return;
766 	}
767 	if (p->col + 1 >= p->tcol->maxcols)
768 		adjbuf(p->tcol, p->col + 1);
769 	if (p->tcol->lastcol <= p->col || (c != ' ' && c != ASCII_NBRSP))
770 		p->tcol->buf[p->col] = c;
771 	if (p->tcol->lastcol < ++p->col)
772 		p->tcol->lastcol = p->col;
773 }
774 
775 /*
776  * See encode().
777  * Do this for a single (probably unicode) value.
778  * Does not check for non-decorated glyphs.
779  */
780 static void
781 encode1(struct termp *p, int c)
782 {
783 	enum termfont	  f;
784 
785 	if (p->flags & TERMP_NOBUF) {
786 		(*p->letter)(p, c);
787 		return;
788 	}
789 
790 	if (p->col + 7 >= p->tcol->maxcols)
791 		adjbuf(p->tcol, p->col + 7);
792 
793 	f = (c == ASCII_HYPH || c > 127 || isgraph(c)) ?
794 	    p->fontq[p->fonti] : TERMFONT_NONE;
795 
796 	if (p->flags & TERMP_BACKBEFORE) {
797 		if (p->tcol->buf[p->col - 1] == ' ' ||
798 		    p->tcol->buf[p->col - 1] == '\t')
799 			p->col--;
800 		else
801 			p->tcol->buf[p->col++] = '\b';
802 		p->flags &= ~TERMP_BACKBEFORE;
803 	}
804 	if (f == TERMFONT_UNDER || f == TERMFONT_BI) {
805 		p->tcol->buf[p->col++] = '_';
806 		p->tcol->buf[p->col++] = '\b';
807 	}
808 	if (f == TERMFONT_BOLD || f == TERMFONT_BI) {
809 		if (c == ASCII_HYPH)
810 			p->tcol->buf[p->col++] = '-';
811 		else
812 			p->tcol->buf[p->col++] = c;
813 		p->tcol->buf[p->col++] = '\b';
814 	}
815 	if (p->tcol->lastcol <= p->col || (c != ' ' && c != ASCII_NBRSP))
816 		p->tcol->buf[p->col] = c;
817 	if (p->tcol->lastcol < ++p->col)
818 		p->tcol->lastcol = p->col;
819 	if (p->flags & TERMP_BACKAFTER) {
820 		p->flags |= TERMP_BACKBEFORE;
821 		p->flags &= ~TERMP_BACKAFTER;
822 	}
823 }
824 
825 static void
826 encode(struct termp *p, const char *word, size_t sz)
827 {
828 	size_t		  i;
829 
830 	if (p->flags & TERMP_NOBUF) {
831 		for (i = 0; i < sz; i++)
832 			(*p->letter)(p, word[i]);
833 		return;
834 	}
835 
836 	if (p->col + 2 + (sz * 5) >= p->tcol->maxcols)
837 		adjbuf(p->tcol, p->col + 2 + (sz * 5));
838 
839 	for (i = 0; i < sz; i++) {
840 		if (ASCII_HYPH == word[i] ||
841 		    isgraph((unsigned char)word[i]))
842 			encode1(p, word[i]);
843 		else {
844 			if (p->tcol->lastcol <= p->col ||
845 			    (word[i] != ' ' && word[i] != ASCII_NBRSP))
846 				p->tcol->buf[p->col] = word[i];
847 			p->col++;
848 
849 			/*
850 			 * Postpone the effect of \z while handling
851 			 * an overstrike sequence from ascii_uc2str().
852 			 */
853 
854 			if (word[i] == '\b' &&
855 			    (p->flags & TERMP_BACKBEFORE)) {
856 				p->flags &= ~TERMP_BACKBEFORE;
857 				p->flags |= TERMP_BACKAFTER;
858 			}
859 		}
860 	}
861 	if (p->tcol->lastcol < p->col)
862 		p->tcol->lastcol = p->col;
863 }
864 
865 void
866 term_setwidth(struct termp *p, const char *wstr)
867 {
868 	struct roffsu	 su;
869 	int		 iop, width;
870 
871 	iop = 0;
872 	width = 0;
873 	if (NULL != wstr) {
874 		switch (*wstr) {
875 		case '+':
876 			iop = 1;
877 			wstr++;
878 			break;
879 		case '-':
880 			iop = -1;
881 			wstr++;
882 			break;
883 		default:
884 			break;
885 		}
886 		if (a2roffsu(wstr, &su, SCALE_MAX) != NULL)
887 			width = term_hspan(p, &su);
888 		else
889 			iop = 0;
890 	}
891 	(*p->setwidth)(p, iop, width);
892 }
893 
894 size_t
895 term_len(const struct termp *p, size_t sz)
896 {
897 
898 	return (*p->width)(p, ' ') * sz;
899 }
900 
901 static size_t
902 cond_width(const struct termp *p, int c, int *skip)
903 {
904 
905 	if (*skip) {
906 		(*skip) = 0;
907 		return 0;
908 	} else
909 		return (*p->width)(p, c);
910 }
911 
912 size_t
913 term_strlen(const struct termp *p, const char *cp)
914 {
915 	size_t		 sz, rsz, i;
916 	int		 ssz, skip, uc;
917 	const char	*seq, *rhs;
918 	enum mandoc_esc	 esc;
919 	static const char rej[] = { '\\', ASCII_NBRSP, ASCII_HYPH,
920 			ASCII_BREAK, '\0' };
921 
922 	/*
923 	 * Account for escaped sequences within string length
924 	 * calculations.  This follows the logic in term_word() as we
925 	 * must calculate the width of produced strings.
926 	 */
927 
928 	sz = 0;
929 	skip = 0;
930 	while ('\0' != *cp) {
931 		rsz = strcspn(cp, rej);
932 		for (i = 0; i < rsz; i++)
933 			sz += cond_width(p, *cp++, &skip);
934 
935 		switch (*cp) {
936 		case '\\':
937 			cp++;
938 			rhs = NULL;
939 			esc = mandoc_escape(&cp, &seq, &ssz);
940 			switch (esc) {
941 			case ESCAPE_UNICODE:
942 				uc = mchars_num2uc(seq + 1, ssz - 1);
943 				break;
944 			case ESCAPE_NUMBERED:
945 				uc = mchars_num2char(seq, ssz);
946 				if (uc < 0)
947 					continue;
948 				break;
949 			case ESCAPE_SPECIAL:
950 				if (p->enc == TERMENC_ASCII) {
951 					rhs = mchars_spec2str(seq, ssz, &rsz);
952 					if (rhs != NULL)
953 						break;
954 				} else {
955 					uc = mchars_spec2cp(seq, ssz);
956 					if (uc > 0)
957 						sz += cond_width(p, uc, &skip);
958 				}
959 				continue;
960 			case ESCAPE_UNDEF:
961 				uc = *seq;
962 				break;
963 			case ESCAPE_DEVICE:
964 				if (p->type == TERMTYPE_PDF) {
965 					rhs = "pdf";
966 					rsz = 3;
967 				} else if (p->type == TERMTYPE_PS) {
968 					rhs = "ps";
969 					rsz = 2;
970 				} else if (p->enc == TERMENC_ASCII) {
971 					rhs = "ascii";
972 					rsz = 5;
973 				} else {
974 					rhs = "utf8";
975 					rsz = 4;
976 				}
977 				break;
978 			case ESCAPE_SKIPCHAR:
979 				skip = 1;
980 				continue;
981 			case ESCAPE_OVERSTRIKE:
982 				rsz = 0;
983 				rhs = seq + ssz;
984 				while (seq < rhs) {
985 					if (*seq == '\\') {
986 						mandoc_escape(&seq, NULL, NULL);
987 						continue;
988 					}
989 					i = (*p->width)(p, *seq++);
990 					if (rsz < i)
991 						rsz = i;
992 				}
993 				sz += rsz;
994 				continue;
995 			default:
996 				continue;
997 			}
998 
999 			/*
1000 			 * Common handling for Unicode and numbered
1001 			 * character escape sequences.
1002 			 */
1003 
1004 			if (rhs == NULL) {
1005 				if (p->enc == TERMENC_ASCII) {
1006 					rhs = ascii_uc2str(uc);
1007 					rsz = strlen(rhs);
1008 				} else {
1009 					if ((uc < 0x20 && uc != 0x09) ||
1010 					    (uc > 0x7E && uc < 0xA0))
1011 						uc = 0xFFFD;
1012 					sz += cond_width(p, uc, &skip);
1013 					continue;
1014 				}
1015 			}
1016 
1017 			if (skip) {
1018 				skip = 0;
1019 				break;
1020 			}
1021 
1022 			/*
1023 			 * Common handling for all escape sequences
1024 			 * printing more than one character.
1025 			 */
1026 
1027 			for (i = 0; i < rsz; i++)
1028 				sz += (*p->width)(p, *rhs++);
1029 			break;
1030 		case ASCII_NBRSP:
1031 			sz += cond_width(p, ' ', &skip);
1032 			cp++;
1033 			break;
1034 		case ASCII_HYPH:
1035 			sz += cond_width(p, '-', &skip);
1036 			cp++;
1037 			break;
1038 		default:
1039 			break;
1040 		}
1041 	}
1042 
1043 	return sz;
1044 }
1045 
1046 int
1047 term_vspan(const struct termp *p, const struct roffsu *su)
1048 {
1049 	double		 r;
1050 	int		 ri;
1051 
1052 	switch (su->unit) {
1053 	case SCALE_BU:
1054 		r = su->scale / 40.0;
1055 		break;
1056 	case SCALE_CM:
1057 		r = su->scale * 6.0 / 2.54;
1058 		break;
1059 	case SCALE_FS:
1060 		r = su->scale * 65536.0 / 40.0;
1061 		break;
1062 	case SCALE_IN:
1063 		r = su->scale * 6.0;
1064 		break;
1065 	case SCALE_MM:
1066 		r = su->scale * 0.006;
1067 		break;
1068 	case SCALE_PC:
1069 		r = su->scale;
1070 		break;
1071 	case SCALE_PT:
1072 		r = su->scale / 12.0;
1073 		break;
1074 	case SCALE_EN:
1075 	case SCALE_EM:
1076 		r = su->scale * 0.6;
1077 		break;
1078 	case SCALE_VS:
1079 		r = su->scale;
1080 		break;
1081 	default:
1082 		abort();
1083 	}
1084 	ri = r > 0.0 ? r + 0.4995 : r - 0.4995;
1085 	return ri < 66 ? ri : 1;
1086 }
1087 
1088 /*
1089  * Convert a scaling width to basic units, rounding towards 0.
1090  */
1091 int
1092 term_hspan(const struct termp *p, const struct roffsu *su)
1093 {
1094 
1095 	return (*p->hspan)(p, su);
1096 }
1097 
1098 /*
1099  * Convert a scaling width to basic units, rounding to closest.
1100  */
1101 int
1102 term_hen(const struct termp *p, const struct roffsu *su)
1103 {
1104 	int bu;
1105 
1106 	if ((bu = (*p->hspan)(p, su)) >= 0)
1107 		return (bu + 11) / 24;
1108 	else
1109 		return -((-bu + 11) / 24);
1110 }
1111