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