xref: /openbsd/usr.bin/mandoc/out.c (revision 3cab2bb3)
1 /*	$OpenBSD: out.c,v 1.51 2019/12/31 22:49:17 schwarze Exp $ */
2 /*
3  * Copyright (c) 2009, 2010, 2011 Kristaps Dzonsons <kristaps@bsd.lv>
4  * Copyright (c) 2011,2014,2015,2017,2018 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 <stdlib.h>
24 #include <string.h>
25 #include <time.h>
26 
27 #include "mandoc_aux.h"
28 #include "tbl.h"
29 #include "out.h"
30 
31 struct	tbl_colgroup {
32 	struct tbl_colgroup	*next;
33 	size_t			 wanted;
34 	int			 startcol;
35 	int			 endcol;
36 };
37 
38 static	size_t	tblcalc_data(struct rofftbl *, struct roffcol *,
39 			const struct tbl_opts *, const struct tbl_dat *,
40 			size_t);
41 static	size_t	tblcalc_literal(struct rofftbl *, struct roffcol *,
42 			const struct tbl_dat *, size_t);
43 static	size_t	tblcalc_number(struct rofftbl *, struct roffcol *,
44 			const struct tbl_opts *, const struct tbl_dat *);
45 
46 
47 /*
48  * Parse the *src string and store a scaling unit into *dst.
49  * If the string doesn't specify the unit, use the default.
50  * If no default is specified, fail.
51  * Return a pointer to the byte after the last byte used,
52  * or NULL on total failure.
53  */
54 const char *
55 a2roffsu(const char *src, struct roffsu *dst, enum roffscale def)
56 {
57 	char		*endptr;
58 
59 	dst->unit = def == SCALE_MAX ? SCALE_BU : def;
60 	dst->scale = strtod(src, &endptr);
61 	if (endptr == src)
62 		return NULL;
63 
64 	switch (*endptr++) {
65 	case 'c':
66 		dst->unit = SCALE_CM;
67 		break;
68 	case 'i':
69 		dst->unit = SCALE_IN;
70 		break;
71 	case 'f':
72 		dst->unit = SCALE_FS;
73 		break;
74 	case 'M':
75 		dst->unit = SCALE_MM;
76 		break;
77 	case 'm':
78 		dst->unit = SCALE_EM;
79 		break;
80 	case 'n':
81 		dst->unit = SCALE_EN;
82 		break;
83 	case 'P':
84 		dst->unit = SCALE_PC;
85 		break;
86 	case 'p':
87 		dst->unit = SCALE_PT;
88 		break;
89 	case 'u':
90 		dst->unit = SCALE_BU;
91 		break;
92 	case 'v':
93 		dst->unit = SCALE_VS;
94 		break;
95 	default:
96 		endptr--;
97 		if (SCALE_MAX == def)
98 			return NULL;
99 		dst->unit = def;
100 		break;
101 	}
102 	return endptr;
103 }
104 
105 /*
106  * Calculate the abstract widths and decimal positions of columns in a
107  * table.  This routine allocates the columns structures then runs over
108  * all rows and cells in the table.  The function pointers in "tbl" are
109  * used for the actual width calculations.
110  */
111 void
112 tblcalc(struct rofftbl *tbl, const struct tbl_span *sp_first,
113     size_t offset, size_t rmargin)
114 {
115 	struct roffsu		 su;
116 	const struct tbl_opts	*opts;
117 	const struct tbl_span	*sp;
118 	const struct tbl_dat	*dp;
119 	struct roffcol		*col;
120 	struct tbl_colgroup	*first_group, **gp, *g;
121 	size_t			*colwidth;
122 	size_t			 ewidth, min1, min2, wanted, width, xwidth;
123 	int			 done, icol, maxcol, necol, nxcol, quirkcol;
124 
125 	/*
126 	 * Allocate the master column specifiers.  These will hold the
127 	 * widths and decimal positions for all cells in the column.  It
128 	 * must be freed and nullified by the caller.
129 	 */
130 
131 	assert(tbl->cols == NULL);
132 	tbl->cols = mandoc_calloc((size_t)sp_first->opts->cols,
133 	    sizeof(struct roffcol));
134 	opts = sp_first->opts;
135 
136 	maxcol = -1;
137 	first_group = NULL;
138 	for (sp = sp_first; sp != NULL; sp = sp->next) {
139 		if (sp->pos != TBL_SPAN_DATA)
140 			continue;
141 
142 		/*
143 		 * Account for the data cells in the layout, matching it
144 		 * to data cells in the data section.
145 		 */
146 
147 		gp = &first_group;
148 		for (dp = sp->first; dp != NULL; dp = dp->next) {
149 			icol = dp->layout->col;
150 			while (maxcol < icol + dp->hspans)
151 				tbl->cols[++maxcol].spacing = SIZE_MAX;
152 			col = tbl->cols + icol;
153 			col->flags |= dp->layout->flags;
154 			if (dp->layout->flags & TBL_CELL_WIGN)
155 				continue;
156 
157 			/* Handle explicit width specifications. */
158 
159 			if (dp->layout->wstr != NULL &&
160 			    dp->layout->width == 0 &&
161 			    a2roffsu(dp->layout->wstr, &su, SCALE_EN)
162 			    != NULL)
163 				dp->layout->width =
164 				    (*tbl->sulen)(&su, tbl->arg);
165 			if (col->width < dp->layout->width)
166 				col->width = dp->layout->width;
167 			if (dp->layout->spacing != SIZE_MAX &&
168 			    (col->spacing == SIZE_MAX ||
169 			     col->spacing < dp->layout->spacing))
170 				col->spacing = dp->layout->spacing;
171 
172 			/*
173 			 * Calculate an automatic width.
174 			 * Except for spanning cells, apply it.
175 			 */
176 
177 			width = tblcalc_data(tbl,
178 			    dp->hspans == 0 ? col : NULL,
179 			    opts, dp,
180 			    dp->block == 0 ? 0 :
181 			    dp->layout->width ? dp->layout->width :
182 			    rmargin ? (rmargin + sp->opts->cols / 2)
183 			    / (sp->opts->cols + 1) : 0);
184 			if (dp->hspans == 0)
185 				continue;
186 
187 			/*
188 			 * Build an ordered, singly linked list
189 			 * of all groups of columns joined by spans,
190 			 * recording the minimum width for each group.
191 			 */
192 
193 			while (*gp != NULL && ((*gp)->startcol < icol ||
194 			    (*gp)->endcol < icol + dp->hspans))
195 				gp = &(*gp)->next;
196 			if (*gp == NULL || (*gp)->startcol > icol ||
197                             (*gp)->endcol > icol + dp->hspans) {
198 				g = mandoc_malloc(sizeof(*g));
199 				g->next = *gp;
200 				g->wanted = width;
201 				g->startcol = icol;
202 				g->endcol = icol + dp->hspans;
203 				*gp = g;
204 			} else if ((*gp)->wanted < width)
205 				(*gp)->wanted = width;
206 		}
207 	}
208 
209 	/*
210 	 * The minimum width of columns explicitly specified
211 	 * in the layout is 1n.
212 	 */
213 
214 	if (maxcol < sp_first->opts->cols - 1)
215 		maxcol = sp_first->opts->cols - 1;
216 	for (icol = 0; icol <= maxcol; icol++) {
217 		col = tbl->cols + icol;
218 		if (col->width < 1)
219 			col->width = 1;
220 
221 		/*
222 		 * Column spacings are needed for span width
223 		 * calculations, so set the default values now.
224 		 */
225 
226 		if (col->spacing == SIZE_MAX || icol == maxcol)
227 			col->spacing = 3;
228 	}
229 
230 	/*
231 	 * Replace the minimum widths with the missing widths,
232 	 * and dismiss groups that are already wide enough.
233 	 */
234 
235 	gp = &first_group;
236 	while ((g = *gp) != NULL) {
237 		done = 0;
238 		for (icol = g->startcol; icol <= g->endcol; icol++) {
239 			width = tbl->cols[icol].width;
240 			if (icol < g->endcol)
241 				width += tbl->cols[icol].spacing;
242 			if (g->wanted <= width) {
243 				done = 1;
244 				break;
245 			} else
246 				(*gp)->wanted -= width;
247 		}
248 		if (done) {
249 			*gp = g->next;
250 			free(g);
251 		} else
252 			gp = &(*gp)->next;
253 	}
254 
255 	colwidth = mandoc_reallocarray(NULL, maxcol + 1, sizeof(*colwidth));
256 	while (first_group != NULL) {
257 
258 		/*
259 		 * Rebuild the array of the widths of all columns
260 		 * participating in spans that require expansion.
261 		 */
262 
263 		for (icol = 0; icol <= maxcol; icol++)
264 			colwidth[icol] = SIZE_MAX;
265 		for (g = first_group; g != NULL; g = g->next)
266 			for (icol = g->startcol; icol <= g->endcol; icol++)
267 				colwidth[icol] = tbl->cols[icol].width;
268 
269 		/*
270 		 * Find the smallest and second smallest column width
271 		 * among the columns which may need expamsion.
272 		 */
273 
274 		min1 = min2 = SIZE_MAX;
275 		for (icol = 0; icol <= maxcol; icol++) {
276 			if (min1 > colwidth[icol]) {
277 				min2 = min1;
278 				min1 = colwidth[icol];
279 			} else if (min1 < colwidth[icol] &&
280 			    min2 > colwidth[icol])
281 				min2 = colwidth[icol];
282 		}
283 
284 		/*
285 		 * Find the minimum wanted width
286 		 * for any one of the narrowest columns,
287 		 * and mark the columns wanting that width.
288 		 */
289 
290 		wanted = min2;
291 		for (g = first_group; g != NULL; g = g->next) {
292 			necol = 0;
293 			for (icol = g->startcol; icol <= g->endcol; icol++)
294 				if (tbl->cols[icol].width == min1)
295 					necol++;
296 			if (necol == 0)
297 				continue;
298 			width = min1 + (g->wanted - 1) / necol + 1;
299 			if (width > min2)
300 				width = min2;
301 			if (wanted > width)
302 				wanted = width;
303 			for (icol = g->startcol; icol <= g->endcol; icol++)
304 				if (colwidth[icol] == min1 ||
305 				    (colwidth[icol] < min2 &&
306 				     colwidth[icol] > width))
307 					colwidth[icol] = width;
308 		}
309 
310 		/* Record the effect of the widening on the group list. */
311 
312 		gp = &first_group;
313 		while ((g = *gp) != NULL) {
314 			done = 0;
315 			for (icol = g->startcol; icol <= g->endcol; icol++) {
316 				if (colwidth[icol] != wanted ||
317 				    tbl->cols[icol].width == wanted)
318 					continue;
319 				if (g->wanted <= wanted - min1) {
320 					done = 1;
321 					break;
322 				}
323 				g->wanted -= wanted - min1;
324 			}
325 			if (done) {
326 				*gp = g->next;
327 				free(g);
328 			} else
329 				gp = &(*gp)->next;
330 		}
331 
332 		/* Record the effect of the widening on the columns. */
333 
334 		for (icol = 0; icol <= maxcol; icol++)
335 			if (colwidth[icol] == wanted)
336 				tbl->cols[icol].width = wanted;
337 	}
338 	free(colwidth);
339 
340 	/*
341 	 * Align numbers with text.
342 	 * Count columns to equalize and columns to maximize.
343 	 * Find maximum width of the columns to equalize.
344 	 * Find total width of the columns *not* to maximize.
345 	 */
346 
347 	necol = nxcol = 0;
348 	ewidth = xwidth = 0;
349 	for (icol = 0; icol <= maxcol; icol++) {
350 		col = tbl->cols + icol;
351 		if (col->width > col->nwidth)
352 			col->decimal += (col->width - col->nwidth) / 2;
353 		else
354 			col->width = col->nwidth;
355 		if (col->flags & TBL_CELL_EQUAL) {
356 			necol++;
357 			if (ewidth < col->width)
358 				ewidth = col->width;
359 		}
360 		if (col->flags & TBL_CELL_WMAX)
361 			nxcol++;
362 		else
363 			xwidth += col->width;
364 	}
365 
366 	/*
367 	 * Equalize columns, if requested for any of them.
368 	 * Update total width of the columns not to maximize.
369 	 */
370 
371 	if (necol) {
372 		for (icol = 0; icol <= maxcol; icol++) {
373 			col = tbl->cols + icol;
374 			if ( ! (col->flags & TBL_CELL_EQUAL))
375 				continue;
376 			if (col->width == ewidth)
377 				continue;
378 			if (nxcol && rmargin)
379 				xwidth += ewidth - col->width;
380 			col->width = ewidth;
381 		}
382 	}
383 
384 	/*
385 	 * If there are any columns to maximize, find the total
386 	 * available width, deducting 3n margins between columns.
387 	 * Distribute the available width evenly.
388 	 */
389 
390 	if (nxcol && rmargin) {
391 		xwidth += 3*maxcol +
392 		    (opts->opts & (TBL_OPT_BOX | TBL_OPT_DBOX) ?
393 		     2 : !!opts->lvert + !!opts->rvert);
394 		if (rmargin <= offset + xwidth)
395 			return;
396 		xwidth = rmargin - offset - xwidth;
397 
398 		/*
399 		 * Emulate a bug in GNU tbl width calculation that
400 		 * manifests itself for large numbers of x-columns.
401 		 * Emulating it for 5 x-columns gives identical
402 		 * behaviour for up to 6 x-columns.
403 		 */
404 
405 		if (nxcol == 5) {
406 			quirkcol = xwidth % nxcol + 2;
407 			if (quirkcol != 3 && quirkcol != 4)
408 				quirkcol = -1;
409 		} else
410 			quirkcol = -1;
411 
412 		necol = 0;
413 		ewidth = 0;
414 		for (icol = 0; icol <= maxcol; icol++) {
415 			col = tbl->cols + icol;
416 			if ( ! (col->flags & TBL_CELL_WMAX))
417 				continue;
418 			col->width = (double)xwidth * ++necol / nxcol
419 			    - ewidth + 0.4995;
420 			if (necol == quirkcol)
421 				col->width--;
422 			ewidth += col->width;
423 		}
424 	}
425 }
426 
427 static size_t
428 tblcalc_data(struct rofftbl *tbl, struct roffcol *col,
429     const struct tbl_opts *opts, const struct tbl_dat *dp, size_t mw)
430 {
431 	size_t		 sz;
432 
433 	/* Branch down into data sub-types. */
434 
435 	switch (dp->layout->pos) {
436 	case TBL_CELL_HORIZ:
437 	case TBL_CELL_DHORIZ:
438 		sz = (*tbl->len)(1, tbl->arg);
439 		if (col != NULL && col->width < sz)
440 			col->width = sz;
441 		return sz;
442 	case TBL_CELL_LONG:
443 	case TBL_CELL_CENTRE:
444 	case TBL_CELL_LEFT:
445 	case TBL_CELL_RIGHT:
446 		return tblcalc_literal(tbl, col, dp, mw);
447 	case TBL_CELL_NUMBER:
448 		return tblcalc_number(tbl, col, opts, dp);
449 	case TBL_CELL_DOWN:
450 		return 0;
451 	default:
452 		abort();
453 	}
454 }
455 
456 static size_t
457 tblcalc_literal(struct rofftbl *tbl, struct roffcol *col,
458     const struct tbl_dat *dp, size_t mw)
459 {
460 	const char	*str;	/* Beginning of the first line. */
461 	const char	*beg;	/* Beginning of the current line. */
462 	char		*end;	/* End of the current line. */
463 	size_t		 lsz;	/* Length of the current line. */
464 	size_t		 wsz;	/* Length of the current word. */
465 	size_t		 msz;   /* Length of the longest line. */
466 
467 	if (dp->string == NULL || *dp->string == '\0')
468 		return 0;
469 	str = mw ? mandoc_strdup(dp->string) : dp->string;
470 	msz = lsz = 0;
471 	for (beg = str; beg != NULL && *beg != '\0'; beg = end) {
472 		end = mw ? strchr(beg, ' ') : NULL;
473 		if (end != NULL) {
474 			*end++ = '\0';
475 			while (*end == ' ')
476 				end++;
477 		}
478 		wsz = (*tbl->slen)(beg, tbl->arg);
479 		if (mw && lsz && lsz + 1 + wsz <= mw)
480 			lsz += 1 + wsz;
481 		else
482 			lsz = wsz;
483 		if (msz < lsz)
484 			msz = lsz;
485 	}
486 	if (mw)
487 		free((void *)str);
488 	if (col != NULL && col->width < msz)
489 		col->width = msz;
490 	return msz;
491 }
492 
493 static size_t
494 tblcalc_number(struct rofftbl *tbl, struct roffcol *col,
495 		const struct tbl_opts *opts, const struct tbl_dat *dp)
496 {
497 	const char	*cp, *lastdigit, *lastpoint;
498 	size_t		 intsz, totsz;
499 	char		 buf[2];
500 
501 	if (dp->string == NULL || *dp->string == '\0')
502 		return 0;
503 
504 	totsz = (*tbl->slen)(dp->string, tbl->arg);
505 	if (col == NULL)
506 		return totsz;
507 
508 	/*
509 	 * Find the last digit and
510 	 * the last decimal point that is adjacent to a digit.
511 	 * The alignment indicator "\&" overrides everything.
512 	 */
513 
514 	lastdigit = lastpoint = NULL;
515 	for (cp = dp->string; cp[0] != '\0'; cp++) {
516 		if (cp[0] == '\\' && cp[1] == '&') {
517 			lastdigit = lastpoint = cp;
518 			break;
519 		} else if (cp[0] == opts->decimal &&
520 		    (isdigit((unsigned char)cp[1]) ||
521 		     (cp > dp->string && isdigit((unsigned char)cp[-1]))))
522 			lastpoint = cp;
523 		else if (isdigit((unsigned char)cp[0]))
524 			lastdigit = cp;
525 	}
526 
527 	/* Not a number, treat as a literal string. */
528 
529 	if (lastdigit == NULL) {
530 		if (col != NULL && col->width < totsz)
531 			col->width = totsz;
532 		return totsz;
533 	}
534 
535 	/* Measure the width of the integer part. */
536 
537 	if (lastpoint == NULL)
538 		lastpoint = lastdigit + 1;
539 	intsz = 0;
540 	buf[1] = '\0';
541 	for (cp = dp->string; cp < lastpoint; cp++) {
542 		buf[0] = cp[0];
543 		intsz += (*tbl->slen)(buf, tbl->arg);
544 	}
545 
546 	/*
547          * If this number has more integer digits than all numbers
548          * seen on earlier lines, shift them all to the right.
549 	 * If it has fewer, shift this number to the right.
550 	 */
551 
552 	if (intsz > col->decimal) {
553 		col->nwidth += intsz - col->decimal;
554 		col->decimal = intsz;
555 	} else
556 		totsz += col->decimal - intsz;
557 
558 	/* Update the maximum total width seen so far. */
559 
560 	if (totsz > col->nwidth)
561 		col->nwidth = totsz;
562 	return totsz;
563 }
564