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

Annotation of texi2mdoc/util.c, Revision 1.22

1.22    ! kristaps    1: /*     $Id: util.c,v 1.21 2015/03/01 13:39:51 kristaps Exp $ */
1.1       kristaps    2: /*
                      3:  * Copyright (c) 2015 Kristaps Dzonsons <kristaps@bsd.lv>
                      4:  *
                      5:  * Permission to use, copy, modify, and distribute this software for any
                      6:  * purpose with or without fee is hereby granted, provided that the above
                      7:  * copyright notice and this permission notice appear in all copies.
                      8:  *
                      9:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                     10:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     11:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     12:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     13:  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     14:  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     15:  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
                     16:  */
                     17: #include <sys/mman.h>
                     18: #include <sys/stat.h>
                     19:
                     20: #include <assert.h>
                     21: #include <ctype.h>
                     22: #include <fcntl.h>
                     23: #include <limits.h>
                     24: #include <stdarg.h>
                     25: #include <stdio.h>
                     26: #include <stdlib.h>
                     27: #include <string.h>
                     28: #include <time.h>
                     29: #include <unistd.h>
                     30:
                     31: #include "extern.h"
                     32:
                     33: /*
                     34:  * Unmap the top-most file in the stack of files currently opened (that
                     35:  * is, nested calls to parsefile()).
                     36:  */
                     37: void
                     38: texifilepop(struct texi *p)
                     39: {
                     40:        struct texifile *f;
                     41:
                     42:        assert(p->filepos > 0);
                     43:        f = &p->files[--p->filepos];
1.14      kristaps   44:        free(f->map);
1.1       kristaps   45: }
                     46:
1.7       kristaps   47: static void
                     48: teximacrofree(struct teximacro *p)
                     49: {
                     50:        size_t   i;
                     51:
                     52:        for (i = 0; i < p->argsz; i++)
                     53:                free(p->args[i]);
                     54:
                     55:        free(p->args);
                     56:        free(p->key);
                     57:        free(p->value);
                     58: }
                     59:
                     60: static void
                     61: texivaluefree(struct texivalue *p)
                     62: {
                     63:
                     64:        free(p->key);
                     65:        free(p->value);
                     66: }
                     67:
1.1       kristaps   68: /*
                     69:  * Unmap all files that we're currently using and free all resources
                     70:  * that we've allocated during the parse.
                     71:  * The utility should exit(...) after this is called.
                     72:  */
                     73: void
                     74: texiexit(struct texi *p)
                     75: {
                     76:        size_t   i;
                     77:
                     78:        /* Make sure we're newline-terminated. */
                     79:        if (p->outcol)
1.20      kristaps   80:                fputc('\n', p->outfile);
                     81:        if (NULL != p->chapters)
                     82:                teximdocclose(p, 1);
1.1       kristaps   83:
                     84:        /* Unmap all files. */
                     85:        while (p->filepos > 0)
                     86:                texifilepop(p);
                     87:
1.7       kristaps   88:        for (i = 0; i < p->macrosz; i++)
                     89:                teximacrofree(&p->macros[i]);
1.1       kristaps   90:        for (i = 0; i < p->dirsz; i++)
                     91:                free(p->dirs[i]);
1.4       kristaps   92:        for (i = 0; i < p->indexsz; i++)
                     93:                free(p->indexs[i]);
1.7       kristaps   94:        for (i = 0; i < p->valsz; i++)
                     95:                texivaluefree(&p->vals[i]);
1.4       kristaps   96:
1.7       kristaps   97:        free(p->macros);
1.1       kristaps   98:        free(p->vals);
1.4       kristaps   99:        free(p->indexs);
1.1       kristaps  100:        free(p->dirs);
                    101:        free(p->subtitle);
                    102:        free(p->title);
                    103: }
                    104:
                    105: /*
                    106:  * Fatal error: unmap all files and exit.
                    107:  * The "errstring" is passed to perror(3).
                    108:  */
                    109: void
                    110: texiabort(struct texi *p, const char *errstring)
                    111: {
                    112:
                    113:        perror(errstring);
                    114:        texiexit(p);
                    115:        exit(EXIT_FAILURE);
                    116: }
                    117:
                    118: /*
                    119:  * Print a generic warning message (to stderr) tied to our current
                    120:  * location in the parse sequence.
                    121:  */
                    122: void
                    123: texiwarn(const struct texi *p, const char *fmt, ...)
                    124: {
1.15      kristaps  125:        va_list                  ap;
                    126:        const struct texifile   *f;
                    127:
                    128:        f = &p->files[p->filepos - 1];
                    129:
                    130:        if (f->insplice)
                    131:                fprintf(stderr, "%s:%zu:%zu (%zuB left in splice): "
                    132:                        "warning: ", f->name, f->line + 1,
                    133:                        f->col + 1, f->insplice);
                    134:        else
                    135:                fprintf(stderr, "%s:%zu:%zu: warning: ",
                    136:                        f->name, f->line + 1, f->col + 1);
1.1       kristaps  137:
                    138:        va_start(ap, fmt);
                    139:        vfprintf(stderr, fmt, ap);
                    140:        va_end(ap);
                    141:        fputc('\n', stderr);
                    142: }
                    143:
                    144: /*
                    145:  * Print an error message (to stderr) tied to our current location in
                    146:  * the parse sequence, invoke texiexit(), then die.
                    147:  */
                    148: void
                    149: texierr(struct texi *p, const char *fmt, ...)
                    150: {
1.15      kristaps  151:        va_list          ap;
                    152:        struct texifile *f;
                    153:
                    154:        f = &p->files[p->filepos - 1];
                    155:
                    156:        if (f->insplice)
                    157:                fprintf(stderr, "%s:%zu:%zu: (%zuB left in splice): "
                    158:                        "error: ", f->name, f->line + 1,
                    159:                        f->col + 1, f->insplice);
                    160:        else
                    161:                fprintf(stderr, "%s:%zu:%zu: error: ",
                    162:                        f->name, f->line + 1, f->col + 1);
1.1       kristaps  163:
                    164:        va_start(ap, fmt);
                    165:        vfprintf(stderr, fmt, ap);
                    166:        va_end(ap);
                    167:        fputc('\n', stderr);
                    168:        texiexit(p);
                    169:        exit(EXIT_FAILURE);
                    170: }
                    171:
                    172: /*
                    173:  * Put a single data character to the output if we're not ignoring.
1.13      kristaps  174:  * Escape starting a line with a control character and slashes.
1.1       kristaps  175:  */
                    176: void
                    177: texiputchar(struct texi *p, char c)
                    178: {
                    179:
                    180:        if (p->ign)
                    181:                return;
                    182:        if ('.' == c && 0 == p->outcol)
1.20      kristaps  183:                fputs("\\&", p->outfile);
1.10      kristaps  184:        if ('\'' == c && 0 == p->outcol)
1.20      kristaps  185:                fputs("\\&", p->outfile);
1.1       kristaps  186:
1.20      kristaps  187:        fputc(c, p->outfile);
1.13      kristaps  188:        if ('\\' == c)
1.20      kristaps  189:                fputc('e', p->outfile);
1.1       kristaps  190:        p->seenvs = 0;
                    191:        if ('\n' == c) {
                    192:                p->outcol = 0;
                    193:                p->seenws = 0;
                    194:        } else
                    195:                p->outcol++;
                    196: }
                    197:
                    198: /*
1.13      kristaps  199:  * Put an opaque series of characters.
                    200:  * Characters starting a line with a control character are escaped, but
                    201:  * that's it, so don't use this for non-controlled sequences of text.
1.1       kristaps  202:  */
                    203: void
                    204: texiputchars(struct texi *p, const char *s)
                    205: {
                    206:
1.13      kristaps  207:        if (p->ign)
                    208:                return;
                    209:        if ('.' == *s && 0 == p->outcol)
1.20      kristaps  210:                fputs("\\&", p->outfile);
1.13      kristaps  211:        if ('\'' == *s && 0 == p->outcol)
1.20      kristaps  212:                fputs("\\&", p->outfile);
                    213:        p->outcol += fputs(s, p->outfile);
1.13      kristaps  214:        p->seenvs = 0;
1.9       kristaps  215: }
                    216:
                    217: /*
                    218:  * This puts all characters onto the output stream but makes sure to
                    219:  * escape mdoc(7) slashes.
1.14      kristaps  220:  * FIXME: useless.
1.9       kristaps  221:  */
                    222: void
