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