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

Annotation of pod2mdoc/pod2mdoc.c, Revision 1.35

1.35    ! schwarze    1: /*     $Id: pod2mdoc.c,v 1.34 2014/07/19 00:42:22 schwarze 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.32      schwarze   55: enum   outstate {
                     56:        OUST_NL = 0,    /* just started a new output line */
                     57:        OUST_TXT,       /* text line output in progress */
                     58:        OUST_MAC        /* macro line output in progress */
                     59: };
                     60:
1.1       schwarze   61: struct state {
1.31      schwarze   62:        const char      *fname; /* file being parsed */
1.1       schwarze   63:        int              parsing; /* after =cut of before command */
                     64:        int              paused; /* in =begin and before =end */
1.11      kristaps   65:        enum sect        sect; /* which section are we in? */
1.4       schwarze   66: #define        LIST_STACKSZ     128
                     67:        enum list        lstack[LIST_STACKSZ]; /* open lists */
                     68:        size_t           lpos; /* where in list stack */
1.31      schwarze   69:        int              haspar; /* in paragraph: do we need Pp? */
1.32      schwarze   70:        enum outstate    oust; /* state of the mdoc output stream */
                     71:        int              wantws; /* let mdoc(7) output whitespace here */
1.31      schwarze   72:        char            *outbuf; /* text buffered for output */
                     73:        size_t           outbufsz; /* allocated size of outbuf */
                     74:        size_t           outbuflen; /* current length of outbuf */
1.1       schwarze   75: };
                     76:
                     77: enum   fmt {
                     78:        FMT_ITALIC,
                     79:        FMT_BOLD,
                     80:        FMT_CODE,
                     81:        FMT_LINK,
                     82:        FMT_ESCAPE,
                     83:        FMT_FILE,
                     84:        FMT_NBSP,
                     85:        FMT_INDEX,
                     86:        FMT_NULL,
                     87:        FMT__MAX
                     88: };
                     89:
                     90: enum   cmd {
                     91:        CMD_POD = 0,
                     92:        CMD_HEAD1,
                     93:        CMD_HEAD2,
                     94:        CMD_HEAD3,
                     95:        CMD_HEAD4,
                     96:        CMD_OVER,
                     97:        CMD_ITEM,
                     98:        CMD_BACK,
                     99:        CMD_BEGIN,
                    100:        CMD_END,
                    101:        CMD_FOR,
                    102:        CMD_ENCODING,
                    103:        CMD_CUT,
                    104:        CMD__MAX
                    105: };
                    106:
                    107: static const char *const cmds[CMD__MAX] = {
                    108:        "pod",          /* CMD_POD */
                    109:        "head1",        /* CMD_HEAD1 */
                    110:        "head2",        /* CMD_HEAD2 */
                    111:        "head3",        /* CMD_HEAD3 */
                    112:        "head4",        /* CMD_HEAD4 */
                    113:        "over",         /* CMD_OVER */
                    114:        "item",         /* CMD_ITEM */
                    115:        "back",         /* CMD_BACK */
                    116:        "begin",        /* CMD_BEGIN */
                    117:        "end",          /* CMD_END */
                    118:        "for",          /* CMD_FOR */
                    119:        "encoding",     /* CMD_ENCODING */
                    120:        "cut"           /* CMD_CUT */
                    121: };
                    122:
                    123: static const char fmts[FMT__MAX] = {
                    124:        'I',            /* FMT_ITALIC */
                    125:        'B',            /* FMT_BOLD */
                    126:        'C',            /* FMT_CODE */
                    127:        'L',            /* FMT_LINK */
                    128:        'E',            /* FMT_ESCAPE */
                    129:        'F',            /* FMT_FILE */
                    130:        'S',            /* FMT_NBSP */
                    131:        'X',            /* FMT_INDEX */
                    132:        'Z'             /* FMT_NULL */
                    133: };
                    134:
1.6       kristaps  135: static int     last;
                    136:
1.31      schwarze  137:
                    138: static void
                    139: outbuf_grow(struct state *st, size_t by)
                    140: {
                    141:
                    142:        st->outbufsz += (by / 128 + 1) * 128;
                    143:        st->outbuf = realloc(st->outbuf, st->outbufsz);
                    144:        if (NULL == st->outbuf) {
                    145:                perror(NULL);
                    146:                exit(EXIT_FAILURE);
                    147:        }
                    148: }
                    149:
                    150: static void
                    151: outbuf_addchar(struct state *st)
                    152: {
                    153:
                    154:        if (st->outbuflen + 2 >= st->outbufsz)
                    155:                outbuf_grow(st, 1);
                    156:        st->outbuf[st->outbuflen++] = last;
                    157:        if ('\\' == last)
                    158:                st->outbuf[st->outbuflen++] = 'e';
                    159:        st->outbuf[st->outbuflen] = '\0';
1.32      schwarze  160:        st->wantws = 0;
1.31      schwarze  161: }
                    162:
                    163: static void
                    164: outbuf_addstr(struct state *st, const char *str)
                    165: {
                    166:        size_t   slen;
                    167:
                    168:        slen = strlen(str);
                    169:        if (st->outbuflen + slen >= st->outbufsz)
                    170:                outbuf_grow(st, slen);
                    171:        memcpy(st->outbuf + st->outbuflen, str, slen+1);
1.33      schwarze  172:        st->outbuflen += slen;
1.31      schwarze  173:        last = str[slen - 1];
1.32      schwarze  174:        st->wantws = 0;
1.31      schwarze  175: }
                    176:
                    177: static void
                    178: outbuf_flush(struct state *st)
                    179: {
                    180:
                    181:        if (0 == st->outbuflen)
                    182:                return;
                    183:
                    184:        fputs(st->outbuf, stdout);
                    185:        *st->outbuf = '\0';
                    186:        st->outbuflen = 0;
1.32      schwarze  187:
                    188:        if (OUST_NL == st->oust)
                    189:                st->oust = OUST_TXT;
1.31      schwarze  190: }
                    191:
                    192: static void
1.32      schwarze  193: mdoc_newln(struct state *st)
1.31      schwarze  194: {
                    195:
1.32      schwarze  196:        if (OUST_NL == st->oust)
1.31      schwarze  197:                return;
1.32      schwarze  198:
1.31      schwarze  199:        putchar('\n');
                    200:        last = '\n';
1.32      schwarze  201:        st->oust = OUST_NL;
                    202:        st->wantws = 1;
1.31      schwarze  203: }
                    204:
1.1       schwarze  205: /*
                    206:  * Given buf[*start] is at the start of an escape name, read til the end
                    207:  * of the escape ('>') then try to do something with it.
                    208:  * Sets start to be one after the '>'.
1.32      schwarze  209:  *
                    210:  * This function does not care about output modes,
                    211:  * it merely appends text to the output buffer,
                    212:  * which can then be used in any mode.
1.1       schwarze  213:  */
                    214: static void
