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

Annotation of texi2mdoc/util.c, Revision 1.27

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

CVSweb