1.14      kristaps  223: texiputbuf(struct texi *p, size_t start, size_t end)
1.9       kristaps  224: {
                    225:
1.14      kristaps  226:        for ( ; start < end; start++)
                    227:                texiputchar(p, BUF(p)[start]);
1.1       kristaps  228: }
                    229:
                    230: /*
                    231:  * Close an mdoc(7) macro opened with teximacroopen().
                    232:  * If there are no more macros on the line, prints a newline.
                    233:  */
                    234: void
                    235: teximacroclose(struct texi *p)
                    236: {
                    237:
                    238:        if (p->ign)
                    239:                return;
                    240:
                    241:        if (0 == --p->outmacro) {
1.20      kristaps  242:                fputc('\n', p->outfile);
1.1       kristaps  243:                p->outcol = p->seenws = 0;
                    244:        }
                    245: }
                    246:
                    247: /*
                    248:  * Open a mdoc(7) macro.
                    249:  * This is used for line macros, e.g., Qq [foo bar baz].
                    250:  * It can be invoked for nested macros, e.g., Qq Li foo .
                    251:  * TODO: flush-right punctuation (e.g., parenthesis).
                    252:  */
                    253: void
                    254: teximacroopen(struct texi *p, const char *s)
                    255: {
                    256:        int      rc;
                    257:
                    258:        if (p->ign)
                    259:                return;
                    260:
                    261:        if (p->outcol && 0 == p->outmacro) {
1.20      kristaps  262:                fputc('\n', p->outfile);
1.1       kristaps  263:                p->outcol = 0;
                    264:        }
                    265:
                    266:        if (0 == p->outmacro)
1.20      kristaps  267:                fputc('.', p->outfile);
1.1       kristaps  268:        else
1.20      kristaps  269:                fputc(' ', p->outfile);
1.1       kristaps  270:
1.20      kristaps  271:        if (EOF != (rc = fputs(s, p->outfile)))
1.1       kristaps  272:                p->outcol += rc;
                    273:
1.20      kristaps  274:        fputc(' ', p->outfile);
1.1       kristaps  275:        p->outcol++;
                    276:        p->outmacro++;
                    277:        p->seenws = 0;
                    278: }
                    279:
                    280: /*
                    281:  * Put a stadnalone mdoc(7) command with the trailing newline.
                    282:  */
                    283: void
                    284: teximacro(struct texi *p, const char *s)
                    285: {
                    286:
                    287:        if (p->ign)
                    288:                return;
                    289:
                    290:        if (p->outmacro)
                    291:                texierr(p, "\"%s\" in open line scope!?", s);
                    292:        if (p->literal)
                    293:                texierr(p, "\"%s\" in a literal scope!?", s);
                    294:
                    295:        if (p->outcol)
1.20      kristaps  296:                fputc('\n', p->outfile);
1.1       kristaps  297:
1.20      kristaps  298:        fputc('.', p->outfile);
                    299:        fputs(s, p->outfile);
                    300:        fputc('\n', p->outfile);
1.1       kristaps  301:        p->outcol = p->seenws = 0;
                    302: }
                    303:
                    304: /*
                    305:  * Introduce vertical space during normal (non-macro) input.
                    306:  */
                    307: void
                    308: texivspace(struct texi *p)
                    309: {
                    310:
1.5       kristaps  311:        if (p->seenvs || TEXILIST_TABLE == p->list)
1.1       kristaps  312:                return;
                    313:        teximacro(p, "Pp");
                    314:        p->seenvs = 1;
                    315: }
                    316:
                    317: /*
                    318:  * Advance by a single byte in the input stream, adjusting our location
                    319:  * in the current input file.
                    320:  */
                    321: void
1.14      kristaps  322: advance(struct texi *p, size_t *pos)
1.1       kristaps  323: {
1.15      kristaps  324:        struct texifile *f;
1.1       kristaps  325:
1.15      kristaps  326:        f = &p->files[p->filepos - 1];
                    327:
                    328:        if (0 == f->insplice) {
                    329:                if ('\n' == BUF(p)[*pos]) {
                    330:                        f->line++;
                    331:                        f->col = 0;
                    332:                } else
                    333:                        f->col++;
1.17      kristaps  334:        } else {
1.15      kristaps  335:                --f->insplice;
1.17      kristaps  336:                if (0 == f->insplice)
                    337:                        f->depth = 0;
                    338:        }
1.1       kristaps  339:
                    340:        (*pos)++;
                    341: }
                    342:
                    343: /*
                    344:  * It's common to wait punctuation to float on the right side of macro
                    345:  * lines in mdoc(7), e.g., ".Em hello ) ."
                    346:  * This function does so, and should be called before teximacroclose().
                    347:  * It will detect that it's the last in the nested macros and
                    348:  * appropriately flush-left punctuation alongside the macro.
                    349:  */
                    350: void
1.14      kristaps  351: texipunctuate(struct texi *p, size_t *pos)
1.1       kristaps  352: {
                    353:        size_t   start, end;
                    354:
                    355:        if (1 != p->outmacro)
                    356:                return;
                    357:
1.14      kristaps  358:        for (start = end = *pos; end < BUFSZ(p); end++) {
                    359:                switch (BUF(p)[end]) {
1.1       kristaps  360:                case (','):
                    361:                case (')'):
                    362:                case ('.'):
                    363:                case ('"'):
                    364:                case (':'):
1.22    ! kristaps  365:                case (';'):
1.1       kristaps  366:                case ('!'):
                    367:                case ('?'):
                    368:                        continue;
                    369:                default:
                    370:                        break;
                    371:                }
                    372:                break;
                    373:        }
                    374:        if (end == *pos)
                    375:                return;
1.14      kristaps  376:        if (end + 1 == BUFSZ(p) || ' ' == BUF(p)[end] ||
                    377:                '\n' == BUF(p)[end]) {
1.1       kristaps  378:                for ( ; start < end; start++) {
                    379:                        texiputchar(p, ' ');
1.14      kristaps  380:                        texiputchar(p, BUF(p)[start]);
                    381:                        advance(p, pos);
1.1       kristaps  382:                }
                    383:        }
                    384: }
                    385:
                    386: /*
                    387:  * Advance to the next non-whitespace word in the input stream.
                    388:  * If we're in literal mode, then print all of the whitespace as we're
                    389:  * doing so.
                    390:  */
                    391: static size_t
1.14      kristaps  392: advancenext(struct texi *p, size_t *pos)
1.1       kristaps  393: {
                    394:
                    395:        if (p->literal) {
1.14      kristaps  396:                while (*pos < BUFSZ(p) && ismspace(BUF(p)[*pos])) {
                    397:                        texiputchar(p, BUF(p)[*pos]);
                    398:                        advance(p, pos);
1.1       kristaps  399:                }
                    400:                return(*pos);
                    401:        }
                    402:
1.14      kristaps  403:        while (*pos < BUFSZ(p) && ismspace(BUF(p)[*pos])) {
1.1       kristaps  404:                p->seenws = 1;
                    405:                /*
                    406:                 * If it looks like we've printed a double-line, then
                    407:                 * output a paragraph.
                    408:                 * FIXME: this is stupid.
                    409:                 */
1.14      kristaps  410:                if (*pos && '\n' == BUF(p)[*pos] && '\n' == BUF(p)[*pos - 1])
1.1       kristaps  411:                        texivspace(p);
1.14      kristaps  412:                advance(p, pos);
1.1       kristaps  413:        }
                    414:        return(*pos);
                    415: }
                    416:
                    417: /*
                    418:  * Advance to the EOLN in the input stream.
1.22    ! kristaps  419:  * This will skip over '@' markers in an effort to ignore escaped
        !           420:  * newlines.
1.1       kristaps  421:  */
                    422: size_t
