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