1.31      schwarze  215: formatescape(struct state *st, const char *buf, size_t *start, size_t end)
1.1       schwarze  216: {
                    217:        char             esc[16]; /* no more needed */
                    218:        size_t           i, max;
                    219:
                    220:        max = sizeof(esc) - 1;
                    221:        i = 0;
                    222:        /* Read til our buffer is full. */
                    223:        while (*start < end && '>' != buf[*start] && i < max)
                    224:                esc[i++] = buf[(*start)++];
                    225:        esc[i] = '\0';
                    226:
                    227:        if (i == max) {
                    228:                /* Too long... skip til we end. */
                    229:                while (*start < end && '>' != buf[*start])
                    230:                        (*start)++;
                    231:                return;
                    232:        } else if (*start >= end)
                    233:                return;
                    234:
                    235:        assert('>' == buf[*start]);
                    236:        (*start)++;
                    237:
                    238:        /*
                    239:         * TODO: right now, we only recognise the named escapes.
                    240:         * Just let the rest of them go.
                    241:         */
1.6       kristaps  242:        if (0 == strcmp(esc, "lt"))
1.31      schwarze  243:                outbuf_addstr(st, "\\(la");
1.1       schwarze  244:        else if (0 == strcmp(esc, "gt"))
1.31      schwarze  245:                outbuf_addstr(st, "\\(ra");
1.33      schwarze  246:        else if (0 == strcmp(esc, "verbar"))
1.31      schwarze  247:                outbuf_addstr(st, "\\(ba");
1.1       schwarze  248:        else if (0 == strcmp(esc, "sol"))
1.31      schwarze  249:                outbuf_addstr(st, "\\(sl");
1.1       schwarze  250: }
                    251:
                    252: /*
1.9       kristaps  253:  * Run some heuristics to intuit a link format.
1.19      kristaps  254:  * I set "start" to be the end of the sequence (last right-carrot) so
1.9       kristaps  255:  * that the caller can safely just continue processing.
1.19      kristaps  256:  * If this is just an empty tag, I'll return 0.
1.32      schwarze  257:  *
                    258:  * Always operates in OUST_MAC mode.
                    259:  * Mode handling is done by the caller.
1.9       kristaps  260:  */
                    261: static int
                    262: trylink(const char *buf, size_t *start, size_t end, size_t dsz)
                    263: {
1.21      kristaps  264:        size_t           linkstart, realend, linkend,
                    265:                         i, j, textsz, stack;
1.9       kristaps  266:
                    267:        /*
                    268:         * Scan to the start of the terminus.
                    269:         * This function is more or less replicated in the formatcode()
                    270:         * for null or index formatting codes.
1.23      kristaps  271:         * However, we're slightly different because we might have
                    272:         * nested escapes we need to ignore.
1.9       kristaps  273:         */
1.21      kristaps  274:        stack = 0;
1.19      kristaps  275:        for (linkstart = realend = *start; realend < end; realend++) {
1.23      kristaps  276:                if ('<' == buf[realend])
                    277:                        stack++;
1.19      kristaps  278:                if ('>' != buf[realend])
1.9       kristaps  279:                        continue;
1.23      kristaps  280:                else if (stack-- > 0)
                    281:                        continue;
                    282:                if (dsz == 1)
1.9       kristaps  283:                        break;
1.19      kristaps  284:                assert(realend > 0);
                    285:                if (' ' != buf[realend - 1])
1.9       kristaps  286:                        continue;
1.19      kristaps  287:                for (i = realend, j = 0; i < end && j < dsz; j++)
1.9       kristaps  288:                        if ('>' != buf[i++])
                    289:                                break;
                    290:                if (dsz == j)
                    291:                        break;
                    292:        }
1.19      kristaps  293:
                    294:        /* Ignore stubs. */
                    295:        if (realend == end || realend == *start)
1.9       kristaps  296:                return(0);
                    297:
1.19      kristaps  298:        /* Set linkend to the end of content. */
                    299:        linkend = dsz > 1 ? realend - 1 : realend;
1.18      kristaps  300:
1.19      kristaps  301:        /* Re-scan to see if we have a title or section. */
                    302:        for (textsz = *start; textsz < linkend; textsz++)
                    303:                if ('|' == buf[textsz] || '/' == buf[textsz])
1.18      kristaps  304:                        break;
                    305:
1.19      kristaps  306:        if (textsz < linkend && '|' == buf[textsz]) {
1.20      kristaps  307:                /* With title: set start, then end at section. */
1.19      kristaps  308:                linkstart = textsz + 1;
1.18      kristaps  309:                textsz = textsz - *start;
1.19      kristaps  310:                for (i = linkstart; i < linkend; i++)
                    311:                        if ('/' == buf[i])
                    312:                                break;
                    313:                if (i < linkend)
                    314:                        linkend = i;
1.20      kristaps  315:        } else if (textsz < linkend && '/' == buf[textsz]) {
                    316:                /* With section: set end at section. */
                    317:                linkend = textsz;
                    318:                textsz = 0;
                    319:        } else
                    320:                /* No title, no section. */
1.18      kristaps  321:                textsz = 0;
1.19      kristaps  322:
                    323:        *start = realend;
                    324:        j = linkend - linkstart;
                    325:
1.20      kristaps  326:        /* Do we have only subsection material? */
                    327:        if (0 == j && '/' == buf[linkend]) {
                    328:                linkstart = linkend + 1;
                    329:                linkend = dsz > 1 ? realend - 1 : realend;
                    330:                if (0 == (j = linkend - linkstart))
                    331:                        return(0);
                    332:                printf("Sx %.*s", (int)j, &buf[linkstart]);
                    333:                return(1);
                    334:        } else if (0 == j)
1.19      kristaps  335:                return(0);
                    336:
                    337:        /* See if we qualify as being a link or not. */
1.20      kristaps  338:        if ((j > 4 && 0 == memcmp("http:", &buf[linkstart], j)) ||
                    339:                (j > 5 && 0 == memcmp("https:", &buf[linkstart], j)) ||
                    340:                (j > 3 && 0 == memcmp("ftp:", &buf[linkstart], j)) ||
                    341:                (j > 4 && 0 == memcmp("sftp:", &buf[linkstart], j)) ||
                    342:                (j > 3 && 0 == memcmp("smb:", &buf[linkstart], j)) ||
                    343:                (j > 3 && 0 == memcmp("afs:", &buf[linkstart], j))) {
                    344:                /* Gross. */
                    345:                printf("Lk %.*s", (int)((dsz > 1 ? realend - 1 :
                    346:                        realend) - linkstart), &buf[linkstart]);
1.19      kristaps  347:                return(1);
                    348:        }
                    349:
                    350:        /* See if we qualify as a mailto. */
1.20      kristaps  351:        if (j > 6 && 0 == memcmp("mailto:", &buf[linkstart], j)) {
1.19      kristaps  352:                printf("Mt %.*s", (int)j, &buf[linkstart]);
                    353:                return(1);
                    354:        }
                    355:
                    356:        /* See if we're a foo(5), foo(5x), or foo(5xx) manpage. */
                    357:        if ((j > 3 && ')' == buf[linkend - 1]) &&
                    358:                ('(' == buf[linkend - 3])) {
                    359:                printf("Xr %.*s %c", (int)(j - 3),
                    360:                        &buf[linkstart], buf[linkend - 2]);
                    361:                return(1);
                    362:        } else if ((j > 4 && ')' == buf[linkend - 1]) &&
                    363:                ('(' == buf[linkend - 4])) {
                    364:                printf("Xr %.*s %.*s", (int)(j - 4),
                    365:                        &buf[linkstart], 2, &buf[linkend - 3]);
                    366:                return(1);
                    367:        } else if ((j > 5 && ')' == buf[linkend - 1]) &&
                    368:                ('(' == buf[linkend - 5])) {
                    369:                printf("Xr %.*s %.*s", (int)(j - 5),
                    370:                        &buf[linkstart], 3, &buf[linkend - 4]);
                    371:                return(1);
                    372:        }
                    373:
                    374:        /* Last try: do we have a double-colon? */
                    375:        for (i = linkstart + 1; i < linkend; i++)
                    376:                if (':' == buf[i] && ':' == buf[i - 1])
1.18      kristaps  377:                        break;
1.9       kristaps  378:
1.19      kristaps  379:        if (i < linkend)
1.10      kristaps  380:                printf("Xr %.*s " PERL_SECTION,
1.19      kristaps  381:                        (int)j, &buf[linkstart]);
1.9       kristaps  382:        else
1.19      kristaps  383:                printf("Xr %.*s 1", (int)j, &buf[linkstart]);
1.9       kristaps  384:
                    385:        return(1);
                    386: }
                    387:
1.13      kristaps  388: /*
                    389:  * Doclifting: if we're a bold "-xx" and we're in the SYNOPSIS section,
                    390:  * then it's likely that we're a flag.
                    391:  * Our flag might be followed by an argument, so make sure that we're
                    392:  * accounting for that, too.
                    393:  * If we don't have a flag at all, however, then assume we're an "Ar".
1.32      schwarze  394:  *
                    395:  * Always operates in OUST_MAC mode.
                    396:  * Mode handlinf is done by the caller.
1.13      kristaps  397:  */
                    398: static void
                    399: dosynopsisfl(const char *buf, size_t *start, size_t end)
                    400: {
                    401:        size_t   i;
                    402: again:
1.14      kristaps  403:        assert(*start + 1 < end);
                    404:        assert('-' == buf[*start]);
                    405:
                    406:        if ( ! isalnum((int)buf[*start + 1]) &&
                    407:                '?' != buf[*start + 1] &&
                    408:                '-' != buf[*start + 1]) {
                    409:                (*start)--;
                    410:                fputs("Ar ", stdout);
                    411:                return;
                    412:        }
                    413:
1.13      kristaps  414:        (*start)++;
                    415:        for (i = *start; i < end; i++)
                    416:                if (isalnum((int)buf[i]))
                    417:                        continue;
1.14      kristaps  418:                else if ('?' == buf[i])
                    419:                        continue;
1.13      kristaps  420:                else if ('-' == buf[i])
                    421:                        continue;
                    422:                else if ('_' == buf[i])
                    423:                        continue;
                    424:                else
                    425:                        break;
                    426:
                    427:        assert(i < end);
                    428:
                    429:        if ( ! (' ' == buf[i] || '>' == buf[i])) {
                    430:                printf("Ar ");
                    431:                return;
                    432:        }
                    433:
                    434:        printf("Fl ");
                    435:        if (end - *start > 1 &&
                    436:                isupper((int)buf[*start]) &&
                    437:                islower((int)buf[*start + 1]) &&
                    438:                (end - *start == 2 ||
                    439:                 ' ' == buf[*start + 2]))
                    440:                printf("\\&");
                    441:        printf("%.*s ", (int)(i - *start), &buf[*start]);
                    442:        *start = i;
                    443:
                    444:        if (' ' == buf[i]) {
                    445:                while (i < end && ' ' == buf[i])
                    446:                        i++;
                    447:                assert(i < end);
                    448:                if ('-' == buf[i]) {
                    449:                        *start = i;
                    450:                        goto again;
                    451:                }
                    452:                printf("Ar ");
                    453:                *start = i;
                    454:        }
                    455: }
                    456:
1.9       kristaps  457: /*
1.1       schwarze  458:  * We're at the character in front of a format code, which is structured
                    459:  * like X<...> and can contain nested format codes.
                    460:  * This consumes the whole format code, and any nested format codes, til
                    461:  * the end of matched production.
1.6       kristaps  462:  * If "nomacro", then we don't print any macros, just contained data
                    463:  * (e.g., following "Sh" or "Nm").
1.15      kristaps  464:  * "pos" is only significant in SYNOPSIS, and should be 0 when invoked
                    465:  * as the first format code on a line (for decoration as an "Nm"),
                    466:  * non-zero otherwise.
1.32      schwarze  467:  *
                    468:  * Output mode handling is most complicated here.
                    469:  * We may enter in any mode.
                    470:  * We usually exit in OUST_MAC mode, except when
                    471:  * entering without OUST_MAC and the code is invalid.
1.1       schwarze  472:  */
1.33      schwarze  473: static int
1.15      kristaps  474: formatcode(struct state *st, const char *buf, size_t *start,
1.32      schwarze  475:        size_t end, int nomacro, int pos)
1.1       schwarze  476: {
                    477:        enum fmt         fmt;
1.5       kristaps  478:        size_t           i, j, dsz;
1.1       schwarze  479:
                    480:        assert(*start + 1 < end);
                    481:        assert('<' == buf[*start + 1]);
                    482:
1.6       kristaps  483:        /*
                    484:         * First, look up the format code.
1.30      schwarze  485:         * If it's not valid, treat it as a NOOP.
1.6       kristaps  486:         */
                    487:        for (fmt = 0; fmt < FMT__MAX; fmt++)
                    488:                if (buf[*start] == fmts[fmt])
                    489:                        break;
                    490:
1.5       kristaps  491:        /*
                    492:         * Determine whether we're overriding our delimiter.
                    493:         * According to POD, if we have more than one '<' followed by a
                    494:         * space, then we need a space followed by matching '>' to close
                    495:         * the expression.
                    496:         * Otherwise we use the usual '<' and '>' matched pair.
                    497:         */
                    498:        i = *start + 1;
                    499:        while (i < end && '<' == buf[i])
                    500:                i++;
                    501:        assert(i > *start + 1);
                    502:        dsz = i - (*start + 1);
                    503:        if (dsz > 1 && (i >= end || ' ' != buf[i]))
                    504:                dsz = 1;
                    505:
                    506:        /* Remember, if dsz>1, to jump the trailing space. */
                    507:        *start += dsz + 1 + (dsz > 1 ? 1 : 0);
1.1       schwarze  508:
                    509:        /*
1.6       kristaps  510:         * Escapes and ignored codes (NULL and INDEX) don't print macro
                    511:         * sequences, so just output them like normal text before
                    512:         * processing for real macros.
1.1       schwarze  513:         */
                    514:        if (FMT_ESCAPE == fmt) {
1.31      schwarze  515:                formatescape(st, buf, start, end);
1.33      schwarze  516:                return(0);
1.1       schwarze  517:        } else if (FMT_NULL == fmt || FMT_INDEX == fmt) {
1.5       kristaps  518:                /*
1.6       kristaps  519:                 * Just consume til the end delimiter, accounting for
                    520:                 * whether it's a custom one.
1.5       kristaps  521:                 */
                    522:                for ( ; *start < end; (*start)++) {
                    523:                        if ('>' != buf[*start])
                    524:                                continue;
                    525:                        else if (dsz == 1)
                    526:                                break;
                    527:                        assert(*start > 0);
                    528:                        if (' ' != buf[*start - 1])
                    529:                                continue;
                    530:                        i = *start;
                    531:                        for (j = 0; i < end && j < dsz; j++)
                    532:                                if ('>' != buf[i++])
                    533:                                        break;
                    534:                        if (dsz != j)
                    535:                                continue;
                    536:                        (*start) += dsz;
                    537:                        break;
                    538:                }
1.24      kristaps  539:                if (*start < end) {
                    540:                        assert('>' == buf[*start]);
                    541:                        (*start)++;
                    542:                }
                    543:                if (isspace(last))
                    544:                        while (*start < end && isspace((int)buf[*start]))
                    545:                                (*start)++;
1.33      schwarze  546:                return(0);
1.1       schwarze  547:        }
                    548:
1.6       kristaps  549:        /*
                    550:         * Check whether we're supposed to print macro stuff (this is
                    551:         * suppressed in, e.g., "Nm" and "Sh" macros).
                    552:         */
1.30      schwarze  553:        if (FMT__MAX != fmt && !nomacro) {
1.32      schwarze  554:
                    555:                /*
                    556:                 * We may already have wantws if there was whitespace
                    557:                 * before the code ("text B<text"), but initial
                    558:                 * whitespace inside our scope ("textB< text")
                    559:                 * allows to break at this point as well.
                    560:                 */
                    561:
                    562:                st->wantws |= ' ' == buf[*start];
1.31      schwarze  563:
1.1       schwarze  564:                /*
1.31      schwarze  565:                 * If we are on a text line and there is no
                    566:                 * whitespace before our content, we have to make
                    567:                 * the previous word a prefix to the macro line.
1.32      schwarze  568:                 * In the following, mdoc_newln() must not be used
                    569:                 * lest we clobber out output state.
1.1       schwarze  570:                 */
1.31      schwarze  571:
1.32      schwarze  572:                if (OUST_MAC != st->oust && !st->wantws) {
                    573:                        if (OUST_NL != st->oust)
1.31      schwarze  574:                                putchar('\n');
                    575:                        printf(".Pf ");
                    576:                }
                    577:
                    578:                outbuf_flush(st);
                    579:
                    580:                /* Whitespace is easier to suppress on macro lines. */
                    581:
1.32      schwarze  582:                if (OUST_MAC == st->oust && !st->wantws)
                    583:                        printf(" Ns ");
1.31      schwarze  584:
                    585:                /* Unless we are on a macro line, start one. */
                    586:
1.32      schwarze  587:                if (OUST_MAC != st->oust && st->wantws) {
                    588:                        if (OUST_NL != st->oust)
1.6       kristaps  589:                                putchar('\n');
1.1       schwarze  590:                        putchar('.');
1.31      schwarze  591:                } else
1.1       schwarze  592:                        putchar(' ');
1.31      schwarze  593:
1.32      schwarze  594:                /*
                    595:                 * Print the macro corresponding to this format code,
                    596:                 * and update the output state afterwards.
                    597:                 */
1.6       kristaps  598:
1.1       schwarze  599:                switch (fmt) {
                    600:                case (FMT_ITALIC):
                    601:                        printf("Em ");
                    602:                        break;
                    603:                case (FMT_BOLD):
1.14      kristaps  604:                        if (SECT_SYNOPSIS == st->sect) {
                    605:                                if (1 == dsz && '-' == buf[*start])
                    606:                                        dosynopsisfl(buf, start, end);
1.15      kristaps  607:                                else if (0 == pos)
                    608:                                        printf("Nm ");
1.14      kristaps  609:                                else
                    610:                                        printf("Ar ");
                    611:                                break;
                    612:                        }
1.27      schwarze  613:                        if (0 == strncmp(buf + *start, "NULL", 4) &&
                    614:                            ('=' == buf[*start + 4] ||
                    615:                             '>' == buf[*start + 4]))
                    616:                                printf("Dv ");
                    617:                        else
                    618:                                printf("Sy ");
1.1       schwarze  619:                        break;
                    620:                case (FMT_CODE):
1.2       schwarze  621:                        printf("Qo Li ");
1.1       schwarze  622:                        break;
                    623:                case (FMT_LINK):
1.19      kristaps  624:                        /* Try to link; use "No" if it's empty. */
1.9       kristaps  625:                        if ( ! trylink(buf, start, end, dsz))
                    626:                                printf("No ");
1.1       schwarze  627:                        break;
                    628:                case (FMT_FILE):
                    629:                        printf("Pa ");
                    630:                        break;
                    631:                case (FMT_NBSP):
                    632:                        printf("No ");
                    633:                        break;
                    634:                default:
                    635:                        abort();
                    636:                }
1.32      schwarze  637:                st->oust = OUST_MAC;
                    638:                st->wantws = 1;
1.31      schwarze  639:        } else
                    640:                outbuf_flush(st);
1.1       schwarze  641:
                    642:        /*
1.6       kristaps  643:         * Process until we reach the end marker (e.g., '>') or until we
1.5       kristaps  644:         * find a nested format code.
1.1       schwarze  645:         * Don't emit any newlines: since we're on a macro line, we
                    646:         * don't want to break the line.
                    647:         */
                    648:        while (*start < end) {
1.5       kristaps  649:                if ('>' == buf[*start] && 1 == dsz) {
1.1       schwarze  650:                        (*start)++;
                    651:                        break;
1.5       kristaps  652:                } else if ('>' == buf[*start] &&
                    653:                                ' ' == buf[*start - 1]) {
                    654:                        /*
                    655:                         * Handle custom delimiters.
                    656:                         * These require a certain number of
                    657:                         * space-preceded carrots before we're really at
                    658:                         * the end.
                    659:                         */
                    660:                        i = *start;
                    661:                        for (j = 0; i < end && j < dsz; j++)
                    662:                                if ('>' != buf[i++])
                    663:                                        break;
                    664:                        if (dsz == j) {
                    665:                                *start += dsz;
                    666:                                break;
                    667:                        }
1.1       schwarze  668:                }
1.34      schwarze  669:                if (*start + 1 < end && '<' == buf[*start + 1] &&
                    670:                    'A' <= buf[*start] && 'Z' >= buf[*start]) {
1.32      schwarze  671:                        formatcode(st, buf, start, end, nomacro, 1);
1.1       schwarze  672:                        continue;
                    673:                }
1.3       schwarze  674:
1.32      schwarze  675:                /* Suppress newlines and multiple spaces. */
                    676:
                    677:                last = buf[(*start)++];
                    678:                if (' ' == last || '\n' == last) {
                    679:                        putchar(' ');
                    680:                        while (*start < end && ' ' == buf[*start])
                    681:                                (*start)++;
                    682:                        continue;
                    683:                }
                    684:
1.33      schwarze  685:                if (OUST_MAC == st->oust && FMT__MAX != fmt) {
1.32      schwarze  686:                        if ( ! st->wantws) {
                    687:                                printf(" Ns ");
                    688:                                st->wantws = 1;
                    689:                        }
                    690:
                    691:                        /*
                    692:                         * Escape macro-like words.
                    693:                         * This matches "Xx " and "XxEOLN".
                    694:                         */
                    695:
                    696:                        if (end - *start > 0 &&
                    697:                            isupper((unsigned char)last) &&
                    698:                            islower((unsigned char)buf[*start]) &&
                    699:                            (end - *start == 1 ||
                    700:                             ' ' == buf[*start + 1] ||
                    701:                             '>' == buf[*start + 1]))
                    702:                                printf("\\&");
                    703:                }
1.3       schwarze  704:
1.32      schwarze  705:                putchar(last);
1.4       schwarze  706:
1.8       kristaps  707:                /* Protect against character escapes. */
1.32      schwarze  708:
1.8       kristaps  709:                if ('\\' == last)
                    710:                        putchar('e');
1.1       schwarze  711:        }
1.2       schwarze  712:
1.33      schwarze  713:        if (FMT__MAX == fmt)
                    714:                return(0);
                    715:
1.2       schwarze  716:        if ( ! nomacro && FMT_CODE == fmt)
                    717:                printf(" Qc ");
1.1       schwarze  718:
1.33      schwarze  719:        st->wantws = ' ' == last;
                    720:        return(1);
1.1       schwarze  721: }
                    722:
                    723: /*
                    724:  * Calls formatcode() til the end of a paragraph.
1.32      schwarze  725:  * Goes to OUST_MAC mode and stays there when returning,
                    726:  * such that the caller can add arguments to the macro line
                    727:  * before closing it out.
1.1       schwarze  728:  */
                    729: static void