1.14      kristaps  423: advanceeoln(struct texi *p, size_t *pos, int consumenl)
1.1       kristaps  424: {
                    425:
1.22    ! kristaps  426:        while (*pos < BUFSZ(p) && '\n' != BUF(p)[*pos]) {
        !           427:                if ('@' == BUF(p)[*pos])
        !           428:                        advance(p, pos);
1.14      kristaps  429:                advance(p, pos);
1.22    ! kristaps  430:        }
1.14      kristaps  431:        if (*pos < BUFSZ(p) && consumenl)
                    432:                advance(p, pos);
1.1       kristaps  433:        return(*pos);
                    434: }
                    435:
                    436: /*
                    437:  * Advance to position "end", which is an absolute position in the
                    438:  * current buffer greater than or equal to the current position.
                    439:  */
                    440: void
1.14      kristaps  441: advanceto(struct texi *p, size_t *pos, size_t end)
1.1       kristaps  442: {
                    443:
                    444:        assert(*pos <= end);
                    445:        while (*pos < end)
1.14      kristaps  446:                advance(p, pos);
1.1       kristaps  447: }
                    448:
1.7       kristaps  449: static void
1.17      kristaps  450: texiexecmacro(struct texi *p, struct teximacro *m, size_t sv, size_t *pos)
1.7       kristaps  451: {
1.11      kristaps  452:        size_t            valsz, realsz, aasz, asz,
                    453:                           ssz, i, j, k, start, end;
                    454:        char             *val;
                    455:        char            **args;
                    456:        const char       *cp;
1.7       kristaps  457:
1.17      kristaps  458:        /* Disregard empty macros. */
1.22    ! kristaps  459:        if (0 == (valsz = realsz = strlen(m->value))) {
        !           460:                args = argparse(p, pos, &asz, m->argsz);
        !           461:                for (i = 0; i < asz; i++)
        !           462:                        free(args[i]);
        !           463:                free(args);
1.17      kristaps  464:                return;
1.22    ! kristaps  465:        }
1.17      kristaps  466:
                    467:        /*
                    468:         * This is important: it protect us from macros that invoke more
                    469:         * macros, possibly going on infinitely.
                    470:         * We use "sv" instead of the current position because we might
                    471:         * be invoked at the end of the macro (i.e., insplice == 0).
                    472:         * The "sv" value was initialised at the start of the macro.
                    473:         */
                    474:        if (sv > 0)
                    475:                if (++p->files[p->filepos].depth > 64)
                    476:                        texierr(p, "maximium recursive depth");
                    477:
1.14      kristaps  478:        args = argparse(p, pos, &asz, m->argsz);
1.7       kristaps  479:        if (asz != m->argsz)
                    480:                texiwarn(p, "invalid macro argument length");
                    481:        aasz = asz < m->argsz ? asz : m->argsz;
                    482:
                    483:        if (0 == aasz) {
1.21      kristaps  484:                texisplice(p, m->value, valsz, *pos);
1.7       kristaps  485:                return;
                    486:        }
                    487:
                    488:        val = strdup(m->value);
                    489:
                    490:        for (i = j = 0; i < realsz; i++) {
                    491:                /* Parse blindly til the backslash delimiter. */
                    492:                if ('\\' != m->value[i]) {
                    493:                        val[j++] = m->value[i];
                    494:                        val[j] = '\0';
                    495:                        continue;
                    496:                } else if (i == realsz - 1)
                    497:                        texierr(p, "trailing argument name delimiter");
                    498:
                    499:                /* Double-backslash is escaped. */
                    500:                if ('\\' == m->value[i + 1]) {
                    501:                        val[j++] = m->value[i++];
                    502:                        val[j] = '\0';
                    503:                        continue;
                    504:                }
                    505:
                    506:                assert('\\' == m->value[i] && i < realsz - 1);
                    507:
                    508:                /* Parse to terminating delimiter. */
                    509:                /* FIXME: embedded, escaped delimiters? */
                    510:                for (start = end = i + 1; end < realsz; end++)
                    511:                        if ('\\' == m->value[end])
                    512:                                break;
                    513:                if (end == realsz)
                    514:                        texierr(p, "unterminated argument name");
                    515:
                    516:                for (k = 0; k < aasz; k++) {
                    517:                        if ((ssz = strlen(m->args[k])) != (end - start))
                    518:                                continue;
                    519:                        if (strncmp(&m->value[start], m->args[k], ssz))
                    520:                                continue;
                    521:                        break;
                    522:                }
                    523:
                    524:                /*
                    525:                 * Argument didn't exist in argument table.
1.14      kristaps  526:                 * Just ignore it.
1.7       kristaps  527:                 */
                    528:                if (k == aasz) {
1.14      kristaps  529:                        i = end;
1.7       kristaps  530:                        continue;
                    531:                }
                    532:
                    533:                if (strlen(args[k]) > ssz) {
                    534:                        valsz += strlen(args[k]);
                    535:                        val = realloc(val, valsz + 1);
                    536:                        if (NULL == val)
                    537:                                texiabort(p, NULL);
                    538:                }
                    539:
1.11      kristaps  540:                for (cp = args[k]; '\0' != *cp; cp++)
                    541:                        val[j++] = *cp;
                    542:
                    543:                val[j] = '\0';
1.7       kristaps  544:                i = end;
                    545:        }
                    546:
1.21      kristaps  547:        texisplice(p, val, strlen(val), *pos);
1.7       kristaps  548:
                    549:        for (i = 0; i < asz; i++)
                    550:                free(args[i]);
                    551:        free(args);
                    552:        free(val);
                    553: }
                    554:
1.1       kristaps  555: /*
                    556:  * Output a free-form word in the input stream, progressing to the next
                    557:  * command or white-space.
                    558:  * This also will advance the input stream.
                    559:  */
                    560: static void
1.14      kristaps  561: parseword(struct texi *p, size_t *pos, char extra)
1.1       kristaps  562: {
                    563:
                    564:        if (p->seenws && 0 == p->outmacro &&
                    565:                 p->outcol > 72 && 0 == p->literal)
                    566:                texiputchar(p, '\n');
                    567:        /* FIXME: abstract this: we use it elsewhere. */
                    568:        if (p->seenws && p->outcol && 0 == p->literal)
                    569:                texiputchar(p, ' ');
                    570:
                    571:        p->seenws = 0;
                    572:
1.14      kristaps  573:        while (*pos < BUFSZ(p) && ! ismspace(BUF(p)[*pos])) {
                    574:                switch (BUF(p)[*pos]) {
1.1       kristaps  575:                case ('@'):
                    576:                case ('}'):
                    577:                case ('{'):
                    578:                        return;
                    579:                }
1.14      kristaps  580:                if ('\0' != extra && BUF(p)[*pos] == extra)
1.1       kristaps  581:                        return;
1.14      kristaps  582:                if (*pos < BUFSZ(p) - 1 &&
                    583:                         '`' == BUF(p)[*pos] &&
                    584:                         '`' == BUF(p)[*pos + 1]) {
1.1       kristaps  585:                        texiputchars(p, "\\(lq");
1.14      kristaps  586:                        advance(p, pos);
                    587:                } else if (*pos < BUFSZ(p) - 1 &&
                    588:                         '\'' == BUF(p)[*pos] &&
                    589:                         '\'' == BUF(p)[*pos + 1]) {
1.1       kristaps  590:                        texiputchars(p, "\\(rq");
1.14      kristaps  591:                        advance(p, pos);
1.1       kristaps  592:                } else
1.14      kristaps  593:                        texiputchar(p, BUF(p)[*pos]);
                    594:                advance(p, pos);
1.1       kristaps  595:        }
                    596: }
                    597:
                    598: /*
                    599:  * Look up the command at position "pos" in the buffer, returning it (or
                    600:  * TEXICMD__MAX if none found) and setting "end" to be the absolute
                    601:  * index after the command name.
                    602:  */
                    603: enum texicmd
