[BACK]Return to pod2mdoc.c CVS log [TXT][DIR] Up to [cvsweb.bsd.lv] / pod2mdoc

Annotation of pod2mdoc/pod2mdoc.c, Revision 1.23

1.23    ! kristaps    1: /*     $Id: pod2mdoc.c,v 1.22 2014/04/03 16:50:32 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.1       schwarze  463:                return(0);
                    464:        }
                    465:
1.6       kristaps  466:        /*
                    467:         * Check whether we're supposed to print macro stuff (this is
                    468:         * suppressed in, e.g., "Nm" and "Sh" macros).
                    469:         */
1.1       schwarze  470:        if ( ! nomacro) {
                    471:                /*
                    472:                 * Print out the macro describing this format code.
                    473:                 * If we're not "reentrant" (not yet on a macro line)
                    474:                 * then print a newline, if necessary, and the macro
                    475:                 * indicator.
                    476:                 * Otherwise, offset us with a space.
                    477:                 */
1.6       kristaps  478:                if ( ! reentrant) {
                    479:                        if (last != '\n')
                    480:                                putchar('\n');
1.1       schwarze  481:                        putchar('.');
1.6       kristaps  482:                } else
1.1       schwarze  483:                        putchar(' ');
                    484:
                    485:                /*
1.6       kristaps  486:                 * If we don't have whitespace before us (and none after
                    487:                 * the opening delimiter), then suppress macro
                    488:                 * whitespace with Pf.
1.1       schwarze  489:                 */
1.6       kristaps  490:                if (' ' != last && '\n' != last && ' ' != buf[*start])
                    491:                        printf("Pf ");
                    492:
1.1       schwarze  493:                switch (fmt) {
                    494:                case (FMT_ITALIC):
                    495:                        printf("Em ");
                    496:                        break;
                    497:                case (FMT_BOLD):
1.14      kristaps  498:                        if (SECT_SYNOPSIS == st->sect) {
                    499:                                if (1 == dsz && '-' == buf[*start])
                    500:                                        dosynopsisfl(buf, start, end);
1.15      kristaps  501:                                else if (0 == pos)
                    502:                                        printf("Nm ");
1.14      kristaps  503:                                else
                    504:                                        printf("Ar ");
                    505:                                break;
                    506:                        }
                    507:                        printf("Sy ");
1.1       schwarze  508:                        break;
                    509:                case (FMT_CODE):
1.2       schwarze  510:                        printf("Qo Li ");
1.1       schwarze  511:                        break;
                    512:                case (FMT_LINK):
1.19      kristaps  513:                        /* Try to link; use "No" if it's empty. */
1.9       kristaps  514:                        if ( ! trylink(buf, start, end, dsz))
                    515:                                printf("No ");
1.1       schwarze  516:                        break;
                    517:                case (FMT_FILE):
                    518:                        printf("Pa ");
                    519:                        break;
                    520:                case (FMT_NBSP):
                    521:                        printf("No ");
                    522:                        break;
                    523:                default:
                    524:                        abort();
                    525:                }
                    526:        }
                    527:
                    528:        /*
1.6       kristaps  529:         * Process until we reach the end marker (e.g., '>') or until we
1.5       kristaps  530:         * find a nested format code.
1.1       schwarze  531:         * Don't emit any newlines: since we're on a macro line, we
                    532:         * don't want to break the line.
                    533:         */
                    534:        while (*start < end) {
1.5       kristaps  535:                if ('>' == buf[*start] && 1 == dsz) {
1.1       schwarze  536:                        (*start)++;
                    537:                        break;
1.5       kristaps  538:                } else if ('>' == buf[*start] &&
                    539:                                ' ' == buf[*start - 1]) {
                    540:                        /*
                    541:                         * Handle custom delimiters.
                    542:                         * These require a certain number of
                    543:                         * space-preceded carrots before we're really at
                    544:                         * the end.
                    545:                         */
                    546:                        i = *start;
                    547:                        for (j = 0; i < end && j < dsz; j++)
                    548:                                if ('>' != buf[i++])
                    549:                                        break;
                    550:                        if (dsz == j) {
                    551:                                *start += dsz;
                    552:                                break;
                    553:                        }
1.1       schwarze  554:                }
                    555:                if (*start + 1 < end && '<' == buf[*start + 1]) {
1.15      kristaps  556:                        formatcode(st, buf, start, end, 1, nomacro, 1);
1.1       schwarze  557:                        continue;
                    558:                }
1.3       schwarze  559:
1.4       schwarze  560:                /*
                    561:                 * Make sure that any macro-like words (or
                    562:                 * really any word starting with a capital
                    563:                 * letter) is assumed to be a macro that must be
                    564:                 * escaped.
                    565:                 * This matches "Xx " and "XxEOLN".
                    566:                 */
                    567:                if ((' ' == last || '\n' == last) &&
                    568:                                end - *start > 1 &&
                    569:                                isupper((int)buf[*start]) &&
                    570:                                islower((int)buf[*start + 1]) &&
                    571:                                (end - *start == 2 ||
                    572:                                 ' ' == buf[*start + 2]))
                    573:                        printf("\\&");
1.3       schwarze  574:
1.4       schwarze  575:                /* Suppress newline. */
1.6       kristaps  576:                if ('\n' == buf[*start])
                    577:                        putchar(last = ' ');
                    578:                else
                    579:                        putchar(last = buf[*start]);
1.4       schwarze  580:
1.8       kristaps  581:                /* Protect against character escapes. */
                    582:                if ('\\' == last)
                    583:                        putchar('e');
                    584:
1.6       kristaps  585:                (*start)++;
                    586:
                    587:                if (' ' == last)
                    588:                        while (*start < end && ' ' == buf[*start])
                    589:                                (*start)++;
1.1       schwarze  590:        }
1.2       schwarze  591:
                    592:        if ( ! nomacro && FMT_CODE == fmt)
                    593:                printf(" Qc ");