1.32      schwarze  730: formatcodeln(struct state *st, const char *linemac,
                    731:        const char *buf, size_t *start, size_t end, int nomacro)
1.1       schwarze  732: {
1.33      schwarze  733:        int      gotmacro, wantws;
1.1       schwarze  734:
1.32      schwarze  735:        assert(OUST_NL == st->oust);
                    736:        assert(st->wantws);
                    737:        printf(".%s ", linemac);
                    738:        st->oust = OUST_MAC;
                    739:
1.33      schwarze  740:        gotmacro = 0;
1.1       schwarze  741:        while (*start < end)  {
1.33      schwarze  742:                wantws = ' ' == buf[*start] || '\n' == buf[*start];
                    743:                if (wantws) {
                    744:                        last = ' ';
                    745:                        do {
                    746:                                (*start)++;
                    747:                        } while (*start < end && ' ' == buf[*start]);
                    748:                }
                    749:
1.34      schwarze  750:                if (*start + 1 < end && '<' == buf[*start + 1] &&
                    751:                    'A' <= buf[*start] && 'Z' >= buf[*start]) {
1.33      schwarze  752:                        st->wantws |= wantws;
                    753:                        gotmacro = formatcode(st, buf,
                    754:                            start, end, nomacro, 1);
1.1       schwarze  755:                        continue;
                    756:                }
1.32      schwarze  757:
1.33      schwarze  758:                if (gotmacro) {
                    759:                        if (*start < end || st->outbuflen) {
                    760:                                if (st->wantws ||
                    761:                                    (wantws && !st->outbuflen))
                    762:                                        printf(" No ");
                    763:                                else
                    764:                                        printf(" Ns ");
                    765:                        }
                    766:                        gotmacro = 0;
                    767:                }
                    768:                outbuf_flush(st);
                    769:                st->wantws = wantws;
                    770:
                    771:                if (*start >= end)
                    772:                        break;
                    773:
                    774:                if (st->wantws) {
                    775:                        putchar(' ');
                    776:                        st->wantws = 0;
1.32      schwarze  777:                }
                    778:
1.4       schwarze  779:                /*
                    780:                 * Since we're already on a macro line, we want to make
                    781:                 * sure that we don't inadvertently invoke a macro.
                    782:                 * We need to do this carefully because section names
                    783:                 * are used in troff and we don't want to escape
                    784:                 * something that needn't be escaped.
                    785:                 */
                    786:                if (' ' == last && end - *start > 1 &&
1.33      schwarze  787:                    isupper((unsigned char)buf[*start]) &&
                    788:                    islower((unsigned char)buf[*start + 1]) &&
                    789:                    (end - *start == 2 || ' ' == buf[*start + 2]))
1.4       schwarze  790:                        printf("\\&");
                    791:
1.33      schwarze  792:                putchar(last = buf[*start]);
1.8       kristaps  793:
                    794:                /* Protect against character escapes. */
1.33      schwarze  795:
1.8       kristaps  796:                if ('\\' == last)
                    797:                        putchar('e');
                    798:
1.1       schwarze  799:                (*start)++;
                    800:        }
                    801: }
                    802:
                    803: /*
1.4       schwarze  804:  * Guess at what kind of list we are.
                    805:  * These are taken straight from the POD manual.
                    806:  * I don't know what people do in real life.
                    807:  */
                    808: static enum list
                    809: listguess(const char *buf, size_t start, size_t end)
                    810: {
                    811:        size_t           len = end - start;
                    812:
                    813:        assert(end >= start);
                    814:
                    815:        if (len == 1 && '*' == buf[start])
                    816:                return(LIST_BULLET);
                    817:        if (len == 2 && '1' == buf[start] && '.' == buf[start + 1])
                    818:                return(LIST_ENUM);
                    819:        else if (len == 1 && '1' == buf[start])
                    820:                return(LIST_ENUM);
                    821:        else
                    822:                return(LIST_TAG);
                    823: }
                    824:
                    825: /*
1.1       schwarze  826:  * A command paragraph, as noted in the perlpod manual, just indicates
                    827:  * that we should do something, optionally with some text to print as
                    828:  * well.
1.32      schwarze  829:  * From the perspective of external callers,
                    830:  * always stays in OUST_NL/wantws mode,
                    831:  * but its children do use OUST_MAC.
1.1       schwarze  832:  */
                    833: static void
                    834: command(struct state *st, const char *buf, size_t start, size_t end)
                    835: {
                    836:        size_t           len, csz;
                    837:        enum cmd         cmd;
                    838:
                    839:        assert('=' == buf[start]);
                    840:        start++;
                    841:        len = end - start;
                    842:
                    843:        for (cmd = 0; cmd < CMD__MAX; cmd++) {
                    844:                csz = strlen(cmds[cmd]);
                    845:                if (len < csz)
                    846:                        continue;
                    847:                if (0 == memcmp(&buf[start], cmd[cmds], csz))
                    848:                        break;
                    849:        }
                    850:
                    851:        /* Ignore bogus commands. */
                    852:
                    853:        if (CMD__MAX == cmd)
                    854:                return;
                    855:
                    856:        start += csz;
1.8       kristaps  857:        while (start < end && ' ' == buf[start])
                    858:                start++;
                    859:
1.1       schwarze  860:        len = end - start;
                    861:
                    862:        if (st->paused) {
                    863:                st->paused = CMD_END != cmd;
                    864:                return;
                    865:        }
                    866:
                    867:        switch (cmd) {
                    868:        case (CMD_POD):
                    869:                break;
                    870:        case (CMD_HEAD1):
                    871:                /*
                    872:                 * The behaviour of head= follows from a quick glance at
                    873:                 * how pod2man handles it.
                    874:                 */
1.11      kristaps  875:                st->sect = SECT_NONE;
                    876:                if (end - start == 4) {
1.1       schwarze  877:                        if (0 == memcmp(&buf[start], "NAME", 4))
1.11      kristaps  878:                                st->sect = SECT_NAME;
                    879:                } else if (end - start == 8) {
                    880:                        if (0 == memcmp(&buf[start], "SYNOPSIS", 8))
                    881:                                st->sect = SECT_SYNOPSIS;
                    882:                }
1.32      schwarze  883:                formatcodeln(st, "Sh", buf, &start, end, 1);
                    884:                mdoc_newln(st);
1.1       schwarze  885:                st->haspar = 1;
                    886:                break;
                    887:        case (CMD_HEAD2):
1.32      schwarze  888:                formatcodeln(st, "Ss", buf, &start, end, 1);
                    889:                mdoc_newln(st);
1.1       schwarze  890:                st->haspar = 1;
                    891:                break;
                    892:        case (CMD_HEAD3):
                    893:                puts(".Pp");
1.32      schwarze  894:                formatcodeln(st, "Em", buf, &start, end, 0);
                    895:                mdoc_newln(st);
1.1       schwarze  896:                puts(".Pp");
                    897:                st->haspar = 1;
                    898:                break;
                    899:        case (CMD_HEAD4):
                    900:                puts(".Pp");
1.32      schwarze  901:                formatcodeln(st, "No", buf, &start, end, 0);
                    902:                mdoc_newln(st);
1.1       schwarze  903:                puts(".Pp");
                    904:                st->haspar = 1;
                    905:                break;
                    906:        case (CMD_OVER):
1.4       schwarze  907:                /*
                    908:                 * If we have an existing list that hasn't had an =item
                    909:                 * yet, then make sure that we open it now.
                    910:                 * We use the default list type, but that can't be
                    911:                 * helped (we haven't seen any items yet).
1.1       schwarze  912:                 */
1.4       schwarze  913:                if (st->lpos > 0)
                    914:                        if (LIST__MAX == st->lstack[st->lpos - 1]) {
                    915:                                st->lstack[st->lpos - 1] = LIST_TAG;
                    916:                                puts(".Bl -tag -width Ds");
                    917:                        }
                    918:                st->lpos++;
                    919:                assert(st->lpos < LIST_STACKSZ);
                    920:                st->lstack[st->lpos - 1] = LIST__MAX;
1.1       schwarze  921:                break;
                    922:        case (CMD_ITEM):
1.6       kristaps  923:                if (0 == st->lpos) {
                    924:                        /*
                    925:                         * Bad markup.
                    926:                         * Try to compensate.
                    927:                         */
                    928:                        st->lstack[st->lpos] = LIST__MAX;
                    929:                        st->lpos++;
                    930:                }
1.4       schwarze  931:                assert(st->lpos > 0);
                    932:                /*
                    933:                 * If we're the first =item, guess at what our content
                    934:                 * will be: "*" is a bullet list, "1." is a numbered
                    935:                 * list, and everything is tagged.
                    936:                 */
                    937:                if (LIST__MAX == st->lstack[st->lpos - 1]) {
                    938:                        st->lstack[st->lpos - 1] =
                    939:                                listguess(buf, start, end);
                    940:                        switch (st->lstack[st->lpos - 1]) {
                    941:                        case (LIST_BULLET):
                    942:                                puts(".Bl -bullet");
                    943:                                break;
                    944:                        case (LIST_ENUM):
                    945:                                puts(".Bl -enum");
                    946:                                break;
                    947:                        default:
                    948:                                puts(".Bl -tag -width Ds");
                    949:                                break;
                    950:                        }
                    951:                }
                    952:                switch (st->lstack[st->lpos - 1]) {
                    953:                case (LIST_TAG):
1.32      schwarze  954:                        formatcodeln(st, "It", buf, &start, end, 0);
                    955:                        mdoc_newln(st);
1.4       schwarze  956:                        break;
                    957:                case (LIST_ENUM):
                    958:                        /* FALLTHROUGH */
                    959:                case (LIST_BULLET):
                    960:                        /*
                    961:                         * Abandon the remainder of the paragraph
                    962:                         * because we're going to be a bulletted or
                    963:                         * numbered list.
                    964:                         */
                    965:                        puts(".It");
                    966:                        break;
                    967:                default:
                    968:                        abort();
                    969:                }
1.1       schwarze  970:                st->haspar = 1;
                    971:                break;
                    972:        case (CMD_BACK):
1.4       schwarze  973:                /* Make sure we don't back over the stack. */
                    974:                if (st->lpos > 0) {
                    975:                        st->lpos--;
                    976:                        puts(".El");
                    977:                }
1.1       schwarze  978:                break;
                    979:        case (CMD_BEGIN):
                    980:                /*
                    981:                 * We disregard all types for now.
                    982:                 * TODO: process at least "text" in a -literal block.
                    983:                 */
                    984:                st->paused = 1;
                    985:                break;
                    986:        case (CMD_FOR):
                    987:                /*
                    988:                 * We ignore all types of encodings and formats
                    989:                 * unilaterally.
                    990:                 */
                    991:                break;
                    992:        case (CMD_ENCODING):
                    993:                break;
                    994:        case (CMD_CUT):
                    995:                st->parsing = 0;
                    996:                return;
                    997:        default:
                    998:                abort();
                    999:        }
                   1000:
                   1001:        /* Any command (but =cut) makes us start parsing. */
                   1002:        st->parsing = 1;
                   1003: }
                   1004:
                   1005: /*
                   1006:  * Just pump out the line in a verbatim block.
1.32      schwarze 1007:  * From the perspective of external callers,
                   1008:  * always stays in OUST_NL/wantws mode.
1.1       schwarze 1009:  */
                   1010: static void