1.19      kristaps  604: texicmd(const struct texi *p, size_t pos, size_t *end, struct teximacro **macro)
1.1       kristaps  605: {
1.4       kristaps  606:        size_t   i, len, toksz;
1.1       kristaps  607:
1.14      kristaps  608:        assert('@' == BUF(p)[pos]);
1.1       kristaps  609:
1.7       kristaps  610:        if (NULL != macro)
                    611:                *macro = NULL;
                    612:
1.14      kristaps  613:        if ((*end = pos) == BUFSZ(p))
1.1       kristaps  614:                return(TEXICMD__MAX);
1.14      kristaps  615:        else if ((*end = ++pos) == BUFSZ(p))
1.1       kristaps  616:                return(TEXICMD__MAX);
                    617:
                    618:        /* Alphabetic commands are special. */
1.16      kristaps  619:        if ( ! isalpha((unsigned char)BUF(p)[pos])) {
1.14      kristaps  620:                if ((*end = pos + 1) == BUFSZ(p))
1.1       kristaps  621:                        return(TEXICMD__MAX);
                    622:                for (i = 0; i < TEXICMD__MAX; i++) {
                    623:                        if (1 != texitoks[i].len)
                    624:                                continue;
1.14      kristaps  625:                        if (0 == strncmp(texitoks[i].tok, &BUF(p)[pos], 1))
1.1       kristaps  626:                                return(i);
                    627:                }
1.14      kristaps  628:                texiwarn(p, "bad command: @%c", BUF(p)[pos]);
1.1       kristaps  629:                return(TEXICMD__MAX);
                    630:        }
                    631:
1.4       kristaps  632:        /* Scan to the end of the possible command name. */
1.14      kristaps  633:        for (*end = pos; *end < BUFSZ(p) && ! ismspace(BUF(p)[*end]); (*end)++)
                    634:                if ((*end > pos && ('@' == BUF(p)[*end] ||
                    635:                          '{' == BUF(p)[*end] || '}' == BUF(p)[*end])))
1.1       kristaps  636:                        break;
                    637:
1.4       kristaps  638:        /* Look for the command. */
1.1       kristaps  639:        len = *end - pos;
                    640:        for (i = 0; i < TEXICMD__MAX; i++) {
                    641:                if (len != texitoks[i].len)
                    642:                        continue;
1.14      kristaps  643:                if (0 == strncmp(texitoks[i].tok, &BUF(p)[pos], len))
1.1       kristaps  644:                        return(i);
                    645:        }
                    646:
1.4       kristaps  647:        /* Look for it in our indices. */
                    648:        for (i = 0; i < p->indexsz; i++) {
                    649:                toksz = strlen(p->indexs[i]);
                    650:                if (len != 5 + toksz)
                    651:                        continue;
1.14      kristaps  652:                if (strncmp(&BUF(p)[pos], p->indexs[i], toksz))
1.4       kristaps  653:                        continue;
1.14      kristaps  654:                if (0 == strncmp(&BUF(p)[pos + toksz], "index", 5))
1.7       kristaps  655:                        return(TEXICMD_USER_INDEX);
                    656:        }
                    657:
                    658:        for (i = 0; i < p->macrosz; i++) {
                    659:                if (len != strlen(p->macros[i].key))
                    660:                        continue;
1.14      kristaps  661:                if (strncmp(&BUF(p)[pos], p->macros[i].key, len))
1.7       kristaps  662:                        continue;
                    663:                if (NULL != macro)
                    664:                        *macro = &p->macros[i];
                    665:                return(TEXICMD__MAX);
1.4       kristaps  666:        }
                    667:
1.14      kristaps  668:        texiwarn(p, "bad command: @%.*s", (int)len, &BUF(p)[pos]);
1.1       kristaps  669:        return(TEXICMD__MAX);
                    670: }
                    671:
                    672: /*
                    673:  * Parse an argument from a bracketed command, e.g., @url{foo, baz}.
                    674:  * Num should be set to the argument we're currently parsing, although
                    675:  * it suffixes for it to be zero or non-zero.
                    676:  * This will return 1 if there are more arguments, 0 otherwise.
                    677:  * This will stop (returning 0) in the event of EOF or if we're not at a
                    678:  * bracket for the zeroth parse.
                    679:  */
                    680: int