1.1       schwarze  594:
                    595:        /*
1.6       kristaps  596:         * We're now subsequent the format code.
                    597:         * If there isn't a space (or newline) here, and we haven't just
                    598:         * printed a space, then suppress space.
1.1       schwarze  599:         */
1.6       kristaps  600:        if ( ! nomacro && ' ' != last)
                    601:                if (' ' != buf[*start] && '\n' != buf[*start])
                    602:                        printf(" Ns ");
1.5       kristaps  603:
1.1       schwarze  604:        return(1);
                    605: }
                    606:
                    607: /*
                    608:  * Calls formatcode() til the end of a paragraph.
                    609:  */
                    610: static void
1.11      kristaps  611: formatcodeln(struct state *st, const char *buf,
                    612:        size_t *start, size_t end, int nomacro)
1.1       schwarze  613: {
                    614:
1.4       schwarze  615:        last = ' ';
1.1       schwarze  616:        while (*start < end)  {
                    617:                if (*start + 1 < end && '<' == buf[*start + 1]) {
1.15      kristaps  618:                        formatcode(st, buf, start, end, 1, nomacro, 1);
1.1       schwarze  619:                        continue;
                    620:                }
1.4       schwarze  621:                /*
                    622:                 * Since we're already on a macro line, we want to make
                    623:                 * sure that we don't inadvertently invoke a macro.
                    624:                 * We need to do this carefully because section names
                    625:                 * are used in troff and we don't want to escape
                    626:                 * something that needn't be escaped.
                    627:                 */
                    628:                if (' ' == last && end - *start > 1 &&
                    629:                                isupper((int)buf[*start]) &&
                    630:                                islower((int)buf[*start + 1]) &&
                    631:                                (end - *start == 2 ||
                    632:                                 ' ' == buf[*start + 2]))
                    633:                        printf("\\&");
                    634:
1.8       kristaps  635:                if ('\n' == buf[*start])
                    636:                        putchar(last = ' ');
                    637:                else
1.1       schwarze  638:                        putchar(last = buf[*start]);
1.8       kristaps  639:
                    640:                /* Protect against character escapes. */
                    641:                if ('\\' == last)
                    642:                        putchar('e');
                    643:
1.1       schwarze  644:                (*start)++;
                    645:        }
                    646: }
                    647:
                    648: /*
1.4       schwarze  649:  * Guess at what kind of list we are.
                    650:  * These are taken straight from the POD manual.
                    651:  * I don't know what people do in real life.
                    652:  */
                    653: static enum list
                    654: listguess(const char *buf, size_t start, size_t end)
                    655: {
                    656:        size_t           len = end - start;
                    657:
                    658:        assert(end >= start);
                    659:
                    660:        if (len == 1 && '*' == buf[start])
                    661:                return(LIST_BULLET);
                    662:        if (len == 2 && '1' == buf[start] && '.' == buf[start + 1])
                    663:                return(LIST_ENUM);
                    664:        else if (len == 1 && '1' == buf[start])
                    665:                return(LIST_ENUM);
                    666:        else
                    667:                return(LIST_TAG);
                    668: }
                    669:
                    670: /*
1.1       schwarze  671:  * A command paragraph, as noted in the perlpod manual, just indicates
                    672:  * that we should do something, optionally with some text to print as
                    673:  * well.
                    674:  */
                    675: static void
                    676: command(struct state *st, const char *buf, size_t start, size_t end)
                    677: {
                    678:        size_t           len, csz;
                    679:        enum cmd         cmd;
                    680:
                    681:        assert('=' == buf[start]);
                    682:        start++;
                    683:        len = end - start;
                    684:
                    685:        for (cmd = 0; cmd < CMD__MAX; cmd++) {
                    686:                csz = strlen(cmds[cmd]);
                    687:                if (len < csz)
                    688:                        continue;
                    689:                if (0 == memcmp(&buf[start], cmd[cmds], csz))
                    690:                        break;
                    691:        }
                    692:
                    693:        /* Ignore bogus commands. */
                    694:
                    695:        if (CMD__MAX == cmd)
                    696:                return;
                    697:
                    698:        start += csz;
1.8       kristaps  699:        while (start < end && ' ' == buf[start])
                    700:                start++;
                    701:
1.1       schwarze  702:        len = end - start;
                    703:
                    704:        if (st->paused) {
                    705:                st->paused = CMD_END != cmd;
                    706:                return;
                    707:        }
                    708:
                    709:        switch (cmd) {
                    710:        case (CMD_POD):
                    711:                break;
                    712:        case (CMD_HEAD1):
                    713:                /*
                    714:                 * The behaviour of head= follows from a quick glance at
                    715:                 * how pod2man handles it.
                    716:                 */
                    717:                printf(".Sh ");
1.11      kristaps  718:                st->sect = SECT_NONE;
                    719:                if (end - start == 4) {
1.1       schwarze  720:                        if (0 == memcmp(&buf[start], "NAME", 4))
1.11      kristaps  721:                                st->sect = SECT_NAME;
                    722:                } else if (end - start == 8) {
                    723:                        if (0 == memcmp(&buf[start], "SYNOPSIS", 8))
                    724:                                st->sect = SECT_SYNOPSIS;
                    725:                }
                    726:                formatcodeln(st, buf, &start, end, 1);
1.1       schwarze  727:                putchar('\n');
                    728:                st->haspar = 1;
                    729:                break;
                    730:        case (CMD_HEAD2):
                    731:                printf(".Ss ");
1.11      kristaps  732:                formatcodeln(st, buf, &start, end, 1);
1.1       schwarze  733:                putchar('\n');
                    734:                st->haspar = 1;
                    735:                break;
                    736:        case (CMD_HEAD3):
                    737:                puts(".Pp");
                    738:                printf(".Em ");
1.11      kristaps  739:                formatcodeln(st, buf, &start, end, 0);
1.1       schwarze  740:                putchar('\n');
                    741:                puts(".Pp");
                    742:                st->haspar = 1;
                    743:                break;
                    744:        case (CMD_HEAD4):
                    745:                puts(".Pp");
                    746:                printf(".No ");
1.11      kristaps  747:                formatcodeln(st, buf, &start, end, 0);
1.1       schwarze  748:                putchar('\n');
                    749:                puts(".Pp");
                    750:                st->haspar = 1;
                    751:                break;
                    752:        case (CMD_OVER):
1.4       schwarze  753:                /*
                    754:                 * If we have an existing list that hasn't had an =item
                    755:                 * yet, then make sure that we open it now.
                    756:                 * We use the default list type, but that can't be
                    757:                 * helped (we haven't seen any items yet).
1.1       schwarze  758:                 */
1.4       schwarze  759:                if (st->lpos > 0)
                    760:                        if (LIST__MAX == st->lstack[st->lpos - 1]) {
                    761:                                st->lstack[st->lpos - 1] = LIST_TAG;
                    762:                                puts(".Bl -tag -width Ds");
                    763:                        }
                    764:                st->lpos++;
                    765:                assert(st->lpos < LIST_STACKSZ);
                    766:                st->lstack[st->lpos - 1] = LIST__MAX;
1.1       schwarze  767:                break;
                    768:        case (CMD_ITEM):
1.6       kristaps  769:                if (0 == st->lpos) {
                    770:                        /*
                    771:                         * Bad markup.
                    772:                         * Try to compensate.
                    773:                         */
                    774:                        st->lstack[st->lpos] = LIST__MAX;
                    775:                        st->lpos++;
                    776:                }
1.4       schwarze  777:                assert(st->lpos > 0);
                    778:                /*
                    779:                 * If we're the first =item, guess at what our content
                    780:                 * will be: "*" is a bullet list, "1." is a numbered
                    781:                 * list, and everything is tagged.
                    782:                 */
                    783:                if (LIST__MAX == st->lstack[st->lpos - 1]) {
                    784:                        st->lstack[st->lpos - 1] =
                    785:                                listguess(buf, start, end);
                    786:                        switch (st->lstack[st->lpos - 1]) {
                    787:                        case (LIST_BULLET):
                    788:                                puts(".Bl -bullet");
                    789:                                break;
                    790:                        case (LIST_ENUM):
                    791:                                puts(".Bl -enum");
                    792:                                break;
                    793:                        default:
                    794:                                puts(".Bl -tag -width Ds");
                    795:                                break;
                    796:                        }
                    797:                }
                    798:                switch (st->lstack[st->lpos - 1]) {
                    799:                case (LIST_TAG):
                    800:                        printf(".It ");
1.11      kristaps  801:                        formatcodeln(st, buf, &start, end, 0);
1.4       schwarze  802:                        putchar('\n');
                    803:                        break;
                    804:                case (LIST_ENUM):
                    805:                        /* FALLTHROUGH */
                    806:                case (LIST_BULLET):
                    807:                        /*
                    808:                         * Abandon the remainder of the paragraph
                    809:                         * because we're going to be a bulletted or
                    810:                         * numbered list.
                    811:                         */
                    812:                        puts(".It");
                    813:                        break;
                    814:                default:
                    815:                        abort();
                    816:                }
1.1       schwarze  817:                st->haspar = 1;
                    818:                break;
                    819:        case (CMD_BACK):
1.4       schwarze  820:                /* Make sure we don't back over the stack. */
                    821:                if (st->lpos > 0) {
                    822:                        st->lpos--;
                    823:                        puts(".El");
                    824:                }
1.1       schwarze  825:                break;
                    826:        case (CMD_BEGIN):
                    827:                /*
                    828:                 * We disregard all types for now.
                    829:                 * TODO: process at least "text" in a -literal block.
                    830:                 */
                    831:                st->paused = 1;
                    832:                break;
                    833:        case (CMD_FOR):
                    834:                /*
                    835:                 * We ignore all types of encodings and formats
                    836:                 * unilaterally.
                    837:                 */
                    838:                break;
                    839:        case (CMD_ENCODING):
                    840:                break;
                    841:        case (CMD_CUT):
                    842:                st->parsing = 0;
                    843:                return;
                    844:        default:
                    845:                abort();
                    846:        }
                    847:
                    848:        /* Any command (but =cut) makes us start parsing. */
                    849:        st->parsing = 1;
                    850: }
                    851:
                    852: /*
                    853:  * Just pump out the line in a verbatim block.
                    854:  */
                    855: static void
                    856: verbatim(struct state *st, const char *buf, size_t start, size_t end)
                    857: {
1.8       kristaps  858:        int              last;
1.22      kristaps  859:        size_t           i;
1.1       schwarze  860:
                    861:        if ( ! st->parsing || st->paused)
                    862:                return;
1.22      kristaps  863: again:
                    864:        /*
                    865:         * If we're in the SYNOPSIS, see if we're an #include block.
                    866:         * If we are, then print the "In" macro and re-loop.
                    867:         * This handles any number of inclusions, but only when they
                    868:         * come before the remaining parts...
                    869:         */
                    870:        if (SECT_SYNOPSIS == st->sect) {
                    871:                i = start;
                    872:                for (i = start; i < end && ' ' == buf[i]; i++)
                    873:                        /* Spin. */ ;
                    874:                if (i == end)
                    875:                        return;
                    876:                /* We're an include block! */
                    877:                if (end - i > 10 &&
                    878:                        0 == memcmp(&buf[i], "#include <", 10)) {
                    879:                        start = i + 10;
                    880:                        while (start < end && ' ' == buf[start])
                    881:                                start++;
                    882:                        fputs(".In ", stdout);
                    883:                        /* Stop til the '>' marker or we hit eoln. */
                    884:                        while (start < end &&
                    885:                                '>' != buf[start] && '\n' != buf[start])
                    886:                                putchar(buf[start++]);
                    887:                        putchar('\n');
                    888:                        if (start < end && '>' == buf[start])
                    889:                                start++;
                    890:                        if (start < end && '\n' == buf[start])
                    891:                                start++;
                    892:                        if (start < end)
                    893:                                goto again;
                    894:                        return;
                    895:                }
                    896:        }
                    897:
                    898:        if (start == end)
                    899:                return;
1.1       schwarze  900:        puts(".Bd -literal");
1.8       kristaps  901:        for (last = ' '; start < end; start++) {
                    902:                /*
                    903:                 * Handle accidental macros (newline starting with
                    904:                 * control character) and escapes.
                    905:                 */
                    906:                if ('\n' == last)
1.7       kristaps  907:                        if ('.' == buf[start] || '\'' == buf[start])
                    908:                                printf("\\&");
1.8       kristaps  909:                putchar(last = buf[start]);
                    910:                if ('\\' == buf[start])
                    911:                        printf("e");
1.7       kristaps  912:        }
                    913:        putchar('\n');
1.1       schwarze  914:        puts(".Ed");
                    915: }
                    916:
                    917: /*
1.13      kristaps  918:  * See dosynopsisop().
                    919:  */
                    920: static int
                    921: hasmatch(const char *buf, size_t start, size_t end)
                    922: {
                    923:        size_t   stack;
                    924:
                    925:        for (stack = 0; start < end; start++)
                    926:                if (buf[start] == '[')
                    927:                        stack++;
                    928:                else if (buf[start] == ']' && 0 == stack)
                    929:                        return(1);
                    930:                else if (buf[start] == ']')
                    931:                        stack--;
                    932:        return(0);
                    933: }
                    934:
                    935: /*
                    936:  * If we're in the SYNOPSIS section and we've encounter braces in an
                    937:  * ordinary paragraph, then try to see whether we're an [-option].
                    938:  * Do this, if we're an opening bracket, by first seeing if we have a
                    939:  * matching end via hasmatch().
                    940:  * If we're an ending bracket, see if we have a stack already.
                    941:  */
                    942: static int
                    943: dosynopsisop(const char *buf, int *last,
                    944:        size_t *start, size_t end, size_t *opstack)
                    945: {
                    946:
                    947:        assert('[' == buf[*start] || ']' == buf[*start]);
                    948:
                    949:        if ('[' == buf[*start] && hasmatch(buf, *start + 1, end)) {
                    950:                if ('\n' != *last)
                    951:                        putchar('\n');
                    952:                puts(".Oo");
                    953:                (*opstack)++;
                    954:        } else if ('[' == buf[*start])
                    955:                return(0);
                    956:
                    957:        if (']' == buf[*start] && *opstack > 0) {
                    958:                if ('\n' != *last)
                    959:                        putchar('\n');
                    960:                puts(".Oc");
                    961:                (*opstack)--;
                    962:        } else if (']' == buf[*start])
                    963:                return(0);
                    964:
                    965:        (*start)++;
                    966:        *last = '\n';
                    967:        while (' ' == buf[*start])
                    968:                (*start)++;
                    969:        return(1);
                    970: }
                    971:
                    972: /*
1.17      kristaps  973:  * Format multiple "Nm" manpage names in the NAME section.
                    974:  */
                    975: static void
                    976: donamenm(struct state *st, const char *buf, size_t *start, size_t end)
                    977: {
                    978:        size_t   word;
                    979:
                    980:        while (*start < end && ' ' == buf[*start])
                    981:                (*start)++;
                    982:
                    983:        if (end == *start) {
                    984:                puts(".Nm unknown");
                    985:                return;
                    986:        }
                    987:
                    988:        while (*start < end) {
                    989:                fputs(".Nm ", stdout);
                    990:                for (word = *start; word < end; word++)
                    991:                        if (',' == buf[word])
                    992:                                break;
                    993:                formatcodeln(st, buf, start, word, 1);
                    994:                if (*start == end) {
                    995:                        putchar('\n');
                    996:                        continue;
                    997:                }
                    998:                assert(',' == buf[*start]);
                    999:                puts(" ,");
                   1000:                (*start)++;
                   1001:                while (*start < end && ' ' == buf[*start])
                   1002:                        (*start)++;
                   1003:        }
                   1004: }
                   1005:
                   1006: /*
1.1       schwarze 1007:  * Ordinary paragraph.
                   1008:  * Well, this is really the hardest--POD seems to assume that, for
                   1009:  * example, a leading space implies a newline, and so on.
                   1010:  * Lots of other snakes in the grass: escaping a newline followed by a
                   1011:  * period (accidental mdoc(7) control), double-newlines after macro
                   1012:  * passages, etc.
                   1013:  */
                   1014: static void
                   1015: ordinary(struct state *st, const char *buf, size_t start, size_t end)
                   1016: {
1.13      kristaps 1017:        size_t          i, j, opstack;
1.15      kristaps 1018:        int             seq;
1.1       schwarze 1019:
                   1020:        if ( ! st->parsing || st->paused)
                   1021:                return;
                   1022:
                   1023:        /*
                   1024:         * Special-case: the NAME section.
                   1025:         * If we find a "-" when searching from the end, assume that
                   1026:         * we're in "name - description" format.
                   1027:         * To wit, print out a "Nm" and "Nd" in that format.
                   1028:         */
1.11      kristaps 1029:        if (SECT_NAME == st->sect) {
1.15      kristaps 1030:                for (i = end - 2; i > start; i--)
                   1031:                        if ('-' == buf[i] && ' ' == buf[i + 1])
1.1       schwarze 1032:                                break;
                   1033:                if ('-' == buf[i]) {
                   1034:                        j = i;
                   1035:                        /* Roll over multiple "-". */
                   1036:                        for ( ; i > start; i--)
                   1037:                                if ('-' != buf[i])
                   1038:                                        break;
1.17      kristaps 1039:                        donamenm(st, buf, &start, i + 1);
1.5       kristaps 1040:                        start = j + 1;
1.17      kristaps 1041:                        while (start < end && ' ' == buf[start])
                   1042:                                start++;
1.15      kristaps 1043:                        fputs(".Nd ", stdout);
1.11      kristaps 1044:                        formatcodeln(st, buf, &start, end, 1);
1.5       kristaps 1045:                        putchar('\n');
1.1       schwarze 1046:                        return;
                   1047:                }
                   1048:        }
                   1049:
                   1050:        if ( ! st->haspar)
                   1051:                puts(".Pp");
                   1052:
                   1053:        st->haspar = 0;
                   1054:        last = '\n';
1.13      kristaps 1055:        opstack = 0;
1.1       schwarze 1056:
1.15      kristaps 1057:        for (seq = 0; start < end; seq++) {
1.1       schwarze 1058:                /*
                   1059:                 * Loop til we get either to a newline or escape.
                   1060:                 * Escape initial control characters.
                   1061:                 */
                   1062:                while (start < end) {
                   1063:                        if (start < end - 1 && '<' == buf[start + 1])
                   1064:                                break;
                   1065:                        else if ('\n' == buf[start])
                   1066:                                break;
                   1067:                        else if ('\n' == last && '.' == buf[start])
                   1068:                                printf("\\&");
                   1069:                        else if ('\n' == last && '\'' == buf[start])
                   1070:                                printf("\\&");
1.12      kristaps 1071:                        /*
                   1072:                         * If we're in the SYNOPSIS, have square
                   1073:                         * brackets indicate that we're opening and
                   1074:                         * closing an optional context.
                   1075:                         */
1.13      kristaps 1076:                        if (SECT_SYNOPSIS == st->sect &&
                   1077:                                ('[' == buf[start] ||
                   1078:                                 ']' == buf[start]) &&
                   1079:                                dosynopsisop(buf, &last,
                   1080:                                        &start, end, &opstack))
                   1081:                                continue;
1.1       schwarze 1082:                        putchar(last = buf[start++]);
1.8       kristaps 1083:                        if ('\\' == last)
                   1084:                                putchar('e');
1.1       schwarze 1085:                }
                   1086:
                   1087:                if (start < end - 1 && '<' == buf[start + 1]) {
                   1088:                        /*
                   1089:                         * We've encountered a format code.
                   1090:                         * This is going to trigger a macro no matter
                   1091:                         * what, so print a newline now.
                   1092:                         * Then print the (possibly nested) macros and
                   1093:                         * following that, a newline.
1.8       kristaps 1094:                         * Consume all whitespace so we don't
                   1095:                         * accidentally start an implicit literal line.
1.16      kristaps 1096:                         * If the macro ends with a flush comma or
                   1097:                         * period, let mdoc(7) handle it for us.
1.1       schwarze 1098:                         */
1.15      kristaps 1099:                        if (formatcode(st, buf, &start, end, 0, 0, seq)) {
1.16      kristaps 1100:                                if ((start == end - 1 ||
                   1101:                                        (start < end - 1 &&
                   1102:                                         (' ' == buf[start + 1] ||
                   1103:                                          '\n' == buf[start + 1]))) &&
                   1104:                                        ('.' == buf[start] ||
                   1105:                                         ',' == buf[start])) {
                   1106:                                        putchar(' ');
                   1107:                                        putchar(buf[start++]);
                   1108:                                }
1.1       schwarze 1109:                                putchar(last = '\n');
1.6       kristaps 1110:                                while (start < end && ' ' == buf[start])
                   1111:                                        start++;
                   1112:                        }
1.1       schwarze 1113:                } else if (start < end && '\n' == buf[start]) {
                   1114:                        /*
                   1115:                         * Print the newline only if we haven't already
                   1116:                         * printed a newline.
                   1117:                         */
                   1118:                        if (last != '\n')
                   1119:                                putchar(last = buf[start]);
                   1120:                        if (++start >= end)
                   1121:                                continue;
                   1122:                        /*
                   1123:                         * If we have whitespace next, eat it to prevent
                   1124:                         * mdoc(7) from thinking that it's meant for
                   1125:                         * verbatim text.
                   1126:                         * It is--but if we start with that, we can't
                   1127:                         * have a macro subsequent it, which may be
                   1128:                         * possible if we have an escape next.
                   1129:                         */
                   1130:                        if (' ' == buf[start] || '\t' == buf[start]) {
                   1131:                                puts(".br");
                   1132:                                last = '\n';
                   1133:                        }
                   1134:                        for ( ; start < end; start++)
                   1135:                                if (' ' != buf[start] && '\t' != buf[start])
                   1136:                                        break;
1.12      kristaps 1137:                }
1.1       schwarze 1138:        }
                   1139:
                   1140:        if (last != '\n')
                   1141:                putchar('\n');
                   1142: }
                   1143:
                   1144: /*
                   1145:  * There are three kinds of paragraphs: verbatim (starts with whitespace
                   1146:  * of some sort), ordinary (starts without "=" marker), or a command
                   1147:  * (default: starts with "=").
                   1148:  */
                   1149: static void
                   1150: dopar(struct state *st, const char *buf, size_t start, size_t end)
                   1151: {
                   1152:
                   1153:        if (end == start)
                   1154:                return;
                   1155:        if (' ' == buf[start] || '\t' == buf[start])
                   1156:                verbatim(st, buf, start, end);
                   1157:        else if ('=' != buf[start])
                   1158:                ordinary(st, buf, start, end);
                   1159:        else
                   1160:                command(st, buf, start, end);
                   1161: }
                   1162:
                   1163: /*
                   1164:  * Loop around paragraphs within a document, processing each one in the
                   1165:  * POD way.
                   1166:  */
                   1167: static void
                   1168: dofile(const struct args *args, const char *fname,
                   1169:        const struct tm *tm, const char *buf, size_t sz)
                   1170: {
                   1171:        size_t           sup, end, i, cur = 0;
                   1172:        struct state     st;
                   1173:        const char      *section, *date;
                   1174:        char             datebuf[64];
                   1175:        char            *title, *cp;
                   1176:
                   1177:        if (0 == sz)
                   1178:                return;
                   1179:
                   1180:        /* Title is last path component of the filename. */
                   1181:
                   1182:        if (NULL != args->title)
                   1183:                title = strdup(args->title);
                   1184:        else if (NULL != (cp = strrchr(fname, '/')))
                   1185:                title = strdup(cp + 1);
                   1186:        else
                   1187:                title = strdup(fname);
                   1188:
                   1189:        if (NULL == title) {
                   1190:                perror(NULL);
                   1191:                exit(EXIT_FAILURE);
                   1192:        }
                   1193:
                   1194:        /* Section is 1 unless suffix is "pm". */
                   1195:
                   1196:        if (NULL == (section = args->section)) {
                   1197:                section = "1";
                   1198:                if (NULL != (cp = strrchr(title, '.'))) {
                   1199:                        *cp++ = '\0';
                   1200:                        if (0 == strcmp(cp, "pm"))
1.10      kristaps 1201:                                section = PERL_SECTION;
1.1       schwarze 1202:                }
                   1203:        }
                   1204:
                   1205:        /* Date.  Or the given "tm" if not supplied. */
                   1206:
                   1207:        if (NULL == (date = args->date)) {
                   1208:                strftime(datebuf, sizeof(datebuf), "%B %d, %Y", tm);
                   1209:                date = datebuf;
                   1210:        }
                   1211:
                   1212:        for (cp = title; '\0' != *cp; cp++)
                   1213:                *cp = toupper((int)*cp);
                   1214:
                   1215:        /* The usual mdoc(7) preamble. */
                   1216:
                   1217:        printf(".Dd %s\n", date);
                   1218:        printf(".Dt %s %s\n", title, section);
                   1219:        puts(".Os");
                   1220:
                   1221:        free(title);
                   1222:
                   1223:        memset(&st, 0, sizeof(struct state));
                   1224:        assert(sz > 0);
                   1225:
                   1226:        /* Main loop over file contents. */
                   1227:
                   1228:        while (cur < sz) {
                   1229:                /* Read until next paragraph. */
                   1230:                for (i = cur + 1; i < sz; i++)
                   1231:                        if ('\n' == buf[i] && '\n' == buf[i - 1]) {
                   1232:                                /* Consume blank paragraphs. */
                   1233:                                while (i + 1 < sz && '\n' == buf[i + 1])
                   1234:                                        i++;
                   1235:                                break;
                   1236:                        }
                   1237:
                   1238:                /* Adjust end marker for EOF. */
                   1239:                end = i < sz ? i - 1 :
                   1240:                        ('\n' == buf[sz - 1] ? sz - 1 : sz);
                   1241:                sup = i < sz ? end + 2 : sz;
                   1242:
                   1243:                /* Process paragraph and adjust start. */
                   1244:                dopar(&st, buf, cur, end);
                   1245:                cur = sup;
                   1246:        }
                   1247: }
                   1248:
                   1249: /*
                   1250:  * Read a single file fully into memory.
                   1251:  * If the file is "-", do it from stdin.
                   1252:  * If successfully read, send the input buffer to dofile() for further
                   1253:  * processing.
                   1254:  */
                   1255: static int
                   1256: readfile(const struct args *args, const char *fname)
                   1257: {
                   1258:        int              fd;
                   1259:        char            *buf;
                   1260:        size_t           bufsz, cur;
                   1261:        ssize_t          ssz;
                   1262:        struct tm       *tm;
                   1263:        time_t           ttm;
                   1264:        struct stat      st;
                   1265:
                   1266:        assert(NULL != fname);
                   1267:
                   1268:        fd = 0 != strcmp("-", fname) ?
                   1269:                open(fname, O_RDONLY, 0) : STDIN_FILENO;
                   1270:
                   1271:        if (-1 == fd) {
                   1272:                perror(fname);
                   1273:                return(0);
                   1274:        }
                   1275:
                   1276:        if (STDIN_FILENO == fd || -1 == fstat(fd, &st)) {
                   1277:                ttm = time(NULL);
                   1278:                tm = localtime(&ttm);
                   1279:        } else
                   1280:                tm = localtime(&st.st_mtime);
                   1281:
                   1282:        /*
                   1283:         * Arbitrarily-sized initial buffer.
                   1284:         * Should be big enough for most files...
                   1285:         */
                   1286:        cur = 0;
                   1287:        bufsz = 1 << 14;
                   1288:        if (NULL == (buf = malloc(bufsz))) {
                   1289:                perror(NULL);
                   1290:                exit(EXIT_FAILURE);
                   1291:        }
                   1292:
                   1293:        while ((ssz = read(fd, buf + cur, bufsz - cur)) > 0) {
                   1294:                /* Double buffer size on fill. */
                   1295:                if ((size_t)ssz == bufsz - cur)  {
                   1296:                        bufsz *= 2;
                   1297:                        if (NULL == (buf = realloc(buf, bufsz))) {
                   1298:                                perror(NULL);
                   1299:                                exit(EXIT_FAILURE);
                   1300:                        }
                   1301:                }
                   1302:                cur += (size_t)ssz;
                   1303:        }
                   1304:        if (ssz < 0) {
                   1305:                perror(fname);
                   1306:                free(buf);
                   1307:                return(0);
                   1308:        }
                   1309:
                   1310:        dofile(args, STDIN_FILENO == fd ?
                   1311:                "STDIN" : fname, tm, buf, cur);
                   1312:        free(buf);
                   1313:        if (STDIN_FILENO != fd)
                   1314:                close(fd);
                   1315:        return(1);
                   1316: }
                   1317:
                   1318: int
                   1319: main(int argc, char *argv[])
                   1320: {
                   1321:        const char      *fname, *name;
                   1322:        struct args      args;
                   1323:        int              c;
                   1324:
                   1325:        name = strrchr(argv[0], '/');
                   1326:        if (name == NULL)
                   1327:                name = argv[0];
                   1328:        else
                   1329:                ++name;
                   1330:
                   1331:        memset(&args, 0, sizeof(struct args));
                   1332:        fname = "-";
                   1333:
                   1334:        /* Accept no arguments for now. */
                   1335:
                   1336:        while (-1 != (c = getopt(argc, argv, "c:d:hln:oq:rs:uv")))
                   1337:                switch (c) {
                   1338:                case ('h'):
                   1339:                        /* FALLTHROUGH */
                   1340:                case ('l'):
                   1341:                        /* FALLTHROUGH */
                   1342:                case ('c'):
                   1343:                        /* FALLTHROUGH */
                   1344:                case ('o'):
                   1345:                        /* FALLTHROUGH */
                   1346:                case ('q'):
                   1347:                        /* FALLTHROUGH */
                   1348:                case ('r'):
                   1349:                        /* FALLTHROUGH */
                   1350:                case ('u'):
                   1351:                        /* FALLTHROUGH */
                   1352:                case ('v'):
                   1353:                        /* Ignore these. */
                   1354:                        break;
                   1355:                case ('d'):
                   1356:                        args.date = optarg;
                   1357:                        break;
                   1358:                case ('n'):
                   1359:                        args.title = optarg;
                   1360:                        break;
                   1361:                case ('s'):
                   1362:                        args.section = optarg;
                   1363:                        break;
                   1364:                default:
                   1365:                        goto usage;
                   1366:                }
                   1367:
                   1368:        argc -= optind;
                   1369:        argv += optind;
                   1370:
                   1371:        /* Accept only a single input file. */
                   1372:
                   1373:        if (argc > 2)
                   1374:                return(EXIT_FAILURE);
                   1375:        else if (1 == argc)
                   1376:                fname = *argv;
                   1377:
                   1378:        return(readfile(&args, fname) ?
                   1379:                EXIT_SUCCESS : EXIT_FAILURE);
                   1380:
                   1381: usage:
                   1382:        fprintf(stderr, "usage: %s [-d date] "
                   1383:                "[-n title] [-s section]\n", name);
                   1384:
                   1385:        return(EXIT_FAILURE);
                   1386: }

CVSweb