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

Annotation of texi2mdoc/util.c, Revision 1.28

1.28    ! kristaps    1: /*     $Id: util.c,v 1.27 2015/03/05 09:36:41 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.28    ! kristaps  600:
        !           601:                if (p->literal) {
        !           602:                        texiputchar(p, BUF(p)[*pos]);
        !           603:                        advance(p, pos);
        !           604:                        continue;
        !           605:                }
        !           606:
        !           607:                if (*pos < BUFSZ(p) - 2 &&
        !           608:                         '-' == BUF(p)[*pos] &&
        !           609:                         '-' == BUF(p)[*pos + 1] &&
        !           610:                         '-' == BUF(p)[*pos + 2]) {
        !           611:                        texiputchars(p, "\\(em");
        !           612:                        advance(p, pos);
        !           613:                        advance(p, pos);
        !           614:                } else if (*pos < BUFSZ(p) - 1 &&
        !           615:                         '-' == BUF(p)[*pos] &&
        !           616:                         '-' == BUF(p)[*pos + 1]) {
        !           617:                        texiputchars(p, "\\(en");
        !           618:                        advance(p, pos);
        !           619:                } else if (*pos < BUFSZ(p) - 1 &&
1.14      kristaps  620:                         '`' == BUF(p)[*pos] &&
                    621:                         '`' == BUF(p)[*pos + 1]) {
1.1       kristaps  622:                        texiputchars(p, "\\(lq");
1.14      kristaps  623:                        advance(p, pos);
                    624:                } else if (*pos < BUFSZ(p) - 1 &&
                    625:                         '\'' == BUF(p)[*pos] &&
                    626:                         '\'' == BUF(p)[*pos + 1]) {
1.1       kristaps  627:                        texiputchars(p, "\\(rq");
1.14      kristaps  628:                        advance(p, pos);
1.1       kristaps  629:                } else
1.14      kristaps  630:                        texiputchar(p, BUF(p)[*pos]);
1.28    ! kristaps  631:
1.14      kristaps  632:                advance(p, pos);
1.1       kristaps  633:        }
1.25      kristaps  634:
1.27      kristaps  635:        if (*pos + 1 < BUFSZ(p) &&
                    636:                '\n' == BUF(p)[*pos] &&
                    637:                '\n' == BUF(p)[*pos + 1])
                    638:                p->seenvs = 1;
                    639:
1.25      kristaps  640:        /*
                    641:         * New sentence, new line:if we (non-macro, non-literal) see a
                    642:         * period at the end of the last printed word, then open a
                    643:         * newline.
                    644:         */
                    645:        if (0 == p->literal && 0 == p->outmacro &&
                    646:                *pos < BUFSZ(p) && '.' == BUF(p)[*pos - 1])
                    647:                texiputchar(p, '\n');
1.1       kristaps  648: }
                    649:
                    650: /*
                    651:  * Look up the command at position "pos" in the buffer, returning it (or
                    652:  * TEXICMD__MAX if none found) and setting "end" to be the absolute
                    653:  * index after the command name.
                    654:  */
                    655: enum texicmd
1.19      kristaps  656: texicmd(const struct texi *p, size_t pos, size_t *end, struct teximacro **macro)
1.1       kristaps  657: {
1.4       kristaps  658:        size_t   i, len, toksz;
1.1       kristaps  659:
1.14      kristaps  660:        assert('@' == BUF(p)[pos]);
1.1       kristaps  661:
1.7       kristaps  662:        if (NULL != macro)
                    663:                *macro = NULL;
                    664:
1.14      kristaps  665:        if ((*end = pos) == BUFSZ(p))
1.1       kristaps  666:                return(TEXICMD__MAX);
1.14      kristaps  667:        else if ((*end = ++pos) == BUFSZ(p))
1.1       kristaps  668:                return(TEXICMD__MAX);
                    669:
                    670:        /* Alphabetic commands are special. */
1.23      kristaps  671:        if ( ! isalpha((unsigned int)BUF(p)[pos])) {
1.14      kristaps  672:                if ((*end = pos + 1) == BUFSZ(p))
1.1       kristaps  673:                        return(TEXICMD__MAX);
                    674:                for (i = 0; i < TEXICMD__MAX; i++) {
                    675:                        if (1 != texitoks[i].len)
                    676:                                continue;
1.14      kristaps  677:                        if (0 == strncmp(texitoks[i].tok, &BUF(p)[pos], 1))
1.1       kristaps  678:                                return(i);
                    679:                }
1.14      kristaps  680:                texiwarn(p, "bad command: @%c", BUF(p)[pos]);
1.1       kristaps  681:                return(TEXICMD__MAX);
                    682:        }
                    683:
1.4       kristaps  684:        /* Scan to the end of the possible command name. */
1.14      kristaps  685:        for (*end = pos; *end < BUFSZ(p) && ! ismspace(BUF(p)[*end]); (*end)++)
                    686:                if ((*end > pos && ('@' == BUF(p)[*end] ||
                    687:                          '{' == BUF(p)[*end] || '}' == BUF(p)[*end])))
1.1       kristaps  688:                        break;
                    689:
1.4       kristaps  690:        /* Look for the command. */
1.1       kristaps  691:        len = *end - pos;
                    692:        for (i = 0; i < TEXICMD__MAX; i++) {
                    693:                if (len != texitoks[i].len)
                    694:                        continue;
1.14      kristaps  695:                if (0 == strncmp(texitoks[i].tok, &BUF(p)[pos], len))
1.1       kristaps  696:                        return(i);
                    697:        }
                    698:
1.4       kristaps  699:        /* Look for it in our indices. */
                    700:        for (i = 0; i < p->indexsz; i++) {
                    701:                toksz = strlen(p->indexs[i]);
                    702:                if (len != 5 + toksz)
                    703:                        continue;
1.14      kristaps  704:                if (strncmp(&BUF(p)[pos], p->indexs[i], toksz))
1.4       kristaps  705:                        continue;
1.14      kristaps  706:                if (0 == strncmp(&BUF(p)[pos + toksz], "index", 5))
1.7       kristaps  707:                        return(TEXICMD_USER_INDEX);
                    708:        }
                    709:
                    710:        for (i = 0; i < p->macrosz; i++) {
                    711:                if (len != strlen(p->macros[i].key))
                    712:                        continue;
1.14      kristaps  713:                if (strncmp(&BUF(p)[pos], p->macros[i].key, len))
1.7       kristaps  714:                        continue;
                    715:                if (NULL != macro)
                    716:                        *macro = &p->macros[i];
                    717:                return(TEXICMD__MAX);
1.4       kristaps  718:        }
                    719:
1.14      kristaps  720:        texiwarn(p, "bad command: @%.*s", (int)len, &BUF(p)[pos]);
1.1       kristaps  721:        return(TEXICMD__MAX);
                    722: }
                    723:
                    724: /*
                    725:  * Parse an argument from a bracketed command, e.g., @url{foo, baz}.
                    726:  * Num should be set to the argument we're currently parsing, although
                    727:  * it suffixes for it to be zero or non-zero.
                    728:  * This will return 1 if there are more arguments, 0 otherwise.
                    729:  * This will stop (returning 0) in the event of EOF or if we're not at a
                    730:  * bracket for the zeroth parse.
                    731:  */
                    732: int
