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

Annotation of pod2mdoc/pod2mdoc.c, Revision 1.55

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

CVSweb