xref: /openbsd-src/usr.bin/mandoc/term_ps.c (revision 5ad04d351680822078003e2b066cfc9680d6157d)
1 /*	$Id: term_ps.c,v 1.25 2014/04/23 21:06:33 schwarze Exp $ */
2 /*
3  * Copyright (c) 2010, 2011 Kristaps Dzonsons <kristaps@bsd.lv>
4  * Copyright (c) 2014 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 <stdarg.h>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <time.h>
27 #include <unistd.h>
28 
29 #include "mandoc.h"
30 #include "mandoc_aux.h"
31 #include "out.h"
32 #include "main.h"
33 #include "term.h"
34 
35 /* These work the buffer used by the header and footer. */
36 #define	PS_BUFSLOP	  128
37 
38 /* Convert PostScript point "x" to an AFM unit. */
39 #define	PNT2AFM(p, x) \
40 	(size_t)((double)(x) * (1000.0 / (double)(p)->ps->scale))
41 
42 /* Convert an AFM unit "x" to a PostScript points */
43 #define	AFM2PNT(p, x) \
44 	((double)(x) / (1000.0 / (double)(p)->ps->scale))
45 
46 struct	glyph {
47 	unsigned short	  wx; /* WX in AFM */
48 };
49 
50 struct	font {
51 	const char	 *name; /* FontName in AFM */
52 #define	MAXCHAR		  95 /* total characters we can handle */
53 	struct glyph	  gly[MAXCHAR]; /* glyph metrics */
54 };
55 
56 struct	termp_ps {
57 	int		  flags;
58 #define	PS_INLINE	 (1 << 0)	/* we're in a word */
59 #define	PS_MARGINS	 (1 << 1)	/* we're in the margins */
60 #define	PS_NEWPAGE	 (1 << 2)	/* new page, no words yet */
61 	size_t		  pscol;	/* visible column (AFM units) */
62 	size_t		  psrow;	/* visible row (AFM units) */
63 	char		 *psmarg;	/* margin buf */
64 	size_t		  psmargsz;	/* margin buf size */
65 	size_t		  psmargcur;	/* cur index in margin buf */
66 	char		  last;		/* character buffer */
67 	enum termfont	  lastf;	/* last set font */
68 	size_t		  scale;	/* font scaling factor */
69 	size_t		  pages;	/* number of pages shown */
70 	size_t		  lineheight;	/* line height (AFM units) */
71 	size_t		  top;		/* body top (AFM units) */
72 	size_t		  bottom;	/* body bottom (AFM units) */
73 	size_t		  height;	/* page height (AFM units */
74 	size_t		  width;	/* page width (AFM units) */
75 	size_t		  lastwidth;	/* page width before last ll */
76 	size_t		  left;		/* body left (AFM units) */
77 	size_t		  header;	/* header pos (AFM units) */
78 	size_t		  footer;	/* footer pos (AFM units) */
79 	size_t		  pdfbytes;	/* current output byte */
80 	size_t		  pdflastpg;	/* byte of last page mark */
81 	size_t		  pdfbody;	/* start of body object */
82 	size_t		 *pdfobjs;	/* table of object offsets */
83 	size_t		  pdfobjsz;	/* size of pdfobjs */
84 };
85 
86 static	double		  ps_hspan(const struct termp *,
87 				const struct roffsu *);
88 static	size_t		  ps_width(const struct termp *, int);
89 static	void		  ps_advance(struct termp *, size_t);
90 static	void		  ps_begin(struct termp *);
91 static	void		  ps_closepage(struct termp *);
92 static	void		  ps_end(struct termp *);
93 static	void		  ps_endline(struct termp *);
94 static	void		  ps_fclose(struct termp *);
95 static	void		  ps_growbuf(struct termp *, size_t);
96 static	void		  ps_letter(struct termp *, int);
97 static	void		  ps_pclose(struct termp *);
98 static	void		  ps_pletter(struct termp *, int);
99 static	void		  ps_printf(struct termp *, const char *, ...);
100 static	void		  ps_putchar(struct termp *, char);
101 static	void		  ps_setfont(struct termp *, enum termfont);
102 static	void		  ps_setwidth(struct termp *, int, size_t);
103 static	struct termp	 *pspdf_alloc(char *);
104 static	void		  pdf_obj(struct termp *, size_t);
105 
106 /*
107  * We define, for the time being, three fonts: bold, oblique/italic, and
108  * normal (roman).  The following table hard-codes the font metrics for
109  * ASCII, i.e., 32--127.
110  */
111 
112 static	const struct font fonts[TERMFONT__MAX] = {
113 	{ "Times-Roman", {
114 		{ 250 },
115 		{ 333 },
116 		{ 408 },
117 		{ 500 },
118 		{ 500 },
119 		{ 833 },
120 		{ 778 },
121 		{ 333 },
122 		{ 333 },
123 		{ 333 },
124 		{ 500 },
125 		{ 564 },
126 		{ 250 },
127 		{ 333 },
128 		{ 250 },
129 		{ 278 },
130 		{ 500 },
131 		{ 500 },
132 		{ 500 },
133 		{ 500 },
134 		{ 500 },
135 		{ 500 },
136 		{ 500 },
137 		{ 500 },
138 		{ 500 },
139 		{ 500 },
140 		{ 278 },
141 		{ 278 },
142 		{ 564 },
143 		{ 564 },
144 		{ 564 },
145 		{ 444 },
146 		{ 921 },
147 		{ 722 },
148 		{ 667 },
149 		{ 667 },
150 		{ 722 },
151 		{ 611 },
152 		{ 556 },
153 		{ 722 },
154 		{ 722 },
155 		{ 333 },
156 		{ 389 },
157 		{ 722 },
158 		{ 611 },
159 		{ 889 },
160 		{ 722 },
161 		{ 722 },
162 		{ 556 },
163 		{ 722 },
164 		{ 667 },
165 		{ 556 },
166 		{ 611 },
167 		{ 722 },
168 		{ 722 },
169 		{ 944 },
170 		{ 722 },
171 		{ 722 },
172 		{ 611 },
173 		{ 333 },
174 		{ 278 },
175 		{ 333 },
176 		{ 469 },
177 		{ 500 },
178 		{ 333 },
179 		{ 444 },
180 		{ 500 },
181 		{ 444 },
182 		{  500},
183 		{  444},
184 		{  333},
185 		{  500},
186 		{  500},
187 		{  278},
188 		{  278},
189 		{  500},
190 		{  278},
191 		{  778},
192 		{  500},
193 		{  500},
194 		{  500},
195 		{  500},
196 		{  333},
197 		{  389},
198 		{  278},
199 		{  500},
200 		{  500},
201 		{  722},
202 		{  500},
203 		{  500},
204 		{  444},
205 		{  480},
206 		{  200},
207 		{  480},
208 		{  541},
209 	} },
210 	{ "Times-Bold", {
211 		{ 250  },
212 		{ 333  },
213 		{ 555  },
214 		{ 500  },
215 		{ 500  },
216 		{ 1000 },
217 		{ 833  },
218 		{ 333  },
219 		{ 333  },
220 		{ 333  },
221 		{ 500  },
222 		{ 570  },
223 		{ 250  },
224 		{ 333  },
225 		{ 250  },
226 		{ 278  },
227 		{ 500  },
228 		{ 500  },
229 		{ 500  },
230 		{ 500  },
231 		{ 500  },
232 		{ 500  },
233 		{ 500  },
234 		{ 500  },
235 		{ 500  },
236 		{ 500  },
237 		{ 333  },
238 		{ 333  },
239 		{ 570  },
240 		{ 570  },
241 		{ 570  },
242 		{ 500  },
243 		{ 930  },
244 		{ 722  },
245 		{ 667  },
246 		{ 722  },
247 		{ 722  },
248 		{ 667  },
249 		{ 611  },
250 		{ 778  },
251 		{ 778  },
252 		{ 389  },
253 		{ 500  },
254 		{ 778  },
255 		{ 667  },
256 		{ 944  },
257 		{ 722  },
258 		{ 778  },
259 		{ 611  },
260 		{ 778  },
261 		{ 722  },
262 		{ 556  },
263 		{ 667  },
264 		{ 722  },
265 		{ 722  },
266 		{ 1000 },
267 		{ 722  },
268 		{ 722  },
269 		{ 667  },
270 		{ 333  },
271 		{ 278  },
272 		{ 333  },
273 		{ 581  },
274 		{ 500  },
275 		{ 333  },
276 		{ 500  },
277 		{ 556  },
278 		{ 444  },
279 		{  556 },
280 		{  444 },
281 		{  333 },
282 		{  500 },
283 		{  556 },
284 		{  278 },
285 		{  333 },
286 		{  556 },
287 		{  278 },
288 		{  833 },
289 		{  556 },
290 		{  500 },
291 		{  556 },
292 		{  556 },
293 		{  444 },
294 		{  389 },
295 		{  333 },
296 		{  556 },
297 		{  500 },
298 		{  722 },
299 		{  500 },
300 		{  500 },
301 		{  444 },
302 		{  394 },
303 		{  220 },
304 		{  394 },
305 		{  520 },
306 	} },
307 	{ "Times-Italic", {
308 		{ 250  },
309 		{ 333  },
310 		{ 420  },
311 		{ 500  },
312 		{ 500  },
313 		{ 833  },
314 		{ 778  },
315 		{ 333  },
316 		{ 333  },
317 		{ 333  },
318 		{ 500  },
319 		{ 675  },
320 		{ 250  },
321 		{ 333  },
322 		{ 250  },
323 		{ 278  },
324 		{ 500  },
325 		{ 500  },
326 		{ 500  },
327 		{ 500  },
328 		{ 500  },
329 		{ 500  },
330 		{ 500  },
331 		{ 500  },
332 		{ 500  },
333 		{ 500  },
334 		{ 333  },
335 		{ 333  },
336 		{ 675  },
337 		{ 675  },
338 		{ 675  },
339 		{ 500  },
340 		{ 920  },
341 		{ 611  },
342 		{ 611  },
343 		{ 667  },
344 		{ 722  },
345 		{ 611  },
346 		{ 611  },
347 		{ 722  },
348 		{ 722  },
349 		{ 333  },
350 		{ 444  },
351 		{ 667  },
352 		{ 556  },
353 		{ 833  },
354 		{ 667  },
355 		{ 722  },
356 		{ 611  },
357 		{ 722  },
358 		{ 611  },
359 		{ 500  },
360 		{ 556  },
361 		{ 722  },
362 		{ 611  },
363 		{ 833  },
364 		{ 611  },
365 		{ 556  },
366 		{ 556  },
367 		{ 389  },
368 		{ 278  },
369 		{ 389  },
370 		{ 422  },
371 		{ 500  },
372 		{ 333  },
373 		{ 500  },
374 		{ 500  },
375 		{ 444  },
376 		{  500 },
377 		{  444 },
378 		{  278 },
379 		{  500 },
380 		{  500 },
381 		{  278 },
382 		{  278 },
383 		{  444 },
384 		{  278 },
385 		{  722 },
386 		{  500 },
387 		{  500 },
388 		{  500 },
389 		{  500 },
390 		{  389 },
391 		{  389 },
392 		{  278 },
393 		{  500 },
394 		{  444 },
395 		{  667 },
396 		{  444 },
397 		{  444 },
398 		{  389 },
399 		{  400 },
400 		{  275 },
401 		{  400 },
402 		{  541 },
403 	} },
404 };
405 
406 void *
407 pdf_alloc(char *outopts)
408 {
409 	struct termp	*p;
410 
411 	if (NULL != (p = pspdf_alloc(outopts)))
412 		p->type = TERMTYPE_PDF;
413 
414 	return(p);
415 }
416 
417 void *
418 ps_alloc(char *outopts)
419 {
420 	struct termp	*p;
421 
422 	if (NULL != (p = pspdf_alloc(outopts)))
423 		p->type = TERMTYPE_PS;
424 
425 	return(p);
426 }
427 
428 static struct termp *
429 pspdf_alloc(char *outopts)
430 {
431 	struct termp	*p;
432 	unsigned int	 pagex, pagey;
433 	size_t		 marginx, marginy, lineheight;
434 	const char	*toks[2];
435 	const char	*pp;
436 	char		*v;
437 
438 	p = mandoc_calloc(1, sizeof(struct termp));
439 	p->enc = TERMENC_ASCII;
440 	p->ps = mandoc_calloc(1, sizeof(struct termp_ps));
441 
442 	p->advance = ps_advance;
443 	p->begin = ps_begin;
444 	p->end = ps_end;
445 	p->endline = ps_endline;
446 	p->hspan = ps_hspan;
447 	p->letter = ps_letter;
448 	p->setwidth = ps_setwidth;
449 	p->width = ps_width;
450 
451 	toks[0] = "paper";
452 	toks[1] = NULL;
453 
454 	pp = NULL;
455 
456 	while (outopts && *outopts)
457 		switch (getsubopt(&outopts, UNCONST(toks), &v)) {
458 		case 0:
459 			pp = v;
460 			break;
461 		default:
462 			break;
463 		}
464 
465 	/* Default to US letter (millimetres). */
466 
467 	pagex = 216;
468 	pagey = 279;
469 
470 	/*
471 	 * The ISO-269 paper sizes can be calculated automatically, but
472 	 * it would require bringing in -lm for pow() and I'd rather not
473 	 * do that.  So just do it the easy way for now.  Since this
474 	 * only happens once, I'm not terribly concerned.
475 	 */
476 
477 	if (pp && strcasecmp(pp, "letter")) {
478 		if (0 == strcasecmp(pp, "a3")) {
479 			pagex = 297;
480 			pagey = 420;
481 		} else if (0 == strcasecmp(pp, "a4")) {
482 			pagex = 210;
483 			pagey = 297;
484 		} else if (0 == strcasecmp(pp, "a5")) {
485 			pagex = 148;
486 			pagey = 210;
487 		} else if (0 == strcasecmp(pp, "legal")) {
488 			pagex = 216;
489 			pagey = 356;
490 		} else if (2 != sscanf(pp, "%ux%u", &pagex, &pagey))
491 			fprintf(stderr, "%s: Unknown paper\n", pp);
492 	}
493 
494 	/*
495 	 * This MUST be defined before any PNT2AFM or AFM2PNT
496 	 * calculations occur.
497 	 */
498 
499 	p->ps->scale = 11;
500 
501 	/* Remember millimetres -> AFM units. */
502 
503 	pagex = PNT2AFM(p, ((double)pagex * 2.834));
504 	pagey = PNT2AFM(p, ((double)pagey * 2.834));
505 
506 	/* Margins are 1/9 the page x and y. */
507 
508 	marginx = (size_t)((double)pagex / 9.0);
509 	marginy = (size_t)((double)pagey / 9.0);
510 
511 	/* Line-height is 1.4em. */
512 
513 	lineheight = PNT2AFM(p, ((double)p->ps->scale * 1.4));
514 
515 	p->ps->width = p->ps->lastwidth = (size_t)pagex;
516 	p->ps->height = (size_t)pagey;
517 	p->ps->header = pagey - (marginy / 2) - (lineheight / 2);
518 	p->ps->top = pagey - marginy;
519 	p->ps->footer = (marginy / 2) - (lineheight / 2);
520 	p->ps->bottom = marginy;
521 	p->ps->left = marginx;
522 	p->ps->lineheight = lineheight;
523 
524 	p->defrmargin = pagex - (marginx * 2);
525 	return(p);
526 }
527 
528 static void
529 ps_setwidth(struct termp *p, int iop, size_t width)
530 {
531 	size_t	 lastwidth;
532 
533 	lastwidth = p->ps->width;
534 	if (0 < iop)
535 		p->ps->width += width;
536 	else if (0 > iop)
537 		p->ps->width -= width;
538 	else
539 		p->ps->width = width ? width : p->ps->lastwidth;
540 	p->ps->lastwidth = lastwidth;
541 }
542 
543 void
544 pspdf_free(void *arg)
545 {
546 	struct termp	*p;
547 
548 	p = (struct termp *)arg;
549 
550 	if (p->ps->psmarg)
551 		free(p->ps->psmarg);
552 	if (p->ps->pdfobjs)
553 		free(p->ps->pdfobjs);
554 
555 	free(p->ps);
556 	term_free(p);
557 }
558 
559 static void
560 ps_printf(struct termp *p, const char *fmt, ...)
561 {
562 	va_list		 ap;
563 	int		 pos, len;
564 
565 	va_start(ap, fmt);
566 
567 	/*
568 	 * If we're running in regular mode, then pipe directly into
569 	 * vprintf().  If we're processing margins, then push the data
570 	 * into our growable margin buffer.
571 	 */
572 
573 	if ( ! (PS_MARGINS & p->ps->flags)) {
574 		len = vprintf(fmt, ap);
575 		va_end(ap);
576 		p->ps->pdfbytes += len < 0 ? 0 : (size_t)len;
577 		return;
578 	}
579 
580 	/*
581 	 * XXX: I assume that the in-margin print won't exceed
582 	 * PS_BUFSLOP (128 bytes), which is reasonable but still an
583 	 * assumption that will cause pukeage if it's not the case.
584 	 */
585 
586 	ps_growbuf(p, PS_BUFSLOP);
587 
588 	pos = (int)p->ps->psmargcur;
589 	vsnprintf(&p->ps->psmarg[pos], PS_BUFSLOP, fmt, ap);
590 
591 	va_end(ap);
592 
593 	p->ps->psmargcur = strlen(p->ps->psmarg);
594 }
595 
596 static void
597 ps_putchar(struct termp *p, char c)
598 {
599 	int		 pos;
600 
601 	/* See ps_printf(). */
602 
603 	if ( ! (PS_MARGINS & p->ps->flags)) {
604 		putchar(c);
605 		p->ps->pdfbytes++;
606 		return;
607 	}
608 
609 	ps_growbuf(p, 2);
610 
611 	pos = (int)p->ps->psmargcur++;
612 	p->ps->psmarg[pos++] = c;
613 	p->ps->psmarg[pos] = '\0';
614 }
615 
616 static void
617 pdf_obj(struct termp *p, size_t obj)
618 {
619 
620 	assert(obj > 0);
621 
622 	if ((obj - 1) >= p->ps->pdfobjsz) {
623 		p->ps->pdfobjsz = obj + 128;
624 		p->ps->pdfobjs = mandoc_reallocarray(p->ps->pdfobjs,
625 		    p->ps->pdfobjsz, sizeof(size_t));
626 	}
627 
628 	p->ps->pdfobjs[(int)obj - 1] = p->ps->pdfbytes;
629 	ps_printf(p, "%zu 0 obj\n", obj);
630 }
631 
632 static void
633 ps_closepage(struct termp *p)
634 {
635 	int		 i;
636 	size_t		 len, base;
637 
638 	/*
639 	 * Close out a page that we've already flushed to output.  In
640 	 * PostScript, we simply note that the page must be showed.  In
641 	 * PDF, we must now create the Length, Resource, and Page node
642 	 * for the page contents.
643 	 */
644 
645 	assert(p->ps->psmarg && p->ps->psmarg[0]);
646 	ps_printf(p, "%s", p->ps->psmarg);
647 
648 	if (TERMTYPE_PS != p->type) {
649 		ps_printf(p, "ET\n");
650 
651 		len = p->ps->pdfbytes - p->ps->pdflastpg;
652 		base = p->ps->pages * 4 + p->ps->pdfbody;
653 
654 		ps_printf(p, "endstream\nendobj\n");
655 
656 		/* Length of content. */
657 		pdf_obj(p, base + 1);
658 		ps_printf(p, "%zu\nendobj\n", len);
659 
660 		/* Resource for content. */
661 		pdf_obj(p, base + 2);
662 		ps_printf(p, "<<\n/ProcSet [/PDF /Text]\n");
663 		ps_printf(p, "/Font <<\n");
664 		for (i = 0; i < (int)TERMFONT__MAX; i++)
665 			ps_printf(p, "/F%d %d 0 R\n", i, 3 + i);
666 		ps_printf(p, ">>\n>>\n");
667 
668 		/* Page node. */
669 		pdf_obj(p, base + 3);
670 		ps_printf(p, "<<\n");
671 		ps_printf(p, "/Type /Page\n");
672 		ps_printf(p, "/Parent 2 0 R\n");
673 		ps_printf(p, "/Resources %zu 0 R\n", base + 2);
674 		ps_printf(p, "/Contents %zu 0 R\n", base);
675 		ps_printf(p, ">>\nendobj\n");
676 	} else
677 		ps_printf(p, "showpage\n");
678 
679 	p->ps->pages++;
680 	p->ps->psrow = p->ps->top;
681 	assert( ! (PS_NEWPAGE & p->ps->flags));
682 	p->ps->flags |= PS_NEWPAGE;
683 }
684 
685 static void
686 ps_end(struct termp *p)
687 {
688 	size_t		 i, xref, base;
689 
690 	/*
691 	 * At the end of the file, do one last showpage.  This is the
692 	 * same behaviour as groff(1) and works for multiple pages as
693 	 * well as just one.
694 	 */
695 
696 	if ( ! (PS_NEWPAGE & p->ps->flags)) {
697 		assert(0 == p->ps->flags);
698 		assert('\0' == p->ps->last);
699 		ps_closepage(p);
700 	}
701 
702 	if (TERMTYPE_PS == p->type) {
703 		ps_printf(p, "%%%%Trailer\n");
704 		ps_printf(p, "%%%%Pages: %zu\n", p->ps->pages);
705 		ps_printf(p, "%%%%EOF\n");
706 		return;
707 	}
708 
709 	pdf_obj(p, 2);
710 	ps_printf(p, "<<\n/Type /Pages\n");
711 	ps_printf(p, "/MediaBox [0 0 %zu %zu]\n",
712 			(size_t)AFM2PNT(p, p->ps->width),
713 			(size_t)AFM2PNT(p, p->ps->height));
714 
715 	ps_printf(p, "/Count %zu\n", p->ps->pages);
716 	ps_printf(p, "/Kids [");
717 
718 	for (i = 0; i < p->ps->pages; i++)
719 		ps_printf(p, " %zu 0 R", i * 4 + p->ps->pdfbody + 3);
720 
721 	base = (p->ps->pages - 1) * 4 + p->ps->pdfbody + 4;
722 
723 	ps_printf(p, "]\n>>\nendobj\n");
724 	pdf_obj(p, base);
725 	ps_printf(p, "<<\n");
726 	ps_printf(p, "/Type /Catalog\n");
727 	ps_printf(p, "/Pages 2 0 R\n");
728 	ps_printf(p, ">>\n");
729 	xref = p->ps->pdfbytes;
730 	ps_printf(p, "xref\n");
731 	ps_printf(p, "0 %zu\n", base + 1);
732 	ps_printf(p, "0000000000 65535 f \n");
733 
734 	for (i = 0; i < base; i++)
735 		ps_printf(p, "%.10zu 00000 n \n",
736 		    p->ps->pdfobjs[(int)i]);
737 
738 	ps_printf(p, "trailer\n");
739 	ps_printf(p, "<<\n");
740 	ps_printf(p, "/Size %zu\n", base + 1);
741 	ps_printf(p, "/Root %zu 0 R\n", base);
742 	ps_printf(p, "/Info 1 0 R\n");
743 	ps_printf(p, ">>\n");
744 	ps_printf(p, "startxref\n");
745 	ps_printf(p, "%zu\n", xref);
746 	ps_printf(p, "%%%%EOF\n");
747 }
748 
749 static void
750 ps_begin(struct termp *p)
751 {
752 	time_t		 t;
753 	int		 i;
754 
755 	/*
756 	 * Print margins into margin buffer.  Nothing gets output to the
757 	 * screen yet, so we don't need to initialise the primary state.
758 	 */
759 
760 	if (p->ps->psmarg) {
761 		assert(p->ps->psmargsz);
762 		p->ps->psmarg[0] = '\0';
763 	}
764 
765 	/*p->ps->pdfbytes = 0;*/
766 	p->ps->psmargcur = 0;
767 	p->ps->flags = PS_MARGINS;
768 	p->ps->pscol = p->ps->left;
769 	p->ps->psrow = p->ps->header;
770 
771 	ps_setfont(p, TERMFONT_NONE);
772 
773 	(*p->headf)(p, p->argf);
774 	(*p->endline)(p);
775 
776 	p->ps->pscol = p->ps->left;
777 	p->ps->psrow = p->ps->footer;
778 
779 	(*p->footf)(p, p->argf);
780 	(*p->endline)(p);
781 
782 	p->ps->flags &= ~PS_MARGINS;
783 
784 	assert(0 == p->ps->flags);
785 	assert(p->ps->psmarg);
786 	assert('\0' != p->ps->psmarg[0]);
787 
788 	/*
789 	 * Print header and initialise page state.  Following this,
790 	 * stuff gets printed to the screen, so make sure we're sane.
791 	 */
792 
793 	t = time(NULL);
794 
795 	if (TERMTYPE_PS == p->type) {
796 		ps_printf(p, "%%!PS-Adobe-3.0\n");
797 		ps_printf(p, "%%%%CreationDate: %s", ctime(&t));
798 		ps_printf(p, "%%%%DocumentData: Clean7Bit\n");
799 		ps_printf(p, "%%%%Orientation: Portrait\n");
800 		ps_printf(p, "%%%%Pages: (atend)\n");
801 		ps_printf(p, "%%%%PageOrder: Ascend\n");
802 		ps_printf(p, "%%%%DocumentMedia: "
803 		    "Default %zu %zu 0 () ()\n",
804 		    (size_t)AFM2PNT(p, p->ps->width),
805 		    (size_t)AFM2PNT(p, p->ps->height));
806 		ps_printf(p, "%%%%DocumentNeededResources: font");
807 
808 		for (i = 0; i < (int)TERMFONT__MAX; i++)
809 			ps_printf(p, " %s", fonts[i].name);
810 
811 		ps_printf(p, "\n%%%%EndComments\n");
812 	} else {
813 		ps_printf(p, "%%PDF-1.1\n");
814 		pdf_obj(p, 1);
815 		ps_printf(p, "<<\n");
816 		ps_printf(p, ">>\n");
817 		ps_printf(p, "endobj\n");
818 
819 		for (i = 0; i < (int)TERMFONT__MAX; i++) {
820 			pdf_obj(p, (size_t)i + 3);
821 			ps_printf(p, "<<\n");
822 			ps_printf(p, "/Type /Font\n");
823 			ps_printf(p, "/Subtype /Type1\n");
824 			ps_printf(p, "/Name /F%d\n", i);
825 			ps_printf(p, "/BaseFont /%s\n", fonts[i].name);
826 			ps_printf(p, ">>\n");
827 		}
828 	}
829 
830 	p->ps->pdfbody = (size_t)TERMFONT__MAX + 3;
831 	p->ps->pscol = p->ps->left;
832 	p->ps->psrow = p->ps->top;
833 	p->ps->flags |= PS_NEWPAGE;
834 	ps_setfont(p, TERMFONT_NONE);
835 }
836 
837 static void
838 ps_pletter(struct termp *p, int c)
839 {
840 	int		 f;
841 
842 	/*
843 	 * If we haven't opened a page context, then output that we're
844 	 * in a new page and make sure the font is correctly set.
845 	 */
846 
847 	if (PS_NEWPAGE & p->ps->flags) {
848 		if (TERMTYPE_PS == p->type) {
849 			ps_printf(p, "%%%%Page: %zu %zu\n",
850 			    p->ps->pages + 1, p->ps->pages + 1);
851 			ps_printf(p, "/%s %zu selectfont\n",
852 			    fonts[(int)p->ps->lastf].name,
853 			    p->ps->scale);
854 		} else {
855 			pdf_obj(p, p->ps->pdfbody +
856 			    p->ps->pages * 4);
857 			ps_printf(p, "<<\n");
858 			ps_printf(p, "/Length %zu 0 R\n",
859 			    p->ps->pdfbody + 1 + p->ps->pages * 4);
860 			ps_printf(p, ">>\nstream\n");
861 		}
862 		p->ps->pdflastpg = p->ps->pdfbytes;
863 		p->ps->flags &= ~PS_NEWPAGE;
864 	}
865 
866 	/*
867 	 * If we're not in a PostScript "word" context, then open one
868 	 * now at the current cursor.
869 	 */
870 
871 	if ( ! (PS_INLINE & p->ps->flags)) {
872 		if (TERMTYPE_PS != p->type) {
873 			ps_printf(p, "BT\n/F%d %zu Tf\n",
874 			    (int)p->ps->lastf, p->ps->scale);
875 			ps_printf(p, "%.3f %.3f Td\n(",
876 			    AFM2PNT(p, p->ps->pscol),
877 			    AFM2PNT(p, p->ps->psrow));
878 		} else
879 			ps_printf(p, "%.3f %.3f moveto\n(",
880 			    AFM2PNT(p, p->ps->pscol),
881 			    AFM2PNT(p, p->ps->psrow));
882 		p->ps->flags |= PS_INLINE;
883 	}
884 
885 	assert( ! (PS_NEWPAGE & p->ps->flags));
886 
887 	/*
888 	 * We need to escape these characters as per the PostScript
889 	 * specification.  We would also escape non-graphable characters
890 	 * (like tabs), but none of them would get to this point and
891 	 * it's superfluous to abort() on them.
892 	 */
893 
894 	switch (c) {
895 	case '(':
896 		/* FALLTHROUGH */
897 	case ')':
898 		/* FALLTHROUGH */
899 	case '\\':
900 		ps_putchar(p, '\\');
901 		break;
902 	default:
903 		break;
904 	}
905 
906 	/* Write the character and adjust where we are on the page. */
907 
908 	f = (int)p->ps->lastf;
909 
910 	if (c <= 32 || (c - 32 >= MAXCHAR)) {
911 		ps_putchar(p, ' ');
912 		p->ps->pscol += (size_t)fonts[f].gly[0].wx;
913 		return;
914 	}
915 
916 	ps_putchar(p, (char)c);
917 	c -= 32;
918 	p->ps->pscol += (size_t)fonts[f].gly[c].wx;
919 }
920 
921 static void
922 ps_pclose(struct termp *p)
923 {
924 
925 	/*
926 	 * Spit out that we're exiting a word context (this is a
927 	 * "partial close" because we don't check the last-char buffer
928 	 * or anything).
929 	 */
930 
931 	if ( ! (PS_INLINE & p->ps->flags))
932 		return;
933 
934 	if (TERMTYPE_PS != p->type) {
935 		ps_printf(p, ") Tj\nET\n");
936 	} else
937 		ps_printf(p, ") show\n");
938 
939 	p->ps->flags &= ~PS_INLINE;
940 }
941 
942 static void
943 ps_fclose(struct termp *p)
944 {
945 
946 	/*
947 	 * Strong closure: if we have a last-char, spit it out after
948 	 * checking that we're in the right font mode.  This will of
949 	 * course open a new scope, if applicable.
950 	 *
951 	 * Following this, close out any scope that's open.
952 	 */
953 
954 	if ('\0' != p->ps->last) {
955 		if (p->ps->lastf != TERMFONT_NONE) {
956 			ps_pclose(p);
957 			ps_setfont(p, TERMFONT_NONE);
958 		}
959 		ps_pletter(p, p->ps->last);
960 		p->ps->last = '\0';
961 	}
962 
963 	if ( ! (PS_INLINE & p->ps->flags))
964 		return;
965 
966 	ps_pclose(p);
967 }
968 
969 static void
970 ps_letter(struct termp *p, int arg)
971 {
972 	char		cc, c;
973 
974 	c = arg >= 128 || arg <= 0 ? '?' : arg;
975 
976 	/*
977 	 * State machine dictates whether to buffer the last character
978 	 * or not.  Basically, encoded words are detected by checking if
979 	 * we're an "8" and switching on the buffer.  Then we put "8" in
980 	 * our buffer, and on the next charater, flush both character
981 	 * and buffer.  Thus, "regular" words are detected by having a
982 	 * regular character and a regular buffer character.
983 	 */
984 
985 	if ('\0' == p->ps->last) {
986 		assert(8 != c);
987 		p->ps->last = c;
988 		return;
989 	} else if (8 == p->ps->last) {
990 		assert(8 != c);
991 		p->ps->last = '\0';
992 	} else if (8 == c) {
993 		assert(8 != p->ps->last);
994 		if ('_' == p->ps->last) {
995 			if (p->ps->lastf != TERMFONT_UNDER) {
996 				ps_pclose(p);
997 				ps_setfont(p, TERMFONT_UNDER);
998 			}
999 		} else if (p->ps->lastf != TERMFONT_BOLD) {
1000 			ps_pclose(p);
1001 			ps_setfont(p, TERMFONT_BOLD);
1002 		}
1003 		p->ps->last = c;
1004 		return;
1005 	} else {
1006 		if (p->ps->lastf != TERMFONT_NONE) {
1007 			ps_pclose(p);
1008 			ps_setfont(p, TERMFONT_NONE);
1009 		}
1010 		cc = p->ps->last;
1011 		p->ps->last = c;
1012 		c = cc;
1013 	}
1014 
1015 	ps_pletter(p, c);
1016 }
1017 
1018 static void
1019 ps_advance(struct termp *p, size_t len)
1020 {
1021 
1022 	/*
1023 	 * Advance some spaces.  This can probably be made smarter,
1024 	 * i.e., to have multiple space-separated words in the same
1025 	 * scope, but this is easier:  just close out the current scope
1026 	 * and readjust our column settings.
1027 	 */
1028 
1029 	ps_fclose(p);
1030 	p->ps->pscol += len;
1031 }
1032 
1033 static void
1034 ps_endline(struct termp *p)
1035 {
1036 
1037 	/* Close out any scopes we have open: we're at eoln. */
1038 
1039 	ps_fclose(p);
1040 
1041 	/*
1042 	 * If we're in the margin, don't try to recalculate our current
1043 	 * row.  XXX: if the column tries to be fancy with multiple
1044 	 * lines, we'll do nasty stuff.
1045 	 */
1046 
1047 	if (PS_MARGINS & p->ps->flags)
1048 		return;
1049 
1050 	/* Left-justify. */
1051 
1052 	p->ps->pscol = p->ps->left;
1053 
1054 	/* If we haven't printed anything, return. */
1055 
1056 	if (PS_NEWPAGE & p->ps->flags)
1057 		return;
1058 
1059 	/*
1060 	 * Put us down a line.  If we're at the page bottom, spit out a
1061 	 * showpage and restart our row.
1062 	 */
1063 
1064 	if (p->ps->psrow >= p->ps->lineheight + p->ps->bottom) {
1065 		p->ps->psrow -= p->ps->lineheight;
1066 		return;
1067 	}
1068 
1069 	ps_closepage(p);
1070 }
1071 
1072 static void
1073 ps_setfont(struct termp *p, enum termfont f)
1074 {
1075 
1076 	assert(f < TERMFONT__MAX);
1077 	p->ps->lastf = f;
1078 
1079 	/*
1080 	 * If we're still at the top of the page, let the font-setting
1081 	 * be delayed until we actually have stuff to print.
1082 	 */
1083 
1084 	if (PS_NEWPAGE & p->ps->flags)
1085 		return;
1086 
1087 	if (TERMTYPE_PS == p->type)
1088 		ps_printf(p, "/%s %zu selectfont\n",
1089 		    fonts[(int)f].name, p->ps->scale);
1090 	else
1091 		ps_printf(p, "/F%d %zu Tf\n",
1092 		    (int)f, p->ps->scale);
1093 }
1094 
1095 static size_t
1096 ps_width(const struct termp *p, int c)
1097 {
1098 
1099 	if (c <= 32 || c - 32 >= MAXCHAR)
1100 		return((size_t)fonts[(int)TERMFONT_NONE].gly[0].wx);
1101 
1102 	c -= 32;
1103 	return((size_t)fonts[(int)TERMFONT_NONE].gly[c].wx);
1104 }
1105 
1106 static double
1107 ps_hspan(const struct termp *p, const struct roffsu *su)
1108 {
1109 	double		 r;
1110 
1111 	/*
1112 	 * All of these measurements are derived by converting from the
1113 	 * native measurement to AFM units.
1114 	 */
1115 
1116 	switch (su->unit) {
1117 	case SCALE_CM:
1118 		r = PNT2AFM(p, su->scale * 28.34);
1119 		break;
1120 	case SCALE_IN:
1121 		r = PNT2AFM(p, su->scale * 72);
1122 		break;
1123 	case SCALE_PC:
1124 		r = PNT2AFM(p, su->scale * 12);
1125 		break;
1126 	case SCALE_PT:
1127 		r = PNT2AFM(p, su->scale * 100);
1128 		break;
1129 	case SCALE_EM:
1130 		r = su->scale *
1131 		    fonts[(int)TERMFONT_NONE].gly[109 - 32].wx;
1132 		break;
1133 	case SCALE_MM:
1134 		r = PNT2AFM(p, su->scale * 2.834);
1135 		break;
1136 	case SCALE_EN:
1137 		r = su->scale *
1138 		    fonts[(int)TERMFONT_NONE].gly[110 - 32].wx;
1139 		break;
1140 	case SCALE_VS:
1141 		r = su->scale * p->ps->lineheight;
1142 		break;
1143 	default:
1144 		r = su->scale;
1145 		break;
1146 	}
1147 
1148 	return(r);
1149 }
1150 
1151 static void
1152 ps_growbuf(struct termp *p, size_t sz)
1153 {
1154 	if (p->ps->psmargcur + sz <= p->ps->psmargsz)
1155 		return;
1156 
1157 	if (sz < PS_BUFSLOP)
1158 		sz = PS_BUFSLOP;
1159 
1160 	p->ps->psmargsz += sz;
1161 	p->ps->psmarg = mandoc_realloc(p->ps->psmarg, p->ps->psmargsz);
1162 }
1163