1.14      kristaps  733: parsearg(struct texi *p, size_t *pos, size_t num)
1.1       kristaps  734: {
1.17      kristaps  735:        size_t            end, sv;
1.7       kristaps  736:        enum texicmd      cmd;
                    737:        struct teximacro *macro;
1.1       kristaps  738:
1.14      kristaps  739:        while (*pos < BUFSZ(p) && ismspace(BUF(p)[*pos]))
                    740:                advance(p, pos);
                    741:        if (*pos == BUFSZ(p) || (0 == num && '{' != BUF(p)[*pos]))
1.1       kristaps  742:                return(0);
                    743:        if (0 == num)
1.14      kristaps  744:                advance(p, pos);
1.1       kristaps  745:
1.14      kristaps  746:        while ((*pos = advancenext(p, pos)) < BUFSZ(p)) {
                    747:                switch (BUF(p)[*pos]) {
1.1       kristaps  748:                case (','):
1.14      kristaps  749:                        advance(p, pos);
1.1       kristaps  750:                        return(1);
                    751:                case ('}'):
1.14      kristaps  752:                        advance(p, pos);
1.1       kristaps  753:                        return(0);
                    754:                case ('{'):
                    755:                        if (0 == p->ign)
                    756:                                texiwarn(p, "unexpected \"{\"");
1.14      kristaps  757:                        advance(p, pos);
1.1       kristaps  758:                        continue;
                    759:                case ('@'):
                    760:                        break;
                    761:                default:
1.14      kristaps  762:                        parseword(p, pos, ',');
1.1       kristaps  763:                        continue;
                    764:                }
                    765:
1.17      kristaps  766:                sv = p->files[p->filepos - 1].insplice;
1.14      kristaps  767:                cmd = texicmd(p, *pos, &end, &macro);
                    768:                advanceto(p, pos, end);
1.7       kristaps  769:                if (NULL != macro)
1.17      kristaps  770:                        texiexecmacro(p, macro, sv, pos);
1.1       kristaps  771:                if (TEXICMD__MAX == cmd)
                    772:                        continue;
                    773:                if (NULL != texitoks[cmd].fp)
1.14      kristaps  774:                        (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps  775:        }
                    776:        return(0);
                    777: }
                    778:
                    779: /*
                    780:  * Parse until the end of a bracketed statement, e.g., @foo{bar baz}.
                    781:  * This will stop in the event of EOF or if we're not at a bracket.
                    782:  */
                    783: void
1.18      kristaps  784: parsebracket(struct texi *p, size_t *pos, int dostack)
1.1       kristaps  785: {
1.18      kristaps  786:        size_t            end, sv, stack;
1.7       kristaps  787:        enum texicmd      cmd;
                    788:        struct teximacro *macro;
1.1       kristaps  789:
1.14      kristaps  790:        while (*pos < BUFSZ(p) && ismspace(BUF(p)[*pos]))
                    791:                advance(p, pos);
1.1       kristaps  792:
1.14      kristaps  793:        if (*pos == BUFSZ(p) || '{' != BUF(p)[*pos])
1.1       kristaps  794:                return;
1.14      kristaps  795:        advance(p, pos);
1.1       kristaps  796:
1.18      kristaps  797:        stack = 0;
1.14      kristaps  798:        while ((*pos = advancenext(p, pos)) < BUFSZ(p)) {
                    799:                switch (BUF(p)[*pos]) {
1.1       kristaps  800:                case ('}'):
1.18      kristaps  801:                        if (stack > 0) {
                    802:                                stack--;
                    803:                                advance(p, pos);
                    804:                                texiputchar(p, '}');
                    805:                                continue;
                    806:                        }
1.14      kristaps  807:                        advance(p, pos);
1.1       kristaps  808:                        return;
                    809:                case ('{'):
1.18      kristaps  810:                        if (dostack) {
                    811:                                stack++;
                    812:                                advance(p, pos);
                    813:                                texiputchar(p, '{');
                    814:                                continue;
                    815:                        }
1.1       kristaps  816:                        if (0 == p->ign)
                    817:                                texiwarn(p, "unexpected \"{\"");
1.14      kristaps  818:                        advance(p, pos);
1.1       kristaps  819:                        continue;
                    820:                case ('@'):
                    821:                        break;
                    822:                default:
1.14      kristaps  823:                        parseword(p, pos, '\0');
1.1       kristaps  824:                        continue;
                    825:                }
                    826:
1.17      kristaps  827:                sv = p->files[p->filepos - 1].insplice;
1.14      kristaps  828:                cmd = texicmd(p, *pos, &end, &macro);
                    829:                advanceto(p, pos, end);
1.7       kristaps  830:                if (NULL != macro)
1.17      kristaps  831:                        texiexecmacro(p, macro, sv, pos);
1.1       kristaps  832:                if (TEXICMD__MAX == cmd)
                    833:                        continue;
                    834:                if (NULL != texitoks[cmd].fp)
1.14      kristaps  835:                        (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps  836:        }
                    837: }
                    838:
                    839: /*
                    840:  * This should be invoked when we're on a macro line and want to process
                    841:  * to the end of the current input line, doing all of our macros along
                    842:  * the way.
                    843:  */
                    844: void
1.14      kristaps  845: parseeoln(struct texi *p, size_t *pos)
1.1       kristaps  846: {
1.17      kristaps  847:        size_t            end, sv;
1.7       kristaps  848:        enum texicmd      cmd;
                    849:        struct teximacro *macro;
1.1       kristaps  850:
1.14      kristaps  851:        while (*pos < BUFSZ(p) && '\n' != BUF(p)[*pos]) {
                    852:                while (*pos < BUFSZ(p) && isws(BUF(p)[*pos])) {
1.1       kristaps  853:                        p->seenws = 1;
                    854:                        if (p->literal)
1.14      kristaps  855:                                texiputchar(p, BUF(p)[*pos]);
                    856:                        advance(p, pos);
1.1       kristaps  857:                }
1.14      kristaps  858:                switch (BUF(p)[*pos]) {
1.1       kristaps  859:                case ('}'):
                    860:                        if (0 == p->ign)
                    861:                                texiwarn(p, "unexpected \"}\"");
1.14      kristaps  862:                        advance(p, pos);
1.1       kristaps  863:                        continue;
                    864:                case ('{'):
                    865:                        if (0 == p->ign)
                    866:                                texiwarn(p, "unexpected \"{\"");
1.14      kristaps  867:                        advance(p, pos);
1.1       kristaps  868:                        continue;
                    869:                case ('@'):
                    870:                        break;
                    871:                default:
1.14      kristaps  872:                        parseword(p, pos, '\0');
1.1       kristaps  873:                        continue;
                    874:                }
                    875:
1.17      kristaps  876:                sv = p->files[p->filepos - 1].insplice;
1.14      kristaps  877:                cmd = texicmd(p, *pos, &end, &macro);
                    878:                advanceto(p, pos, end);
1.7       kristaps  879:                if (NULL != macro)
1.17      kristaps  880:                        texiexecmacro(p, macro, sv, pos);
1.1       kristaps  881:                if (TEXICMD__MAX == cmd)
                    882:                        continue;
                    883:                if (NULL != texitoks[cmd].fp)
1.14      kristaps  884:                        (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps  885:        }
1.14      kristaps  886:
                    887:        if (*pos < BUFSZ(p) && '\n' == BUF(p)[*pos])
                    888:                advance(p, pos);
1.19      kristaps  889: }
                    890:
                    891: /*
                    892:  * Peek to see if there's a command after subsequent whitespace.
                    893:  * If so, return the macro identifier.
                    894:  * This DOES NOT work with user-defined macros.
                    895:  */
                    896: enum texicmd
                    897: peekcmd(const struct texi *p, size_t pos)
                    898: {
                    899:        size_t          end;
                    900:
                    901:        while (pos < BUFSZ(p) && ismspace(BUF(p)[pos]))
                    902:                pos++;
                    903:        if (pos == BUFSZ(p) || '@' != BUF(p)[pos])
                    904:                return(TEXICMD__MAX);
                    905:        return(texicmd(p, pos, &end, NULL));
1.1       kristaps  906: }
                    907:
                    908: /*
                    909:  * Parse a single word or command.
                    910:  * This will return immediately at the EOF.
                    911:  */
1.14      kristaps  912: static void
                    913: parsesingle(struct texi *p, size_t *pos)
1.1       kristaps  914: {
1.17      kristaps  915:        size_t            end, sv;
1.7       kristaps  916:        enum texicmd      cmd;
                    917:        struct teximacro *macro;
1.1       kristaps  918:
1.14      kristaps  919:        if ((*pos = advancenext(p, pos)) >= BUFSZ(p))
1.1       kristaps  920:                return;
                    921:
1.14      kristaps  922:        switch (BUF(p)[*pos]) {
1.1       kristaps  923:        case ('}'):
                    924:                if (0 == p->ign)
                    925:                        texiwarn(p, "unexpected \"}\"");
1.14      kristaps  926:                advance(p, pos);
1.1       kristaps  927:                return;
                    928:        case ('{'):
                    929:                if (0 == p->ign)
                    930:                        texiwarn(p, "unexpected \"{\"");
1.14      kristaps  931:                advance(p, pos);
1.1       kristaps  932:                return;
                    933:        case ('@'):
                    934:                break;
                    935:        default:
1.14      kristaps  936:                parseword(p, pos, '\0');
1.1       kristaps  937:                return;
                    938:        }
                    939:
1.17      kristaps  940:        sv = p->files[p->filepos - 1].insplice;
1.14      kristaps  941:        cmd = texicmd(p, *pos, &end, &macro);
                    942:        advanceto(p, pos, end);
1.7       kristaps  943:        if (NULL != macro)
1.17      kristaps  944:                texiexecmacro(p, macro, sv, pos);
1.1       kristaps  945:        if (TEXICMD__MAX == cmd)
                    946:                return;
                    947:        if (NULL != texitoks[cmd].fp)
1.14      kristaps  948:                (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps  949: }
                    950:
                    951: /*
                    952:  * This is used in the @deffn type of command.
                    953:  * These have an arbitrary number of line arguments; however, these
                    954:  * arguments may or may not be surrounded by brackets.
                    955:  * In this function, we parse each one as either a bracketed or
                    956:  * non-bracketed argument, returning 0 when we've reached the end of
                    957:  * line or 1 otherwise.
                    958:  */
                    959: int
1.14      kristaps  960: parselinearg(struct texi *p, size_t *pos)
1.1       kristaps  961: {
                    962:
1.14      kristaps  963:        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos])) {
1.1       kristaps  964:                p->seenws = 1;
1.14      kristaps  965:                advance(p, pos);
1.1       kristaps  966:        }
                    967:
1.14      kristaps  968:        if (*pos < BUFSZ(p) && '{' == BUF(p)[*pos])
1.18      kristaps  969:                parsebracket(p, pos, 0);
1.14      kristaps  970:        else if (*pos < BUFSZ(p) && '\n' != BUF(p)[*pos])
                    971:                parsesingle(p, pos);
1.1       kristaps  972:        else
                    973:                return(0);
                    974:
                    975:        return(1);
                    976: }
                    977:
                    978: /*
                    979:  * Parse til the end of the buffer.
                    980:  */
1.14      kristaps  981: static void
                    982: parseeof(struct texi *p)
1.1       kristaps  983: {
                    984:        size_t   pos;
                    985:
1.14      kristaps  986:        for (pos = 0; pos < BUFSZ(p); )
                    987:                parsesingle(p, &pos);
1.1       kristaps  988: }
                    989:
1.8       kristaps  990: void
1.21      kristaps  991: texisplice(struct texi *p, const char *buf, size_t sz, size_t pos)
1.8       kristaps  992: {
1.14      kristaps  993:        char            *cp;
                    994:        struct texifile *f;
1.8       kristaps  995:
1.14      kristaps  996:        assert(p->filepos > 0);
                    997:        f = &p->files[p->filepos - 1];
1.8       kristaps  998:
1.14      kristaps  999:        if (f->mapsz + sz > f->mapmaxsz) {
                   1000:                f->mapmaxsz = f->mapsz + sz + 1024;
                   1001:                cp = realloc(f->map, f->mapmaxsz);
                   1002:                if (NULL == cp)
                   1003:                        texiabort(p, NULL);
                   1004:                f->map = cp;
                   1005:        }
1.8       kristaps 1006:
1.15      kristaps 1007:        f->insplice += sz;
1.21      kristaps 1008:        memmove(f->map + pos + sz, f->map + pos, f->mapsz - pos);
                   1009:        memcpy(f->map + pos, buf, sz);
1.14      kristaps 1010:        f->mapsz += sz;
1.8       kristaps 1011: }
                   1012:
                   1013: /*
1.1       kristaps 1014:  * Parse a block sequence until we have the "@end endtoken" command
                   1015:  * invocation.
                   1016:  * This will return immediately at EOF.
                   1017:  */
                   1018: void
1.14      kristaps 1019: parseto(struct texi *p, size_t *pos, const char *endtoken)
1.1       kristaps 1020: {
1.17      kristaps 1021:        size_t            end, sv;
1.7       kristaps 1022:        enum texicmd      cmd;
                   1023:        size_t            endtoksz;
                   1024:        struct teximacro *macro;
1.1       kristaps 1025:
                   1026:        endtoksz = strlen(endtoken);
                   1027:        assert(endtoksz > 0);
                   1028:
1.14      kristaps 1029:        while ((*pos = advancenext(p, pos)) < BUFSZ(p)) {
                   1030:                switch (BUF(p)[*pos]) {
1.1       kristaps 1031:                case ('}'):
                   1032:                        if (0 == p->ign)
                   1033:                                texiwarn(p, "unexpected \"}\"");
1.14      kristaps 1034:                        advance(p, pos);
1.1       kristaps 1035:                        continue;
                   1036:                case ('{'):
                   1037:                        if (0 == p->ign)
                   1038:                                texiwarn(p, "unexpected \"{\"");
1.14      kristaps 1039:                        advance(p, pos);
1.1       kristaps 1040:                        continue;
                   1041:                case ('@'):
                   1042:                        break;
                   1043:                default:
1.14      kristaps 1044:                        parseword(p, pos, '\0');
1.1       kristaps 1045:                        continue;
                   1046:                }
                   1047:
1.17      kristaps 1048:                sv = p->files[p->filepos - 1].insplice;
1.14      kristaps 1049:                cmd = texicmd(p, *pos, &end, &macro);
                   1050:                advanceto(p, pos, end);
1.1       kristaps 1051:                if (TEXICMD_END == cmd) {
1.14      kristaps 1052:                        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1053:                                advance(p, pos);
1.1       kristaps 1054:                        /*
                   1055:                         * FIXME: check the full word, not just its
                   1056:                         * initial substring!
                   1057:                         */
1.14      kristaps 1058:                        if (BUFSZ(p) - *pos >= endtoksz && 0 == strncmp
                   1059:                                 (&BUF(p)[*pos], endtoken, endtoksz)) {
                   1060:                                advanceeoln(p, pos, 0);
1.1       kristaps 1061:                                break;
                   1062:                        }
                   1063:                        if (0 == p->ign)
                   1064:                                texiwarn(p, "unexpected \"end\"");
1.14      kristaps 1065:                        advanceeoln(p, pos, 0);
1.1       kristaps 1066:                        continue;
1.7       kristaps 1067:                }
                   1068:                if (NULL != macro)
1.17      kristaps 1069:                        texiexecmacro(p, macro, sv, pos);
1.7       kristaps 1070:                if (TEXICMD__MAX == cmd)
                   1071:                        continue;
                   1072:                if (NULL != texitoks[cmd].fp)
1.14      kristaps 1073:                        (*texitoks[cmd].fp)(p, cmd, pos);
1.1       kristaps 1074:        }
                   1075: }
                   1076:
                   1077: /*
1.12      kristaps 1078:  * Like parsefile() but used for reading from stdandard input.
                   1079:  * This can only be called for the first file!
                   1080:  */
                   1081: void
                   1082: parsestdin(struct texi *p)
                   1083: {
                   1084:        struct texifile *f;
                   1085:        ssize_t          ssz;
                   1086:
                   1087:        assert(0 == p->filepos);
                   1088:        f = &p->files[p->filepos];
                   1089:        memset(f, 0, sizeof(struct texifile));
                   1090:
                   1091:        f->type = TEXISRC_STDIN;
                   1092:        f->name = "<stdin>";
                   1093:
1.14      kristaps 1094:        for (f->mapsz = 0; ; f->mapsz += (size_t)ssz) {
                   1095:                if (f->mapsz == f->mapmaxsz) {
                   1096:                        if (f->mapmaxsz == (1U << 31))
1.12      kristaps 1097:                                texierr(p, "stdin buffer too long");
1.14      kristaps 1098:                        f->mapmaxsz = f->mapmaxsz > 65536 / 2 ?
                   1099:                                2 * f->mapmaxsz : 65536;
                   1100:                        f->map = realloc(f->map, f->mapmaxsz);
1.12      kristaps 1101:                        if (NULL == f->map)
                   1102:                                texiabort(p, NULL);
                   1103:                }
1.14      kristaps 1104:                ssz = read(STDIN_FILENO, f->map +
                   1105:                        (int)f->mapsz, f->mapmaxsz - f->mapsz);
1.12      kristaps 1106:                if (0 == ssz)
                   1107:                        break;
                   1108:                else if (-1 == ssz)
                   1109:                        texiabort(p, NULL);
                   1110:        }
                   1111:
                   1112:        p->filepos++;
1.14      kristaps 1113:        parseeof(p);
1.12      kristaps 1114:        texifilepop(p);
                   1115: }
                   1116:
                   1117: /*
1.1       kristaps 1118:  * Memory-map the file "fname" and begin parsing it unless "parse" is
                   1119:  * zero, in which case we just dump the file to stdout (making sure it
                   1120:  * doesn't trip up mdoc(7) along the way).
                   1121:  * This can be called in a nested context.
                   1122:  */
                   1123: void
                   1124: parsefile(struct texi *p, const char *fname, int parse)
                   1125: {
                   1126:        struct texifile *f;
                   1127:        int              fd;
                   1128:        struct stat      st;
                   1129:        size_t           i;
1.14      kristaps 1130:        char            *map;
1.1       kristaps 1131:
1.5       kristaps 1132:        if (64 == p->filepos)
1.6       kristaps 1133:                texierr(p, "too many open files");
1.1       kristaps 1134:        f = &p->files[p->filepos];
                   1135:        memset(f, 0, sizeof(struct texifile));
                   1136:
1.12      kristaps 1137:        f->type = TEXISRC_FILE;
1.1       kristaps 1138:        f->name = fname;
                   1139:        if (-1 == (fd = open(fname, O_RDONLY, 0))) {
                   1140:                texiabort(p, fname);
                   1141:        } else if (-1 == fstat(fd, &st)) {
                   1142:                close(fd);
                   1143:                texiabort(p, fname);
                   1144:        }
                   1145:
1.14      kristaps 1146:        f->mapsz = f->mapmaxsz = st.st_size;
                   1147:        map = mmap(NULL, f->mapsz,
1.1       kristaps 1148:                PROT_READ, MAP_SHARED, fd, 0);
                   1149:        close(fd);
                   1150:
1.14      kristaps 1151:        if (MAP_FAILED == map)
1.1       kristaps 1152:                texiabort(p, fname);
                   1153:
                   1154:        if ( ! parse) {
1.13      kristaps 1155:                for (i = 0; i < f->mapsz; i++)
1.14      kristaps 1156:                        texiputchar(p, map[i]);
1.13      kristaps 1157:                if (p->outcol)
                   1158:                        texiputchar(p, '\n');
1.14      kristaps 1159:                munmap(map, f->mapsz);
                   1160:                return;
                   1161:        }
                   1162:
                   1163:        p->filepos++;
                   1164:        f->map = malloc(f->mapsz);
                   1165:        memcpy(f->map, map, f->mapsz);
                   1166:        munmap(map, f->mapsz);
                   1167:        parseeof(p);
1.1       kristaps 1168:        texifilepop(p);
                   1169: }
                   1170:
1.2       kristaps 1171: /*
                   1172:  * Look up the value to a stored pair's value starting in "buf" from
                   1173:  * start to end.
                   1174:  * Return the pointer to the value memory, which can be NULL if the
                   1175:  * pointer key does not exist.
                   1176:  * The pointer can point to NULL if the value has been unset.
                   1177:  */
                   1178: static char **
1.14      kristaps 1179: valuequery(const struct texi *p, size_t start, size_t end)
1.2       kristaps 1180: {
                   1181:        size_t   i, sz, len;
                   1182:
                   1183:        assert(end >= start);
                   1184:        /* Ignore zero-length. */
                   1185:        if (0 == (len = (end - start)))
                   1186:                return(NULL);
                   1187:        for (i = 0; i < p->valsz; i++) {
                   1188:                sz = strlen(p->vals[i].key);
                   1189:                if (sz != len)
                   1190:                        continue;
1.14      kristaps 1191:                if (0 == strncmp(p->vals[i].key, &BUF(p)[start], len))
1.2       kristaps 1192:                        return(&p->vals[i].value);
                   1193:        }
                   1194:        return(NULL);
                   1195: }
                   1196:
                   1197: /*
                   1198:  * Parse a key until the end of line, e.g., @clear foo\n, and return the
                   1199:  * pointer to its value via valuequery().
                   1200:  */
                   1201: static char **
1.14      kristaps 1202: valuelquery(struct texi *p, size_t *pos)
1.2       kristaps 1203: {
                   1204:        size_t    start, end;
                   1205:        char    **ret;
                   1206:
1.14      kristaps 1207:        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1208:                advance(p, pos);
                   1209:        if (*pos == BUFSZ(p))
1.2       kristaps 1210:                return(NULL);
1.14      kristaps 1211:        for (start = end = *pos; end < BUFSZ(p); end++)
                   1212:                if ('\n' == BUF(p)[end])
1.2       kristaps 1213:                        break;
1.14      kristaps 1214:        advanceto(p, pos, end);
                   1215:        if (*pos < BUFSZ(p)) {
                   1216:                assert('\n' == 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
1.14      kristaps 1225: valuelclear(struct texi *p, size_t *pos)
1.2       kristaps 1226: {
                   1227:        char    **ret;
                   1228:
1.14      kristaps 1229:        if (NULL == (ret = valuelquery(p, pos)))
1.2       kristaps 1230:                return;
                   1231:        free(*ret);
                   1232:        *ret = NULL;
                   1233: }
                   1234:
                   1235: const char *
1.14      kristaps 1236: valuellookup(struct texi *p, size_t *pos)
1.2       kristaps 1237: {
                   1238:        char    **ret;
                   1239:
1.14      kristaps 1240:        if (NULL == (ret = valuelquery(p, pos)))
1.2       kristaps 1241:                return(NULL);
                   1242:        return(*ret);
                   1243: }
                   1244:
                   1245: /*
                   1246:  * Parse a key from a bracketed string, e.g., @value{foo}, and return
                   1247:  * the pointer to its value.
                   1248:  * If the returned pointer is NULL, either there was no string within
                   1249:  * the brackets (or no brackets), or the value was not found, or the
                   1250:  * value had previously been unset.
                   1251:  */
                   1252: const char *
1.14      kristaps 1253: valueblookup(struct texi *p, size_t *pos)
1.2       kristaps 1254: {
                   1255:        size_t    start, end;
                   1256:        char    **ret;
                   1257:
1.14      kristaps 1258:        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1259:                advance(p, pos);
                   1260:        if (*pos == BUFSZ(p) || '{' != BUF(p)[*pos])
1.2       kristaps 1261:                return(NULL);
1.14      kristaps 1262:        advance(p, pos);
                   1263:        for (start = end = *pos; end < BUFSZ(p); end++)
                   1264:                if ('}' == BUF(p)[end])
1.2       kristaps 1265:                        break;
1.14      kristaps 1266:        advanceto(p, pos, end);
                   1267:        if (*pos < BUFSZ(p)) {
                   1268:                assert('}' == BUF(p)[*pos]);
                   1269:                advance(p, pos);
1.2       kristaps 1270:        }
1.14      kristaps 1271:        if (NULL == (ret = valuequery(p, start, end)))
1.2       kristaps 1272:                return(NULL);
                   1273:        return(*ret);
                   1274: }
                   1275:
                   1276: void
                   1277: valueadd(struct texi *p, char *key, char *val)
                   1278: {
                   1279:        size_t   i;
                   1280:
                   1281:        assert(NULL != key);
                   1282:        assert(NULL != val);
                   1283:
                   1284:        for (i = 0; i < p->valsz; i++)
                   1285:                if (0 == strcmp(p->vals[i].key, key))
                   1286:                        break;
                   1287:
                   1288:        if (i < p->valsz) {
                   1289:                free(key);
                   1290:                free(p->vals[i].value);
                   1291:                p->vals[i].value = val;
                   1292:        } else {
1.4       kristaps 1293:                /* FIXME: reallocarray() */
1.2       kristaps 1294:                p->vals = realloc(p->vals,
                   1295:                        (p->valsz + 1) *
                   1296:                         sizeof(struct texivalue));
1.4       kristaps 1297:                if (NULL == p->vals)
                   1298:                        texiabort(p, NULL);
1.2       kristaps 1299:                p->vals[p->valsz].key = key;
                   1300:                p->vals[p->valsz].value = val;
                   1301:                p->valsz++;
                   1302:        }
1.7       kristaps 1303: }
                   1304:
                   1305: /*
                   1306:  * Take the arguments to a macro, e.g., @foo{bar, baz, xyzzy} (or the
                   1307:  * declaration form, @macro foo {arg1, ...}) and textually convert it to
                   1308:  * an array of arguments of size "argsz".
                   1309:  * These need to be freed individually and as a whole.
                   1310:  * NOTE: this will puke on @, or @} macros, which can trick it into
                   1311:  * stopping argument parsing earlier.
                   1312:  * Ergo, textual: this doesn't interpret the arguments in any way.
                   1313:  */
                   1314: char **
1.14      kristaps 1315: argparse(struct texi *p, size_t *pos, size_t *argsz, size_t hint)
1.7       kristaps 1316: {
                   1317:        char    **args;
                   1318:        size_t    start, end, stack;
                   1319:
1.14      kristaps 1320:        while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1321:                advance(p, pos);
1.7       kristaps 1322:
                   1323:        args = NULL;
                   1324:        *argsz = 0;
                   1325:
1.17      kristaps 1326:        if (*pos == BUFSZ(p))
                   1327:                return(args);
                   1328:
1.14      kristaps 1329:        if ('{' != BUF(p)[*pos] && hint) {
1.10      kristaps 1330:                /*
                   1331:                 * Special case: if we encounter an unbracketed argument
                   1332:                 * and we're being invoked with non-zero arguments
                   1333:                 * (versus being set, i.e., hint>0), then parse until
                   1334:                 * the end of line.
                   1335:                 */
                   1336:                *argsz = 1;
                   1337:                args = calloc(1, sizeof(char *));
                   1338:                if (NULL == args)
                   1339:                        texiabort(p, NULL);
                   1340:                start = *pos;
1.14      kristaps 1341:                while (*pos < BUFSZ(p)) {
                   1342:                        if ('\n' == BUF(p)[*pos])
1.10      kristaps 1343:                                break;
1.14      kristaps 1344:                        advance(p, pos);
1.10      kristaps 1345:                }
                   1346:                args[0] = malloc(*pos - start + 1);
1.14      kristaps 1347:                memcpy(args[0], &BUF(p)[start], *pos - start);
1.10      kristaps 1348:                args[0][*pos - start] = '\0';
1.14      kristaps 1349:                if (*pos < BUFSZ(p) && '\n' == BUF(p)[*pos])
                   1350:                        advance(p, pos);
1.10      kristaps 1351:                return(args);
1.14      kristaps 1352:        } else if ('{' != BUF(p)[*pos])
1.7       kristaps 1353:                return(args);
1.17      kristaps 1354:
                   1355:        assert('{' == BUF(p)[*pos]);
1.7       kristaps 1356:
                   1357:        /* Parse til the closing '}', putting into the array. */
1.14      kristaps 1358:        advance(p, pos);
                   1359:        while (*pos < BUFSZ(p)) {
                   1360:                while (*pos < BUFSZ(p) && isws(BUF(p)[*pos]))
                   1361:                        advance(p, pos);
1.7       kristaps 1362:                start = *pos;
                   1363:                stack = 0;
1.14      kristaps 1364:                while (*pos < BUFSZ(p)) {
1.7       kristaps 1365:                        /*
                   1366:                         * According to the manual, commas within
                   1367:                         * embedded commands are escaped.
                   1368:                         * We keep track of embedded-ness in the "stack"
                   1369:                         * state anyway, so this is free.
                   1370:                         */
1.14      kristaps 1371:                        if (',' == BUF(p)[*pos] && 0 == stack && 1 != hint)
1.7       kristaps 1372:                                break;
1.14      kristaps 1373:                        else if (0 == stack && '}' == BUF(p)[*pos])
1.7       kristaps 1374:                                break;
1.14      kristaps 1375:                        else if (0 != stack && '}' == BUF(p)[*pos])
1.7       kristaps 1376:                                stack--;
1.14      kristaps 1377:                        else if ('{' == BUF(p)[*pos])
1.7       kristaps 1378:                                stack++;
1.14      kristaps 1379:                        advance(p, pos);
1.7       kristaps 1380:                }
                   1381:                if (stack)
                   1382:                        texiwarn(p, "unterminated macro "
                   1383:                                "in macro arguments");
1.14      kristaps 1384:                if ((end = *pos) == BUFSZ(p))
1.7       kristaps 1385:                        break;
                   1386:                /* Test for zero-length '{  }'. */
1.14      kristaps 1387:                if (start == end && '}' == BUF(p)[*pos] && 0 == *argsz)
1.7       kristaps 1388:                        break;
                   1389:                /* FIXME: use reallocarray. */
                   1390:                args = realloc
                   1391:                        (args, sizeof(char *) *
                   1392:                         (*argsz + 1));
                   1393:                if (NULL == args)
                   1394:                        texiabort(p, NULL);
                   1395:                args[*argsz] = malloc(end - start + 1);
                   1396:                if (NULL == args[*argsz])
                   1397:                        texiabort(p, NULL);
                   1398:                memcpy(args[*argsz],
1.14      kristaps 1399:                        &BUF(p)[start], end - start);
1.7       kristaps 1400:                args[*argsz][end - start] = '\0';
                   1401:                (*argsz)++;
1.14      kristaps 1402:                if ('}' == BUF(p)[*pos])
1.7       kristaps 1403:                        break;
1.14      kristaps 1404:                advance(p, pos);
1.7       kristaps 1405:        }
                   1406:
1.14      kristaps 1407:        if (*pos == BUFSZ(p))
1.7       kristaps 1408:                texierr(p, "unterminated arguments");
1.14      kristaps 1409:        assert('}' == BUF(p)[*pos]);
                   1410:        advance(p, pos);
1.7       kristaps 1411:        return(args);
1.2       kristaps 1412: }
1.20      kristaps 1413:
                   1414: /*
                   1415:  * If we're printing chapters, then do some naviation here and then
                   1416:  * close our outfile.
                   1417:  * I want to call this the SEE ALSO section, but that's not really what
                   1418:  * it is: we'll refer to the "initial" (top) node and the next and
                   1419:  * previous chapters.
                   1420:  */
                   1421: void
                   1422: teximdocclose(struct texi *p, int last)
                   1423: {
                   1424:        char     buf[PATH_MAX];
                   1425:
                   1426:        if (NULL == p->chapters || 0 == p->chapnum)
                   1427:                return;
                   1428:
                   1429:        teximacro(p, "Sh INFO NAVIGATION");
                   1430:
                   1431:        /* Print a reference to the "top" node. */
                   1432:        if (p->chapnum > 1) {
1.22      kristaps 1433:                texiputchars(p, "Top node,");
1.20      kristaps 1434:                snprintf(buf, sizeof(buf), "node1 7");
                   1435:                teximacroopen(p, "Xr ");
                   1436:                texiputchars(p, buf);
1.22      kristaps 1437:                texiputchars(p, " ;");
1.20      kristaps 1438:                teximacroclose(p);
                   1439:        }
                   1440:
                   1441:        /* Print a reference to the previous node. */
                   1442:        if (p->chapnum > 2) {
1.22      kristaps 1443:                texiputchars(p, "previous node,");
1.20      kristaps 1444:                snprintf(buf, sizeof(buf),
                   1445:                        "node%zu 7", p->chapnum - 1);
                   1446:                teximacroopen(p, "Xr ");
                   1447:                texiputchars(p, buf);
                   1448:                if ( ! last)
1.22      kristaps 1449:                        texiputchars(p, " ;");
1.20      kristaps 1450:                teximacroclose(p);
                   1451:        }
                   1452:
                   1453:        /* Print a reference to the next node. */
                   1454:        if ( ! last) {
1.22      kristaps 1455:                if (1 == p->chapnum)
                   1456:                        texiputchars(p, "Next node,");
                   1457:                else
                   1458:                        texiputchars(p, "next node,");
1.20      kristaps 1459:                snprintf(buf, sizeof(buf),
                   1460:                        "node%zu 7", p->chapnum + 1);
                   1461:                teximacroopen(p, "Xr ");
                   1462:                texiputchars(p, buf);
                   1463:                teximacroclose(p);
                   1464:        }
                   1465:
                   1466:        fclose(p->outfile);
                   1467: }
                   1468:
                   1469: /*
                   1470:  * Open a mdoc(7) context.
                   1471:  * If we're printing chapters, then open the outfile here, too.
                   1472:  * Otherwise just print the mdoc(7) prologue.
                   1473:  */
                   1474: void
1.21      kristaps 1475: teximdocopen(struct texi *p, size_t *pos)
1.20      kristaps 1476: {
                   1477:        const char      *cp;
                   1478:        time_t           t;
                   1479:        char             date[32];
                   1480:        char             fname[PATH_MAX];
                   1481:
                   1482:        if (NULL != p->chapters) {
                   1483:                snprintf(fname, sizeof(fname), "%s/node%zu.7",
                   1484:                        p->chapters, ++p->chapnum);
                   1485:                p->outfile = fopen(fname, "w");
                   1486:                if (NULL == p->outfile)
                   1487:                        texiabort(p, fname);
                   1488:        }
                   1489:
                   1490:        /*
                   1491:         * Here we print our standard mdoc(7) prologue.
                   1492:         * We use the title set with @settitle for the `Nd' description
                   1493:         * and the source document filename (the first one as invoked on
                   1494:         * the command line) for the title.
                   1495:         * The date is set to the current date.
                   1496:         */
                   1497:        t = time(NULL);
                   1498:        strftime(date, sizeof(date), "%F", localtime(&t));
                   1499:
                   1500:        teximacroopen(p, "Dd");
                   1501:        texiputchars(p, date);
                   1502:        teximacroclose(p);
                   1503:        teximacroopen(p, "Dt");
                   1504:        for (cp = p->title; '\0' != *cp; cp++)
                   1505:                texiputchar(p, toupper((unsigned int)*cp));
                   1506:        texiputchars(p, " 7");
                   1507:        teximacroclose(p);
                   1508:        teximacro(p, "Os");
                   1509:        teximacro(p, "Sh NAME");
                   1510:        teximacroopen(p, "Nm");
                   1511:        for (cp = p->title; '\0' != *cp; cp++)
                   1512:                texiputchar(p, *cp);
                   1513:        teximacroclose(p);
                   1514:        teximacroopen(p, "Nd");
1.21      kristaps 1515:        /*
                   1516:         * The subtitle `Nd' can consist of arbitrary macros, so paste
                   1517:         * it and parse to the end of the line.
                   1518:         */
                   1519:        if (NULL != p->subtitle) {
                   1520:                texisplice(p, p->subtitle, strlen(p->subtitle), *pos);
                   1521:                parseeoln(p, pos);
                   1522:        } else
1.20      kristaps 1523:                texiputchars(p, "Unknown description");
                   1524:        teximacroclose(p);
                   1525: }
                   1526:

CVSweb