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

Annotation of pod2mdoc/pod2mdoc.c, Revision 1.33

1.33    ! schwarze    1: /*     $Id: pod2mdoc.c,v 1.32 2014/07/18 05:09:32 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:                }
                    669:                if (*start + 1 < end && '<' == buf[*start + 1]) {
1.32      schwarze  670:                        formatcode(st, buf, start, end, nomacro, 1);
1.1       schwarze  671:                        continue;
                    672:                }
1.3       schwarze  673:
1.32      schwarze  674:                /* Suppress newlines and multiple spaces. */
                    675:
                    676:                last = buf[(*start)++];
                    677:                if (' ' == last || '\n' == last) {
                    678:                        putchar(' ');
                    679:                        while (*start < end && ' ' == buf[*start])
                    680:                                (*start)++;
                    681:                        continue;
                    682:                }
                    683:
1.33    ! schwarze  684:                if (OUST_MAC == st->oust && FMT__MAX != fmt) {
1.32      schwarze  685:                        if ( ! st->wantws) {
                    686:                                printf(" Ns ");
                    687:                                st->wantws = 1;
                    688:                        }
                    689:
                    690:                        /*
                    691:                         * Escape macro-like words.
                    692:                         * This matches "Xx " and "XxEOLN".
                    693:                         */
                    694:
                    695:                        if (end - *start > 0 &&
                    696:                            isupper((unsigned char)last) &&
                    697:                            islower((unsigned char)buf[*start]) &&
                    698:                            (end - *start == 1 ||
                    699:                             ' ' == buf[*start + 1] ||
                    700:                             '>' == buf[*start + 1]))
                    701:                                printf("\\&");
                    702:                }
1.3       schwarze  703:
1.32      schwarze  704:                putchar(last);
1.4       schwarze  705:
1.8       kristaps  706:                /* Protect against character escapes. */
1.32      schwarze  707:
1.8       kristaps  708:                if ('\\' == last)
                    709:                        putchar('e');
1.1       schwarze  710:        }
1.2       schwarze  711:
1.33    ! schwarze  712:        if (FMT__MAX == fmt)
        !           713:                return(0);
        !           714:
1.2       schwarze  715:        if ( ! nomacro && FMT_CODE == fmt)
                    716:                printf(" Qc ");
1.1       schwarze  717:
1.33    ! schwarze  718:        st->wantws = ' ' == last;
        !           719:        return(1);
1.1       schwarze  720: }
                    721:
                    722: /*
                    723:  * Calls formatcode() til the end of a paragraph.
1.32      schwarze  724:  * Goes to OUST_MAC mode and stays there when returning,
                    725:  * such that the caller can add arguments to the macro line
                    726:  * before closing it out.
1.1       schwarze  727:  */
                    728: static void
1.32      schwarze  729: formatcodeln(struct state *st, const char *linemac,
                    730:        const char *buf, size_t *start, size_t end, int nomacro)