1.35    ! schwarze 1011: verbatim(struct state *st, char *buf, size_t start, size_t end)
1.1       schwarze 1012: {
1.35    ! schwarze 1013:        size_t           i, ift, ifo, ifa, ifc;
        !          1014:        char            *cp;
1.1       schwarze 1015:
1.35    ! schwarze 1016:        if ( ! st->parsing || st->paused || start == end)
1.1       schwarze 1017:                return;
1.22      kristaps 1018: again:
                   1019:        /*
                   1020:         * If we're in the SYNOPSIS, see if we're an #include block.
                   1021:         * If we are, then print the "In" macro and re-loop.
                   1022:         * This handles any number of inclusions, but only when they
                   1023:         * come before the remaining parts...
                   1024:         */
                   1025:        if (SECT_SYNOPSIS == st->sect) {
                   1026:                i = start;
1.35    ! schwarze 1027:                while (i < end && buf[i] == ' ')
        !          1028:                        i++;
1.22      kristaps 1029:                if (i == end)
                   1030:                        return;
1.35    ! schwarze 1031:
1.22      kristaps 1032:                /* We're an include block! */
                   1033:                if (end - i > 10 &&
                   1034:                        0 == memcmp(&buf[i], "#include <", 10)) {
                   1035:                        start = i + 10;
                   1036:                        while (start < end && ' ' == buf[start])
                   1037:                                start++;
                   1038:                        fputs(".In ", stdout);
                   1039:                        /* Stop til the '>' marker or we hit eoln. */
                   1040:                        while (start < end &&
                   1041:                                '>' != buf[start] && '\n' != buf[start])
                   1042:                                putchar(buf[start++]);
                   1043:                        putchar('\n');
                   1044:                        if (start < end && '>' == buf[start])
                   1045:                                start++;
                   1046:                        if (start < end && '\n' == buf[start])
                   1047:                                start++;
                   1048:                        if (start < end)
                   1049:                                goto again;
                   1050:                        return;
                   1051:                }
1.35    ! schwarze 1052:
        !          1053:                /* Parse function declaration. */
        !          1054:                ifo = ifa = ifc = 0;
        !          1055:                for (ift = i; i < end && buf[i] != '\n'; i++) {
        !          1056:                        if (ifa) {
        !          1057:                                if (buf[i] == ')')
        !          1058:                                        ifc = i;
        !          1059:                        } else if (ifo && buf[i] == '(')
        !          1060:                                ifa = i;
        !          1061:                        else if (buf[i] == ' ')
        !          1062:                                ifo = i;
        !          1063:                }
        !          1064:
        !          1065:                /* Encode function declaration. */
        !          1066:                if (ifc) {
        !          1067:                        buf[ifo++] = '\0';
        !          1068:                        printf(".Ft %s", buf + ift);
        !          1069:                        if (buf[ifo] == '*') {
        !          1070:                                fputs(" *", stdout);
        !          1071:                                ifo++;
        !          1072:                        }
        !          1073:                        putchar('\n');
        !          1074:                        buf[ifa++] = '\0';
        !          1075:                        printf(".Fo %s\n", buf + ifo);
        !          1076:                        buf[ifc++] = '\0';
        !          1077:                        for (;;) {
        !          1078:                                cp = strchr(buf + ifa, ',');
        !          1079:                                if (cp != NULL)
        !          1080:                                        *cp = '\0';
        !          1081:                                printf(".Fa \"%s\"\n", buf + ifa);
        !          1082:                                if (cp == NULL)
        !          1083:                                        break;
        !          1084:                                ifa = cp - buf + 1;
        !          1085:                        }
        !          1086:                        puts(".Fc");
        !          1087:                        if (buf[ifc] == ';')
        !          1088:                                ifc++;
        !          1089:                        if (ifc < i) {
        !          1090:                                buf[i] = '\0';
        !          1091:                                puts(buf + ifc);
        !          1092:                        }
        !          1093:                        start = i + 1;
        !          1094:                        if (start < end)
        !          1095:                                goto again;
        !          1096:                        return;
        !          1097:                }
1.22      kristaps 1098:        }
                   1099:
1.1       schwarze 1100:        puts(".Bd -literal");
1.8       kristaps 1101:        for (last = ' '; start < end; start++) {
                   1102:                /*
                   1103:                 * Handle accidental macros (newline starting with
                   1104:                 * control character) and escapes.
                   1105:                 */
                   1106:                if ('\n' == last)
1.7       kristaps 1107:                        if ('.' == buf[start] || '\'' == buf[start])
                   1108:                                printf("\\&");
1.8       kristaps 1109:                putchar(last = buf[start]);
                   1110:                if ('\\' == buf[start])
                   1111:                        printf("e");
1.7       kristaps 1112:        }
1.31      schwarze 1113:        putchar(last = '\n');
1.1       schwarze 1114:        puts(".Ed");
                   1115: }
                   1116:
                   1117: /*
1.13      kristaps 1118:  * See dosynopsisop().
                   1119:  */
                   1120: static int
                   1121: hasmatch(const char *buf, size_t start, size_t end)
                   1122: {
                   1123:        size_t   stack;
                   1124:
                   1125:        for (stack = 0; start < end; start++)
                   1126:                if (buf[start] == '[')
                   1127:                        stack++;
                   1128:                else if (buf[start] == ']' && 0 == stack)
                   1129:                        return(1);
                   1130:                else if (buf[start] == ']')
                   1131:                        stack--;
                   1132:        return(0);
                   1133: }
                   1134:
                   1135: /*
                   1136:  * If we're in the SYNOPSIS section and we've encounter braces in an
                   1137:  * ordinary paragraph, then try to see whether we're an [-option].
                   1138:  * Do this, if we're an opening bracket, by first seeing if we have a
                   1139:  * matching end via hasmatch().
                   1140:  * If we're an ending bracket, see if we have a stack already.
                   1141:  */
                   1142: static int