1.14      kristaps  681: parsearg(struct texi *p, size_t *pos, size_t num)
1.1       kristaps  682: {
1.17      kristaps  683:        size_t            end, sv;
1.7       kristaps  684:        enum texicmd      cmd;
                    685:        struct teximacro *macro;
1.1       kristaps  686:
1.14      kristaps  687:        while (*pos < BUFSZ(p) && ismspace(BUF(p)[*pos]))
                    688:                advance(p, pos);
                    689:        if (*pos == BUFSZ(p) || (0 == num && '{' != BUF(p)[*pos]))
1.1       kristaps  690:                return(0);
                    691:        if (0 == num)
1.14      kristaps  692:                advance(p, pos);
1.1       kristaps  693:
1.14      kristaps  694:        while ((*pos = advancenext(p, pos)) < BUFSZ(p)) {
                    695:                switch (BUF(p)[*pos]) {
1.1       kristaps  696:                case (','):
1.14      kristaps  697:                        advance(p, pos);
1.1       kristaps  698:                        return(1);
                    699:                case ('}'):
1.14      kristaps  700:                        advance(p, pos);
1.1       kristaps  701:                        return(0);
                    702:                case ('{'):
                    703:                        if (0 == p->ign)
                    704:                                texiwarn(p, "unexpected \"{\"");
1.14      kristaps  705:                        advance(p, pos);
1.1       kristaps  706:                        continue;
                    707:                case ('@'):
                    708:                        break;
                    709:                default:
1.14      kristaps  710:                        parseword(p, pos, ',');
1.1       kristaps  711:                        continue;
                    712:                }
                    713:
1.17      kristaps  714:                sv = p->files[p->filepos - 1].insplice;
1.14      kristaps  715:                cmd = texicmd(p, *pos, &end, &macro);
                    716:                advanceto(p, pos, end);
1.7       kristaps  717:                if (NULL != macro)
1.17      kristaps  718:                        texiexecmacro(p, macro, sv, pos);
1.1       kristaps  719:                if (TEXICMD__MAX == cmd)
                    720:                        continue;
                    721:                if (NULL != texitoks[cmd].fp)
1.14      kristaps  722:                        (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps  723:        }
                    724:        return(0);
                    725: }
                    726:
                    727: /*
                    728:  * Parse until the end of a bracketed statement, e.g., @foo{bar baz}.
                    729:  * This will stop in the event of EOF or if we're not at a bracket.
                    730:  */
                    731: void
1.18      kristaps  732: parsebracket(struct texi *p, size_t *pos, int dostack)
1.1       kristaps  733: {
1.18      kristaps  734:        size_t            end, sv, stack;
1.7       kristaps  735:        enum texicmd      cmd;
                    736:        struct teximacro *macro;
1.1       kristaps  737:
1.14      kristaps  738:        while (*pos < BUFSZ(p) && ismspace(BUF(p)[*pos]))
                    739:                advance(p, pos);
1.1       kristaps  740:
1.14      kristaps  741:        if (*pos == BUFSZ(p) || '{' != BUF(p)[*pos])
1.1       kristaps  742:                return;
1.14      kristaps  743:        advance(p, pos);
1.1       kristaps  744:
1.18      kristaps  745:        stack = 0;
1.14      kristaps  746:        while ((*pos = advancenext(p, pos)) < BUFSZ(p)) {
                    747:                switch (BUF(p)[*pos]) {
1.1       kristaps  748:                case ('}'):
1.18      kristaps  749:                        if (stack > 0) {
                    750:                                stack--;
                    751:                                advance(p, pos);
                    752:                                texiputchar(p, '}');
                    753:                                continue;
                    754:                        }
1.14      kristaps  755:                        advance(p, pos);
1.1       kristaps  756:                        return;
                    757:                case ('{'):
1.18      kristaps  758:                        if (dostack) {
                    759:                                stack++;
                    760:                                advance(p, pos);
                    761:                                texiputchar(p, '{');
                    762:                                continue;
                    763:                        }
1.1       kristaps  764:                        if (0 == p->ign)
                    765:                                texiwarn(p, "unexpected \"{\"");
1.14      kristaps  766:                        advance(p, pos);
1.1       kristaps  767:                        continue;
                    768:                case ('@'):
                    769:                        break;
                    770:                default:
1.14      kristaps  771:                        parseword(p, pos, '\0');
1.1       kristaps  772:                        continue;
                    773:                }
                    774:
1.17      kristaps  775:                sv = p->files[p->filepos - 1].insplice;
1.14      kristaps  776:                cmd = texicmd(p, *pos, &end, &macro);
                    777:                advanceto(p, pos, end);
1.7       kristaps  778:                if (NULL != macro)
1.17      kristaps  779:                        texiexecmacro(p, macro, sv, pos);
1.1       kristaps  780:                if (TEXICMD__MAX == cmd)
                    781:                        continue;
                    782:                if (NULL != texitoks[cmd].fp)
1.14      kristaps  783:                        (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps  784:        }
                    785: }
                    786:
                    787: /*
                    788:  * This should be invoked when we're on a macro line and want to process
                    789:  * to the end of the current input line, doing all of our macros along
                    790:  * the way.
                    791:  */
                    792: void
1.14      kristaps  793: parseeoln(struct texi *p, size_t *pos)
1.1       kristaps  794: {
1.17      kristaps  795:        size_t            end, sv;
1.7       kristaps  796:        enum texicmd      cmd;
                    797:        struct teximacro *macro;
1.1       kristaps  798:
1.14      kristaps  799:        while (*pos < BUFSZ(p) && '\n' != BUF(p)[*pos]) {
                    800:                while (*pos < BUFSZ(p) && isws(BUF(p)[*pos])) {
1.1       kristaps  801:                        p->seenws = 1;
                    802:                        if (p->literal)
1.14      kristaps  803:                                texiputchar(p, BUF(p)[*pos]);
                    804:                        advance(p, pos);
1.1       kristaps  805:                }
1.14      kristaps  806:                switch (BUF(p)[*pos]) {
1.1       kristaps  807:                case ('}'):
                    808:                        if (0 == p->ign)
                    809:                                texiwarn(p, "unexpected \"}\"");
1.14      kristaps  810:                        advance(p, pos);
1.1       kristaps  811:                        continue;
                    812:                case ('{'):
                    813:                        if (0 == p->ign)
                    814:                                texiwarn(p, "unexpected \"{\"");
1.14      kristaps  815:                        advance(p, pos);
1.1       kristaps  816:                        continue;
                    817:                case ('@'):
                    818:                        break;
                    819:                default:
1.14      kristaps  820:                        parseword(p, pos, '\0');
1.1       kristaps  821:                        continue;
                    822:                }
                    823:
1.17      kristaps  824:                sv = p->files[p->filepos - 1].insplice;
1.14      kristaps  825:                cmd = texicmd(p, *pos, &end, &macro);
                    826:                advanceto(p, pos, end);
1.7       kristaps  827:                if (NULL != macro)
1.17      kristaps  828:                        texiexecmacro(p, macro, sv, pos);
1.1       kristaps  829:                if (TEXICMD__MAX == cmd)
                    830:                        continue;
                    831:                if (NULL != texitoks[cmd].fp)
1.14      kristaps  832:                        (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps  833:        }
1.14      kristaps  834:
                    835:        if (*pos < BUFSZ(p) && '\n' == BUF(p)[*pos])
                    836:                advance(p, pos);
1.19      kristaps  837: }
                    838:
                    839: /*
                    840:  * Peek to see if there's a command after subsequent whitespace.
                    841:  * If so, return the macro identifier.
                    842:  * This DOES NOT work with user-defined macros.
                    843:  */
                    844: enum texicmd
                    845: peekcmd(const struct texi *p, size_t pos)
                    846: {
                    847:        size_t          end;
                    848:
                    849:        while (pos < BUFSZ(p) && ismspace(BUF(p)[pos]))
                    850:                pos++;
                    851:        if (pos == BUFSZ(p) || '@' != BUF(p)[pos])
                    852:                return(TEXICMD__MAX);
                    853:        return(texicmd(p, pos, &end, NULL));
1.1       kristaps  854: }
                    855:
                    856: /*
                    857:  * Parse a single word or command.
                    858:  * This will return immediately at the EOF.
                    859:  */
1.14      kristaps  860: static void
                    861: parsesingle(struct texi *p, size_t *pos)
1.1       kristaps  862: {
1.17      kristaps  863:        size_t            end, sv;
1.7       kristaps  864:        enum texicmd      cmd;
                    865:        struct teximacro *macro;
1.1       kristaps  866:
1.14      kristaps  867:        if ((*pos = advancenext(p, pos)) >= BUFSZ(p))
1.1       kristaps  868:                return;
                    869:
1.14      kristaps  870:        switch (BUF(p)[*pos]) {
1.1       kristaps  871:        case ('}'):
                    872:                if (0 == p->ign)
                    873:                        texiwarn(p, "unexpected \"}\"");
1.14      kristaps  874:                advance(p, pos);
1.1       kristaps  875:                return;
                    876:        case ('{'):
                    877:                if (0 == p->ign)
                    878:                        texiwarn(p, "unexpected \"{\"");
1.14      kristaps  879:                advance(p, pos);
1.1       kristaps  880:                return;
                    881:        case ('@'):
                    882:                break;
                    883:        default:
1.14      kristaps  884:                parseword(p, pos, '\0');
1.1       kristaps  885:                return;
                    886:        }
                    887:
1.17      kristaps  888:        sv = p->files[p->filepos - 1].insplice;
1.14      kristaps  889:        cmd = texicmd(p, *pos, &end, &macro);
                    890:        advanceto(p, pos, end);
1.7       kristaps  891:        if (NULL != macro)
1.17      kristaps  892:                texiexecmacro(p, macro, sv, pos);
1.1       kristaps  893:        if (TEXICMD__MAX == cmd)
                    894:                return;
                    895:        if (NULL != texitoks[cmd].fp)
1.14      kristaps  896:                (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps  897: }
                    898:
                    899: /*
                    900:  * This is used in the @deffn type of command.
                    901:  * These have an arbitrary number of line arguments; however, these
                    902:  * arguments may or may not be surrounded by brackets.
                    903:  * In this function, we parse each one as either a bracketed or
                    904:  * non-bracketed argument, returning 0 when we've reached the end of
                    905:  * line or 1 otherwise.
                    906:  */
                    907: int
1.14      kristaps  908: parselinearg(struct texi *p, size_t *pos)
1.1       kristaps  909: {
                    910:
1.14      kristaps  911:        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos])) {
1.1       kristaps  912:                p->seenws = 1;
1.14      kristaps  913:                advance(p, pos);
1.1       kristaps  914:        }
                    915:
1.14      kristaps  916:        if (*pos < BUFSZ(p) && '{' == BUF(p)[*pos])
1.18      kristaps  917:                parsebracket(p, pos, 0);
1.14      kristaps  918:        else if (*pos < BUFSZ(p) && '\n' != BUF(p)[*pos])
                    919:                parsesingle(p, pos);
1.1       kristaps  920:        else
                    921:                return(0);
                    922:
                    923:        return(1);
                    924: }
                    925:
                    926: /*
                    927:  * Parse til the end of the buffer.
                    928:  */
1.14      kristaps  929: static void
                    930: parseeof(struct texi *p)
1.1       kristaps  931: {
                    932:        size_t   pos;
                    933:
1.14      kristaps  934:        for (pos = 0; pos < BUFSZ(p); )
                    935:                parsesingle(p, &pos);
1.1       kristaps  936: }
                    937:
1.8       kristaps  938: void
1.21      kristaps  939: texisplice(struct texi *p, const char *buf, size_t sz, size_t pos)
1.8       kristaps  940: {
1.14      kristaps  941:        char            *cp;
                    942:        struct texifile *f;
1.8       kristaps  943:
1.14      kristaps  944:        assert(p->filepos > 0);
                    945:        f = &p->files[p->filepos - 1];
1.8       kristaps  946:
1.14      kristaps  947:        if (f->mapsz + sz > f->mapmaxsz) {
                    948:                f->mapmaxsz = f->mapsz + sz + 1024;
                    949:                cp = realloc(f->map, f->mapmaxsz);
                    950:                if (NULL == cp)
                    951:                        texiabort(p, NULL);
                    952:                f->map = cp;
                    953:        }
1.8       kristaps  954:
1.15      kristaps  955:        f->insplice += sz;
1.21      kristaps  956:        memmove(f->map + pos + sz, f->map + pos, f->mapsz - pos);
                    957:        memcpy(f->map + pos, buf, sz);
1.14      kristaps  958:        f->mapsz += sz;
1.8       kristaps  959: }
                    960:
                    961: /*
1.1       kristaps  962:  * Parse a block sequence until we have the "@end endtoken" command
                    963:  * invocation.
                    964:  * This will return immediately at EOF.
                    965:  */
                    966: void
1.14      kristaps  967: parseto(struct texi *p, size_t *pos, const char *endtoken)
1.1       kristaps  968: {
1.17      kristaps  969:        size_t            end, sv;
1.7       kristaps  970:        enum texicmd      cmd;
                    971:        size_t            endtoksz;
                    972:        struct teximacro *macro;
1.1       kristaps  973:
                    974:        endtoksz = strlen(endtoken);
                    975:        assert(endtoksz > 0);
                    976:
1.14      kristaps  977:        while ((*pos = advancenext(p, pos)) < BUFSZ(p)) {
                    978:                switch (BUF(p)[*pos]) {
1.1       kristaps  979:                case ('}'):
                    980:                        if (0 == p->ign)
                    981:                                texiwarn(p, "unexpected \"}\"");
1.14      kristaps  982:                        advance(p, pos);
1.1       kristaps  983:                        continue;
                    984:                case ('{'):
                    985:                        if (0 == p->ign)
                    986:                                texiwarn(p, "unexpected \"{\"");
1.14      kristaps  987:                        advance(p, pos);
1.1       kristaps  988:                        continue;
                    989:                case ('@'):
                    990:                        break;
                    991:                default:
1.14      kristaps  992:                        parseword(p, pos, '\0');
1.1       kristaps  993:                        continue;
                    994:                }
                    995:
1.17      kristaps  996:                sv = p->files[p->filepos - 1].insplice;
1.14      kristaps  997:                cmd = texicmd(p, *pos, &end, &macro);
                    998:                advanceto(p, pos, end);
1.1       kristaps  999:                if (TEXICMD_END == cmd) {
1.14      kristaps 1000:                        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1001:                                advance(p, pos);
1.1       kristaps 1002:                        /*
                   1003:                         * FIXME: check the full word, not just its
                   1004:                         * initial substring!
                   1005:                         */
1.14      kristaps 1006:                        if (BUFSZ(p) - *pos >= endtoksz && 0 == strncmp
                   1007:                                 (&BUF(p)[*pos], endtoken, endtoksz)) {
                   1008:                                advanceeoln(p, pos, 0);
1.1       kristaps 1009:                                break;
                   1010:                        }
                   1011:                        if (0 == p->ign)
                   1012:                                texiwarn(p, "unexpected \"end\"");
1.14      kristaps 1013:                        advanceeoln(p, pos, 0);
1.1       kristaps 1014:                        continue;
1.7       kristaps 1015:                }
                   1016:                if (NULL != macro)
1.17      kristaps 1017:                        texiexecmacro(p, macro, sv, pos);
1.7       kristaps 1018:                if (TEXICMD__MAX == cmd)
                   1019:                        continue;
                   1020:                if (NULL != texitoks[cmd].fp)
1.14      kristaps 1021:                        (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps 1022:        }
                   1023: }
                   1024:
                   1025: /*
1.12      kristaps 1026:  * Like parsefile() but used for reading from stdandard input.
                   1027:  * This can only be called for the first file!
                   1028:  */
                   1029: void
                   1030: parsestdin(struct texi *p)
                   1031: {
                   1032:        struct texifile *f;
                   1033:        ssize_t          ssz;
                   1034:
                   1035:        assert(0 == p->filepos);
                   1036:        f = &p->files[p->filepos];
                   1037:        memset(f, 0, sizeof(struct texifile));
                   1038:
                   1039:        f->type = TEXISRC_STDIN;
                   1040:        f->name = "<stdin>";
                   1041:
1.14      kristaps 1042:        for (f->mapsz = 0; ; f->mapsz += (size_t)ssz) {
                   1043:                if (f->mapsz == f->mapmaxsz) {
                   1044:                        if (f->mapmaxsz == (1U << 31))
1.12      kristaps 1045:                                texierr(p, "stdin buffer too long");
1.14      kristaps 1046:                        f->mapmaxsz = f->mapmaxsz > 65536 / 2 ?
                   1047:                                2 * f->mapmaxsz : 65536;
                   1048:                        f->map = realloc(f->map, f->mapmaxsz);
1.12      kristaps 1049:                        if (NULL == f->map)
                   1050:                                texiabort(p, NULL);
                   1051:                }
1.14      kristaps 1052:                ssz = read(STDIN_FILENO, f->map +
                   1053:                        (int)f->mapsz, f->mapmaxsz - f->mapsz);
1.12      kristaps 1054:                if (0 == ssz)
                   1055:                        break;
                   1056:                else if (-1 == ssz)
                   1057:                        texiabort(p, NULL);
                   1058:        }
                   1059:
                   1060:        p->filepos++;
1.14      kristaps 1061:        parseeof(p);
1.12      kristaps 1062:        texifilepop(p);
                   1063: }
                   1064:
                   1065: /*
1.1       kristaps 1066:  * Memory-map the file "fname" and begin parsing it unless "parse" is
                   1067:  * zero, in which case we just dump the file to stdout (making sure it
                   1068:  * doesn't trip up mdoc(7) along the way).
                   1069:  * This can be called in a nested context.
                   1070:  */
                   1071: void
                   1072: parsefile(struct texi *p, const char *fname, int parse)
                   1073: {
                   1074:        struct texifile *f;
                   1075:        int              fd;
                   1076:        struct stat      st;
                   1077:        size_t           i;
1.14      kristaps 1078:        char            *map;
1.1       kristaps 1079:
1.5       kristaps 1080:        if (64 == p->filepos)
1.6       kristaps 1081:                texierr(p, "too many open files");
1.1       kristaps 1082:        f = &p->files[p->filepos];
                   1083:        memset(f, 0, sizeof(struct texifile));
                   1084:
1.12      kristaps 1085:        f->type = TEXISRC_FILE;
1.1       kristaps 1086:        f->name = fname;
                   1087:        if (-1 == (fd = open(fname, O_RDONLY, 0))) {
                   1088:                texiabort(p, fname);
                   1089:        } else if (-1 == fstat(fd, &st)) {
                   1090:                close(fd);
                   1091:                texiabort(p, fname);
                   1092:        }
                   1093:
1.14      kristaps 1094:        f->mapsz = f->mapmaxsz = st.st_size;
                   1095:        map = mmap(NULL, f->mapsz,
1.1       kristaps 1096:                PROT_READ, MAP_SHARED, fd, 0);
                   1097:        close(fd);
                   1098:
1.14      kristaps 1099:        if (MAP_FAILED == map)
1.1       kristaps 1100:                texiabort(p, fname);
                   1101:
                   1102:        if ( ! parse) {
1.13      kristaps 1103:                for (i = 0; i < f->mapsz; i++)
1.14      kristaps 1104:                        texiputchar(p, map[i]);
1.13      kristaps 1105:                if (p->outcol)
                   1106:                        texiputchar(p, '\n');
1.14      kristaps 1107:                munmap(map, f->mapsz);
                   1108:                return;
                   1109:        }
                   1110:
                   1111:        p->filepos++;
                   1112:        f->map = malloc(f->mapsz);
                   1113:        memcpy(f->map, map, f->mapsz);
                   1114:        munmap(map, f->mapsz);
                   1115:        parseeof(p);
1.1       kristaps 1116:        texifilepop(p);
                   1117: }
                   1118:
1.2       kristaps 1119: /*
                   1120:  * Look up the value to a stored pair's value starting in "buf" from
                   1121:  * start to end.
                   1122:  * Return the pointer to the value memory, which can be NULL if the
                   1123:  * pointer key does not exist.
                   1124:  * The pointer can point to NULL if the value has been unset.
                   1125:  */
                   1126: static char **
1.14      kristaps 1127: valuequery(const struct texi *p, size_t start, size_t end)
1.2       kristaps 1128: {
                   1129:        size_t   i, sz, len;
                   1130:
                   1131:        assert(end >= start);
                   1132:        /* Ignore zero-length. */
                   1133:        if (0 == (len = (end - start)))
                   1134:                return(NULL);
                   1135:        for (i = 0; i < p->valsz; i++) {
                   1136:                sz = strlen(p->vals[i].key);
                   1137:                if (sz != len)
                   1138:                        continue;
1.14      kristaps 1139:                if (0 == strncmp(p->vals[i].key, &BUF(p)[start], len))
1.2       kristaps 1140:                        return(&p->vals[i].value);
                   1141:        }
                   1142:        return(NULL);
                   1143: }
                   1144:
                   1145: /*
                   1146:  * Parse a key until the end of line, e.g., @clear foo\n, and return the
                   1147:  * pointer to its value via valuequery().
                   1148:  */
                   1149: static char **
1.14      kristaps 1150: valuelquery(struct texi *p, size_t *pos)
1.2       kristaps 1151: {
                   1152:        size_t    start, end;
                   1153:        char    **ret;
                   1154:
1.14      kristaps 1155:        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1156:                advance(p, pos);
                   1157:        if (*pos == BUFSZ(p))
1.2       kristaps 1158:                return(NULL);
1.14      kristaps 1159:        for (start = end = *pos; end < BUFSZ(p); end++)
                   1160:                if ('\n' == BUF(p)[end])
1.2       kristaps 1161:                        break;
1.14      kristaps 1162:        advanceto(p, pos, end);
                   1163:        if (*pos < BUFSZ(p)) {
                   1164:                assert('\n' == BUF(p)[*pos]);
                   1165:                advance(p, pos);
1.2       kristaps 1166:        }
1.14      kristaps 1167:        if (NULL == (ret = valuequery(p, start, end)))
1.2       kristaps 1168:                return(NULL);
                   1169:        return(ret);
                   1170: }
                   1171:
                   1172: void
1.14      kristaps 1173: valuelclear(struct texi *p, size_t *pos)
1.2       kristaps 1174: {
                   1175:        char    **ret;
                   1176:
1.14      kristaps 1177:        if (NULL == (ret = valuelquery(p, pos)))
1.2       kristaps 1178:                return;
                   1179:        free(*ret);
                   1180:        *ret = NULL;
                   1181: }
                   1182:
                   1183: const char *
1.14      kristaps 1184: valuellookup(struct texi *p, size_t *pos)
1.2       kristaps 1185: {
                   1186:        char    **ret;
                   1187:
1.14      kristaps 1188:        if (NULL == (ret = valuelquery(p, pos)))
1.2       kristaps 1189:                return(NULL);
                   1190:        return(*ret);
                   1191: }
                   1192:
                   1193: /*
                   1194:  * Parse a key from a bracketed string, e.g., @value{foo}, and return
                   1195:  * the pointer to its value.
                   1196:  * If the returned pointer is NULL, either there was no string within
                   1197:  * the brackets (or no brackets), or the value was not found, or the
                   1198:  * value had previously been unset.
                   1199:  */
                   1200: const char *
1.14      kristaps 1201: valueblookup(struct texi *p, size_t *pos)
1.2       kristaps 1202: {
                   1203:        size_t    start, end;
                   1204:        char    **ret;
                   1205:
1.14      kristaps 1206:        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1207:                advance(p, pos);
                   1208:        if (*pos == BUFSZ(p) || '{' != BUF(p)[*pos])
1.2       kristaps 1209:                return(NULL);
1.14      kristaps 1210:        advance(p, pos);
                   1211:        for (start = end = *pos; end < BUFSZ(p); end++)
                   1212:                if ('}' == BUF(p)[end])
1.2       kristaps 1213:                        break;
1.14      kristaps 1214:        advanceto(p, pos, end);
                   1215:        if (*pos < BUFSZ(p)) {
                   1216:                assert('}' == BUF(p)[*pos]);
                   1217:                advance(p, pos);
1.2       kristaps 1218:        }
1.14      kristaps 1219:        if (NULL == (ret = valuequery(p, start, end)))
1.2       kristaps 1220:                return(NULL);
                   1221:        return(*ret);
                   1222: }
                   1223:
                   1224: void
                   1225: valueadd(struct texi *p, char *key, char *val)
                   1226: {
                   1227:        size_t   i;
                   1228:
                   1229:        assert(NULL != key);
                   1230:        assert(NULL != val);
                   1231:
                   1232:        for (i = 0; i < p->valsz; i++)
                   1233:                if (0 == strcmp(p->vals[i].key, key))
                   1234:                        break;
                   1235:
                   1236:        if (i < p->valsz) {
                   1237:                free(key);
                   1238:                free(p->vals[i].value);
                   1239:                p->vals[i].value = val;
                   1240:        } else {
1.4       kristaps 1241:                /* FIXME: reallocarray() */
1.2       kristaps 1242:                p->vals = realloc(p->vals,
                   1243:                        (p->valsz + 1) *
                   1244:                         sizeof(struct texivalue));
1.4       kristaps 1245:                if (NULL == p->vals)
                   1246:                        texiabort(p, NULL);
1.2       kristaps 1247:                p->vals[p->valsz].key = key;
                   1248:                p->vals[p->valsz].value = val;
                   1249:                p->valsz++;
                   1250:        }
1.7       kristaps 1251: }
                   1252:
                   1253: /*
                   1254:  * Take the arguments to a macro, e.g., @foo{bar, baz, xyzzy} (or the
                   1255:  * declaration form, @macro foo {arg1, ...}) and textually convert it to
                   1256:  * an array of arguments of size "argsz".
                   1257:  * These need to be freed individually and as a whole.
                   1258:  * NOTE: this will puke on @, or @} macros, which can trick it into
                   1259:  * stopping argument parsing earlier.
                   1260:  * Ergo, textual: this doesn't interpret the arguments in any way.
                   1261:  */
                   1262: char **
1.14      kristaps 1263: argparse(struct texi *p, size_t *pos, size_t *argsz, size_t hint)
1.7       kristaps 1264: {
                   1265:        char    **args;
                   1266:        size_t    start, end, stack;
                   1267:
1.14      kristaps 1268:        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1269:                advance(p, pos);
1.7       kristaps 1270:
                   1271:        args = NULL;
                   1272:        *argsz = 0;
                   1273:
1.17      kristaps 1274:        if (*pos == BUFSZ(p))
                   1275:                return(args);
                   1276:
1.14      kristaps 1277:        if ('{' != BUF(p)[*pos] && hint) {
1.10      kristaps 1278:                /*
                   1279:                 * Special case: if we encounter an unbracketed argument
                   1280:                 * and we're being invoked with non-zero arguments
                   1281:                 * (versus being set, i.e., hint>0), then parse until
                   1282:                 * the end of line.
                   1283:                 */
                   1284:                *argsz = 1;
                   1285:                args = calloc(1, sizeof(char *));
                   1286:                if (NULL == args)
                   1287:                        texiabort(p, NULL);
                   1288:                start = *pos;
1.14      kristaps 1289:                while (*pos < BUFSZ(p)) {
                   1290:                        if ('\n' == BUF(p)[*pos])
1.10      kristaps 1291:                                break;
1.14      kristaps 1292:                        advance(p, pos);
1.10      kristaps 1293:                }
                   1294:                args[0] = malloc(*pos - start + 1);
1.14      kristaps 1295:                memcpy(args[0], &BUF(p)[start], *pos - start);
1.10      kristaps 1296:                args[0][*pos - start] = '\0';
1.14      kristaps 1297:                if (*pos < BUFSZ(p) && '\n' == BUF(p)[*pos])
                   1298:                        advance(p, pos);
1.10      kristaps 1299:                return(args);
1.14      kristaps 1300:        } else if ('{' != BUF(p)[*pos])
1.7       kristaps 1301:                return(args);
1.17      kristaps 1302:
                   1303:        assert('{' == BUF(p)[*pos]);
1.7       kristaps 1304:
                   1305:        /* Parse til the closing '}', putting into the array. */
1.14      kristaps 1306:        advance(p, pos);
                   1307:        while (*pos < BUFSZ(p)) {
                   1308:                while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1309:                        advance(p, pos);
1.7       kristaps 1310:                start = *pos;
                   1311:                stack = 0;
1.14      kristaps 1312:                while (*pos < BUFSZ(p)) {
1.7       kristaps 1313:                        /*
                   1314:                         * According to the manual, commas within
                   1315:                         * embedded commands are escaped.
                   1316:                         * We keep track of embedded-ness in the "stack"
                   1317:                         * state anyway, so this is free.
                   1318:                         */
1.14      kristaps 1319:                        if (',' == BUF(p)[*pos] && 0 == stack && 1 != hint)
1.7       kristaps 1320:                                break;
1.14      kristaps 1321:                        else if (0 == stack && '}' == BUF(p)[*pos])
1.7       kristaps 1322:                                break;
1.14      kristaps 1323:                        else if (0 != stack && '}' == BUF(p)[*pos])
1.7       kristaps 1324:                                stack--;
1.14      kristaps 1325:                        else if ('{' == BUF(p)[*pos])
1.7       kristaps 1326:                                stack++;
1.14      kristaps 1327:                        advance(p, pos);
1.7       kristaps 1328:                }
                   1329:                if (stack)
                   1330:                        texiwarn(p, "unterminated macro "
                   1331:                                "in macro arguments");
1.14      kristaps 1332:                if ((end = *pos) == BUFSZ(p))
1.7       kristaps 1333:                        break;
                   1334:                /* Test for zero-length '{  }'. */
1.14      kristaps 1335:                if (start == end && '}' == BUF(p)[*pos] && 0 == *argsz)
1.7       kristaps 1336:                        break;
                   1337:                /* FIXME: use reallocarray. */
                   1338:                args = realloc
                   1339:                        (args, sizeof(char *) *
                   1340:                         (*argsz + 1));
                   1341:                if (NULL == args)
                   1342:                        texiabort(p, NULL);
                   1343:                args[*argsz] = malloc(end - start + 1);
                   1344:                if (NULL == args[*argsz])
                   1345:                        texiabort(p, NULL);
                   1346:                memcpy(args[*argsz],
1.14      kristaps 1347:                        &BUF(p)[start], end - start);
1.7       kristaps 1348:                args[*argsz][end - start] = '\0';
                   1349:                (*argsz)++;
1.14      kristaps 1350:                if ('}' == BUF(p)[*pos])
1.7       kristaps 1351:                        break;
1.14      kristaps 1352:                advance(p, pos);
1.7       kristaps 1353:        }
                   1354:
1.14      kristaps 1355:        if (*pos == BUFSZ(p))
1.7       kristaps 1356:                texierr(p, "unterminated arguments");
1.14      kristaps 1357:        assert('}' == BUF(p)[*pos]);
                   1358:        advance(p, pos);
1.7       kristaps 1359:        return(args);
1.2       kristaps 1360: }
1.20      kristaps 1361:
                   1362: /*
                   1363:  * If we're printing chapters, then do some naviation here and then
                   1364:  * close our outfile.
                   1365:  * I want to call this the SEE ALSO section, but that's not really what
                   1366:  * it is: we'll refer to the "initial" (top) node and the next and
                   1367:  * previous chapters.
                   1368:  */
                   1369: void
                   1370: teximdocclose(struct texi *p, int last)
                   1371: {
                   1372:        char     buf[PATH_MAX];
                   1373:
                   1374:        if (NULL == p->chapters || 0 == p->chapnum)
                   1375:                return;
                   1376:
                   1377:        teximacro(p, "Sh INFO NAVIGATION");
                   1378:
                   1379:        /* Print a reference to the "top" node. */
                   1380:        if (p->chapnum > 1) {
1.22    ! kristaps 1381:                texiputchars(p, "Top node,");
1.20      kristaps 1382:                snprintf(buf, sizeof(buf), "node1 7");
                   1383:                teximacroopen(p, "Xr ");
                   1384:                texiputchars(p, buf);
1.22    ! kristaps 1385:                texiputchars(p, " ;");
1.20      kristaps 1386:                teximacroclose(p);
                   1387:        }
                   1388:
                   1389:        /* Print a reference to the previous node. */
                   1390:        if (p->chapnum > 2) {
1.22    ! kristaps 1391:                texiputchars(p, "previous node,");
1.20      kristaps 1392:                snprintf(buf, sizeof(buf),
                   1393:                        "node%zu 7", p->chapnum - 1);
                   1394:                teximacroopen(p, "Xr ");
                   1395:                texiputchars(p, buf);
                   1396:                if ( ! last)
1.22    ! kristaps 1397:                        texiputchars(p, " ;");
1.20      kristaps 1398:                teximacroclose(p);
                   1399:        }
                   1400:
                   1401:        /* Print a reference to the next node. */
                   1402:        if ( ! last) {
1.22    ! kristaps 1403:                if (1 == p->chapnum)
        !          1404:                        texiputchars(p, "Next node,");
        !          1405:                else
        !          1406:                        texiputchars(p, "next node,");
1.20      kristaps 1407:                snprintf(buf, sizeof(buf),
                   1408:                        "node%zu 7", p->chapnum + 1);
                   1409:                teximacroopen(p, "Xr ");
                   1410:                texiputchars(p, buf);
                   1411:                teximacroclose(p);
                   1412:        }
                   1413:
                   1414:        fclose(p->outfile);
                   1415: }
                   1416:
                   1417: /*
                   1418:  * Open a mdoc(7) context.
                   1419:  * If we're printing chapters, then open the outfile here, too.
                   1420:  * Otherwise just print the mdoc(7) prologue.
                   1421:  */
                   1422: void
1.21      kristaps 1423: teximdocopen(struct texi *p, size_t *pos)
1.20      kristaps 1424: {
                   1425:        const char      *cp;
                   1426:        time_t           t;
                   1427:        char             date[32];
                   1428:        char             fname[PATH_MAX];
                   1429:
                   1430:        if (NULL != p->chapters) {
                   1431:                snprintf(fname, sizeof(fname), "%s/node%zu.7",
                   1432:                        p->chapters, ++p->chapnum);
                   1433:                p->outfile = fopen(fname, "w");
                   1434:                if (NULL == p->outfile)
                   1435:                        texiabort(p, fname);
                   1436:        }
                   1437:
                   1438:        /*
                   1439:         * Here we print our standard mdoc(7) prologue.
                   1440:         * We use the title set with @settitle for the `Nd' description
                   1441:         * and the source document filename (the first one as invoked on
                   1442:         * the command line) for the title.
                   1443:         * The date is set to the current date.
                   1444:         */
                   1445:        t = time(NULL);
                   1446:        strftime(date, sizeof(date), "%F", localtime(&t));
                   1447:
                   1448:        teximacroopen(p, "Dd");
                   1449:        texiputchars(p, date);
                   1450:        teximacroclose(p);
                   1451:        teximacroopen(p, "Dt");
                   1452:        for (cp = p->title; '\0' != *cp; cp++)
                   1453:                texiputchar(p, toupper((unsigned int)*cp));
                   1454:        texiputchars(p, " 7");
                   1455:        teximacroclose(p);
                   1456:        teximacro(p, "Os");
                   1457:        teximacro(p, "Sh NAME");
                   1458:        teximacroopen(p, "Nm");
                   1459:        for (cp = p->title; '\0' != *cp; cp++)
                   1460:                texiputchar(p, *cp);
                   1461:        teximacroclose(p);
                   1462:        teximacroopen(p, "Nd");
1.21      kristaps 1463:        /*
                   1464:         * The subtitle `Nd' can consist of arbitrary macros, so paste
                   1465:         * it and parse to the end of the line.
                   1466:         */
                   1467:        if (NULL != p->subtitle) {
                   1468:                texisplice(p, p->subtitle, strlen(p->subtitle), *pos);
                   1469:                parseeoln(p, pos);
                   1470:        } else
1.20      kristaps 1471:                texiputchars(p, "Unknown description");
                   1472:        teximacroclose(p);
                   1473:        p->seenvs = 1;
                   1474: }
                   1475:

CVSweb