1.1       schwarze  731: {
1.33    ! schwarze  732:        int      gotmacro, wantws;
1.1       schwarze  733:
1.32      schwarze  734:        assert(OUST_NL == st->oust);
                    735:        assert(st->wantws);
                    736:        printf(".%s ", linemac);
                    737:        st->oust = OUST_MAC;
                    738:
1.33    ! schwarze  739:        gotmacro = 0;
1.1       schwarze  740:        while (*start < end)  {
1.33    ! schwarze  741:                wantws = ' ' == buf[*start] || '\n' == buf[*start];
        !           742:                if (wantws) {
        !           743:                        last = ' ';
        !           744:                        do {
        !           745:                                (*start)++;
        !           746:                        } while (*start < end && ' ' == buf[*start]);
        !           747:                }
        !           748:
1.1       schwarze  749:                if (*start + 1 < end && '<' == buf[*start + 1]) {
1.33    ! schwarze  750:                        st->wantws |= wantws;
        !           751:                        gotmacro = formatcode(st, buf,
        !           752:                            start, end, nomacro, 1);
1.1       schwarze  753:                        continue;
                    754:                }
1.32      schwarze  755:
1.33    ! schwarze  756:                if (gotmacro) {
        !           757:                        if (*start < end || st->outbuflen) {
        !           758:                                if (st->wantws ||
        !           759:                                    (wantws && !st->outbuflen))
        !           760:                                        printf(" No ");
        !           761:                                else
        !           762:                                        printf(" Ns ");
        !           763:                        }
        !           764:                        gotmacro = 0;
        !           765:                }
        !           766:                outbuf_flush(st);
        !           767:                st->wantws = wantws;
        !           768:
        !           769:                if (*start >= end)
        !           770:                        break;
        !           771:
        !           772:                if (st->wantws) {
        !           773:                        putchar(' ');
        !           774:                        st->wantws = 0;
1.32      schwarze  775:                }
                    776:
1.4       schwarze  777:                /*
                    778:                 * Since we're already on a macro line, we want to make
                    779:                 * sure that we don't inadvertently invoke a macro.
                    780:                 * We need to do this carefully because section names
                    781:                 * are used in troff and we don't want to escape
                    782:                 * something that needn't be escaped.
                    783:                 */
                    784:                if (' ' == last && end - *start > 1 &&
1.33    ! schwarze  785:                    isupper((unsigned char)buf[*start]) &&
        !           786:                    islower((unsigned char)buf[*start + 1]) &&
        !           787:                    (end - *start == 2 || ' ' == buf[*start + 2]))
1.4       schwarze  788:                        printf("\\&");
                    789:
1.33    ! schwarze  790:                putchar(last = buf[*start]);
1.8       kristaps  791:
                    792:                /* Protect against character escapes. */
1.33    ! schwarze  793:
1.8       kristaps  794:                if ('\\' == last)
                    795:                        putchar('e');
                    796:
1.1       schwarze  797:                (*start)++;
                    798:        }
                    799: }
                    800:
                    801: /*
1.4       schwarze  802:  * Guess at what kind of list we are.
                    803:  * These are taken straight from the POD manual.
                    804:  * I don't know what people do in real life.
                    805:  */
                    806: static enum list
                    807: listguess(const char *buf, size_t start, size_t end)
                    808: {
                    809:        size_t           len = end - start;
                    810:
                    811:        assert(end >= start);
                    812:
                    813:        if (len == 1 && '*' == buf[start])
                    814:                return(LIST_BULLET);
                    815:        if (len == 2 && '1' == buf[start] && '.' == buf[start + 1])
                    816:                return(LIST_ENUM);
                    817:        else if (len == 1 && '1' == buf[start])
                    818:                return(LIST_ENUM);
                    819:        else
                    820:                return(LIST_TAG);
                    821: }
                    822:
                    823: /*
1.1       schwarze  824:  * A command paragraph, as noted in the perlpod manual, just indicates
                    825:  * that we should do something, optionally with some text to print as
                    826:  * well.
1.32      schwarze  827:  * From the perspective of external callers,
                    828:  * always stays in OUST_NL/wantws mode,
                    829:  * but its children do use OUST_MAC.
1.1       schwarze  830:  */
                    831: static void
                    832: command(struct state *st, const char *buf, size_t start, size_t end)
                    833: {
                    834:        size_t           len, csz;
                    835:        enum cmd         cmd;
                    836:
                    837:        assert('=' == buf[start]);
                    838:        start++;
                    839:        len = end - start;
                    840:
                    841:        for (cmd = 0; cmd < CMD__MAX; cmd++) {
                    842:                csz = strlen(cmds[cmd]);
                    843:                if (len < csz)
                    844:                        continue;
                    845:                if (0 == memcmp(&buf[start], cmd[cmds], csz))
                    846:                        break;
                    847:        }
                    848:
                    849:        /* Ignore bogus commands. */
                    850:
                    851:        if (CMD__MAX == cmd)
                    852:                return;
                    853:
                    854:        start += csz;
1.8       kristaps  855:        while (start < end && ' ' == buf[start])
                    856:                start++;
                    857:
1.1       schwarze  858:        len = end - start;
                    859:
                    860:        if (st->paused) {
                    861:                st->paused = CMD_END != cmd;
                    862:                return;
                    863:        }
                    864:
                    865:        switch (cmd) {
                    866:        case (CMD_POD):
                    867:                break;
                    868:        case (CMD_HEAD1):
                    869:                /*
                    870:                 * The behaviour of head= follows from a quick glance at
                    871:                 * how pod2man handles it.
                    872:                 */
1.11      kristaps  873:                st->sect = SECT_NONE;
                    874:                if (end - start == 4) {
1.1       schwarze  875:                        if (0 == memcmp(&buf[start], "NAME", 4))
1.11      kristaps  876:                                st->sect = SECT_NAME;
                    877:                } else if (end - start == 8) {
                    878:                        if (0 == memcmp(&buf[start], "SYNOPSIS", 8))
                    879:                                st->sect = SECT_SYNOPSIS;
                    880:                }
1.32      schwarze  881:                formatcodeln(st, "Sh", buf, &start, end, 1);
                    882:                mdoc_newln(st);
1.1       schwarze  883:                st->haspar = 1;
                    884:                break;
                    885:        case (CMD_HEAD2):
1.32      schwarze  886:                formatcodeln(st, "Ss", buf, &start, end, 1);
                    887:                mdoc_newln(st);
1.1       schwarze  888:                st->haspar = 1;
                    889:                break;
                    890:        case (CMD_HEAD3):
                    891:                puts(".Pp");
1.32      schwarze  892:                formatcodeln(st, "Em", buf, &start, end, 0);
                    893:                mdoc_newln(st);
1.1       schwarze  894:                puts(".Pp");
                    895:                st->haspar = 1;
                    896:                break;
                    897:        case (CMD_HEAD4):
                    898:                puts(".Pp");
1.32      schwarze  899:                formatcodeln(st, "No", buf, &start, end, 0);
                    900:                mdoc_newln(st);
1.1       schwarze  901:                puts(".Pp");
                    902:                st->haspar = 1;
                    903:                break;
                    904:        case (CMD_OVER):
1.4       schwarze  905:                /*
                    906:                 * If we have an existing list that hasn't had an =item
                    907:                 * yet, then make sure that we open it now.
                    908:                 * We use the default list type, but that can't be
                    909:                 * helped (we haven't seen any items yet).
1.1       schwarze  910:                 */
1.4       schwarze  911:                if (st->lpos > 0)
                    912:                        if (LIST__MAX == st->lstack[st->lpos - 1]) {
                    913:                                st->lstack[st->lpos - 1] = LIST_TAG;
                    914:                                puts(".Bl -tag -width Ds");
                    915:                        }
                    916:                st->lpos++;
                    917:                assert(st->lpos < LIST_STACKSZ);
                    918:                st->lstack[st->lpos - 1] = LIST__MAX;
1.1       schwarze  919:                break;
                    920:        case (CMD_ITEM):
1.6       kristaps  921:                if (0 == st->lpos) {
                    922:                        /*
                    923:                         * Bad markup.
                    924:                         * Try to compensate.
                    925:                         */
                    926:                        st->lstack[st->lpos] = LIST__MAX;
                    927:                        st->lpos++;
                    928:                }
1.4       schwarze  929:                assert(st->lpos > 0);
                    930:                /*
                    931:                 * If we're the first =item, guess at what our content
                    932:                 * will be: "*" is a bullet list, "1." is a numbered
                    933:                 * list, and everything is tagged.
                    934:                 */
                    935:                if (LIST__MAX == st->lstack[st->lpos - 1]) {
                    936:                        st->lstack[st->lpos - 1] =
                    937:                                listguess(buf, start, end);
                    938:                        switch (st->lstack[st->lpos - 1]) {
                    939:                        case (LIST_BULLET):
                    940:                                puts(".Bl -bullet");
                    941:                                break;
                    942:                        case (LIST_ENUM):
                    943:                                puts(".Bl -enum");
                    944:                                break;
                    945:                        default:
                    946:                                puts(".Bl -tag -width Ds");
                    947:                                break;
                    948:                        }
                    949:                }
                    950:                switch (st->lstack[st->lpos - 1]) {
                    951:                case (LIST_TAG):
1.32      schwarze  952:                        formatcodeln(st, "It", buf, &start, end, 0);
                    953:                        mdoc_newln(st);
1.4       schwarze  954:                        break;
                    955:                case (LIST_ENUM):
                    956:                        /* FALLTHROUGH */
                    957:                case (LIST_BULLET):
                    958:                        /*
                    959:                         * Abandon the remainder of the paragraph
                    960:                         * because we're going to be a bulletted or
                    961:                         * numbered list.
                    962:                         */
                    963:                        puts(".It");
                    964:                        break;
                    965:                default:
                    966:                        abort();
                    967:                }
1.1       schwarze  968:                st->haspar = 1;
                    969:                break;
                    970:        case (CMD_BACK):
1.4       schwarze  971:                /* Make sure we don't back over the stack. */
                    972:                if (st->lpos > 0) {
                    973:                        st->lpos--;
                    974:                        puts(".El");
                    975:                }
1.1       schwarze  976:                break;
                    977:        case (CMD_BEGIN):
                    978:                /*
                    979:                 * We disregard all types for now.
                    980:                 * TODO: process at least "text" in a -literal block.
                    981:                 */
                    982:                st->paused = 1;
                    983:                break;
                    984:        case (CMD_FOR):
                    985:                /*
                    986:                 * We ignore all types of encodings and formats
                    987:                 * unilaterally.
                    988:                 */
                    989:                break;
                    990:        case (CMD_ENCODING):
                    991:                break;
                    992:        case (CMD_CUT):
                    993:                st->parsing = 0;
                    994:                return;
                    995:        default:
                    996:                abort();
                    997:        }
                    998:
                    999:        /* Any command (but =cut) makes us start parsing. */
                   1000:        st->parsing = 1;
                   1001: }
                   1002:
                   1003: /*
                   1004:  * Just pump out the line in a verbatim block.
1.32      schwarze 1005:  * From the perspective of external callers,
                   1006:  * always stays in OUST_NL/wantws mode.
1.1       schwarze 1007:  */
                   1008: static void
                   1009: verbatim(struct state *st, const char *buf, size_t start, size_t end)
                   1010: {
1.22      kristaps 1011:        size_t           i;
1.1       schwarze 1012:
                   1013:        if ( ! st->parsing || st->paused)
                   1014:                return;
1.22      kristaps 1015: again:
                   1016:        /*
                   1017:         * If we're in the SYNOPSIS, see if we're an #include block.
                   1018:         * If we are, then print the "In" macro and re-loop.
                   1019:         * This handles any number of inclusions, but only when they
                   1020:         * come before the remaining parts...
                   1021:         */
                   1022:        if (SECT_SYNOPSIS == st->sect) {
                   1023:                i = start;
                   1024:                for (i = start; i < end && ' ' == buf[i]; i++)
                   1025:                        /* Spin. */ ;
                   1026:                if (i == end)
                   1027:                        return;
                   1028:                /* We're an include block! */
                   1029:                if (end - i > 10 &&
                   1030:                        0 == memcmp(&buf[i], "#include <", 10)) {
                   1031:                        start = i + 10;
                   1032:                        while (start < end && ' ' == buf[start])
                   1033:                                start++;
                   1034:                        fputs(".In ", stdout);
                   1035:                        /* Stop til the '>' marker or we hit eoln. */
                   1036:                        while (start < end &&
                   1037:                                '>' != buf[start] && '\n' != buf[start])
                   1038:                                putchar(buf[start++]);
                   1039:                        putchar('\n');
                   1040:                        if (start < end && '>' == buf[start])
                   1041:                                start++;
                   1042:                        if (start < end && '\n' == buf[start])
                   1043:                                start++;
                   1044:                        if (start < end)
                   1045:                                goto again;
                   1046:                        return;
                   1047:                }
                   1048:        }
                   1049:
                   1050:        if (start == end)
                   1051:                return;
1.1       schwarze 1052:        puts(".Bd -literal");
1.8       kristaps 1053:        for (last = ' '; start < end; start++) {
                   1054:                /*
                   1055:                 * Handle accidental macros (newline starting with
                   1056:                 * control character) and escapes.
                   1057:                 */
                   1058:                if ('\n' == last)
1.7       kristaps 1059:                        if ('.' == buf[start] || '\'' == buf[start])
                   1060:                                printf("\\&");
1.8       kristaps 1061:                putchar(last = buf[start]);
                   1062:                if ('\\' == buf[start])
                   1063:                        printf("e");
1.7       kristaps 1064:        }
1.31      schwarze 1065:        putchar(last = '\n');
1.1       schwarze 1066:        puts(".Ed");
                   1067: }
                   1068:
                   1069: /*
1.13      kristaps 1070:  * See dosynopsisop().
                   1071:  */
                   1072: static int
                   1073: hasmatch(const char *buf, size_t start, size_t end)
                   1074: {
                   1075:        size_t   stack;
                   1076:
                   1077:        for (stack = 0; start < end; start++)
                   1078:                if (buf[start] == '[')
                   1079:                        stack++;
                   1080:                else if (buf[start] == ']' && 0 == stack)
                   1081:                        return(1);
                   1082:                else if (buf[start] == ']')
                   1083:                        stack--;
                   1084:        return(0);
                   1085: }
                   1086:
                   1087: /*
                   1088:  * If we're in the SYNOPSIS section and we've encounter braces in an
                   1089:  * ordinary paragraph, then try to see whether we're an [-option].
                   1090:  * Do this, if we're an opening bracket, by first seeing if we have a
                   1091:  * matching end via hasmatch().
                   1092:  * If we're an ending bracket, see if we have a stack already.
                   1093:  */
                   1094: static int