1.32      schwarze 1143: dosynopsisop(struct state *st, const char *buf,
                   1144:        size_t *start, size_t end, size_t *opstack)
1.13      kristaps 1145: {
                   1146:
                   1147:        assert('[' == buf[*start] || ']' == buf[*start]);
                   1148:
                   1149:        if ('[' == buf[*start] && hasmatch(buf, *start + 1, end)) {
1.32      schwarze 1150:                mdoc_newln(st);
1.13      kristaps 1151:                puts(".Oo");
                   1152:                (*opstack)++;
                   1153:        } else if ('[' == buf[*start])
                   1154:                return(0);
                   1155:
                   1156:        if (']' == buf[*start] && *opstack > 0) {
1.32      schwarze 1157:                mdoc_newln(st);
1.13      kristaps 1158:                puts(".Oc");
                   1159:                (*opstack)--;
                   1160:        } else if (']' == buf[*start])
                   1161:                return(0);
                   1162:
                   1163:        (*start)++;
1.31      schwarze 1164:        last = '\n';
1.13      kristaps 1165:        while (' ' == buf[*start])
                   1166:                (*start)++;
                   1167:        return(1);
                   1168: }
                   1169:
                   1170: /*
1.17      kristaps 1171:  * Format multiple "Nm" manpage names in the NAME section.
1.32      schwarze 1172:  * From the perspective of external callers,
                   1173:  * always stays in OUST_NL/wantws mode,
                   1174:  * but its children do use OUST_MAC.
1.17      kristaps 1175:  */
                   1176: static void
                   1177: donamenm(struct state *st, const char *buf, size_t *start, size_t end)
                   1178: {
                   1179:        size_t   word;
                   1180:
1.32      schwarze 1181:        assert(OUST_NL == st->oust);
                   1182:        assert(st->wantws);
                   1183:
1.17      kristaps 1184:        while (*start < end && ' ' == buf[*start])
                   1185:                (*start)++;
                   1186:
                   1187:        if (end == *start) {
                   1188:                puts(".Nm unknown");
                   1189:                return;
                   1190:        }
                   1191:
                   1192:        while (*start < end) {
                   1193:                for (word = *start; word < end; word++)
                   1194:                        if (',' == buf[word])
                   1195:                                break;
1.32      schwarze 1196:                formatcodeln(st, "Nm", buf, start, word, 1);
1.17      kristaps 1197:                if (*start == end) {
1.32      schwarze 1198:                        mdoc_newln(st);
                   1199:                        break;
1.17      kristaps 1200:                }
                   1201:                assert(',' == buf[*start]);
1.32      schwarze 1202:                printf(" ,");
                   1203:                mdoc_newln(st);
1.17      kristaps 1204:                (*start)++;
                   1205:                while (*start < end && ' ' == buf[*start])
                   1206:                        (*start)++;
                   1207:        }
                   1208: }
                   1209:
                   1210: /*
1.1       schwarze 1211:  * Ordinary paragraph.
                   1212:  * Well, this is really the hardest--POD seems to assume that, for
                   1213:  * example, a leading space implies a newline, and so on.
                   1214:  * Lots of other snakes in the grass: escaping a newline followed by a
                   1215:  * period (accidental mdoc(7) control), double-newlines after macro
                   1216:  * passages, etc.
1.32      schwarze 1217:  *
                   1218:  * Uses formatcode() to go to OUST_MAC mode
                   1219:  * and outbuf_flush() to go to OUST_TXT mode.
                   1220:  * Main text mode wantws handling is in this function.
                   1221:  * Must make sure to go back to OUST_NL/wantws mode before returning.
1.1       schwarze 1222:  */
                   1223: static void
                   1224: ordinary(struct state *st, const char *buf, size_t start, size_t end)
                   1225: {
1.13      kristaps 1226:        size_t          i, j, opstack;
1.15      kristaps 1227:        int             seq;
1.1       schwarze 1228:
                   1229:        if ( ! st->parsing || st->paused)
                   1230:                return;
                   1231:
                   1232:        /*
                   1233:         * Special-case: the NAME section.
                   1234:         * If we find a "-" when searching from the end, assume that
                   1235:         * we're in "name - description" format.
                   1236:         * To wit, print out a "Nm" and "Nd" in that format.
                   1237:         */
1.11      kristaps 1238:        if (SECT_NAME == st->sect) {
1.15      kristaps 1239:                for (i = end - 2; i > start; i--)
                   1240:                        if ('-' == buf[i] && ' ' == buf[i + 1])
1.1       schwarze 1241:                                break;
                   1242:                if ('-' == buf[i]) {
                   1243:                        j = i;
                   1244:                        /* Roll over multiple "-". */
                   1245:                        for ( ; i > start; i--)
                   1246:                                if ('-' != buf[i])
                   1247:                                        break;
1.17      kristaps 1248:                        donamenm(st, buf, &start, i + 1);
1.5       kristaps 1249:                        start = j + 1;
1.17      kristaps 1250:                        while (start < end && ' ' == buf[start])
                   1251:                                start++;
1.32      schwarze 1252:                        formatcodeln(st, "Nd", buf, &start, end, 1);
                   1253:                        mdoc_newln(st);
1.1       schwarze 1254:                        return;
                   1255:                }
                   1256:        }
                   1257:
                   1258:        if ( ! st->haspar)
                   1259:                puts(".Pp");
                   1260:
                   1261:        st->haspar = 0;
                   1262:        last = '\n';
1.13      kristaps 1263:        opstack = 0;
1.1       schwarze 1264:
1.15      kristaps 1265:        for (seq = 0; start < end; seq++) {
1.1       schwarze 1266:                /*
                   1267:                 * Loop til we get either to a newline or escape.
                   1268:                 * Escape initial control characters.
                   1269:                 */
                   1270:                while (start < end) {
1.34      schwarze 1271:                        if (start < end - 1 && '<' == buf[start + 1] &&
                   1272:                            'A' <= buf[start] && 'Z' >= buf[start])
1.1       schwarze 1273:                                break;
                   1274:                        else if ('\n' == buf[start])
                   1275:                                break;
                   1276:                        else if ('\n' == last && '.' == buf[start])
1.31      schwarze 1277:                                outbuf_addstr(st, "\\&");
1.1       schwarze 1278:                        else if ('\n' == last && '\'' == buf[start])
1.31      schwarze 1279:                                outbuf_addstr(st, "\\&");
1.12      kristaps 1280:                        /*
                   1281:                         * If we're in the SYNOPSIS, have square
                   1282:                         * brackets indicate that we're opening and
                   1283:                         * closing an optional context.
                   1284:                         */
1.32      schwarze 1285:
1.13      kristaps 1286:                        if (SECT_SYNOPSIS == st->sect &&
                   1287:                                ('[' == buf[start] ||
                   1288:                                 ']' == buf[start]) &&
1.32      schwarze 1289:                                dosynopsisop(st, buf,
                   1290:                                    &start, end, &opstack))
1.13      kristaps 1291:                                continue;
1.32      schwarze 1292:
                   1293:                        /*
                   1294:                         * On whitespace, flush the output buffer
                   1295:                         * and allow breaking to a macro line.
                   1296:                         * Otherwise, buffer text and clear wantws.
                   1297:                         */
                   1298:
1.31      schwarze 1299:                        last = buf[start++];
                   1300:                        if (' ' == last) {
                   1301:                                outbuf_flush(st);
                   1302:                                putchar(' ');
1.32      schwarze 1303:                                st->wantws = 1;
1.31      schwarze 1304:                        } else
                   1305:                                outbuf_addchar(st);
1.1       schwarze 1306:                }
                   1307:
1.34      schwarze 1308:                if (start < end - 1 && '<' == buf[start + 1] &&
                   1309:                    'A' <= buf[start] && 'Z' >= buf[start]) {
1.32      schwarze 1310:                        formatcode(st, buf, &start, end, 0, seq);
                   1311:                        if (OUST_MAC == st->oust) {
1.30      schwarze 1312:                                /*
                   1313:                                 * Let mdoc(7) handle trailing punctuation.
                   1314:                                 * XXX Some punctuation characters
                   1315:                                 *     are not handled yet.
                   1316:                                 */
1.16      kristaps 1317:                                if ((start == end - 1 ||
                   1318:                                        (start < end - 1 &&
                   1319:                                         (' ' == buf[start + 1] ||
                   1320:                                          '\n' == buf[start + 1]))) &&
                   1321:                                        ('.' == buf[start] ||
                   1322:                                         ',' == buf[start])) {
                   1323:                                        putchar(' ');
                   1324:                                        putchar(buf[start++]);
                   1325:                                }
1.32      schwarze 1326:
                   1327:                                if (st->wantws ||
                   1328:                                    ' ' == buf[start] ||
                   1329:                                    '\n' == buf[start])
                   1330:                                        mdoc_newln(st);
                   1331:
1.30      schwarze 1332:                                /*
                   1333:                                 * Consume all whitespace
                   1334:                                 * so we don't accidentally start
                   1335:                                 * an implicit literal line.
                   1336:                                 */
1.32      schwarze 1337:
1.6       kristaps 1338:                                while (start < end && ' ' == buf[start])
                   1339:                                        start++;
1.32      schwarze 1340:
                   1341:                                /*
                   1342:                                 * Some text is following.
                   1343:                                 * Implement requested spacing.
                   1344:                                 */
                   1345:
                   1346:                                if ( ! st->wantws && start < end &&
1.34      schwarze 1347:                                    ('<' != buf[start + 1] ||
                   1348:                                     'A' > buf[start] ||
                   1349:                                     'Z' < buf[start])) {
1.32      schwarze 1350:                                        printf(" Ns ");
                   1351:                                        st->wantws = 1;
                   1352:                                }
1.6       kristaps 1353:                        }
1.1       schwarze 1354:                } else if (start < end && '\n' == buf[start]) {
1.32      schwarze 1355:                        outbuf_flush(st);
                   1356:                        mdoc_newln(st);
1.1       schwarze 1357:                        if (++start >= end)
                   1358:                                continue;
                   1359:                        /*
                   1360:                         * If we have whitespace next, eat it to prevent
                   1361:                         * mdoc(7) from thinking that it's meant for
                   1362:                         * verbatim text.
                   1363:                         * It is--but if we start with that, we can't
                   1364:                         * have a macro subsequent it, which may be
                   1365:                         * possible if we have an escape next.
                   1366:                         */
1.31      schwarze 1367:                        if (' ' == buf[start] || '\t' == buf[start])
1.1       schwarze 1368:                                puts(".br");
                   1369:                        for ( ; start < end; start++)
                   1370:                                if (' ' != buf[start] && '\t' != buf[start])
                   1371:                                        break;
1.12      kristaps 1372:                }
1.1       schwarze 1373:        }
1.32      schwarze 1374:        outbuf_flush(st);
                   1375:        mdoc_newln(st);
1.1       schwarze 1376: }
                   1377:
                   1378: /*
                   1379:  * There are three kinds of paragraphs: verbatim (starts with whitespace
                   1380:  * of some sort), ordinary (starts without "=" marker), or a command
                   1381:  * (default: starts with "=").
                   1382:  */
                   1383: static void
