Annotation of pod2mdoc/pod2mdoc.c, Revision 1.25
1.25 ! schwarze 1: /* $Id: pod2mdoc.c,v 1.24 2014/04/07 11:58:35 kristaps Exp $ */
1.1 schwarze 2: /*
3: * Copyright (c) 2014 Kristaps Dzonsons <kristaps@bsd.lv>
4: *
5: * Permission to use, copy, modify, and distribute this software for any
6: * purpose with or without fee is hereby granted, provided that the above
7: * copyright notice and this permission notice appear in all copies.
8: *
9: * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
10: * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11: * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
12: * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13: * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14: * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15: * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16: */
17: #include <sys/stat.h>
18: #include <sys/time.h>
19:
20: #include <assert.h>
21: #include <ctype.h>
22: #include <fcntl.h>
23: #include <getopt.h>
24: #include <stdio.h>
25: #include <stdlib.h>
26: #include <string.h>
27: #include <unistd.h>
28:
1.10 kristaps 29: /*
1.19 kristaps 30: * In what section can we find Perl module manuals?
31: * Sometimes (Mac OS X) it's 3pm, sometimes (OpenBSD, etc.) 3p.
32: * XXX IF YOU CHANGE THIS, CHANGE POD2MDOC.1 AS WELL.
1.10 kristaps 33: */
34: #define PERL_SECTION "3p"
35:
1.1 schwarze 36: struct args {
37: const char *title; /* override "Dt" title */
38: const char *date; /* override "Dd" date */
39: const char *section; /* override "Dt" section */
40: };
41:
1.4 schwarze 42: enum list {
43: LIST_BULLET = 0,
44: LIST_ENUM,
45: LIST_TAG,
46: LIST__MAX
47: };
48:
1.11 kristaps 49: enum sect {
50: SECT_NONE = 0,
51: SECT_NAME, /* NAME section */
52: SECT_SYNOPSIS, /* SYNOPSIS section */
53: };
54:
1.1 schwarze 55: struct state {
56: int parsing; /* after =cut of before command */
57: int paused; /* in =begin and before =end */
58: int haspar; /* in paragraph: do we need Pp? */
1.11 kristaps 59: enum sect sect; /* which section are we in? */
1.1 schwarze 60: const char *fname; /* file being parsed */
1.4 schwarze 61: #define LIST_STACKSZ 128
62: enum list lstack[LIST_STACKSZ]; /* open lists */
63: size_t lpos; /* where in list stack */
1.1 schwarze 64: };
65:
66: enum fmt {
67: FMT_ITALIC,
68: FMT_BOLD,
69: FMT_CODE,
70: FMT_LINK,
71: FMT_ESCAPE,
72: FMT_FILE,
73: FMT_NBSP,
74: FMT_INDEX,
75: FMT_NULL,
76: FMT__MAX
77: };
78:
79: enum cmd {
80: CMD_POD = 0,
81: CMD_HEAD1,
82: CMD_HEAD2,
83: CMD_HEAD3,
84: CMD_HEAD4,
85: CMD_OVER,
86: CMD_ITEM,
87: CMD_BACK,
88: CMD_BEGIN,
89: CMD_END,
90: CMD_FOR,
91: CMD_ENCODING,
92: CMD_CUT,
93: CMD__MAX
94: };
95:
96: static const char *const cmds[CMD__MAX] = {
97: "pod", /* CMD_POD */
98: "head1", /* CMD_HEAD1 */
99: "head2", /* CMD_HEAD2 */
100: "head3", /* CMD_HEAD3 */
101: "head4", /* CMD_HEAD4 */
102: "over", /* CMD_OVER */
103: "item", /* CMD_ITEM */
104: "back", /* CMD_BACK */
105: "begin", /* CMD_BEGIN */
106: "end", /* CMD_END */
107: "for", /* CMD_FOR */
108: "encoding", /* CMD_ENCODING */
109: "cut" /* CMD_CUT */
110: };
111:
112: static const char fmts[FMT__MAX] = {
113: 'I', /* FMT_ITALIC */
114: 'B', /* FMT_BOLD */
115: 'C', /* FMT_CODE */
116: 'L', /* FMT_LINK */
117: 'E', /* FMT_ESCAPE */
118: 'F', /* FMT_FILE */
119: 'S', /* FMT_NBSP */
120: 'X', /* FMT_INDEX */
121: 'Z' /* FMT_NULL */
122: };
123:
1.6 kristaps 124: static int last;
125:
1.1 schwarze 126: /*
127: * Given buf[*start] is at the start of an escape name, read til the end
128: * of the escape ('>') then try to do something with it.
129: * Sets start to be one after the '>'.
130: */
131: static void
132: formatescape(const char *buf, size_t *start, size_t end)
133: {
134: char esc[16]; /* no more needed */
135: size_t i, max;
136:
137: max = sizeof(esc) - 1;
138: i = 0;
139: /* Read til our buffer is full. */
140: while (*start < end && '>' != buf[*start] && i < max)
141: esc[i++] = buf[(*start)++];
142: esc[i] = '\0';
143:
144: if (i == max) {
145: /* Too long... skip til we end. */
146: while (*start < end && '>' != buf[*start])
147: (*start)++;
148: return;
149: } else if (*start >= end)
150: return;
151:
152: assert('>' == buf[*start]);
153: (*start)++;
154:
155: /*
156: * TODO: right now, we only recognise the named escapes.
157: * Just let the rest of them go.
158: */
1.6 kristaps 159: if (0 == strcmp(esc, "lt"))
1.1 schwarze 160: printf("\\(la");
161: else if (0 == strcmp(esc, "gt"))
162: printf("\\(ra");
163: else if (0 == strcmp(esc, "vb"))
164: printf("\\(ba");
165: else if (0 == strcmp(esc, "sol"))
166: printf("\\(sl");
1.6 kristaps 167: else
168: return;
169:
170: last = 'a';
1.1 schwarze 171: }
172:
173: /*
1.9 kristaps 174: * Run some heuristics to intuit a link format.
1.19 kristaps 175: * I set "start" to be the end of the sequence (last right-carrot) so
1.9 kristaps 176: * that the caller can safely just continue processing.
1.19 kristaps 177: * If this is just an empty tag, I'll return 0.
1.9 kristaps 178: */
179: static int
180: trylink(const char *buf, size_t *start, size_t end, size_t dsz)
181: {
1.21 kristaps 182: size_t linkstart, realend, linkend,
183: i, j, textsz, stack;
1.18 kristaps 184: const char *text;
1.9 kristaps 185:
186: /*
187: * Scan to the start of the terminus.
188: * This function is more or less replicated in the formatcode()
189: * for null or index formatting codes.
1.23 kristaps 190: * However, we're slightly different because we might have
191: * nested escapes we need to ignore.
1.9 kristaps 192: */
1.21 kristaps 193: stack = 0;
1.19 kristaps 194: for (linkstart = realend = *start; realend < end; realend++) {
1.23 kristaps 195: if ('<' == buf[realend])
196: stack++;
1.19 kristaps 197: if ('>' != buf[realend])
1.9 kristaps 198: continue;
1.23 kristaps 199: else if (stack-- > 0)
200: continue;
201: if (dsz == 1)
1.9 kristaps 202: break;
1.19 kristaps 203: assert(realend > 0);
204: if (' ' != buf[realend - 1])
1.9 kristaps 205: continue;
1.19 kristaps 206: for (i = realend, j = 0; i < end && j < dsz; j++)
1.9 kristaps 207: if ('>' != buf[i++])
208: break;
209: if (dsz == j)
210: break;
211: }
1.19 kristaps 212:
213: /* Ignore stubs. */
214: if (realend == end || realend == *start)
1.9 kristaps 215: return(0);
216:
1.19 kristaps 217: /* Set linkend to the end of content. */
218: linkend = dsz > 1 ? realend - 1 : realend;
1.18 kristaps 219:
1.19 kristaps 220: /* Re-scan to see if we have a title or section. */
1.18 kristaps 221: text = &buf[*start];
1.19 kristaps 222: for (textsz = *start; textsz < linkend; textsz++)
223: if ('|' == buf[textsz] || '/' == buf[textsz])
1.18 kristaps 224: break;
225:
1.19 kristaps 226: if (textsz < linkend && '|' == buf[textsz]) {
1.20 kristaps 227: /* With title: set start, then end at section. */
1.19 kristaps 228: linkstart = textsz + 1;
1.18 kristaps 229: textsz = textsz - *start;
1.19 kristaps 230: for (i = linkstart; i < linkend; i++)
231: if ('/' == buf[i])
232: break;
233: if (i < linkend)
234: linkend = i;
1.20 kristaps 235: } else if (textsz < linkend && '/' == buf[textsz]) {
236: /* With section: set end at section. */
237: linkend = textsz;
238: textsz = 0;
239: } else
240: /* No title, no section. */
1.18 kristaps 241: textsz = 0;
1.19 kristaps 242:
243: *start = realend;
244: j = linkend - linkstart;
245:
1.20 kristaps 246: /* Do we have only subsection material? */
247: if (0 == j && '/' == buf[linkend]) {
248: linkstart = linkend + 1;
249: linkend = dsz > 1 ? realend - 1 : realend;
250: if (0 == (j = linkend - linkstart))
251: return(0);
252: printf("Sx %.*s", (int)j, &buf[linkstart]);
253: return(1);
254: } else if (0 == j)
1.19 kristaps 255: return(0);
256:
257: /* See if we qualify as being a link or not. */
1.20 kristaps 258: if ((j > 4 && 0 == memcmp("http:", &buf[linkstart], j)) ||
259: (j > 5 && 0 == memcmp("https:", &buf[linkstart], j)) ||
260: (j > 3 && 0 == memcmp("ftp:", &buf[linkstart], j)) ||
261: (j > 4 && 0 == memcmp("sftp:", &buf[linkstart], j)) ||
262: (j > 3 && 0 == memcmp("smb:", &buf[linkstart], j)) ||
263: (j > 3 && 0 == memcmp("afs:", &buf[linkstart], j))) {
264: /* Gross. */
265: printf("Lk %.*s", (int)((dsz > 1 ? realend - 1 :
266: realend) - linkstart), &buf[linkstart]);
1.19 kristaps 267: return(1);
268: }
269:
270: /* See if we qualify as a mailto. */
1.20 kristaps 271: if (j > 6 && 0 == memcmp("mailto:", &buf[linkstart], j)) {
1.19 kristaps 272: printf("Mt %.*s", (int)j, &buf[linkstart]);
273: return(1);
274: }
275:
276: /* See if we're a foo(5), foo(5x), or foo(5xx) manpage. */
277: if ((j > 3 && ')' == buf[linkend - 1]) &&
278: ('(' == buf[linkend - 3])) {
279: printf("Xr %.*s %c", (int)(j - 3),
280: &buf[linkstart], buf[linkend - 2]);
281: return(1);
282: } else if ((j > 4 && ')' == buf[linkend - 1]) &&
283: ('(' == buf[linkend - 4])) {
284: printf("Xr %.*s %.*s", (int)(j - 4),
285: &buf[linkstart], 2, &buf[linkend - 3]);
286: return(1);
287: } else if ((j > 5 && ')' == buf[linkend - 1]) &&
288: ('(' == buf[linkend - 5])) {
289: printf("Xr %.*s %.*s", (int)(j - 5),
290: &buf[linkstart], 3, &buf[linkend - 4]);
291: return(1);
292: }
293:
294: /* Last try: do we have a double-colon? */
295: for (i = linkstart + 1; i < linkend; i++)
296: if (':' == buf[i] && ':' == buf[i - 1])
1.18 kristaps 297: break;
1.9 kristaps 298:
1.19 kristaps 299: if (i < linkend)
1.10 kristaps 300: printf("Xr %.*s " PERL_SECTION,
1.19 kristaps 301: (int)j, &buf[linkstart]);
1.9 kristaps 302: else
1.19 kristaps 303: printf("Xr %.*s 1", (int)j, &buf[linkstart]);
1.9 kristaps 304:
305: return(1);
306: }
307:
1.13 kristaps 308: /*
309: * Doclifting: if we're a bold "-xx" and we're in the SYNOPSIS section,
310: * then it's likely that we're a flag.
311: * Our flag might be followed by an argument, so make sure that we're
312: * accounting for that, too.
313: * If we don't have a flag at all, however, then assume we're an "Ar".
314: */
315: static void
316: dosynopsisfl(const char *buf, size_t *start, size_t end)
317: {
318: size_t i;
319: again:
1.14 kristaps 320: assert(*start + 1 < end);
321: assert('-' == buf[*start]);
322:
323: if ( ! isalnum((int)buf[*start + 1]) &&
324: '?' != buf[*start + 1] &&
325: '-' != buf[*start + 1]) {
326: (*start)--;
327: fputs("Ar ", stdout);
328: return;
329: }
330:
1.13 kristaps 331: (*start)++;
332: for (i = *start; i < end; i++)
333: if (isalnum((int)buf[i]))
334: continue;
1.14 kristaps 335: else if ('?' == buf[i])
336: continue;
1.13 kristaps 337: else if ('-' == buf[i])
338: continue;
339: else if ('_' == buf[i])
340: continue;
341: else
342: break;
343:
344: assert(i < end);
345:
346: if ( ! (' ' == buf[i] || '>' == buf[i])) {
347: printf("Ar ");
348: return;
349: }
350:
351: printf("Fl ");
352: if (end - *start > 1 &&
353: isupper((int)buf[*start]) &&
354: islower((int)buf[*start + 1]) &&
355: (end - *start == 2 ||
356: ' ' == buf[*start + 2]))
357: printf("\\&");
358: printf("%.*s ", (int)(i - *start), &buf[*start]);
359: *start = i;
360:
361: if (' ' == buf[i]) {
362: while (i < end && ' ' == buf[i])
363: i++;
364: assert(i < end);
365: if ('-' == buf[i]) {
366: *start = i;
367: goto again;
368: }
369: printf("Ar ");
370: *start = i;
371: }
372: }
373:
1.9 kristaps 374: /*
1.1 schwarze 375: * We're at the character in front of a format code, which is structured
376: * like X<...> and can contain nested format codes.
377: * This consumes the whole format code, and any nested format codes, til
378: * the end of matched production.
379: * If "reentrant", then we're being called after a macro has already
380: * been printed to the current line.
1.6 kristaps 381: * If "nomacro", then we don't print any macros, just contained data
382: * (e.g., following "Sh" or "Nm").
1.15 kristaps 383: * "pos" is only significant in SYNOPSIS, and should be 0 when invoked
384: * as the first format code on a line (for decoration as an "Nm"),
385: * non-zero otherwise.
1.6 kristaps 386: * Return whether we've printed a macro or not--in other words, whether
387: * this should trigger a subsequent newline (this should be ignored when
388: * reentrant).
1.1 schwarze 389: */
390: static int
1.15 kristaps 391: formatcode(struct state *st, const char *buf, size_t *start,
392: size_t end, int reentrant, int nomacro, int pos)
1.1 schwarze 393: {
394: enum fmt fmt;
1.5 kristaps 395: size_t i, j, dsz;
1.1 schwarze 396:
397: assert(*start + 1 < end);
398: assert('<' == buf[*start + 1]);
399:
1.6 kristaps 400: /*
401: * First, look up the format code.
402: * If it's not valid, then exit immediately.
403: */
404: for (fmt = 0; fmt < FMT__MAX; fmt++)
405: if (buf[*start] == fmts[fmt])
406: break;
407:
408: if (FMT__MAX == fmt) {
409: putchar(last = buf[(*start)++]);
1.8 kristaps 410: if ('\\' == last)
411: putchar('e');
1.6 kristaps 412: return(0);
413: }
414:
1.5 kristaps 415: /*
416: * Determine whether we're overriding our delimiter.
417: * According to POD, if we have more than one '<' followed by a
418: * space, then we need a space followed by matching '>' to close
419: * the expression.
420: * Otherwise we use the usual '<' and '>' matched pair.
421: */
422: i = *start + 1;
423: while (i < end && '<' == buf[i])
424: i++;
425: assert(i > *start + 1);
426: dsz = i - (*start + 1);
427: if (dsz > 1 && (i >= end || ' ' != buf[i]))
428: dsz = 1;
429:
430: /* Remember, if dsz>1, to jump the trailing space. */
431: *start += dsz + 1 + (dsz > 1 ? 1 : 0);
1.1 schwarze 432:
433: /*
1.6 kristaps 434: * Escapes and ignored codes (NULL and INDEX) don't print macro
435: * sequences, so just output them like normal text before
436: * processing for real macros.
1.1 schwarze 437: */
438: if (FMT_ESCAPE == fmt) {
439: formatescape(buf, start, end);
440: return(0);
441: } else if (FMT_NULL == fmt || FMT_INDEX == fmt) {
1.5 kristaps 442: /*
1.6 kristaps 443: * Just consume til the end delimiter, accounting for
444: * whether it's a custom one.
1.5 kristaps 445: */
446: for ( ; *start < end; (*start)++) {
447: if ('>' != buf[*start])
448: continue;
449: else if (dsz == 1)
450: break;
451: assert(*start > 0);
452: if (' ' != buf[*start - 1])
453: continue;
454: i = *start;
455: for (j = 0; i < end && j < dsz; j++)
456: if ('>' != buf[i++])
457: break;
458: if (dsz != j)
459: continue;
460: (*start) += dsz;
461: break;
462: }
1.24 kristaps 463: if (*start < end) {
464: assert('>' == buf[*start]);
465: (*start)++;
466: }
467: if (isspace(last))
468: while (*start < end && isspace((int)buf[*start]))
469: (*start)++;
1.1 schwarze 470: return(0);
471: }
472:
1.6 kristaps 473: /*
474: * Check whether we're supposed to print macro stuff (this is
475: * suppressed in, e.g., "Nm" and "Sh" macros).
476: */
1.1 schwarze 477: if ( ! nomacro) {
478: /*
479: * Print out the macro describing this format code.
480: * If we're not "reentrant" (not yet on a macro line)
481: * then print a newline, if necessary, and the macro
482: * indicator.
483: * Otherwise, offset us with a space.
484: */
1.6 kristaps 485: if ( ! reentrant) {
486: if (last != '\n')
487: putchar('\n');
1.1 schwarze 488: putchar('.');
1.6 kristaps 489: } else
1.1 schwarze 490: putchar(' ');
491:
492: /*
1.6 kristaps 493: * If we don't have whitespace before us (and none after
494: * the opening delimiter), then suppress macro
495: * whitespace with Pf.
1.1 schwarze 496: */
1.6 kristaps 497: if (' ' != last && '\n' != last && ' ' != buf[*start])
498: printf("Pf ");
499:
1.1 schwarze 500: switch (fmt) {
501: case (FMT_ITALIC):
502: printf("Em ");
503: break;
504: case (FMT_BOLD):
1.14 kristaps 505: if (SECT_SYNOPSIS == st->sect) {
506: if (1 == dsz && '-' == buf[*start])
507: dosynopsisfl(buf, start, end);
1.15 kristaps 508: else if (0 == pos)
509: printf("Nm ");
1.14 kristaps 510: else
511: printf("Ar ");
512: break;
513: }
514: printf("Sy ");
1.1 schwarze 515: break;
516: case (FMT_CODE):
1.2 schwarze 517: printf("Qo Li ");
1.1 schwarze 518: break;
519: case (FMT_LINK):
1.19 kristaps 520: /* Try to link; use "No" if it's empty. */
1.9 kristaps 521: if ( ! trylink(buf, start, end, dsz))
522: printf("No ");
1.1 schwarze 523: break;
524: case (FMT_FILE):
525: printf("Pa ");
526: break;
527: case (FMT_NBSP):
528: printf("No ");
529: break;
530: default:
531: abort();
532: }
533: }
534:
535: /*
1.6 kristaps 536: * Process until we reach the end marker (e.g., '>') or until we
1.5 kristaps 537: * find a nested format code.
1.1 schwarze 538: * Don't emit any newlines: since we're on a macro line, we
539: * don't want to break the line.
540: */
541: while (*start < end) {
1.5 kristaps 542: if ('>' == buf[*start] && 1 == dsz) {
1.1 schwarze 543: (*start)++;
544: break;
1.5 kristaps 545: } else if ('>' == buf[*start] &&
546: ' ' == buf[*start - 1]) {
547: /*
548: * Handle custom delimiters.
549: * These require a certain number of
550: * space-preceded carrots before we're really at
551: * the end.
552: */
553: i = *start;
554: for (j = 0; i < end && j < dsz; j++)
555: if ('>' != buf[i++])
556: break;
557: if (dsz == j) {
558: *start += dsz;
559: break;
560: }
1.1 schwarze 561: }
562: if (*start + 1 < end && '<' == buf[*start + 1]) {
1.15 kristaps 563: formatcode(st, buf, start, end, 1, nomacro, 1);
1.1 schwarze 564: continue;
565: }
1.3 schwarze 566:
1.4 schwarze 567: /*
568: * Make sure that any macro-like words (or
569: * really any word starting with a capital
570: * letter) is assumed to be a macro that must be
571: * escaped.
572: * This matches "Xx " and "XxEOLN".
573: */
574: if ((' ' == last || '\n' == last) &&
575: end - *start > 1 &&
576: isupper((int)buf[*start]) &&
577: islower((int)buf[*start + 1]) &&
578: (end - *start == 2 ||
579: ' ' == buf[*start + 2]))
580: printf("\\&");
1.3 schwarze 581:
1.4 schwarze 582: /* Suppress newline. */
1.6 kristaps 583: if ('\n' == buf[*start])
584: putchar(last = ' ');
585: else
586: putchar(last = buf[*start]);
1.4 schwarze 587:
1.8 kristaps 588: /* Protect against character escapes. */
589: if ('\\' == last)
590: putchar('e');
591:
1.6 kristaps 592: (*start)++;
593:
594: if (' ' == last)
595: while (*start < end && ' ' == buf[*start])
596: (*start)++;
1.1 schwarze 597: }
1.2 schwarze 598:
599: if ( ! nomacro && FMT_CODE == fmt)
600: printf(" Qc ");
1.1 schwarze 601:
602: /*
1.6 kristaps 603: * We're now subsequent the format code.
604: * If there isn't a space (or newline) here, and we haven't just
605: * printed a space, then suppress space.
1.1 schwarze 606: */
1.6 kristaps 607: if ( ! nomacro && ' ' != last)
608: if (' ' != buf[*start] && '\n' != buf[*start])
609: printf(" Ns ");
1.5 kristaps 610:
1.1 schwarze 611: return(1);
612: }
613:
614: /*
615: * Calls formatcode() til the end of a paragraph.
616: */
617: static void
1.11 kristaps 618: formatcodeln(struct state *st, const char *buf,
619: size_t *start, size_t end, int nomacro)
1.1 schwarze 620: {
621:
1.4 schwarze 622: last = ' ';
1.1 schwarze 623: while (*start < end) {
624: if (*start + 1 < end && '<' == buf[*start + 1]) {
1.15 kristaps 625: formatcode(st, buf, start, end, 1, nomacro, 1);
1.1 schwarze 626: continue;
627: }
1.4 schwarze 628: /*
629: * Since we're already on a macro line, we want to make
630: * sure that we don't inadvertently invoke a macro.
631: * We need to do this carefully because section names
632: * are used in troff and we don't want to escape
633: * something that needn't be escaped.
634: */
635: if (' ' == last && end - *start > 1 &&
636: isupper((int)buf[*start]) &&
637: islower((int)buf[*start + 1]) &&
638: (end - *start == 2 ||
639: ' ' == buf[*start + 2]))
640: printf("\\&");
641:
1.8 kristaps 642: if ('\n' == buf[*start])
643: putchar(last = ' ');
644: else
1.1 schwarze 645: putchar(last = buf[*start]);
1.8 kristaps 646:
647: /* Protect against character escapes. */
648: if ('\\' == last)
649: putchar('e');
650:
1.1 schwarze 651: (*start)++;
652: }
653: }
654:
655: /*
1.4 schwarze 656: * Guess at what kind of list we are.
657: * These are taken straight from the POD manual.
658: * I don't know what people do in real life.
659: */
660: static enum list
661: listguess(const char *buf, size_t start, size_t end)
662: {
663: size_t len = end - start;
664:
665: assert(end >= start);
666:
667: if (len == 1 && '*' == buf[start])
668: return(LIST_BULLET);
669: if (len == 2 && '1' == buf[start] && '.' == buf[start + 1])
670: return(LIST_ENUM);
671: else if (len == 1 && '1' == buf[start])
672: return(LIST_ENUM);
673: else
674: return(LIST_TAG);
675: }
676:
677: /*
1.1 schwarze 678: * A command paragraph, as noted in the perlpod manual, just indicates
679: * that we should do something, optionally with some text to print as
680: * well.
681: */
682: static void
683: command(struct state *st, const char *buf, size_t start, size_t end)
684: {
685: size_t len, csz;
686: enum cmd cmd;
687:
688: assert('=' == buf[start]);
689: start++;
690: len = end - start;
691:
692: for (cmd = 0; cmd < CMD__MAX; cmd++) {
693: csz = strlen(cmds[cmd]);
694: if (len < csz)
695: continue;
696: if (0 == memcmp(&buf[start], cmd[cmds], csz))
697: break;
698: }
699:
700: /* Ignore bogus commands. */
701:
702: if (CMD__MAX == cmd)
703: return;
704:
705: start += csz;
1.8 kristaps 706: while (start < end && ' ' == buf[start])
707: start++;
708:
1.1 schwarze 709: len = end - start;
710:
711: if (st->paused) {
712: st->paused = CMD_END != cmd;
713: return;
714: }
715:
716: switch (cmd) {
717: case (CMD_POD):
718: break;
719: case (CMD_HEAD1):
720: /*
721: * The behaviour of head= follows from a quick glance at
722: * how pod2man handles it.
723: */
724: printf(".Sh ");
1.11 kristaps 725: st->sect = SECT_NONE;
726: if (end - start == 4) {
1.1 schwarze 727: if (0 == memcmp(&buf[start], "NAME", 4))
1.11 kristaps 728: st->sect = SECT_NAME;
729: } else if (end - start == 8) {
730: if (0 == memcmp(&buf[start], "SYNOPSIS", 8))
731: st->sect = SECT_SYNOPSIS;
732: }
733: formatcodeln(st, buf, &start, end, 1);
1.1 schwarze 734: putchar('\n');
735: st->haspar = 1;
736: break;
737: case (CMD_HEAD2):
738: printf(".Ss ");
1.11 kristaps 739: formatcodeln(st, buf, &start, end, 1);
1.1 schwarze 740: putchar('\n');
741: st->haspar = 1;
742: break;
743: case (CMD_HEAD3):
744: puts(".Pp");
745: printf(".Em ");
1.11 kristaps 746: formatcodeln(st, buf, &start, end, 0);
1.1 schwarze 747: putchar('\n');
748: puts(".Pp");
749: st->haspar = 1;
750: break;
751: case (CMD_HEAD4):
752: puts(".Pp");
753: printf(".No ");
1.11 kristaps 754: formatcodeln(st, buf, &start, end, 0);
1.1 schwarze 755: putchar('\n');
756: puts(".Pp");
757: st->haspar = 1;
758: break;
759: case (CMD_OVER):
1.4 schwarze 760: /*
761: * If we have an existing list that hasn't had an =item
762: * yet, then make sure that we open it now.
763: * We use the default list type, but that can't be
764: * helped (we haven't seen any items yet).
1.1 schwarze 765: */
1.4 schwarze 766: if (st->lpos > 0)
767: if (LIST__MAX == st->lstack[st->lpos - 1]) {
768: st->lstack[st->lpos - 1] = LIST_TAG;
769: puts(".Bl -tag -width Ds");
770: }
771: st->lpos++;
772: assert(st->lpos < LIST_STACKSZ);
773: st->lstack[st->lpos - 1] = LIST__MAX;
1.1 schwarze 774: break;
775: case (CMD_ITEM):
1.6 kristaps 776: if (0 == st->lpos) {
777: /*
778: * Bad markup.
779: * Try to compensate.
780: */
781: st->lstack[st->lpos] = LIST__MAX;
782: st->lpos++;
783: }
1.4 schwarze 784: assert(st->lpos > 0);
785: /*
786: * If we're the first =item, guess at what our content
787: * will be: "*" is a bullet list, "1." is a numbered
788: * list, and everything is tagged.
789: */
790: if (LIST__MAX == st->lstack[st->lpos - 1]) {
791: st->lstack[st->lpos - 1] =
792: listguess(buf, start, end);
793: switch (st->lstack[st->lpos - 1]) {
794: case (LIST_BULLET):
795: puts(".Bl -bullet");
796: break;
797: case (LIST_ENUM):
798: puts(".Bl -enum");
799: break;
800: default:
801: puts(".Bl -tag -width Ds");
802: break;
803: }
804: }
805: switch (st->lstack[st->lpos - 1]) {
806: case (LIST_TAG):
807: printf(".It ");
1.11 kristaps 808: formatcodeln(st, buf, &start, end, 0);
1.4 schwarze 809: putchar('\n');
810: break;
811: case (LIST_ENUM):
812: /* FALLTHROUGH */
813: case (LIST_BULLET):
814: /*
815: * Abandon the remainder of the paragraph
816: * because we're going to be a bulletted or
817: * numbered list.
818: */
819: puts(".It");
820: break;
821: default:
822: abort();
823: }
1.1 schwarze 824: st->haspar = 1;
825: break;
826: case (CMD_BACK):
1.4 schwarze 827: /* Make sure we don't back over the stack. */
828: if (st->lpos > 0) {
829: st->lpos--;
830: puts(".El");
831: }
1.1 schwarze 832: break;
833: case (CMD_BEGIN):
834: /*
835: * We disregard all types for now.
836: * TODO: process at least "text" in a -literal block.
837: */
838: st->paused = 1;
839: break;
840: case (CMD_FOR):
841: /*
842: * We ignore all types of encodings and formats
843: * unilaterally.
844: */
845: break;
846: case (CMD_ENCODING):
847: break;
848: case (CMD_CUT):
849: st->parsing = 0;
850: return;
851: default:
852: abort();
853: }
854:
855: /* Any command (but =cut) makes us start parsing. */
856: st->parsing = 1;
857: }
858:
859: /*
860: * Just pump out the line in a verbatim block.
861: */
862: static void
863: verbatim(struct state *st, const char *buf, size_t start, size_t end)
864: {
1.8 kristaps 865: int last;
1.22 kristaps 866: size_t i;
1.1 schwarze 867:
868: if ( ! st->parsing || st->paused)
869: return;
1.22 kristaps 870: again:
871: /*
872: * If we're in the SYNOPSIS, see if we're an #include block.
873: * If we are, then print the "In" macro and re-loop.
874: * This handles any number of inclusions, but only when they
875: * come before the remaining parts...
876: */
877: if (SECT_SYNOPSIS == st->sect) {
878: i = start;
879: for (i = start; i < end && ' ' == buf[i]; i++)
880: /* Spin. */ ;
881: if (i == end)
882: return;
883: /* We're an include block! */
884: if (end - i > 10 &&
885: 0 == memcmp(&buf[i], "#include <", 10)) {
886: start = i + 10;
887: while (start < end && ' ' == buf[start])
888: start++;
889: fputs(".In ", stdout);
890: /* Stop til the '>' marker or we hit eoln. */
891: while (start < end &&
892: '>' != buf[start] && '\n' != buf[start])
893: putchar(buf[start++]);
894: putchar('\n');
895: if (start < end && '>' == buf[start])
896: start++;
897: if (start < end && '\n' == buf[start])
898: start++;
899: if (start < end)
900: goto again;
901: return;
902: }
903: }
904:
905: if (start == end)
906: return;
1.1 schwarze 907: puts(".Bd -literal");
1.8 kristaps 908: for (last = ' '; start < end; start++) {
909: /*
910: * Handle accidental macros (newline starting with
911: * control character) and escapes.
912: */
913: if ('\n' == last)
1.7 kristaps 914: if ('.' == buf[start] || '\'' == buf[start])
915: printf("\\&");
1.8 kristaps 916: putchar(last = buf[start]);
917: if ('\\' == buf[start])
918: printf("e");
1.7 kristaps 919: }
920: putchar('\n');
1.1 schwarze 921: puts(".Ed");
922: }
923:
924: /*
1.13 kristaps 925: * See dosynopsisop().
926: */
927: static int
928: hasmatch(const char *buf, size_t start, size_t end)
929: {
930: size_t stack;
931:
932: for (stack = 0; start < end; start++)
933: if (buf[start] == '[')
934: stack++;
935: else if (buf[start] == ']' && 0 == stack)
936: return(1);
937: else if (buf[start] == ']')
938: stack--;
939: return(0);
940: }
941:
942: /*
943: * If we're in the SYNOPSIS section and we've encounter braces in an
944: * ordinary paragraph, then try to see whether we're an [-option].
945: * Do this, if we're an opening bracket, by first seeing if we have a
946: * matching end via hasmatch().
947: * If we're an ending bracket, see if we have a stack already.
948: */
949: static int
950: dosynopsisop(const char *buf, int *last,
951: size_t *start, size_t end, size_t *opstack)
952: {
953:
954: assert('[' == buf[*start] || ']' == buf[*start]);
955:
956: if ('[' == buf[*start] && hasmatch(buf, *start + 1, end)) {
957: if ('\n' != *last)
958: putchar('\n');
959: puts(".Oo");
960: (*opstack)++;
961: } else if ('[' == buf[*start])
962: return(0);
963:
964: if (']' == buf[*start] && *opstack > 0) {
965: if ('\n' != *last)
966: putchar('\n');
967: puts(".Oc");
968: (*opstack)--;
969: } else if (']' == buf[*start])
970: return(0);
971:
972: (*start)++;
973: *last = '\n';
974: while (' ' == buf[*start])
975: (*start)++;
976: return(1);
977: }
978:
979: /*
1.17 kristaps 980: * Format multiple "Nm" manpage names in the NAME section.
981: */
982: static void
983: donamenm(struct state *st, const char *buf, size_t *start, size_t end)
984: {
985: size_t word;
986:
987: while (*start < end && ' ' == buf[*start])
988: (*start)++;
989:
990: if (end == *start) {
991: puts(".Nm unknown");
992: return;
993: }
994:
995: while (*start < end) {
996: fputs(".Nm ", stdout);
997: for (word = *start; word < end; word++)
998: if (',' == buf[word])
999: break;
1000: formatcodeln(st, buf, start, word, 1);
1001: if (*start == end) {
1002: putchar('\n');
1003: continue;
1004: }
1005: assert(',' == buf[*start]);
1006: puts(" ,");
1007: (*start)++;
1008: while (*start < end && ' ' == buf[*start])
1009: (*start)++;
1010: }
1011: }
1012:
1013: /*
1.1 schwarze 1014: * Ordinary paragraph.
1015: * Well, this is really the hardest--POD seems to assume that, for
1016: * example, a leading space implies a newline, and so on.
1017: * Lots of other snakes in the grass: escaping a newline followed by a
1018: * period (accidental mdoc(7) control), double-newlines after macro
1019: * passages, etc.
1020: */
1021: static void
1022: ordinary(struct state *st, const char *buf, size_t start, size_t end)
1023: {
1.13 kristaps 1024: size_t i, j, opstack;
1.15 kristaps 1025: int seq;
1.1 schwarze 1026:
1027: if ( ! st->parsing || st->paused)
1028: return;
1029:
1030: /*
1031: * Special-case: the NAME section.
1032: * If we find a "-" when searching from the end, assume that
1033: * we're in "name - description" format.
1034: * To wit, print out a "Nm" and "Nd" in that format.
1035: */
1.11 kristaps 1036: if (SECT_NAME == st->sect) {
1.15 kristaps 1037: for (i = end - 2; i > start; i--)
1038: if ('-' == buf[i] && ' ' == buf[i + 1])
1.1 schwarze 1039: break;
1040: if ('-' == buf[i]) {
1041: j = i;
1042: /* Roll over multiple "-". */
1043: for ( ; i > start; i--)
1044: if ('-' != buf[i])
1045: break;
1.17 kristaps 1046: donamenm(st, buf, &start, i + 1);
1.5 kristaps 1047: start = j + 1;
1.17 kristaps 1048: while (start < end && ' ' == buf[start])
1049: start++;
1.15 kristaps 1050: fputs(".Nd ", stdout);
1.11 kristaps 1051: formatcodeln(st, buf, &start, end, 1);
1.5 kristaps 1052: putchar('\n');
1.1 schwarze 1053: return;
1054: }
1055: }
1056:
1057: if ( ! st->haspar)
1058: puts(".Pp");
1059:
1060: st->haspar = 0;
1061: last = '\n';
1.13 kristaps 1062: opstack = 0;
1.1 schwarze 1063:
1.15 kristaps 1064: for (seq = 0; start < end; seq++) {
1.1 schwarze 1065: /*
1066: * Loop til we get either to a newline or escape.
1067: * Escape initial control characters.
1068: */
1069: while (start < end) {
1070: if (start < end - 1 && '<' == buf[start + 1])
1071: break;
1072: else if ('\n' == buf[start])
1073: break;
1074: else if ('\n' == last && '.' == buf[start])
1075: printf("\\&");
1076: else if ('\n' == last && '\'' == buf[start])
1077: printf("\\&");
1.12 kristaps 1078: /*
1079: * If we're in the SYNOPSIS, have square
1080: * brackets indicate that we're opening and
1081: * closing an optional context.
1082: */
1.13 kristaps 1083: if (SECT_SYNOPSIS == st->sect &&
1084: ('[' == buf[start] ||
1085: ']' == buf[start]) &&
1086: dosynopsisop(buf, &last,
1087: &start, end, &opstack))
1088: continue;
1.1 schwarze 1089: putchar(last = buf[start++]);
1.8 kristaps 1090: if ('\\' == last)
1091: putchar('e');
1.1 schwarze 1092: }
1093:
1094: if (start < end - 1 && '<' == buf[start + 1]) {
1095: /*
1096: * We've encountered a format code.
1097: * This is going to trigger a macro no matter
1098: * what, so print a newline now.
1099: * Then print the (possibly nested) macros and
1100: * following that, a newline.
1.8 kristaps 1101: * Consume all whitespace so we don't
1102: * accidentally start an implicit literal line.
1.16 kristaps 1103: * If the macro ends with a flush comma or
1104: * period, let mdoc(7) handle it for us.
1.1 schwarze 1105: */
1.15 kristaps 1106: if (formatcode(st, buf, &start, end, 0, 0, seq)) {
1.16 kristaps 1107: if ((start == end - 1 ||
1108: (start < end - 1 &&
1109: (' ' == buf[start + 1] ||
1110: '\n' == buf[start + 1]))) &&
1111: ('.' == buf[start] ||
1112: ',' == buf[start])) {
1113: putchar(' ');
1114: putchar(buf[start++]);
1115: }
1.1 schwarze 1116: putchar(last = '\n');
1.6 kristaps 1117: while (start < end && ' ' == buf[start])
1118: start++;
1119: }
1.1 schwarze 1120: } else if (start < end && '\n' == buf[start]) {
1121: /*
1122: * Print the newline only if we haven't already
1123: * printed a newline.
1124: */
1125: if (last != '\n')
1126: putchar(last = buf[start]);
1127: if (++start >= end)
1128: continue;
1129: /*
1130: * If we have whitespace next, eat it to prevent
1131: * mdoc(7) from thinking that it's meant for
1132: * verbatim text.
1133: * It is--but if we start with that, we can't
1134: * have a macro subsequent it, which may be
1135: * possible if we have an escape next.
1136: */
1137: if (' ' == buf[start] || '\t' == buf[start]) {
1138: puts(".br");
1139: last = '\n';
1140: }
1141: for ( ; start < end; start++)
1142: if (' ' != buf[start] && '\t' != buf[start])
1143: break;
1.12 kristaps 1144: }
1.1 schwarze 1145: }
1146:
1147: if (last != '\n')
1148: putchar('\n');
1149: }
1150:
1151: /*
1152: * There are three kinds of paragraphs: verbatim (starts with whitespace
1153: * of some sort), ordinary (starts without "=" marker), or a command
1154: * (default: starts with "=").
1155: */
1156: static void
1157: dopar(struct state *st, const char *buf, size_t start, size_t end)
1158: {
1159:
1160: if (end == start)
1161: return;
1162: if (' ' == buf[start] || '\t' == buf[start])
1163: verbatim(st, buf, start, end);
1164: else if ('=' != buf[start])
1165: ordinary(st, buf, start, end);
1166: else
1167: command(st, buf, start, end);
1168: }
1169:
1170: /*
1171: * Loop around paragraphs within a document, processing each one in the
1172: * POD way.
1173: */
1174: static void
1175: dofile(const struct args *args, const char *fname,
1176: const struct tm *tm, const char *buf, size_t sz)
1177: {
1178: size_t sup, end, i, cur = 0;
1179: struct state st;
1180: const char *section, *date;
1181: char datebuf[64];
1182: char *title, *cp;
1183:
1184: if (0 == sz)
1185: return;
1186:
1187: /* Title is last path component of the filename. */
1188:
1189: if (NULL != args->title)
1190: title = strdup(args->title);
1191: else if (NULL != (cp = strrchr(fname, '/')))
1192: title = strdup(cp + 1);
1193: else
1194: title = strdup(fname);
1195:
1196: if (NULL == title) {
1197: perror(NULL);
1198: exit(EXIT_FAILURE);
1199: }
1200:
1201: /* Section is 1 unless suffix is "pm". */
1202:
1203: if (NULL == (section = args->section)) {
1204: section = "1";
1205: if (NULL != (cp = strrchr(title, '.'))) {
1206: *cp++ = '\0';
1207: if (0 == strcmp(cp, "pm"))
1.10 kristaps 1208: section = PERL_SECTION;
1.1 schwarze 1209: }
1210: }
1211:
1212: /* Date. Or the given "tm" if not supplied. */
1213:
1214: if (NULL == (date = args->date)) {
1215: strftime(datebuf, sizeof(datebuf), "%B %d, %Y", tm);
1216: date = datebuf;
1217: }
1218:
1219: for (cp = title; '\0' != *cp; cp++)
1220: *cp = toupper((int)*cp);
1221:
1222: /* The usual mdoc(7) preamble. */
1223:
1224: printf(".Dd %s\n", date);
1225: printf(".Dt %s %s\n", title, section);
1226: puts(".Os");
1227:
1228: free(title);
1229:
1230: memset(&st, 0, sizeof(struct state));
1231: assert(sz > 0);
1232:
1233: /* Main loop over file contents. */
1234:
1235: while (cur < sz) {
1236: /* Read until next paragraph. */
1237: for (i = cur + 1; i < sz; i++)
1238: if ('\n' == buf[i] && '\n' == buf[i - 1]) {
1239: /* Consume blank paragraphs. */
1240: while (i + 1 < sz && '\n' == buf[i + 1])
1241: i++;
1242: break;
1243: }
1244:
1245: /* Adjust end marker for EOF. */
1246: end = i < sz ? i - 1 :
1247: ('\n' == buf[sz - 1] ? sz - 1 : sz);
1248: sup = i < sz ? end + 2 : sz;
1249:
1250: /* Process paragraph and adjust start. */
1251: dopar(&st, buf, cur, end);
1252: cur = sup;
1253: }
1254: }
1255:
1256: /*
1257: * Read a single file fully into memory.
1258: * If the file is "-", do it from stdin.
1259: * If successfully read, send the input buffer to dofile() for further
1260: * processing.
1261: */
1262: static int
1263: readfile(const struct args *args, const char *fname)
1264: {
1265: int fd;
1266: char *buf;
1267: size_t bufsz, cur;
1268: ssize_t ssz;
1269: struct tm *tm;
1270: time_t ttm;
1271: struct stat st;
1272:
1273: assert(NULL != fname);
1274:
1275: fd = 0 != strcmp("-", fname) ?
1276: open(fname, O_RDONLY, 0) : STDIN_FILENO;
1277:
1278: if (-1 == fd) {
1279: perror(fname);
1280: return(0);
1281: }
1282:
1283: if (STDIN_FILENO == fd || -1 == fstat(fd, &st)) {
1284: ttm = time(NULL);
1285: tm = localtime(&ttm);
1286: } else
1287: tm = localtime(&st.st_mtime);
1288:
1289: /*
1290: * Arbitrarily-sized initial buffer.
1291: * Should be big enough for most files...
1292: */
1293: cur = 0;
1294: bufsz = 1 << 14;
1295: if (NULL == (buf = malloc(bufsz))) {
1296: perror(NULL);
1297: exit(EXIT_FAILURE);
1298: }
1299:
1300: while ((ssz = read(fd, buf + cur, bufsz - cur)) > 0) {
1301: /* Double buffer size on fill. */
1302: if ((size_t)ssz == bufsz - cur) {
1303: bufsz *= 2;
1304: if (NULL == (buf = realloc(buf, bufsz))) {
1305: perror(NULL);
1306: exit(EXIT_FAILURE);
1307: }
1308: }
1309: cur += (size_t)ssz;
1310: }
1311: if (ssz < 0) {
1312: perror(fname);
1313: free(buf);
1314: return(0);
1315: }
1316:
1317: dofile(args, STDIN_FILENO == fd ?
1318: "STDIN" : fname, tm, buf, cur);
1319: free(buf);
1320: if (STDIN_FILENO != fd)
1321: close(fd);
1322: return(1);
1323: }
1324:
1325: int
1326: main(int argc, char *argv[])
1327: {
1328: const char *fname, *name;
1329: struct args args;
1330: int c;
1331:
1332: name = strrchr(argv[0], '/');
1333: if (name == NULL)
1334: name = argv[0];
1335: else
1336: ++name;
1337:
1338: memset(&args, 0, sizeof(struct args));
1339: fname = "-";
1340:
1341: /* Accept no arguments for now. */
1342:
1343: while (-1 != (c = getopt(argc, argv, "c:d:hln:oq:rs:uv")))
1344: switch (c) {
1345: case ('h'):
1346: /* FALLTHROUGH */
1347: case ('l'):
1348: /* FALLTHROUGH */
1349: case ('c'):
1350: /* FALLTHROUGH */
1351: case ('o'):
1352: /* FALLTHROUGH */
1353: case ('q'):
1354: /* FALLTHROUGH */
1355: case ('r'):
1356: /* FALLTHROUGH */
1357: case ('u'):
1358: /* FALLTHROUGH */
1359: case ('v'):
1360: /* Ignore these. */
1361: break;
1362: case ('d'):
1363: args.date = optarg;
1364: break;
1365: case ('n'):
1366: args.title = optarg;
1367: break;
1368: case ('s'):
1369: args.section = optarg;
1370: break;
1371: default:
1372: goto usage;
1373: }
1374:
1375: argc -= optind;
1376: argv += optind;
1377:
1378: /* Accept only a single input file. */
1379:
1.25 ! schwarze 1380: if (argc > 1)
! 1381: goto usage;
1.1 schwarze 1382: else if (1 == argc)
1383: fname = *argv;
1384:
1385: return(readfile(&args, fname) ?
1386: EXIT_SUCCESS : EXIT_FAILURE);
1387:
1388: usage:
1389: fprintf(stderr, "usage: %s [-d date] "
1.25 ! schwarze 1390: "[-n title] [-s section] [file]\n", name);
1.1 schwarze 1391:
1392: return(EXIT_FAILURE);
1393: }
CVSweb