1.32      schwarze 1095: dosynopsisop(struct state *st, const char *buf,
                   1096:        size_t *start, size_t end, size_t *opstack)
1.13      kristaps 1097: {
                   1098:
                   1099:        assert('[' == buf[*start] || ']' == buf[*start]);
                   1100:
                   1101:        if ('[' == buf[*start] && hasmatch(buf, *start + 1, end)) {
1.32      schwarze 1102:                mdoc_newln(st);
1.13      kristaps 1103:                puts(".Oo");
                   1104:                (*opstack)++;
                   1105:        } else if ('[' == buf[*start])
                   1106:                return(0);
                   1107:
                   1108:        if (']' == buf[*start] && *opstack > 0) {
1.32      schwarze 1109:                mdoc_newln(st);
1.13      kristaps 1110:                puts(".Oc");
                   1111:                (*opstack)--;
                   1112:        } else if (']' == buf[*start])
                   1113:                return(0);
                   1114:
                   1115:        (*start)++;
1.31      schwarze 1116:        last = '\n';
1.13      kristaps 1117:        while (' ' == buf[*start])
                   1118:                (*start)++;
                   1119:        return(1);
                   1120: }
                   1121:
                   1122: /*
1.17      kristaps 1123:  * Format multiple "Nm" manpage names in the NAME section.
1.32      schwarze 1124:  * From the perspective of external callers,
                   1125:  * always stays in OUST_NL/wantws mode,
                   1126:  * but its children do use OUST_MAC.
1.17      kristaps 1127:  */
                   1128: static void
                   1129: donamenm(struct state *st, const char *buf, size_t *start, size_t end)
                   1130: {
                   1131:        size_t   word;
                   1132:
1.32      schwarze 1133:        assert(OUST_NL == st->oust);
                   1134:        assert(st->wantws);
                   1135:
1.17      kristaps 1136:        while (*start < end && ' ' == buf[*start])
                   1137:                (*start)++;
                   1138:
                   1139:        if (end == *start) {
                   1140:                puts(".Nm unknown");
                   1141:                return;
                   1142:        }
                   1143:
                   1144:        while (*start < end) {
                   1145:                for (word = *start; word < end; word++)
                   1146:                        if (',' == buf[word])
                   1147:                                break;
1.32      schwarze 1148:                formatcodeln(st, "Nm", buf, start, word, 1);
1.17      kristaps 1149:                if (*start == end) {
1.32      schwarze 1150:                        mdoc_newln(st);
                   1151:                        break;
1.17      kristaps 1152:                }
                   1153:                assert(',' == buf[*start]);
1.32      schwarze 1154:                printf(" ,");
                   1155:                mdoc_newln(st);
1.17      kristaps 1156:                (*start)++;
                   1157:                while (*start < end && ' ' == buf[*start])
                   1158:                        (*start)++;
                   1159:        }
                   1160: }
                   1161:
                   1162: /*
1.1       schwarze 1163:  * Ordinary paragraph.
                   1164:  * Well, this is really the hardest--POD seems to assume that, for
                   1165:  * example, a leading space implies a newline, and so on.
                   1166:  * Lots of other snakes in the grass: escaping a newline followed by a
                   1167:  * period (accidental mdoc(7) control), double-newlines after macro
                   1168:  * passages, etc.
1.32      schwarze 1169:  *
                   1170:  * Uses formatcode() to go to OUST_MAC mode
                   1171:  * and outbuf_flush() to go to OUST_TXT mode.
                   1172:  * Main text mode wantws handling is in this function.
                   1173:  * Must make sure to go back to OUST_NL/wantws mode before returning.
1.1       schwarze 1174:  */
                   1175: static void
                   1176: ordinary(struct state *st, const char *buf, size_t start, size_t end)
                   1177: {
1.13      kristaps 1178:        size_t          i, j, opstack;
1.15      kristaps 1179:        int             seq;
1.1       schwarze 1180:
                   1181:        if ( ! st->parsing || st->paused)
                   1182:                return;
                   1183:
                   1184:        /*
                   1185:         * Special-case: the NAME section.
                   1186:         * If we find a "-" when searching from the end, assume that
                   1187:         * we're in "name - description" format.
                   1188:         * To wit, print out a "Nm" and "Nd" in that format.
                   1189:         */
1.11      kristaps 1190:        if (SECT_NAME == st->sect) {
1.15      kristaps 1191:                for (i = end - 2; i > start; i--)
                   1192:                        if ('-' == buf[i] && ' ' == buf[i + 1])
1.1       schwarze 1193:                                break;
                   1194:                if ('-' == buf[i]) {
                   1195:                        j = i;
                   1196:                        /* Roll over multiple "-". */
                   1197:                        for ( ; i > start; i--)
                   1198:                                if ('-' != buf[i])
                   1199:                                        break;
1.17      kristaps 1200:                        donamenm(st, buf, &start, i + 1);
1.5       kristaps 1201:                        start = j + 1;
1.17      kristaps 1202:                        while (start < end && ' ' == buf[start])
                   1203:                                start++;
1.32      schwarze 1204:                        formatcodeln(st, "Nd", buf, &start, end, 1);
                   1205:                        mdoc_newln(st);
1.1       schwarze 1206:                        return;
                   1207:                }
                   1208:        }
                   1209:
                   1210:        if ( ! st->haspar)
                   1211:                puts(".Pp");
                   1212:
                   1213:        st->haspar = 0;
                   1214:        last = '\n';
1.13      kristaps 1215:        opstack = 0;
1.1       schwarze 1216:
1.15      kristaps 1217:        for (seq = 0; start < end; seq++) {
1.1       schwarze 1218:                /*
                   1219:                 * Loop til we get either to a newline or escape.
                   1220:                 * Escape initial control characters.
                   1221:                 */
                   1222:                while (start < end) {
                   1223:                        if (start < end - 1 && '<' == buf[start + 1])
                   1224:                                break;
                   1225:                        else if ('\n' == buf[start])
                   1226:                                break;
                   1227:                        else if ('\n' == last && '.' == buf[start])
1.31      schwarze 1228:                                outbuf_addstr(st, "\\&");
1.1       schwarze 1229:                        else if ('\n' == last && '\'' == buf[start])
1.31      schwarze 1230:                                outbuf_addstr(st, "\\&");
1.12      kristaps 1231:                        /*
                   1232:                         * If we're in the SYNOPSIS, have square
                   1233:                         * brackets indicate that we're opening and
                   1234:                         * closing an optional context.
                   1235:                         */
1.32      schwarze 1236:
1.13      kristaps 1237:                        if (SECT_SYNOPSIS == st->sect &&
                   1238:                                ('[' == buf[start] ||
                   1239:                                 ']' == buf[start]) &&
1.32      schwarze 1240:                                dosynopsisop(st, buf,
                   1241:                                    &start, end, &opstack))
1.13      kristaps 1242:                                continue;
1.32      schwarze 1243:
                   1244:                        /*
                   1245:                         * On whitespace, flush the output buffer
                   1246:                         * and allow breaking to a macro line.
                   1247:                         * Otherwise, buffer text and clear wantws.
                   1248:                         */
                   1249:
1.31      schwarze 1250:                        last = buf[start++];
                   1251:                        if (' ' == last) {
                   1252:                                outbuf_flush(st);
                   1253:                                putchar(' ');
1.32      schwarze 1254:                                st->wantws = 1;
1.31      schwarze 1255:                        } else
                   1256:                                outbuf_addchar(st);
1.1       schwarze 1257:                }
                   1258:
                   1259:                if (start < end - 1 && '<' == buf[start + 1]) {
1.32      schwarze 1260:                        formatcode(st, buf, &start, end, 0, seq);
                   1261:                        if (OUST_MAC == st->oust) {
1.30      schwarze 1262:                                /*
                   1263:                                 * Let mdoc(7) handle trailing punctuation.
                   1264:                                 * XXX Some punctuation characters
                   1265:                                 *     are not handled yet.
                   1266:                                 */
1.16      kristaps 1267:                                if ((start == end - 1 ||
                   1268:                                        (start < end - 1 &&
                   1269:                                         (' ' == buf[start + 1] ||
                   1270:                                          '\n' == buf[start + 1]))) &&
                   1271:                                        ('.' == buf[start] ||
                   1272:                                         ',' == buf[start])) {
                   1273:                                        putchar(' ');
                   1274:                                        putchar(buf[start++]);
                   1275:                                }
1.32      schwarze 1276:
                   1277:                                if (st->wantws ||
                   1278:                                    ' ' == buf[start] ||
                   1279:                                    '\n' == buf[start])
                   1280:                                        mdoc_newln(st);
                   1281:
1.30      schwarze 1282:                                /*
                   1283:                                 * Consume all whitespace
                   1284:                                 * so we don't accidentally start
                   1285:                                 * an implicit literal line.
                   1286:                                 */
1.32      schwarze 1287:
1.6       kristaps 1288:                                while (start < end && ' ' == buf[start])
                   1289:                                        start++;
1.32      schwarze 1290:
                   1291:                                /*
                   1292:                                 * Some text is following.
                   1293:                                 * Implement requested spacing.
                   1294:                                 */
                   1295:
                   1296:                                if ( ! st->wantws && start < end &&
                   1297:                                    '<' != buf[start + 1]) {
                   1298:                                        printf(" Ns ");
                   1299:                                        st->wantws = 1;
                   1300:                                }
1.6       kristaps 1301:                        }
1.1       schwarze 1302:                } else if (start < end && '\n' == buf[start]) {
1.32      schwarze 1303:                        outbuf_flush(st);
                   1304:                        mdoc_newln(st);
1.1       schwarze 1305:                        if (++start >= end)
                   1306:                                continue;
                   1307:                        /*
                   1308:                         * If we have whitespace next, eat it to prevent
                   1309:                         * mdoc(7) from thinking that it's meant for
                   1310:                         * verbatim text.
                   1311:                         * It is--but if we start with that, we can't
                   1312:                         * have a macro subsequent it, which may be
                   1313:                         * possible if we have an escape next.
                   1314:                         */
1.31      schwarze 1315:                        if (' ' == buf[start] || '\t' == buf[start])
1.1       schwarze 1316:                                puts(".br");
                   1317:                        for ( ; start < end; start++)
                   1318:                                if (' ' != buf[start] && '\t' != buf[start])
                   1319:                                        break;
1.12      kristaps 1320:                }
1.1       schwarze 1321:        }
1.32      schwarze 1322:        outbuf_flush(st);
                   1323:        mdoc_newln(st);
1.1       schwarze 1324: }
                   1325:
                   1326: /*
                   1327:  * There are three kinds of paragraphs: verbatim (starts with whitespace
                   1328:  * of some sort), ordinary (starts without "=" marker), or a command
                   1329:  * (default: starts with "=").
                   1330:  */
                   1331: static void
                   1332: dopar(struct state *st, const char *buf, size_t start, size_t end)
                   1333: {
                   1334:
1.32      schwarze 1335:        assert(OUST_NL == st->oust);
                   1336:        assert(st->wantws);
                   1337:
1.1       schwarze 1338:        if (end == start)
                   1339:                return;
                   1340:        if (' ' == buf[start] || '\t' == buf[start])
                   1341:                verbatim(st, buf, start, end);
                   1342:        else if ('=' != buf[start])
                   1343:                ordinary(st, buf, start, end);
                   1344:        else
                   1345:                command(st, buf, start, end);
                   1346: }
                   1347:
                   1348: /*
                   1349:  * Loop around paragraphs within a document, processing each one in the
                   1350:  * POD way.
                   1351:  */
                   1352: static void
                   1353: dofile(const struct args *args, const char *fname,
                   1354:        const struct tm *tm, const char *buf, size_t sz)
                   1355: {
1.29      schwarze 1356:        char             datebuf[64];
1.1       schwarze 1357:        struct state     st;
1.29      schwarze 1358:        const char      *fbase, *fext, *section, *date;
1.1       schwarze 1359:        char            *title, *cp;
1.29      schwarze 1360:        size_t           sup, end, i, cur = 0;
1.1       schwarze 1361:
                   1362:        if (0 == sz)
                   1363:                return;
                   1364:
1.29      schwarze 1365:        /*
                   1366:         * Parsing the filename is almost always required,
                   1367:         * except when both the title and the section
                   1368:         * are provided on the command line.
                   1369:         */
                   1370:
                   1371:        if (NULL == args->title || NULL == args->section) {
                   1372:                fbase = strrchr(fname, '/');
                   1373:                if (NULL == fbase)
                   1374:                        fbase = fname;
                   1375:                else
                   1376:                        fbase++;
                   1377:                fext = strrchr(fbase, '.');
                   1378:        } else
                   1379:                fext = NULL;
                   1380:
                   1381:        /*
                   1382:         * The title will be converted to uppercase,
                   1383:         * so it needs to be copied.
                   1384:         */
                   1385:
                   1386:        title = (NULL != args->title) ? strdup(args->title) :
                   1387:                (NULL != fext) ? strndup(fbase, fext - fbase) :
                   1388:                strdup(fbase);
1.1       schwarze 1389:
                   1390:        if (NULL == title) {
                   1391:                perror(NULL);
                   1392:                exit(EXIT_FAILURE);
                   1393:        }
                   1394:
                   1395:        /* Section is 1 unless suffix is "pm". */
                   1396:
1.29      schwarze 1397:        section = (NULL != args->section) ? args->section :
                   1398:            (NULL == fext || strcmp(fext + 1, "pm")) ? "1" :
                   1399:            PERL_SECTION;
1.1       schwarze 1400:
                   1401:        /* Date.  Or the given "tm" if not supplied. */
                   1402:
                   1403:        if (NULL == (date = args->date)) {
                   1404:                strftime(datebuf, sizeof(datebuf), "%B %d, %Y", tm);
                   1405:                date = datebuf;
                   1406:        }
                   1407:
                   1408:        for (cp = title; '\0' != *cp; cp++)
                   1409:                *cp = toupper((int)*cp);
                   1410:
                   1411:        /* The usual mdoc(7) preamble. */
                   1412:
                   1413:        printf(".Dd %s\n", date);
                   1414:        printf(".Dt %s %s\n", title, section);
                   1415:        puts(".Os");
                   1416:
                   1417:        free(title);
                   1418:
                   1419:        memset(&st, 0, sizeof(struct state));
1.32      schwarze 1420:        st.oust = OUST_NL;
                   1421:        st.wantws = 1;
                   1422:
1.1       schwarze 1423:        assert(sz > 0);
                   1424:
                   1425:        /* Main loop over file contents. */
                   1426:
                   1427:        while (cur < sz) {
                   1428:                /* Read until next paragraph. */
                   1429:                for (i = cur + 1; i < sz; i++)
                   1430:                        if ('\n' == buf[i] && '\n' == buf[i - 1]) {
                   1431:                                /* Consume blank paragraphs. */
                   1432:                                while (i + 1 < sz && '\n' == buf[i + 1])
                   1433:                                        i++;
                   1434:                                break;
                   1435:                        }
                   1436:
                   1437:                /* Adjust end marker for EOF. */
                   1438:                end = i < sz ? i - 1 :
                   1439:                        ('\n' == buf[sz - 1] ? sz - 1 : sz);
                   1440:                sup = i < sz ? end + 2 : sz;
                   1441:
                   1442:                /* Process paragraph and adjust start. */
                   1443:                dopar(&st, buf, cur, end);
                   1444:                cur = sup;
                   1445:        }
                   1446: }
                   1447:
                   1448: /*
                   1449:  * Read a single file fully into memory.
                   1450:  * If the file is "-", do it from stdin.
                   1451:  * If successfully read, send the input buffer to dofile() for further
                   1452:  * processing.
                   1453:  */
                   1454: static int
                   1455: readfile(const struct args *args, const char *fname)
                   1456: {
                   1457:        int              fd;
                   1458:        char            *buf;
                   1459:        size_t           bufsz, cur;
                   1460:        ssize_t          ssz;
                   1461:        struct tm       *tm;
                   1462:        time_t           ttm;
                   1463:        struct stat      st;
                   1464:
                   1465:        fd = 0 != strcmp("-", fname) ?
                   1466:                open(fname, O_RDONLY, 0) : STDIN_FILENO;
                   1467:
                   1468:        if (-1 == fd) {
                   1469:                perror(fname);
                   1470:                return(0);
                   1471:        }
                   1472:
                   1473:        if (STDIN_FILENO == fd || -1 == fstat(fd, &st)) {
                   1474:                ttm = time(NULL);
                   1475:                tm = localtime(&ttm);
                   1476:        } else
                   1477:                tm = localtime(&st.st_mtime);
                   1478:
                   1479:        /*
                   1480:         * Arbitrarily-sized initial buffer.
                   1481:         * Should be big enough for most files...
                   1482:         */
                   1483:        cur = 0;
                   1484:        bufsz = 1 << 14;
                   1485:        if (NULL == (buf = malloc(bufsz))) {
                   1486:                perror(NULL);
                   1487:                exit(EXIT_FAILURE);
                   1488:        }
                   1489:
                   1490:        while ((ssz = read(fd, buf + cur, bufsz - cur)) > 0) {
                   1491:                /* Double buffer size on fill. */
                   1492:                if ((size_t)ssz == bufsz - cur)  {
                   1493:                        bufsz *= 2;
                   1494:                        if (NULL == (buf = realloc(buf, bufsz))) {
                   1495:                                perror(NULL);
                   1496:                                exit(EXIT_FAILURE);
                   1497:                        }
                   1498:                }
                   1499:                cur += (size_t)ssz;
                   1500:        }
                   1501:        if (ssz < 0) {
                   1502:                perror(fname);
                   1503:                free(buf);
                   1504:                return(0);
                   1505:        }
                   1506:
                   1507:        dofile(args, STDIN_FILENO == fd ?
                   1508:                "STDIN" : fname, tm, buf, cur);
                   1509:        free(buf);
                   1510:        if (STDIN_FILENO != fd)
                   1511:                close(fd);
                   1512:        return(1);
                   1513: }
                   1514:
                   1515: int
                   1516: main(int argc, char *argv[])
                   1517: {
                   1518:        const char      *fname, *name;
                   1519:        struct args      args;
                   1520:        int              c;
                   1521:
                   1522:        name = strrchr(argv[0], '/');
                   1523:        if (name == NULL)
                   1524:                name = argv[0];
                   1525:        else
                   1526:                ++name;
                   1527:
                   1528:        memset(&args, 0, sizeof(struct args));
                   1529:        fname = "-";
                   1530:
                   1531:        /* Accept no arguments for now. */
                   1532:
                   1533:        while (-1 != (c = getopt(argc, argv, "c:d:hln:oq:rs:uv")))
                   1534:                switch (c) {
                   1535:                case ('h'):
                   1536:                        /* FALLTHROUGH */
                   1537:                case ('l'):
                   1538:                        /* FALLTHROUGH */
                   1539:                case ('c'):
                   1540:                        /* FALLTHROUGH */
                   1541:                case ('o'):
                   1542:                        /* FALLTHROUGH */
                   1543:                case ('q'):
                   1544:                        /* FALLTHROUGH */
                   1545:                case ('r'):
                   1546:                        /* FALLTHROUGH */
                   1547:                case ('u'):
                   1548:                        /* FALLTHROUGH */
                   1549:                case ('v'):
                   1550:                        /* Ignore these. */
                   1551:                        break;
                   1552:                case ('d'):
                   1553:                        args.date = optarg;
                   1554:                        break;
                   1555:                case ('n'):
                   1556:                        args.title = optarg;
                   1557:                        break;
                   1558:                case ('s'):
                   1559:                        args.section = optarg;
                   1560:                        break;
                   1561:                default:
                   1562:                        goto usage;
                   1563:                }
                   1564:
                   1565:        argc -= optind;
                   1566:        argv += optind;
                   1567:
                   1568:        /* Accept only a single input file. */
                   1569:
1.25      schwarze 1570:        if (argc > 1)
                   1571:                goto usage;
1.1       schwarze 1572:        else if (1 == argc)
                   1573:                fname = *argv;
                   1574:
                   1575:        return(readfile(&args, fname) ?
                   1576:                EXIT_SUCCESS : EXIT_FAILURE);
                   1577:
                   1578: usage:
                   1579:        fprintf(stderr, "usage: %s [-d date] "
1.25      schwarze 1580:            "[-n title] [-s section] [file]\n", name);
1.1       schwarze 1581:
                   1582:        return(EXIT_FAILURE);
                   1583: }

CVSweb