1.35    ! schwarze 1384: dopar(struct state *st, char *buf, size_t start, size_t end)
1.1       schwarze 1385: {
                   1386:
1.32      schwarze 1387:        assert(OUST_NL == st->oust);
                   1388:        assert(st->wantws);
                   1389:
1.1       schwarze 1390:        if (end == start)
                   1391:                return;
                   1392:        if (' ' == buf[start] || '\t' == buf[start])
                   1393:                verbatim(st, buf, start, end);
                   1394:        else if ('=' != buf[start])
                   1395:                ordinary(st, buf, start, end);
                   1396:        else
                   1397:                command(st, buf, start, end);
                   1398: }
                   1399:
                   1400: /*
                   1401:  * Loop around paragraphs within a document, processing each one in the
                   1402:  * POD way.
                   1403:  */
                   1404: static void
                   1405: dofile(const struct args *args, const char *fname,
1.35    ! schwarze 1406:        const struct tm *tm, char *buf, size_t sz)
1.1       schwarze 1407: {
1.29      schwarze 1408:        char             datebuf[64];
1.1       schwarze 1409:        struct state     st;
1.29      schwarze 1410:        const char      *fbase, *fext, *section, *date;
1.1       schwarze 1411:        char            *title, *cp;
1.29      schwarze 1412:        size_t           sup, end, i, cur = 0;
1.1       schwarze 1413:
                   1414:        if (0 == sz)
                   1415:                return;
                   1416:
1.29      schwarze 1417:        /*
                   1418:         * Parsing the filename is almost always required,
                   1419:         * except when both the title and the section
                   1420:         * are provided on the command line.
                   1421:         */
                   1422:
                   1423:        if (NULL == args->title || NULL == args->section) {
                   1424:                fbase = strrchr(fname, '/');
                   1425:                if (NULL == fbase)
                   1426:                        fbase = fname;
                   1427:                else
                   1428:                        fbase++;
                   1429:                fext = strrchr(fbase, '.');
                   1430:        } else
                   1431:                fext = NULL;
                   1432:
                   1433:        /*
                   1434:         * The title will be converted to uppercase,
                   1435:         * so it needs to be copied.
                   1436:         */
                   1437:
                   1438:        title = (NULL != args->title) ? strdup(args->title) :
                   1439:                (NULL != fext) ? strndup(fbase, fext - fbase) :
                   1440:                strdup(fbase);
1.1       schwarze 1441:
                   1442:        if (NULL == title) {
                   1443:                perror(NULL);
                   1444:                exit(EXIT_FAILURE);
                   1445:        }
                   1446:
                   1447:        /* Section is 1 unless suffix is "pm". */
                   1448:
1.29      schwarze 1449:        section = (NULL != args->section) ? args->section :
                   1450:            (NULL == fext || strcmp(fext + 1, "pm")) ? "1" :
                   1451:            PERL_SECTION;
1.1       schwarze 1452:
                   1453:        /* Date.  Or the given "tm" if not supplied. */
                   1454:
                   1455:        if (NULL == (date = args->date)) {
                   1456:                strftime(datebuf, sizeof(datebuf), "%B %d, %Y", tm);
                   1457:                date = datebuf;
                   1458:        }
                   1459:
                   1460:        for (cp = title; '\0' != *cp; cp++)
                   1461:                *cp = toupper((int)*cp);
                   1462:
                   1463:        /* The usual mdoc(7) preamble. */
                   1464:
                   1465:        printf(".Dd %s\n", date);
                   1466:        printf(".Dt %s %s\n", title, section);
                   1467:        puts(".Os");
                   1468:
                   1469:        free(title);
                   1470:
                   1471:        memset(&st, 0, sizeof(struct state));
1.32      schwarze 1472:        st.oust = OUST_NL;
                   1473:        st.wantws = 1;
                   1474:
1.1       schwarze 1475:        assert(sz > 0);
                   1476:
                   1477:        /* Main loop over file contents. */
                   1478:
                   1479:        while (cur < sz) {
                   1480:                /* Read until next paragraph. */
                   1481:                for (i = cur + 1; i < sz; i++)
                   1482:                        if ('\n' == buf[i] && '\n' == buf[i - 1]) {
                   1483:                                /* Consume blank paragraphs. */
                   1484:                                while (i + 1 < sz && '\n' == buf[i + 1])
                   1485:                                        i++;
                   1486:                                break;
                   1487:                        }
                   1488:
                   1489:                /* Adjust end marker for EOF. */
                   1490:                end = i < sz ? i - 1 :
                   1491:                        ('\n' == buf[sz - 1] ? sz - 1 : sz);
                   1492:                sup = i < sz ? end + 2 : sz;
                   1493:
                   1494:                /* Process paragraph and adjust start. */
                   1495:                dopar(&st, buf, cur, end);
                   1496:                cur = sup;
                   1497:        }
                   1498: }
                   1499:
                   1500: /*
                   1501:  * Read a single file fully into memory.
                   1502:  * If the file is "-", do it from stdin.
                   1503:  * If successfully read, send the input buffer to dofile() for further
                   1504:  * processing.
                   1505:  */
                   1506: static int
                   1507: readfile(const struct args *args, const char *fname)
                   1508: {
                   1509:        int              fd;
                   1510:        char            *buf;
                   1511:        size_t           bufsz, cur;
                   1512:        ssize_t          ssz;
                   1513:        struct tm       *tm;
                   1514:        time_t           ttm;
                   1515:        struct stat      st;
                   1516:
                   1517:        fd = 0 != strcmp("-", fname) ?
                   1518:                open(fname, O_RDONLY, 0) : STDIN_FILENO;
                   1519:
                   1520:        if (-1 == fd) {
                   1521:                perror(fname);
                   1522:                return(0);
                   1523:        }
                   1524:
                   1525:        if (STDIN_FILENO == fd || -1 == fstat(fd, &st)) {
                   1526:                ttm = time(NULL);
                   1527:                tm = localtime(&ttm);
                   1528:        } else
                   1529:                tm = localtime(&st.st_mtime);
                   1530:
                   1531:        /*
                   1532:         * Arbitrarily-sized initial buffer.
                   1533:         * Should be big enough for most files...
                   1534:         */
                   1535:        cur = 0;
                   1536:        bufsz = 1 << 14;
                   1537:        if (NULL == (buf = malloc(bufsz))) {
                   1538:                perror(NULL);
                   1539:                exit(EXIT_FAILURE);
                   1540:        }
                   1541:
                   1542:        while ((ssz = read(fd, buf + cur, bufsz - cur)) > 0) {
                   1543:                /* Double buffer size on fill. */
                   1544:                if ((size_t)ssz == bufsz - cur)  {
                   1545:                        bufsz *= 2;
                   1546:                        if (NULL == (buf = realloc(buf, bufsz))) {
                   1547:                                perror(NULL);
                   1548:                                exit(EXIT_FAILURE);
                   1549:                        }
                   1550:                }
                   1551:                cur += (size_t)ssz;
                   1552:        }
                   1553:        if (ssz < 0) {
                   1554:                perror(fname);
                   1555:                free(buf);
                   1556:                return(0);
                   1557:        }
                   1558:
                   1559:        dofile(args, STDIN_FILENO == fd ?
                   1560:                "STDIN" : fname, tm, buf, cur);
                   1561:        free(buf);
                   1562:        if (STDIN_FILENO != fd)
                   1563:                close(fd);
                   1564:        return(1);
                   1565: }
                   1566:
                   1567: int
                   1568: main(int argc, char *argv[])
                   1569: {
                   1570:        const char      *fname, *name;
                   1571:        struct args      args;
                   1572:        int              c;
                   1573:
                   1574:        name = strrchr(argv[0], '/');
                   1575:        if (name == NULL)
                   1576:                name = argv[0];
                   1577:        else
                   1578:                ++name;
                   1579:
                   1580:        memset(&args, 0, sizeof(struct args));
                   1581:        fname = "-";
                   1582:
                   1583:        /* Accept no arguments for now. */
                   1584:
                   1585:        while (-1 != (c = getopt(argc, argv, "c:d:hln:oq:rs:uv")))
                   1586:                switch (c) {
                   1587:                case ('h'):
                   1588:                        /* FALLTHROUGH */
                   1589:                case ('l'):
                   1590:                        /* FALLTHROUGH */
                   1591:                case ('c'):
                   1592:                        /* FALLTHROUGH */
                   1593:                case ('o'):
                   1594:                        /* FALLTHROUGH */
                   1595:                case ('q'):
                   1596:                        /* FALLTHROUGH */
                   1597:                case ('r'):
                   1598:                        /* FALLTHROUGH */
                   1599:                case ('u'):
                   1600:                        /* FALLTHROUGH */
                   1601:                case ('v'):
                   1602:                        /* Ignore these. */
                   1603:                        break;
                   1604:                case ('d'):
                   1605:                        args.date = optarg;
                   1606:                        break;
                   1607:                case ('n'):
                   1608:                        args.title = optarg;
                   1609:                        break;
                   1610:                case ('s'):
                   1611:                        args.section = optarg;
                   1612:                        break;
                   1613:                default:
                   1614:                        goto usage;
                   1615:                }
                   1616:
                   1617:        argc -= optind;
                   1618:        argv += optind;
                   1619:
                   1620:        /* Accept only a single input file. */
                   1621:
1.25      schwarze 1622:        if (argc > 1)
                   1623:                goto usage;
1.1       schwarze 1624:        else if (1 == argc)
                   1625:                fname = *argv;
                   1626:
                   1627:        return(readfile(&args, fname) ?
                   1628:                EXIT_SUCCESS : EXIT_FAILURE);
                   1629:
                   1630: usage:
                   1631:        fprintf(stderr, "usage: %s [-d date] "
1.25      schwarze 1632:            "[-n title] [-s section] [file]\n", name);
1.1       schwarze 1633:
                   1634:        return(EXIT_FAILURE);
                   1635: }

CVSweb