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

Diff for /docbook2mdoc/docbook2mdoc.c between version 1.27 and 1.132

version 1.27, 2014/04/02 10:06:14 version 1.132, 2019/04/21 14:48:11
Line 1 
Line 1 
 /*      $Id$ */  /* $Id$ */
 /*  /*
  * Copyright (c) 2014 Kristaps Dzonsons <kristaps@bsd.lv>   * Copyright (c) 2014 Kristaps Dzonsons <kristaps@bsd.lv>
    * Copyright (c) 2019 Ingo Schwarze <schwarze@openbsd.org>
  *   *
  * Permission to use, copy, modify, and distribute this software for any   * Permission to use, copy, modify, and distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above   * purpose with or without fee is hereby granted, provided that the above
Line 14 
Line 15 
  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF   * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.   * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */   */
 #include <sys/queue.h>  
   
 #include <assert.h>  #include <assert.h>
 #include <ctype.h>  #include <ctype.h>
 #include <expat.h>  
 #include <fcntl.h>  
 #include <getopt.h>  
 #include <stdio.h>  #include <stdio.h>
 #include <stdlib.h>  #include <stdlib.h>
 #include <string.h>  #include <string.h>
 #include <unistd.h>  
   
 #include "extern.h"  #include "node.h"
   #include "macro.h"
   #include "format.h"
   
 /*  /*
  * Global parse state.   * The implementation of the mdoc(7) formatter.
  * Keep this as simple and small as possible.  
  */   */
 struct  parse {  
         XML_Parser       xml;  
         enum nodeid      node; /* current (NODE_ROOT if pre-tree) */  
         const char      *fname; /* filename */  
         int              stop; /* should we stop now? */  
         struct pnode    *root; /* root of parse tree */  
         struct pnode    *cur; /* current node in tree */  
         char            *b; /* nil-terminated buffer for pre-print */  
         size_t           bsz; /* current length of b */  
         size_t           mbsz; /* max bsz allocation */  
         int              newln; /* output: are we on a fresh line */  
 };  
   
 struct  node {  static void      pnode_print(struct format *, struct pnode *);
         const char      *name; /* docbook element name */  static void      pnode_printrefentry(struct format *, struct pnode *);
         unsigned int     flags;  
 #define NODE_IGNTEXT     1 /* ignore all contained text */  
 };  
   
 TAILQ_HEAD(pnodeq, pnode);  
 TAILQ_HEAD(pattrq, pattr);  
   
 struct  pattr {  static void
         enum attrkey     key;  pnode_printtext(struct format *f, struct pnode *n)
         enum attrval     val;  {
         char            *rawval;          struct pnode    *nn;
         TAILQ_ENTRY(pattr) child;          char            *cp;
 };          int              accept_arg;
   
 struct  pnode {          cp = n->b;
         enum nodeid      node; /* node type */          accept_arg = f->flags & FMT_ARG;
         char            *b; /* binary data buffer */          if (f->linestate == LINE_MACRO && !n->spc && !accept_arg) {
         size_t           bsz; /* data buffer size */                  for (;;) {
         struct pnode    *parent; /* parent (or NULL if top) */                          if (*cp == '\0')
         struct pnodeq    childq; /* queue of children */                                  return;
         struct pattrq    attrq; /* attributes of node */                          if (strchr("!),.:;?]", *cp) == NULL)
         TAILQ_ENTRY(pnode) child;                                  break;
 };                          printf(" %c", *cp++);
                   }
                   if (isspace((unsigned char)*cp)) {
                           while (isspace((unsigned char)*cp))
                                   cp++;
                           macro_close(f);
                   } else {
                           fputs(" Ns", stdout);
                           f->flags &= FMT_IMPL;
                           accept_arg = 1;
                   }
           }
           if (f->linestate == LINE_MACRO && !accept_arg &&
               (f->flags & (FMT_CHILD | FMT_IMPL)) == 0)
                   macro_close(f);
   
 static  const char *attrkeys[ATTRKEY__MAX] = {          /*
         "choice",           * Text preceding a macro without intervening whitespace
         "id",           * requires a .Pf macro.
         "rep"           * Set the spacing flag to avoid a redundant .Ns macro.
 };           */
   
 static  const char *attrvals[ATTRVAL__MAX] = {          if (f->linestate != LINE_MACRO &&
         "norepeat",              (nn = TAILQ_NEXT(n, child)) != NULL && nn->spc == 0) {
         "opt",                  switch (pnode_class(nn->node)) {
         "plain",                  case CLASS_LINE:
         "repeat",                  case CLASS_ENCL:
         "req"                          macro_open(f, "Pf");
 };                          accept_arg = 1;
                           f->flags |= FMT_CHILD;
                           nn->spc = 1;
                           break;
                   default:
                           break;
                   }
           }
   
 static  const struct node nodes[NODE__MAX] = {          switch (f->linestate) {
         { NULL, 0 },          case LINE_NEW:
         { "acronym", 0 },                  break;
         { "application", 0 },          case LINE_TEXT:
         { "arg", 0 },                  if (n->spc) {
         { "citerefentry", NODE_IGNTEXT },                          if (n->node == NODE_TEXT)
         { "cmdsynopsis", NODE_IGNTEXT },                                  macro_close(f);
         { "code", 0 },                          else
         { "command", 0 },                                  putchar(' ');
         { "date", 0 },                  }
         { "emphasis", 0 },                  break;
         { "entry", 0 },          case LINE_MACRO:
         { "envar", 0 },                  if (accept_arg)
         { "filename", 0 },                          putchar(' ');
         { "funcdef", 0 },                  else
         { "funcprototype", NODE_IGNTEXT },                          macro_close(f);
         { "funcsynopsis", NODE_IGNTEXT },                  break;
         { "funcsynopsisinfo", 0 },          }
         { "function", 0 },  
         { "itemizedlist", NODE_IGNTEXT },  
         { "group", NODE_IGNTEXT },  
         { "link", 0 },  
         { "listitem", NODE_IGNTEXT },  
         { "literal", 0 },  
         { "manvolnum", 0 },  
         { "option", 0 },  
         { "orderedlist", NODE_IGNTEXT },  
         { "para", 0 },  
         { "paramdef", 0 },  
         { "parameter", 0 },  
         { "programlisting", 0 },  
         { "prompt", 0 },  
         { "refclass", NODE_IGNTEXT },  
         { "refdescriptor", NODE_IGNTEXT },  
         { "refentry", NODE_IGNTEXT },  
         { "refentryinfo", NODE_IGNTEXT },  
         { "refentrytitle", 0 },  
         { "refmeta", NODE_IGNTEXT },  
         { "refmiscinfo", NODE_IGNTEXT },  
         { "refname", 0 },  
         { "refnamediv", NODE_IGNTEXT },  
         { "refpurpose", 0 },  
         { "refsect1", NODE_IGNTEXT },  
         { "refsect2", NODE_IGNTEXT },  
         { "refsynopsisdiv", NODE_IGNTEXT },  
         { "replaceable", 0 },  
         { "row", NODE_IGNTEXT },  
         { "sbr", NODE_IGNTEXT },  
         { "screen", NODE_IGNTEXT },  
         { "structname", 0 },  
         { "synopsis", 0 },  
         { "table", NODE_IGNTEXT },  
         { "tbody", NODE_IGNTEXT },  
         { "term", 0 },  
         { NULL, 0 },  
         { "tfoot", NODE_IGNTEXT },  
         { "tgroup", NODE_IGNTEXT },  
         { "thead", NODE_IGNTEXT },  
         { "title", 0 },  
         { "ulink", 0 },  
         { "userinput", 0 },  
         { "variablelist", NODE_IGNTEXT },  
         { "varlistentry", NODE_IGNTEXT },  
         { "varname", 0 },  
 };  
   
 static void          if (n->node == NODE_ESCAPE) {
 pnode_print(struct parse *p, struct pnode *pn);                  fputs(n->b, stdout);
                   if (f->linestate == LINE_NEW)
                           f->linestate = LINE_TEXT;
                   return;
           }
   
 /*          /*
  * Process a stream of characters.           * Remove the prefix '-' from <option> elements
  * We store text as nodes in and of themselves.           * because the arguments of .Fl macros do not need it.
  * If a text node is already open, append to it.           */
  * If it's not open, open one under the current context.  
  */          if (n->parent != NULL && n->parent->node == NODE_OPTION && *cp == '-')
                   cp++;
   
           if (f->linestate == LINE_MACRO)
                   macro_addarg(f, cp, 0);
           else
                   print_text(f, cp, 0);
   }
   
 static void  static void
 xml_char(void *arg, const XML_Char *p, int sz)  pnode_printimagedata(struct format *f, struct pnode *n)
 {  {
         struct parse    *ps = arg;          const char      *cp;
         struct pnode    *dat;  
         int              i;  
   
         /* Stopped or no tree yet. */          if ((cp = pnode_getattr_raw(n, ATTRKEY_FILEREF, NULL)) == NULL)
         if (ps->stop || NODE_ROOT == ps->node)                  cp = pnode_getattr_raw(n, ATTRKEY_ENTITYREF, NULL);
                 return;          if (cp != NULL) {
                   print_text(f, "[image:", ARG_SPACE);
                   print_text(f, cp, ARG_SPACE);
                   print_text(f, "]", 0);
           } else
                   print_text(f, "[image]", ARG_SPACE);
   }
   
         /* Not supposed to be collecting text. */  static void
         assert(NULL != ps->cur);  pnode_printrefnamediv(struct format *f, struct pnode *n)
         if (NODE_IGNTEXT & nodes[ps->node].flags)  {
                 return;          struct pnode    *nc, *nn;
           int              comma;
   
         /*          f->parastate = PARA_HAVE;
          * Are we in the midst of processing text?          macro_line(f, "Sh NAME");
          * If we're not processing text right now, then create a text          f->parastate = PARA_HAVE;
          * node for doing so.          comma = 0;
          * However, don't do so unless we have some non-whitespace to          TAILQ_FOREACH_SAFE(nc, &n->childq, child, nn) {
          * process: strip out all leading whitespace to be sure.                  if (nc->node != NODE_REFNAME)
          */                          continue;
         if (NODE_TEXT != ps->node) {                  if (comma)
                 for (i = 0; i < sz; i++)                          macro_addarg(f, ",", ARG_SPACE);
                         if ( ! isspace((int)p[i]))                  macro_open(f, "Nm");
                                 break;                  macro_addnode(f, nc, ARG_SPACE);
                 if (i == sz)                  pnode_unlink(nc);
                         return;                  comma = 1;
                 p += i;  
                 sz -= i;  
                 dat = calloc(1, sizeof(struct pnode));  
                 if (NULL == dat) {  
                         perror(NULL);  
                         exit(EXIT_FAILURE);  
                 }  
   
                 dat->node = ps->node = NODE_TEXT;  
                 dat->parent = ps->cur;  
                 TAILQ_INIT(&dat->childq);  
                 TAILQ_INIT(&dat->attrq);  
                 TAILQ_INSERT_TAIL(&ps->cur->childq, dat, child);  
                 ps->cur = dat;  
                 assert(NULL != ps->root);  
         }          }
           macro_close(f);
         /* Append to current buffer. */  
         assert(sz >= 0);  
         ps->cur->b = realloc(ps->cur->b,  
                 ps->cur->bsz + (size_t)sz);  
         if (NULL == ps->cur->b) {  
                 perror(NULL);  
                 exit(EXIT_FAILURE);  
         }  
         memcpy(ps->cur->b + ps->cur->bsz, p, sz);  
         ps->cur->bsz += (size_t)sz;  
 }  }
   
   /*
    * If the SYNOPSIS macro has a superfluous title, kill it.
    */
 static void  static void
 pnode_trim(struct pnode *pn)  pnode_printrefsynopsisdiv(struct format *f, struct pnode *n)
 {  {
           struct pnode    *nc, *nn;
   
         assert(NODE_TEXT == pn->node);          TAILQ_FOREACH_SAFE(nc, &n->childq, child, nn)
         for ( ; pn->bsz > 0; pn->bsz--)                  if (nc->node == NODE_TITLE)
                 if ( ! isspace((int)pn->b[pn->bsz - 1]))                          pnode_unlink(nc);
                         break;  
           f->parastate = PARA_HAVE;
           macro_line(f, "Sh SYNOPSIS");
           f->parastate = PARA_HAVE;
 }  }
   
 /*  /*
  * Begin an element.   * Start a hopefully-named `Sh' section.
  * First, look for the element.  
  * If we don't find it and we're not parsing, keep going.  
  * If we don't find it and we're parsing, puke and exit.  
  * If we find it but we're not parsing yet (i.e., it's not a refentry  
  * and thus out of context), keep going.  
  * If we find it and we're at the root and already have a tree, puke and  
  * exit (FIXME: I don't think this is right?).  
  * If we find it but we're parsing a text node, close out the text node,  
  * return to its parent, and keep going.  
  * Make sure that the element is in the right context.  
  * Lastly, put the node onto our parse tree and continue.  
  */   */
 static void  static void
 xml_elem_start(void *arg, const XML_Char *name, const XML_Char **atts)  pnode_printsection(struct format *f, struct pnode *n)
 {  {
         struct parse     *ps = arg;          struct pnode    *nc, *ncc;
         enum nodeid       node;          const char      *title;
         enum attrkey      key;          int              flags, level;
         enum attrval      val;  
         struct pnode     *dat;  
         struct pattr     *pattr;  
         const XML_Char  **att;  
   
         if (ps->stop)          if (n->parent == NULL) {
                   pnode_printrefentry(f, n);
                 return;                  return;
           }
   
         /* Close out text node, if applicable... */          level = ++f->level;
         if (NODE_TEXT == ps->node) {          flags = ARG_SPACE;
                 assert(NULL != ps->cur);          switch (n->node) {
                 pnode_trim(ps->cur);          case NODE_PREFACE:
                 ps->cur = ps->cur->parent;          case NODE_SECTION:
                 assert(NULL != ps->cur);          case NODE_APPENDIX:
                 ps->node = ps->cur->node;                  if (level == 1)
                           flags |= ARG_UPPER;
                   break;
           case NODE_SIMPLESECT:
           case NODE_LEGALNOTICE:
                   if (level < 2)
                           level = 2;
                   break;
           default:
                   if (level < 3)
                           level = 3;
                   break;
         }          }
   
         for (node = 0; node < NODE__MAX; node++)          TAILQ_FOREACH(nc, &n->childq, child)
                 if (NULL == nodes[node].name)                  if (nc->node == NODE_TITLE)
                         continue;  
                 else if (0 == strcmp(nodes[node].name, name))  
                         break;                          break;
   
         if (NODE__MAX == node && NODE_ROOT == ps->node) {          if (nc == NULL) {
                 return;                  switch (n->node) {
         } else if (NODE__MAX == node) {                  case NODE_PREFACE:
                 fprintf(stderr, "%s:%zu:%zu: unknown node \"%s\"\n",                          title = "Preface";
                         ps->fname, XML_GetCurrentLineNumber(ps->xml),                          break;
                         XML_GetCurrentColumnNumber(ps->xml), name);                  case NODE_APPENDIX:
                 ps->stop = 1;                          title = "Appendix";
                 return;                          break;
         } else if (NODE_ROOT == ps->node && NULL != ps->root) {                  case NODE_LEGALNOTICE:
                 fprintf(stderr, "%s:%zu:%zu: multiple refentries\n",                          title = "Legal Notice";
                         ps->fname, XML_GetCurrentLineNumber(ps->xml),                          break;
                         XML_GetCurrentColumnNumber(ps->xml));                  case NODE_CAUTION:
                 ps->stop = 1;                          title = "Caution";
                 return;                          break;
         } else if (NODE_ROOT == ps->node && NODE_REFENTRY != node) {                  case NODE_NOTE:
                 return;                          title = "Note";
         } else if ( ! isparent(node, ps->node)) {                          break;
                 fprintf(stderr, "%s:%zu:%zu: bad parent \"%s\" "                  case NODE_TIP:
                         "of node \"%s\"\n",                          title = "Tip";
                         ps->fname, XML_GetCurrentLineNumber(ps->xml),                          break;
                         XML_GetCurrentColumnNumber(ps->xml),                  case NODE_WARNING:
                         NULL == nodes[ps->node].name ?                          title = "Warning";
                         "(none)" : nodes[ps->node].name,                          break;
                         NULL == nodes[node].name ?                  default:
                         "(none)" : nodes[node].name);                          title = "Unknown";
                 ps->stop = 1;                          break;
                 return;                  }
         }          }
   
         if (NULL == (dat = calloc(1, sizeof(struct pnode)))) {          switch (level) {
                 perror(NULL);          case 1:
                 exit(EXIT_FAILURE);                  macro_close(f);
                   f->parastate = PARA_HAVE;
                   macro_open(f, "Sh");
                   break;
           case 2:
                   macro_close(f);
                   f->parastate = PARA_HAVE;
                   macro_open(f, "Ss");
                   break;
           default:
                   if (f->parastate == PARA_MID)
                           f->parastate = PARA_WANT;
                   macro_open(f, "Sy");
                   break;
         }          }
   
         dat->node = ps->node = node;          if (nc != NULL)
         dat->parent = ps->cur;                  macro_addnode(f, nc, flags);
         TAILQ_INIT(&dat->childq);          else
         TAILQ_INIT(&dat->attrq);                  macro_addarg(f, title, flags | ARG_QUOTED);
           macro_close(f);
   
         if (NULL != ps->cur)  
                 TAILQ_INSERT_TAIL(&ps->cur->childq, dat, child);  
   
         ps->cur = dat;  
         if (NULL == ps->root)  
                 ps->root = dat;  
   
         /*          /*
          * Process attributes.           * DocBook has no equivalent for -split mode,
            * so just switch the default in the AUTHORS section.
          */           */
         for (att = atts; NULL != *att; att += 2) {  
                 for (key = 0; key < ATTRKEY__MAX; key++)  
                         if (0 == strcmp(*att, attrkeys[key]))  
                                 break;  
                 if (ATTRKEY__MAX == key) {  
                         fprintf(stderr, "%s:%zu:%zu: unknown "  
                                 "attribute \"%s\"\n", ps->fname,  
                                 XML_GetCurrentLineNumber(ps->xml),  
                                 XML_GetCurrentColumnNumber(ps->xml),  
                                 *att);  
                         continue;  
                 } else if ( ! isattrkey(node, key)) {  
                         fprintf(stderr, "%s:%zu:%zu: bad "  
                                 "attribute \"%s\"\n", ps->fname,  
                                 XML_GetCurrentLineNumber(ps->xml),  
                                 XML_GetCurrentColumnNumber(ps->xml),  
                                 *att);  
                         continue;  
                 }  
                 for (val = 0; val < ATTRVAL__MAX; val++)  
                         if (0 == strcmp(*(att + 1), attrvals[val]))  
                                 break;  
                 if (ATTRVAL__MAX != val && ! isattrval(key, val)) {  
                         fprintf(stderr, "%s:%zu:%zu: bad "  
                                 "value \"%s\"\n", ps->fname,  
                                 XML_GetCurrentLineNumber(ps->xml),  
                                 XML_GetCurrentColumnNumber(ps->xml),  
                                 *(att + 1));  
                         continue;  
                 }  
                 pattr = calloc(1, sizeof(struct pattr));  
                 pattr->key = key;  
                 pattr->val = val;  
                 if (ATTRVAL__MAX == val)  
                         pattr->rawval = strdup(*(att + 1));  
                 TAILQ_INSERT_TAIL(&dat->attrq, pattr, child);  
         }  
   
           if (nc != NULL) {
                   if (level == 1 &&
                       (ncc = TAILQ_FIRST(&nc->childq)) != NULL &&
                       ncc->node == NODE_TEXT &&
                       strcasecmp(ncc->b, "AUTHORS") == 0)
                           macro_line(f, "An -nosplit");
                   pnode_unlink(nc);
           }
           f->parastate = level > 2 ? PARA_WANT : PARA_HAVE;
 }  }
   
 /*  /*
  * Roll up the parse tree.   * Start a reference, extracting the title and volume.
  * If we're at a text node, roll that one up first.  
  * If we hit the root, then assign ourselves as the NODE_ROOT.  
  */   */
 static void  static void
 xml_elem_end(void *arg, const XML_Char *name)  pnode_printciterefentry(struct format *f, struct pnode *n)
 {  {
         struct parse    *ps = arg;          struct pnode    *nc, *title, *manvol;
   
         if (ps->stop || NODE_ROOT == ps->node)          title = manvol = NULL;
                 return;          TAILQ_FOREACH(nc, &n->childq, child) {
                   if (nc->node == NODE_MANVOLNUM)
         /* Close out text node, if applicable... */                          manvol = nc;
         if (NODE_TEXT == ps->node) {                  else if (nc->node == NODE_REFENTRYTITLE)
                 assert(NULL != ps->cur);                          title = nc;
                 pnode_trim(ps->cur);  
                 ps->cur = ps->cur->parent;  
                 assert(NULL != ps->cur);  
                 ps->node = ps->cur->node;  
         }          }
           macro_open(f, "Xr");
         if (NULL == (ps->cur = ps->cur->parent))          if (title == NULL)
                 ps->node = NODE_ROOT;                  macro_addarg(f, "unknown", ARG_SPACE);
         else          else
                 ps->node = ps->cur->node;                  macro_addnode(f, title, ARG_SPACE | ARG_SINGLE);
           if (manvol == NULL)
                   macro_addarg(f, "1", ARG_SPACE);
           else
                   macro_addnode(f, manvol, ARG_SPACE | ARG_SINGLE);
           pnode_unlinksub(n);
 }  }
   
 /*  /*
  * Recursively free a node (NULL is ok).   * The <mml:mfenced> node is a little peculiar.
    * First, it can have arbitrary open and closing tokens, which default
    * to parentheses.
    * Second, >1 arguments are separated by commas.
  */   */
 static void  static void
 pnode_free(struct pnode *pn)  pnode_printmathfenced(struct format *f, struct pnode *n)
 {  {
         struct pnode    *pp;          struct pnode    *nc;
         struct pattr    *ap;  
   
         if (NULL == pn)          printf("left %s ", pnode_getattr_raw(n, ATTRKEY_OPEN, "("));
                 return;  
   
         while (NULL != (pp = TAILQ_FIRST(&pn->childq))) {          nc = TAILQ_FIRST(&n->childq);
                 TAILQ_REMOVE(&pn->childq, pp, child);          pnode_print(f, nc);
                 pnode_free(pp);  
         }  
   
         while (NULL != (ap = TAILQ_FIRST(&pn->attrq))) {          while ((nc = TAILQ_NEXT(nc, child)) != NULL) {
                 TAILQ_REMOVE(&pn->attrq, ap, child);                  putchar(',');
                 free(ap->rawval);                  pnode_print(f, nc);
                 free(ap);  
         }          }
           printf("right %s ", pnode_getattr_raw(n, ATTRKEY_CLOSE, ")"));
         free(pn->b);          pnode_unlinksub(n);
         free(pn);  
 }  }
   
 /*  /*
  * Unlink a node from its parent and pnode_free() it.   * These math nodes require special handling because they have infix
    * syntax, instead of the usual prefix or prefix.
    * So we need to break up the first and second child node with a
    * particular eqn(7) word.
  */   */
 static void  static void
 pnode_unlink(struct pnode *pn)  pnode_printmath(struct format *f, struct pnode *n)
 {  {
           struct pnode    *nc;
   
         if (NULL != pn->parent)          nc = TAILQ_FIRST(&n->childq);
                 TAILQ_REMOVE(&pn->parent->childq, pn, child);          pnode_print(f, nc);
         pnode_free(pn);  
 }  
   
 /*          switch (n->node) {
  * Unlink all children of a node and pnode_free() them.          case NODE_MML_MSUP:
  */                  fputs(" sup ", stdout);
 static void                  break;
 pnode_unlinksub(struct pnode *pn)          case NODE_MML_MFRAC:
 {                  fputs(" over ", stdout);
                   break;
           case NODE_MML_MSUB:
                   fputs(" sub ", stdout);
                   break;
           default:
                   break;
           }
   
         while ( ! TAILQ_EMPTY(&pn->childq))          nc = TAILQ_NEXT(nc, child);
                 pnode_unlink(TAILQ_FIRST(&pn->childq));          pnode_print(f, nc);
           pnode_unlinksub(n);
 }  }
   
 /*  
  * Reset the lookaside buffer.  
  */  
 static void  static void
 bufclear(struct parse *p)  pnode_printfuncprototype(struct format *f, struct pnode *n)
 {  {
           struct pnode    *fdef, *ftype, *nc, *nn;
   
         p->b[p->bsz = 0] = '\0';          /*
 }           * Extract <funcdef> child and ignore <void> child.
            * Leave other children in place, to be treated as parameters.
            */
   
 /*          fdef = NULL;
  * Append NODE_TEXT contents to the current buffer, reallocating its          TAILQ_FOREACH_SAFE(nc, &n->childq, child, nn) {
  * size if necessary.                  switch (nc->node) {
  * The buffer is ALWAYS nil-terminated.                  case NODE_FUNCDEF:
  */                          if (fdef == NULL) {
 static void                                  fdef = nc;
 bufappend(struct parse *p, struct pnode *pn)                                  TAILQ_REMOVE(&n->childq, nc, child);
 {                                  nc->parent = NULL;
                           }
         assert(NODE_TEXT == pn->node);                          break;
         if (p->bsz + pn->bsz + 1 > p->mbsz) {                  case NODE_VOID:
                 p->mbsz = p->bsz + pn->bsz + 1;                          pnode_unlink(nc);
                 if (NULL == (p->b = realloc(p->b, p->mbsz))) {                          break;
                         perror(NULL);                  default:
                         exit(EXIT_FAILURE);                          break;
                 }                  }
         }          }
         memcpy(p->b + p->bsz, pn->b, pn->bsz);  
         p->bsz += pn->bsz;  
         p->b[p->bsz] = '\0';  
 }  
   
 /*          /*
  * Recursively append all NODE_TEXT nodes to the buffer.           * If no children are left, the function is void; use .Fn.
  * This descends into non-text nodes, but doesn't do anything beyond           * Otherwise, use .Fo.
  * them.           */
  * In other words, this is a recursive text grok.  
  */  
 static void  
 bufappend_r(struct parse *p, struct pnode *pn)  
 {  
         struct pnode    *pp;  
   
         if (NODE_TEXT == pn->node)          nc = TAILQ_FIRST(&n->childq);
                 bufappend(p, pn);          if (fdef != NULL) {
         TAILQ_FOREACH(pp, &pn->childq, child)                  ftype = TAILQ_FIRST(&fdef->childq);
                 bufappend_r(p, pp);                  if (ftype != NULL && ftype->node == NODE_TEXT) {
 }                          macro_argline(f, "Ft", ftype->b);
                           pnode_unlink(ftype);
                   }
                   if (nc == NULL) {
                           macro_open(f, "Fn");
                           macro_addnode(f, fdef, ARG_SPACE | ARG_SINGLE);
                           macro_addarg(f, "void", ARG_SPACE);
                           macro_close(f);
                   } else
                           macro_nodeline(f, "Fo", fdef, ARG_SINGLE);
                   pnode_unlink(fdef);
           } else if (nc == NULL)
                   macro_line(f, "Fn UNKNOWN void");
           else
                   macro_line(f, "Fo UNKNOWN");
   
 /*          if (nc == NULL)
  * Recursively search and return the first instance of "node".                  return;
  */  
 static struct pnode *  
 pnode_findfirst(struct pnode *pn, enum nodeid node)  
 {  
         struct pnode    *pp, *res;  
   
         res = NULL;          while (nc != NULL) {
         TAILQ_FOREACH(pp, &pn->childq, child) {                  macro_nodeline(f, "Fa", nc, ARG_SINGLE);
                 res = pp->node == node ? pp :                  pnode_unlink(nc);
                         pnode_findfirst(pp, node);                  nc = TAILQ_FIRST(&n->childq);
                 if (NULL != res)  
                         break;  
         }          }
           macro_line(f, "Fc");
         return(res);  
 }  }
   
 #define MACROLINE_NORM  0  
 #define MACROLINE_UPPER 1  
 /*  /*
  * Recursively print text presumably on a macro line.   * The <arg> element is more complicated than it should be because text
  * Convert all whitespace to regular spaces.   * nodes are treated like ".Ar foo", but non-text nodes need to be
    * re-sent into the printer (i.e., without the preceding ".Ar").
    * This also handles the case of "repetition" (or in other words, the
    * ellipsis following an argument) and optionality.
  */   */
 static void  static void
 pnode_printmacrolinetext(struct parse *p, struct pnode *pn, int fl)  pnode_printarg(struct format *f, struct pnode *n)
 {  {
         char            *cp;          struct pnode    *nc;
           struct pattr    *a;
           int              isop, isrep, was_impl;
   
         if (0 == p->newln)          isop = 1;
                 putchar(' ');          isrep = was_impl = 0;
           TAILQ_FOREACH(a, &n->attrq, child) {
         bufclear(p);                  if (a->key == ATTRKEY_CHOICE &&
         bufappend_r(p, pn);                      (a->val == ATTRVAL_PLAIN || a->val == ATTRVAL_REQ))
                           isop = 0;
         /* Convert all space to spaces. */                  else if (a->key == ATTRKEY_REP && a->val == ATTRVAL_REPEAT)
         for (cp = p->b; '\0' != *cp; cp++)                          isrep = 1;
                 if (isspace((int)*cp))          }
                         *cp = ' ';          if (isop) {
                   if (f->flags & FMT_IMPL) {
         for (cp = p->b; isspace((int)*cp); cp++)                          was_impl = 1;
                 /* Spin past whitespace (XXX: necessary?) */ ;                          macro_open(f, "Oo");
         for ( ; '\0' != *cp; cp++) {                  } else {
                 /* Escape us if we look like a macro. */                          macro_open(f, "Op");
                 if ((cp == p->b || ' ' == *(cp - 1)) &&                          f->flags |= FMT_IMPL;
                         isupper((int)*cp) &&                  }
                         '\0' != *(cp + 1) &&          }
                         islower((int)*(cp + 1)) &&          TAILQ_FOREACH(nc, &n->childq, child) {
                         ('\0' == *(cp + 2) ||                  if (nc->node == NODE_TEXT)
                          ' ' == *(cp + 2) ||                          macro_open(f, "Ar");
                          (islower((int)*(cp + 2)) &&                  pnode_print(f, nc);
                           ('\0' == *(cp + 3) ||          }
                            ' ' == *(cp + 3)))))          if (isrep && f->linestate == LINE_MACRO)
                         fputs("\\&", stdout);                  macro_addarg(f, "...", ARG_SPACE);
                 if (MACROLINE_UPPER & fl)          if (isop) {
                         putchar(toupper((int)*cp));                  if (was_impl)
                           macro_open(f, "Oc");
                 else                  else
                         putchar((int)*cp);                          f->flags &= ~FMT_IMPL;
                 /* If we're a character escape, escape us. */  
                 if ('\\' == *cp)  
                         putchar('e');  
         }          }
           pnode_unlinksub(n);
 }  }
   
 static void  static void
 pnode_printmacrolinepart(struct parse *p, struct pnode *pn)  pnode_printgroup(struct format *f, struct pnode *n)
 {  {
           struct pnode    *nc;
           struct pattr    *a;
           int              bar, isop, isrep, was_impl;
   
         pnode_printmacrolinetext(p, pn, 0);          isop = 1;
           isrep = was_impl = 0;
           TAILQ_FOREACH(a, &n->attrq, child) {
                   if (a->key == ATTRKEY_CHOICE &&
                       (a->val == ATTRVAL_PLAIN || a->val == ATTRVAL_REQ))
                           isop = 0;
                   else if (a->key == ATTRKEY_REP && a->val == ATTRVAL_REPEAT)
                           isrep = 1;
           }
           if (isop) {
                   if (f->flags & FMT_IMPL) {
                           was_impl = 1;
                           macro_open(f, "Oo");
                   } else {
                           macro_open(f, "Op");
                           f->flags |= FMT_IMPL;
                   }
           } else if (isrep) {
                   if (f->flags & FMT_IMPL) {
                           was_impl = 1;
                           macro_open(f, "Bro");
                   } else {
                           macro_open(f, "Brq");
                           f->flags |= FMT_IMPL;
                   }
           }
           bar = 0;
           TAILQ_FOREACH(nc, &n->childq, child) {
                   if (bar && f->linestate == LINE_MACRO)
                           macro_addarg(f, "|", ARG_SPACE);
                   pnode_print(f, nc);
                   bar = 1;
           }
           if (isop) {
                   if (was_impl)
                           macro_open(f, "Oc");
                   else
                           f->flags &= ~FMT_IMPL;
           } else if (isrep) {
                   if (was_impl)
                           macro_open(f, "Brc");
                   else
                           f->flags &= ~FMT_IMPL;
           }
           if (isrep && f->linestate == LINE_MACRO)
                   macro_addarg(f, "...", ARG_SPACE);
           pnode_unlinksub(n);
 }  }
   
 /*  
  * Just pnode_printmacrolinepart() but with a newline.  
  * If no text, just the newline.  
  */  
 static void  static void
 pnode_printmacroline(struct parse *p, struct pnode *pn)  pnode_printsystemitem(struct format *f, struct pnode *n)
 {  {
           switch (pnode_getattr(n, ATTRKEY_CLASS)) {
         assert(0 == p->newln);          case ATTRVAL_IPADDRESS:
         pnode_printmacrolinetext(p, pn, 0);                  break;
         putchar('\n');          case ATTRVAL_SYSTEMNAME:
         p->newln = 1;                  macro_open(f, "Pa");
                   break;
           case ATTRVAL_EVENT:
           default:
                   macro_open(f, "Sy");
                   break;
           }
 }  }
   
 static void  static void
 pnode_printmopen(struct parse *p)  pnode_printauthor(struct format *f, struct pnode *n)
 {  {
         if (p->newln) {          struct pnode    *nc, *nn;
                 putchar('.');          int              have_contrib, have_name;
                 p->newln = 0;  
         } else  
                 putchar(' ');  
 }  
   
 static void          /*
 pnode_printmclose(struct parse *p, int sv)           * Print <contrib> children up front, before the .An scope,
 {           * and figure out whether we a name of a person.
            */
   
         if (sv && ! p->newln) {          have_contrib = have_name = 0;
                 putchar('\n');          TAILQ_FOREACH_SAFE(nc, &n->childq, child, nn) {
                 p->newln = 1;                  switch (nc->node) {
                   case NODE_CONTRIB:
                           if (have_contrib)
                                   print_text(f, ",", 0);
                           print_textnode(f, nc);
                           pnode_unlink(nc);
                           have_contrib = 1;
                           break;
                   case NODE_PERSONNAME:
                           have_name = 1;
                           break;
                   default:
                           break;
                   }
         }          }
 }          if (TAILQ_FIRST(&n->childq) == NULL)
                   return;
   
 /*          if (have_contrib)
  * If the SYNOPSIS macro has a superfluous title, kill it.                  print_text(f, ":", 0);
  */  
 static void  
 pnode_printrefsynopsisdiv(struct parse *p, struct pnode *pn)  
 {  
         struct pnode    *pp;  
   
         TAILQ_FOREACH(pp, &pn->childq, child)          /*
                 if (NODE_TITLE == pp->node) {           * If we have a name, print it in the .An scope and leave
                         pnode_unlink(pp);           * all other content for child handlers, to print after the
                         return;           * scope.  Otherwise, print everything in the scope.
            */
   
           macro_open(f, "An");
           TAILQ_FOREACH_SAFE(nc, &n->childq, child, nn) {
                   if (nc->node == NODE_PERSONNAME || have_name == 0) {
                           macro_addnode(f, nc, ARG_SPACE);
                           pnode_unlink(nc);
                 }                  }
 }          }
   
 /*          /*
  * Start a hopefully-named `Sh' section.           * If there is an email address,
  */           * print it on the same macro line.
 static void           */
 pnode_printrefsect(struct parse *p, struct pnode *pn)  
 {  
         struct pnode    *pp;  
   
         TAILQ_FOREACH(pp, &pn->childq, child)          if ((nc = pnode_findfirst(n, NODE_EMAIL)) != NULL) {
                 if (NODE_TITLE == pp->node)                  f->flags |= FMT_CHILD;
                         break;                  macro_open(f, "Aq Mt");
                   macro_addnode(f, nc, ARG_SPACE);
                   pnode_unlink(nc);
           }
   
         if (NODE_REFSECT1 == pn->node)          /*
                 fputs(".Sh", stdout);           * If there are still unprinted children, end the scope
         else           * with a comma.  Otherwise, leave the scope open in case
                 fputs(".Ss", stdout);           * a text node follows that starts with closing punctuation.
            */
   
         p->newln = 0;          if (TAILQ_FIRST(&n->childq) != NULL) {
                   macro_addarg(f, ",", ARG_SPACE);
         if (NULL != pp) {                  macro_close(f);
                 pnode_printmacrolinetext(p, pp,  
                         NODE_REFSECT1 == pn->node ?  
                         MACROLINE_UPPER : 0);  
                 pnode_printmclose(p, 1);  
                 pnode_unlink(pp);  
         } else {  
                 puts("UNKNOWN");  
                 p->newln = 1;  
         }          }
 }  }
   
 /*  
  * Start a reference, extracting the title and volume.  
  */  
 static void  static void
 pnode_printciterefentry(struct parse *p, struct pnode *pn)  pnode_printxref(struct format *f, struct pnode *n)
 {  {
         struct pnode    *pp, *title, *manvol;          const char      *linkend;
   
         title = manvol = NULL;          linkend = pnode_getattr_raw(n, ATTRKEY_LINKEND, NULL);
         assert(p->newln);          if (linkend != NULL) {
         TAILQ_FOREACH(pp, &pn->childq, child)                  macro_open(f, "Sx");
                 if (NODE_MANVOLNUM == pp->node)                  macro_addarg(f, linkend, ARG_SPACE);
                         manvol = pp;          }
                 else if (NODE_REFENTRYTITLE == pp->node)  
                         title = pp;  
   
         fputs(".Xr", stdout);  
         p->newln = 0;  
   
         if (NULL != title) {  
                 pnode_printmacrolinepart(p, title);  
         } else  
                 fputs(" unknown ", stdout);  
   
         if (NULL == manvol) {  
                 puts(" 1");  
                 p->newln = 1;  
         } else  
                 pnode_printmacroline(p, manvol);  
 }  }
   
 static void  static void
 pnode_printrefmeta(struct parse *p, struct pnode *pn)  pnode_printlink(struct format *f, struct pnode *n)
 {  {
         struct pnode    *pp, *title, *manvol;          struct pnode    *nc;
           const char      *uri, *text;
   
         title = manvol = NULL;          uri = pnode_getattr_raw(n, ATTRKEY_LINKEND, NULL);
         assert(p->newln);          if (uri != NULL) {
         TAILQ_FOREACH(pp, &pn->childq, child)                  if (TAILQ_FIRST(&n->childq) != NULL) {
                 if (NODE_MANVOLNUM == pp->node)                          TAILQ_FOREACH(nc, &n->childq, child)
                         manvol = pp;                                  pnode_print(f, nc);
                 else if (NODE_REFENTRYTITLE == pp->node)                          text = "";
                         title = pp;                  } else if ((text = pnode_getattr_raw(n,
                       ATTRKEY_ENDTERM, NULL)) != NULL) {
         puts(".Dd $Mdocdate" "$");                          if (f->linestate == LINE_MACRO && f->flags & FMT_ARG)
         fputs(".Dt", stdout);                                  macro_addarg(f, text, ARG_SPACE);
         p->newln = 0;                          else
                                   print_text(f, text, ARG_SPACE);
         if (NULL != title)                  }
                 pnode_printmacrolinetext(p, title, MACROLINE_UPPER);                  if (text != NULL) {
         else                          if (f->flags & FMT_IMPL)
                 fputs(" UNKNOWN ", stdout);                                  macro_open(f, "Po");
                           else {
         if (NULL == manvol) {                                  macro_open(f, "Pq");
                 puts(" 1");                                  f->flags |= FMT_CHILD;
                 p->newln = 1;                          }
         } else                  }
                 pnode_printmacroline(p, manvol);                  macro_open(f, "Sx");
                   macro_addarg(f, uri, ARG_SPACE);
         puts(".Os");                  if (text != NULL && f->flags & FMT_IMPL)
                           macro_open(f, "Pc");
                   pnode_unlinksub(n);
                   return;
           }
           uri = pnode_getattr_raw(n, ATTRKEY_XLINK_HREF, NULL);
           if (uri == NULL)
                   uri = pnode_getattr_raw(n, ATTRKEY_URL, NULL);
           if (uri != NULL) {
                   macro_open(f, "Lk");
                   macro_addarg(f, uri, ARG_SPACE | ARG_SINGLE);
                   if (TAILQ_FIRST(&n->childq) != NULL)
                           macro_addnode(f, n, ARG_SPACE | ARG_SINGLE);
                   pnode_unlinksub(n);
           }
 }  }
   
 static void  static void
 pnode_printfuncdef(struct parse *p, struct pnode *pn)  pnode_printolink(struct format *f, struct pnode *n)
 {  {
         struct pnode    *pp, *ftype, *func;          const char      *uri, *ptr, *local;
   
         assert(p->newln);          uri = pnode_getattr_raw(n, ATTRKEY_TARGETDOC, NULL);
         ftype = func = NULL;          ptr = pnode_getattr_raw(n, ATTRKEY_TARGETPTR, NULL);
         TAILQ_FOREACH(pp, &pn->childq, child)          local = pnode_getattr_raw(n, ATTRKEY_LOCALINFO, NULL);
                 if (NODE_TEXT == pp->node)          if (uri == NULL) {
                         ftype = pp;                  uri = ptr;
                 else if (NODE_FUNCTION == pp->node)                  ptr = NULL;
                         func = pp;  
   
         if (NULL != ftype) {  
                 fputs(".Ft", stdout);  
                 p->newln = 0;  
                 pnode_printmacroline(p, ftype);  
         }          }
           if (uri == NULL) {
                   uri = local;
                   local = NULL;
           }
           if (uri == NULL)
                   return;
   
         if (NULL != func) {          macro_open(f, "Lk");
                 fputs(".Fo", stdout);          macro_addarg(f, uri, ARG_SPACE | ARG_SINGLE);
                 p->newln = 0;          macro_addnode(f, n, ARG_SPACE | ARG_SINGLE);
                 pnode_printmacroline(p, func);          if (ptr != NULL || local != NULL) {
         } else {                  macro_close(f);
                 puts(".Fo UNKNOWN");                  macro_open(f, "Pq");
                 p->newln = 1;                  if (ptr != NULL)
                           macro_addarg(f, ptr, ARG_SPACE);
                   if (local != NULL)
                           macro_addarg(f, local, ARG_SPACE);
         }          }
           pnode_unlinksub(n);
 }  }
   
 static void  static void
 pnode_printparamdef(struct parse *p, struct pnode *pn)  pnode_printprologue(struct format *f, struct pnode *root)
 {  {
         struct pnode    *pp, *ptype, *param;          struct pnode    *date, *refmeta, *name, *vol, *descr, *nc, *nn;
           const char      *sname;
   
         assert(p->newln);          /* Collect information. */
         ptype = param = NULL;  
         TAILQ_FOREACH(pp, &pn->childq, child)  
                 if (NODE_TEXT == pp->node)  
                         ptype = pp;  
                 else if (NODE_PARAMETER == pp->node)  
                         param = pp;  
   
         fputs(".Fa \"", stdout);          if ((date = pnode_takefirst(root, NODE_PUBDATE)) == NULL)
         p->newln = 0;                  date = pnode_takefirst(root, NODE_DATE);
         if (NULL != ptype) {  
                 pnode_printmacrolinepart(p, ptype);          name = vol = NULL;
                 putchar(' ');          if ((refmeta = pnode_findfirst(root, NODE_REFMETA)) != NULL) {
                   TAILQ_FOREACH_SAFE(nc, &refmeta->childq, child, nn) {
                           switch (nc->node) {
                           case NODE_REFENTRYTITLE:
                                   name = nc;
                                   break;
                           case NODE_MANVOLNUM:
                                   vol = nc;
                                   break;
                           default:
                                   continue;
                           }
                           TAILQ_REMOVE(&refmeta->childq, nc, child);
                   }
         }          }
   
         if (NULL != param)          if (pnode_findfirst(root, NODE_REFNAMEDIV) == NULL &&
                 pnode_printmacrolinepart(p, param);              ((nc = pnode_findfirst(root, NODE_BOOKINFO)) != NULL ||
                (nc = pnode_findfirst(root, NODE_REFENTRYINFO)) != NULL))
                   descr = pnode_takefirst(nc, NODE_TITLE);
           else
                   descr = NULL;
   
         puts("\"");          /* Print prologue. */
         p->newln = 1;  
 }  
   
 static void          if (date == NULL)
 pnode_printfuncprototype(struct parse *p, struct pnode *pn)                  macro_line(f, "Dd $Mdocdate" "$");
 {          else
         struct pnode    *pp, *fdef;                  macro_nodeline(f, "Dd", date, 0);
   
         assert(p->newln);          macro_open(f, "Dt");
         TAILQ_FOREACH(fdef, &pn->childq, child)          if (name == NULL) {
                 if (NODE_FUNCDEF == fdef->node)                  sname = pnode_getattr_raw(root, ATTRKEY_ID, "UNKNOWN");
                         break;                  macro_addarg(f, sname, ARG_SPACE | ARG_SINGLE | ARG_UPPER);
           } else
         if (NULL != fdef)                  macro_addnode(f, name, ARG_SPACE | ARG_SINGLE | ARG_UPPER);
                 pnode_printfuncdef(p, fdef);          if (vol == NULL)
                   macro_addarg(f, "1", ARG_SPACE);
         else          else
                 puts(".Fo UNKNOWN");                  macro_addnode(f, vol, ARG_SPACE | ARG_SINGLE);
   
         TAILQ_FOREACH(pp, &pn->childq, child)          macro_line(f, "Os");
                 if (NODE_PARAMDEF == pp->node)  
                         pnode_printparamdef(p, pp);  
   
         puts(".Fc");          if (descr != NULL) {
         p->newln = 1;                  macro_line(f, "Sh NAME");
                   if (name == NULL)
                           macro_argline(f, "Nm", sname);
                   else
                           macro_nodeline(f, "Nm", name, ARG_SINGLE);
                   macro_nodeline(f, "Nd", descr, 0);
           }
   
           /* Clean up. */
   
           pnode_unlink(date);
           pnode_unlink(name);
           pnode_unlink(vol);
           pnode_unlink(descr);
           f->parastate = PARA_HAVE;
 }  }
   
 /*  
  * The <arg> element is more complicated than it should be because text  
  * nodes are treated like ".Ar foo", but non-text nodes need to be  
  * re-sent into the printer (i.e., without the preceding ".Ar").  
  * This also handles the case of "repetition" (or in other words, the  
  * ellipsis following an argument) and optionality.  
  */  
 static void  static void
 pnode_printarg(struct parse *p, struct pnode *pn)  pnode_printrefentry(struct format *f, struct pnode *n)
 {  {
         struct pnode    *pp;          struct pnode    *info, *meta, *nc, *title;
         struct pattr    *ap;          struct pnode    *match, *later;
         int              isop, isrep;  
   
         isop = 1;          /* Collect nodes that remained behind when writing the prologue. */
         isrep = 0;  
         TAILQ_FOREACH(ap, &pn->attrq, child)  
                 if (ATTRKEY_CHOICE == ap->key &&  
                         (ATTRVAL_PLAIN == ap->val ||  
                          ATTRVAL_REQ == ap->val))  
                         isop = 0;  
                 else if (ATTRKEY_REP == ap->key &&  
                         (ATTRVAL_REPEAT == ap->val))  
                         isrep = 1;  
   
         if (isop) {          meta = NULL;
                 pnode_printmopen(p);          info = pnode_takefirst(n, NODE_BOOKINFO);
                 fputs("Op", stdout);          if (info != NULL && TAILQ_FIRST(&info->childq) == NULL) {
                   pnode_unlink(info);
                   info = NULL;
         }          }
           if (info == NULL) {
         TAILQ_FOREACH(pp, &pn->childq, child) {                  info = pnode_takefirst(n, NODE_REFENTRYINFO);
                 if (NODE_TEXT == pp->node) {                  if (info != NULL && TAILQ_FIRST(&info->childq) == NULL) {
                         pnode_printmopen(p);                          pnode_unlink(info);
                         fputs("Ar", stdout);                          info = NULL;
                 }                  }
                 pnode_print(p, pp);                  meta = pnode_takefirst(n, NODE_REFMETA);
                 if (NODE_TEXT == pp->node && isrep)                  if (meta != NULL && TAILQ_FIRST(&meta->childq) == NULL) {
                         fputs("...", stdout);                          pnode_unlink(meta);
                           meta = NULL;
                   }
         }          }
 }          if (info == NULL && meta == NULL)
                   return;
   
 static void          /*
 pnode_printgroup(struct parse *p, struct pnode *pn)           * Find the best place to put this information.
 {           * Use the last existing AUTHORS node, if any.
         struct pnode    *pp, *np;           * Otherwise, put it behind all standard sections that
         struct pattr    *ap;           * conventionally precede AUTHORS, and also behind any
         int              isop, sv;           * non-standard sections that follow the last of these,
            * but before the next standard section.
            */
   
         isop = 1;          match = later = NULL;
         TAILQ_FOREACH(ap, &pn->attrq, child)          TAILQ_FOREACH(nc, &n->childq, child) {
                 if (ATTRKEY_CHOICE == ap->key &&                  switch (nc->node) {
                         (ATTRVAL_PLAIN == ap->val ||                  case NODE_REFENTRY:
                          ATTRVAL_REQ == ap->val)) {                  case NODE_REFNAMEDIV:
                         isop = 0;                  case NODE_REFSYNOPSISDIV:
                   case NODE_PREFACE:
                           later = NULL;
                           continue;
                   case NODE_APPENDIX:
                   case NODE_INDEX:
                           if (later == NULL)
                                   later = nc;
                           continue;
                   default:
                         break;                          break;
                 }                  }
                   if ((title = pnode_findfirst(nc, NODE_TITLE)) == NULL ||
                       (title = TAILQ_FIRST(&title->childq)) == NULL ||
                       title->node != NODE_TEXT)
                           continue;
                   if (strcasecmp(title->b, "AUTHORS") == 0 ||
                       strcasecmp(title->b, "AUTHOR") == 0)
                           match = nc;
                   else if (strcasecmp(title->b, "NAME") == 0 ||
                       strcasecmp(title->b, "SYNOPSIS") == 0 ||
                       strcasecmp(title->b, "DESCRIPTION") == 0 ||
                       strcasecmp(title->b, "RETURN VALUES") == 0 ||
                       strcasecmp(title->b, "ENVIRONMENT") == 0 ||
                       strcasecmp(title->b, "FILES") == 0 ||
                       strcasecmp(title->b, "EXIT STATUS") == 0 ||
                       strcasecmp(title->b, "EXAMPLES") == 0 ||
                       strcasecmp(title->b, "DIAGNOSTICS") == 0 ||
                       strcasecmp(title->b, "ERRORS") == 0 ||
                       strcasecmp(title->b, "SEE ALSO") == 0 ||
                       strcasecmp(title->b, "STANDARDS") == 0 ||
                       strcasecmp(title->b, "HISTORY") == 0)
                           later = NULL;
                   else if ((strcasecmp(title->b, "CAVEATS") == 0 ||
                       strcasecmp(title->b, "BUGS") == 0) &&
                       later == NULL)
                           later = nc;
           }
   
         /*          /*
          * Make sure we're on a macro line.           * If no AUTHORS section was found, create one from scratch,
          * This will prevent pnode_print() for putting us on a           * and insert that at the place selected earlier.
          * subsequent line.  
          */           */
         sv = p->newln;  
         pnode_printmopen(p);  
         if (isop)  
                 fputs("Op", stdout);  
         else if (sv)  
                 fputs("No", stdout);  
   
           if (match == NULL) {
                   if ((match = calloc(1, sizeof(*match))) == NULL) {
                           perror(NULL);
                           exit(1);
                   }
                   match->node = NODE_SECTION;
                   match->spc = 1;
                   match->parent = n;
                   TAILQ_INIT(&match->childq);
                   TAILQ_INIT(&match->attrq);
                   if ((nc = pnode_alloc(match)) == NULL) {
                           perror(NULL);
                           exit(1);
                   }
                   nc->node = NODE_TITLE;
                   nc->spc = 1;
                   if ((nc = pnode_alloc(nc)) == NULL) {
                           perror(NULL);
                           exit(1);
                   }
                   nc->node = NODE_TEXT;
                   if ((nc->b = strdup("AUTHORS")) == NULL) {
                           perror(NULL);
                           exit(1);
                   }
                   nc->spc = 1;
                   if (later == NULL)
                           TAILQ_INSERT_TAIL(&n->childq, match, child);
                   else
                           TAILQ_INSERT_BEFORE(later, match, child);
           }
   
         /*          /*
          * Keep on printing text separated by the vertical bar as long           * Dump the stuff excised at the beginning
          * as we're within the same origin node as the group.           * into this AUTHORS section.
          * This is kind of a nightmare.  
          * Eh, DocBook...  
          * FIXME: if there's a "Fl", we don't cut off the leading "-"  
          * like we do in pnode_print().  
          */           */
         TAILQ_FOREACH(pp, &pn->childq, child) {  
                 pnode_print(p, pp);          if (info != NULL)
                 np = TAILQ_NEXT(pp, child);                  TAILQ_INSERT_TAIL(&match->childq, info, child);
                 while (NULL != np) {          if (meta != NULL)
                         if (pp->node != np->node)                  TAILQ_INSERT_TAIL(&match->childq, meta, child);
   }
   
   /*
    * We can have multiple <term> elements within a <varlistentry>, which
    * we should comma-separate as list headers.
    */
   static void
   pnode_printvarlistentry(struct format *f, struct pnode *n)
   {
           struct pnode    *nc, *nn;
           int              first = 1;
   
           macro_open(f, "It");
           f->parastate = PARA_HAVE;
           f->flags |= FMT_IMPL;
           TAILQ_FOREACH_SAFE(nc, &n->childq, child, nn) {
                   if (nc->node != NODE_TERM && nc->node != NODE_GLOSSTERM)
                           continue;
                   if (first == 0) {
                           switch (f->linestate) {
                           case LINE_NEW:
                                 break;                                  break;
                         fputs(" |", stdout);                          case LINE_TEXT:
                         pnode_printmacrolinepart(p, np);                                  print_text(f, ",", 0);
                         pp = np;                                  break;
                         np = TAILQ_NEXT(np, child);                          case LINE_MACRO:
                                   macro_addarg(f, ",", 0);
                                   break;
                           }
                 }                  }
                   f->parastate = PARA_HAVE;
                   pnode_print(f, nc);
                   pnode_unlink(nc);
                   first = 0;
         }          }
           macro_close(f);
         pnode_printmclose(p, sv);          f->parastate = PARA_HAVE;
           while ((nc = TAILQ_FIRST(&n->childq)) != NULL) {
                   pnode_print(f, nc);
                   pnode_unlink(nc);
           }
           macro_close(f);
           f->parastate = PARA_HAVE;
 }  }
   
 static void  static void
 pnode_printprologue(struct parse *p, struct pnode *pn)  pnode_printtitle(struct format *f, struct pnode *n)
 {  {
         struct pnode    *pp;          struct pnode    *nc, *nn;
   
         pp = NULL == p->root ? NULL :          TAILQ_FOREACH_SAFE(nc, &n->childq, child, nn) {
                 pnode_findfirst(p->root, NODE_REFMETA);                  if (nc->node == NODE_TITLE) {
                           if (f->parastate == PARA_MID)
         if (NULL != pp) {                                  f->parastate = PARA_WANT;
                 pnode_printrefmeta(p, pp);                          macro_nodeline(f, "Sy", nc, 0);
                 pnode_unlink(pp);                          pnode_unlink(nc);
         } else {                  }
                 puts(".\\\" Supplying bogus prologue...");  
                 puts(".Dd $Mdocdate" "$");  
                 puts(".Dt UNKNOWN 1");  
                 puts(".Os");  
         }          }
 }  }
   
 static void  static void
 pnode_printvarlistentry(struct parse *p, struct pnode *pn)  pnode_printrow(struct format *f, struct pnode *n)
 {  {
         struct pnode    *pp;          struct pnode    *nc;
   
         assert(p->newln);          macro_line(f, "Bl -dash -compact");
         TAILQ_FOREACH(pp, &pn->childq, child)          TAILQ_FOREACH(nc, &n->childq, child) {
                 if (NODE_TERM == pp->node) {                  macro_line(f, "It");
                         fputs(".It", stdout);                  pnode_print(f, nc);
                         p->newln = 0;          }
                         pnode_print(p, pp);          macro_line(f, "El");
                         pnode_unlink(pp);          pnode_unlink(n);
                         pnode_printmclose(p, 1);  
                         return;  
                 }  
   
         puts(".It");  
         p->newln = 1;  
 }  }
   
 static void  static void
 pnode_printrow(struct parse *p, struct pnode *pn)  pnode_printtgroup1(struct format *f, struct pnode *n)
 {  {
         struct pnode    *pp;          struct pnode    *nc;
   
         puts(".Bl -dash -compact");          macro_line(f, "Bl -bullet -compact");
           while ((nc = pnode_findfirst(n, NODE_ENTRY)) != NULL) {
         TAILQ_FOREACH(pp, &pn->childq, child) {                  macro_line(f, "It");
                 assert(p->newln);                  f->parastate = PARA_HAVE;
                 puts(".It");                  pnode_print(f, nc);
                 pnode_print(p, pp);                  f->parastate = PARA_HAVE;
                 pnode_printmclose(p, 1);                  pnode_unlink(nc);
         }          }
         assert(p->newln);          macro_line(f, "El");
         puts(".El");          pnode_unlinksub(n);
 }  }
   
 static void  static void
 pnode_printtable(struct parse *p, struct pnode *pn)  pnode_printtgroup2(struct format *f, struct pnode *n)
 {  {
         struct pnode    *pp;          struct pnode    *nr, *ne;
   
         assert(p->newln);          f->parastate = PARA_HAVE;
         TAILQ_FOREACH(pp, &pn->childq, child)          macro_line(f, "Bl -tag -width Ds");
                 if (NODE_TITLE == pp->node) {          while ((nr = pnode_findfirst(n, NODE_ROW)) != NULL) {
                         puts(".Pp");                  if ((ne = pnode_findfirst(n, NODE_ENTRY)) == NULL)
                         pnode_print(p, pp);                          break;
                         pnode_unlink(pp);                  macro_open(f, "It");
                 }                  f->flags |= FMT_IMPL;
         assert(p->newln);                  f->parastate = PARA_HAVE;
         puts(".Bl -ohang");                  pnode_print(f, ne);
         while (NULL != (pp = pnode_findfirst(pn, NODE_ROW))) {                  macro_close(f);
                 puts(".It Table Row");                  pnode_unlink(ne);
                 pnode_printrow(p, pp);                  f->parastate = PARA_HAVE;
                 pnode_printmclose(p, 1);                  pnode_print(f, nr);
                 pnode_unlink(pp);                  f->parastate = PARA_HAVE;
                   pnode_unlink(nr);
         }          }
         assert(p->newln);          macro_line(f, "El");
         puts(".El");          pnode_unlinksub(n);
 }  }
   
 static void  static void
 pnode_printlist(struct parse *p, struct pnode *pn)  pnode_printtgroup(struct format *f, struct pnode *n)
 {  {
         struct pnode    *pp;          struct pnode    *nc;
   
         assert(p->newln);          switch (atoi(pnode_getattr_raw(n, ATTRKEY_COLS, "0"))) {
         TAILQ_FOREACH(pp, &pn->childq, child)          case 1:
                 if (NODE_TITLE == pp->node) {                  pnode_printtgroup1(f, n);
                         puts(".Pp");                  return;
                         pnode_print(p, pp);          case 2:
                         pnode_unlink(pp);                  pnode_printtgroup2(f, n);
                 }                  return;
         assert(p->newln);          default:
                   break;
           }
   
         if (NODE_ORDEREDLIST == pn->node)          f->parastate = PARA_HAVE;
                 puts(".Bl -enum");          macro_line(f, "Bl -ohang");
         else          while ((nc = pnode_findfirst(n, NODE_ROW)) != NULL) {
                 puts(".Bl -item");                  macro_line(f, "It Table Row");
                   pnode_printrow(f, nc);
         TAILQ_FOREACH(pp, &pn->childq, child) {  
                 assert(p->newln);  
                 puts(".It");  
                 pnode_print(p, pp);  
                 pnode_printmclose(p, 1);  
         }          }
         assert(p->newln);          macro_line(f, "El");
         puts(".El");          pnode_unlinksub(n);
 }  }
   
 static void  static void
 pnode_printvariablelist(struct parse *p, struct pnode *pn)  pnode_printlist(struct format *f, struct pnode *n)
 {  {
         struct pnode    *pp;          struct pnode    *nc;
   
         assert(p->newln);          pnode_printtitle(f, n);
         TAILQ_FOREACH(pp, &pn->childq, child)          f->parastate = PARA_HAVE;
                 if (NODE_TITLE == pp->node) {          macro_argline(f, "Bl",
                         puts(".Pp");              n->node == NODE_ORDEREDLIST ? "-enum" : "-bullet");
                         pnode_print(p, pp);          TAILQ_FOREACH(nc, &n->childq, child) {
                         pnode_unlink(pp);                  macro_line(f, "It");
                 }                  f->parastate = PARA_HAVE;
                   pnode_print(f, nc);
                   f->parastate = PARA_HAVE;
           }
           macro_line(f, "El");
           pnode_unlinksub(n);
   }
   
         assert(p->newln);  static void
         puts(".Bl -tag -width Ds");  pnode_printvariablelist(struct format *f, struct pnode *n)
         TAILQ_FOREACH(pp, &pn->childq, child)  {
                 if (NODE_VARLISTENTRY != pp->node) {          struct pnode    *nc;
                         assert(p->newln);  
                         fputs(".It", stdout);          pnode_printtitle(f, n);
                         pnode_printmacroline(p, pp);          f->parastate = PARA_HAVE;
                 } else {          macro_line(f, "Bl -tag -width Ds");
                         assert(p->newln);          TAILQ_FOREACH(nc, &n->childq, child) {
                         pnode_print(p, pp);                  if (nc->node == NODE_VARLISTENTRY)
                 }                          pnode_printvarlistentry(f, nc);
         assert(p->newln);                  else
         puts(".El");                          macro_nodeline(f, "It", nc, 0);
           }
           macro_line(f, "El");
           pnode_unlinksub(n);
 }  }
   
 /*  /*
Line 1017  pnode_printvariablelist(struct parse *p, struct pnode 
Line 1106  pnode_printvariablelist(struct parse *p, struct pnode 
  * whatever), don't print inline macros.   * whatever), don't print inline macros.
  */   */
 static void  static void
 pnode_print(struct parse *p, struct pnode *pn)  pnode_print(struct format *f, struct pnode *n)
 {  {
         struct pnode    *pp;          struct pnode    *nc, *nn;
         char            *cp;          int              was_impl;
         int              last, sv;  
   
         if (NULL == pn)          if (n == NULL)
                 return;                  return;
   
         sv = p->newln;          was_impl = f->flags & FMT_IMPL;
           if (n->spc)
                   f->flags &= ~FMT_NOSPC;
           else
                   f->flags |= FMT_NOSPC;
   
         switch (pn->node) {          switch (n->node) {
         case (NODE_APPLICATION):          case NODE_ARG:
                 pnode_printmopen(p);                  pnode_printarg(f, n);
                 fputs("Nm", stdout);  
                 break;                  break;
         case (NODE_ARG):          case NODE_AUTHOR:
                 pnode_printarg(p, pn);                  pnode_printauthor(f, n);
                 pnode_unlinksub(pn);  
                 break;                  break;
         case (NODE_CITEREFENTRY):          case NODE_AUTHORGROUP:
                 assert(p->newln);                  macro_line(f, "An -split");
                 pnode_printciterefentry(p, pn);  
                 pnode_unlinksub(pn);  
                 break;                  break;
         case (NODE_CODE):          case NODE_BLOCKQUOTE:
                 pnode_printmopen(p);                  f->parastate = PARA_HAVE;
                 fputs("Li", stdout);                  macro_line(f, "Bd -ragged -offset indent");
                   f->parastate = PARA_HAVE;
                 break;                  break;
         case (NODE_COMMAND):          case NODE_CITEREFENTRY:
                 pnode_printmopen(p);                  pnode_printciterefentry(f, n);
                 fputs("Nm", stdout);  
                 break;                  break;
         case (NODE_EMPHASIS):          case NODE_CITETITLE:
                 pnode_printmopen(p);                  macro_open(f, "%T");
                 fputs("Em", stdout);  
                 break;                  break;
         case (NODE_ENVAR):          case NODE_COMMAND:
                 pnode_printmopen(p);                  macro_open(f, "Nm");
                 fputs("Ev", stdout);  
                 break;                  break;
         case (NODE_FILENAME):          case NODE_CONSTANT:
                 pnode_printmopen(p);                  macro_open(f, "Dv");
                 fputs("Pa", stdout);  
                 break;                  break;
         case (NODE_FUNCTION):          case NODE_COPYRIGHT:
                 pnode_printmopen(p);                  print_text(f, "Copyright", ARG_SPACE);
                 fputs("Fn", stdout);                  fputs(" \\(co", stdout);
                 break;                  break;
         case (NODE_FUNCPROTOTYPE):          case NODE_EDITOR:
                 assert(p->newln);                  print_text(f, "editor:", ARG_SPACE);
                 pnode_printfuncprototype(p, pn);                  pnode_printauthor(f, n);
                 pnode_unlinksub(pn);  
                 break;                  break;
         case (NODE_FUNCSYNOPSISINFO):          case NODE_EMAIL:
                 pnode_printmopen(p);                  if (was_impl)
                 fputs("Fd", stdout);                          macro_open(f, "Ao Mt");
                   else {
                           macro_open(f, "Aq Mt");
                           f->flags |= FMT_IMPL;
                   }
                 break;                  break;
         case (NODE_ITEMIZEDLIST):          case NODE_EMPHASIS:
                 assert(p->newln);          case NODE_FIRSTTERM:
                 pnode_printlist(p, pn);          case NODE_GLOSSTERM:
                 pnode_unlinksub(pn);                  if ((nc = TAILQ_FIRST(&n->childq)) != NULL &&
                       pnode_class(nc->node) < CLASS_LINE)
                           macro_open(f, "Em");
                   if (n->node == NODE_GLOSSTERM)
                           f->parastate = PARA_HAVE;
                 break;                  break;
         case (NODE_GROUP):          case NODE_ENVAR:
                 pnode_printgroup(p, pn);                  macro_open(f, "Ev");
                 pnode_unlinksub(pn);  
                 break;                  break;
         case (NODE_LITERAL):          case NODE_ERRORNAME:
                 pnode_printmopen(p);                  macro_open(f, "Er");
                 fputs("Li", stdout);  
                 break;                  break;
         case (NODE_OPTION):          case NODE_FILENAME:
                 pnode_printmopen(p);                  macro_open(f, "Pa");
                 fputs("Fl", stdout);  
                 break;                  break;
         case (NODE_ORDEREDLIST):          case NODE_FOOTNOTE:
                 assert(p->newln);                  macro_line(f, "Bo");
                 pnode_printlist(p, pn);                  f->parastate = PARA_HAVE;
                 pnode_unlinksub(pn);  
                 break;                  break;
         case (NODE_PARA):          case NODE_FUNCTION:
                 assert(p->newln);                  macro_open(f, "Fn");
                 if (NULL != pn->parent &&  
                         NODE_LISTITEM == pn->parent->node)  
                         break;  
                 puts(".Pp");  
                 break;                  break;
         case (NODE_PARAMETER):          case NODE_FUNCPROTOTYPE:
                 /* Suppress non-text children... */                  pnode_printfuncprototype(f, n);
                 pnode_printmopen(p);  
                 fputs("Fa \"", stdout);  
                 pnode_printmacrolinepart(p, pn);  
                 puts("\"");  
                 pnode_unlinksub(pn);  
                 break;                  break;
         case (NODE_PROGRAMLISTING):          case NODE_FUNCSYNOPSISINFO:
                   macro_open(f, "Fd");
                   break;
           case NODE_IMAGEDATA:
                   pnode_printimagedata(f, n);
                   break;
           case NODE_INFORMALEQUATION:
                   f->parastate = PARA_HAVE;
                   macro_line(f, "Bd -ragged -offset indent");
                   f->parastate = PARA_HAVE;
                 /* FALLTHROUGH */                  /* FALLTHROUGH */
         case (NODE_SCREEN):          case NODE_INLINEEQUATION:
                 assert(p->newln);                  macro_line(f, "EQ");
                 puts(".Bd -literal");  
                 break;                  break;
         case (NODE_REFENTRYINFO):          case NODE_ITEMIZEDLIST:
                 /* Suppress. */                  pnode_printlist(f, n);
                 pnode_unlinksub(pn);  
                 break;                  break;
         case (NODE_REFMETA):          case NODE_GROUP:
                 abort();                  pnode_printgroup(f, n);
                 break;                  break;
         case (NODE_REFNAME):          case NODE_KEYSYM:
                 /* Suppress non-text children... */          case NODE_PRODUCTNAME:
                 pnode_printmopen(p);                  macro_open(f, "Sy");
                 fputs("Nm", stdout);  
                 p->newln = 0;  
                 pnode_printmacrolinepart(p, pn);  
                 pnode_unlinksub(pn);  
                 break;                  break;
         case (NODE_REFNAMEDIV):          case NODE_LINK:
                 assert(p->newln);                  pnode_printlink(f, n);
                 puts(".Sh NAME");  
                 break;                  break;
         case (NODE_REFPURPOSE):          case NODE_LITERAL:
                 assert(p->newln);                  if (n->parent != NULL && n->parent->node == NODE_QUOTE)
                 pnode_printmopen(p);                          macro_open(f, "Li");
                 fputs("Nd", stdout);                  else if (was_impl)
                           macro_open(f, "So Li");
                   else {
                           macro_open(f, "Ql");
                           f->flags |= FMT_IMPL;
                   }
                 break;                  break;
         case (NODE_REFSYNOPSISDIV):          case NODE_LITERALLAYOUT:
                 assert(p->newln);                  macro_close(f);
                 pnode_printrefsynopsisdiv(p, pn);                  f->parastate = PARA_HAVE;
                 puts(".Sh SYNOPSIS");                  macro_argline(f, "Bd", pnode_getattr(n, ATTRKEY_CLASS) ==
                       ATTRVAL_MONOSPACED ? "-literal" : "-unfilled");
                   f->parastate = PARA_HAVE;
                 break;                  break;
         case (NODE_REFSECT1):          case NODE_MARKUP:
                 /* FALLTHROUGH */                  macro_open(f, "Ic");
         case (NODE_REFSECT2):  
                 assert(p->newln);  
                 pnode_printrefsect(p, pn);  
                 break;                  break;
         case (NODE_REPLACEABLE):          case NODE_MML_MFENCED:
                 pnode_printmopen(p);                  pnode_printmathfenced(f, n);
                 fputs("Ar", stdout);  
                 break;                  break;
         case (NODE_SBR):          case NODE_MML_MROW:
                 assert(p->newln);          case NODE_MML_MI:
                 puts(".br");          case NODE_MML_MN:
           case NODE_MML_MO:
                   if (TAILQ_EMPTY(&n->childq))
                           break;
                   fputs(" { ", stdout);
                 break;                  break;
         case (NODE_STRUCTNAME):          case NODE_MML_MFRAC:
                 pnode_printmopen(p);          case NODE_MML_MSUB:
                 fputs("Vt", stdout);          case NODE_MML_MSUP:
                   pnode_printmath(f, n);
                 break;                  break;
         case (NODE_TABLE):          case NODE_OLINK:
                 assert(p->newln);                  pnode_printolink(f, n);
                 pnode_printtable(p, pn);  
                 pnode_unlinksub(pn);  
                 break;                  break;
         case (NODE_TEXT):          case NODE_OPTION:
                 if (0 == p->newln)                  if ((nc = TAILQ_FIRST(&n->childq)) != NULL &&
                         putchar(' ');                      pnode_class(nc->node) < CLASS_LINE)
                 bufclear(p);                          macro_open(f, "Fl");
                 bufappend(p, pn);                  break;
                 /*          case NODE_ORDEREDLIST:
                  * Output all characters, squeezing out whitespace                  pnode_printlist(f, n);
                  * between newlines.                  break;
                  * XXX: all whitespace, including tabs (?).          case NODE_PARA:
                  * Remember to escape control characters and escapes.                  if (f->parastate == PARA_MID)
                  */                          f->parastate = PARA_WANT;
                 assert(p->bsz);                  break;
                 cp = p->b;          case NODE_PARAMDEF:
                 /*          case NODE_PARAMETER:
                  * There's often a superfluous "-" in its <option> tags                  /* More often, these appear inside NODE_FUNCPROTOTYPE. */
                  * before the actual flags themselves.                  macro_open(f, "Fa");
                  * "Fl" does this for us, so remove it.                  macro_addnode(f, n, ARG_SPACE | ARG_SINGLE);
                  */                  pnode_unlinksub(n);
                 if (NULL != pn->parent &&                  break;
                         NODE_OPTION == pn->parent->node &&          case NODE_QUOTE:
                         '-' == *cp)                  if ((nc = TAILQ_FIRST(&n->childq)) != NULL &&
                         cp++;                      nc->node == NODE_FILENAME &&
                 for (last = '\n'; '\0' != *cp; ) {                      TAILQ_NEXT(nc, child) == NULL) {
                         if ('\n' == last) {                          if (n->spc)
                                 /* Consume all whitespace. */                                  nc->spc = 1;
                                 if (isspace((int)*cp)) {                  } else if (was_impl)
                                         while (isspace((int)*cp))                          macro_open(f, "Do");
                                                 cp++;                  else {
                                         continue;                          macro_open(f, "Dq");
                                 } else if ('\'' == *cp || '.' == *cp)                          f->flags |= FMT_IMPL;
                                         fputs("\\&", stdout);  
                         }  
                         putchar(last = *cp++);  
                         /* If we're a character escape, escape us. */  
                         if ('\\' == last)  
                                 putchar('e');  
                 }                  }
                 p->newln = 0;  
                 break;                  break;
         case (NODE_USERINPUT):          case NODE_PROGRAMLISTING:
                 pnode_printmopen(p);          case NODE_SCREEN:
                 fputs("Li", stdout);          case NODE_SYNOPSIS:
                   f->parastate = PARA_HAVE;
                   macro_line(f, "Bd -literal");
                   f->parastate = PARA_HAVE;
                 break;                  break;
         case (NODE_VARIABLELIST):          case NODE_SYSTEMITEM:
                 assert(p->newln);                  pnode_printsystemitem(f, n);
                 pnode_printvariablelist(p, pn);  
                 pnode_unlinksub(pn);  
                 break;                  break;
         case (NODE_VARLISTENTRY):          case NODE_REFENTRY:
                 assert(p->newln);                  pnode_printrefentry(f, n);
                 pnode_printvarlistentry(p, pn);  
                 break;                  break;
         case (NODE_VARNAME):          case NODE_REFNAME:
                 pnode_printmopen(p);                  /* More often, these appear inside NODE_REFNAMEDIV. */
                 fputs("Va", stdout);                  macro_open(f, "Nm");
                 break;                  break;
           case NODE_REFNAMEDIV:
                   pnode_printrefnamediv(f, n);
                   break;
           case NODE_REFPURPOSE:
                   macro_open(f, "Nd");
                   break;
           case NODE_REFSYNOPSISDIV:
                   pnode_printrefsynopsisdiv(f, n);
                   break;
           case NODE_PREFACE:
           case NODE_SECTION:
           case NODE_SIMPLESECT:
           case NODE_APPENDIX:
           case NODE_LEGALNOTICE:
           case NODE_NOTE:
           case NODE_TIP:
           case NODE_CAUTION:
           case NODE_WARNING:
                   pnode_printsection(f, n);
                   break;
           case NODE_REPLACEABLE:
                   macro_open(f, "Ar");
                   break;
           case NODE_SBR:
                   if (f->parastate == PARA_MID)
                           macro_line(f, "br");
                   break;
           case NODE_SUBSCRIPT:
                   if (f->linestate == LINE_MACRO)
                           macro_addarg(f, "_", 0);
                   else
                           print_text(f, "_", 0);
                   if ((nc = TAILQ_FIRST(&n->childq)) != NULL)
                           nc->spc = 0;
                   break;
           case NODE_SUPERSCRIPT:
                   fputs("\\(ha", stdout);
                   if ((nc = TAILQ_FIRST(&n->childq)) != NULL)
                           nc->spc = 0;
                   break;
           case NODE_TEXT:
           case NODE_ESCAPE:
                   pnode_printtext(f, n);
                   break;
           case NODE_TGROUP:
                   pnode_printtgroup(f, n);
                   break;
           case NODE_TITLE:
           case NODE_SUBTITLE:
                   if (f->parastate == PARA_MID)
                           f->parastate = PARA_WANT;
                   macro_nodeline(f, "Sy", n, 0);
                   pnode_unlinksub(n);
                   break;
           case NODE_TYPE:
                   macro_open(f, "Vt");
                   break;
           case NODE_VARIABLELIST:
                   pnode_printvariablelist(f, n);
                   break;
           case NODE_VARNAME:
                   macro_open(f, "Va");
                   break;
           case NODE_VOID:
                   print_text(f, "void", ARG_SPACE);
                   break;
           case NODE_XREF:
                   pnode_printxref(f, n);
                   break;
         default:          default:
                 break;                  break;
         }          }
   
         TAILQ_FOREACH(pp, &pn->childq, child)          TAILQ_FOREACH(nc, &n->childq, child)
                 pnode_print(p, pp);                  pnode_print(f, nc);
   
         switch (pn->node) {          switch (n->node) {
         case (NODE_APPLICATION):          case NODE_EMAIL:
         case (NODE_ARG):                  if (was_impl) {
         case (NODE_CODE):                          f->flags &= ~FMT_NOSPC;
         case (NODE_COMMAND):                          macro_open(f, "Ac");
         case (NODE_EMPHASIS):                  } else
         case (NODE_ENVAR):                          f->flags &= ~FMT_IMPL;
         case (NODE_FILENAME):  
         case (NODE_FUNCTION):  
         case (NODE_FUNCSYNOPSISINFO):  
         case (NODE_LITERAL):  
         case (NODE_OPTION):  
         case (NODE_PARAMETER):  
         case (NODE_REPLACEABLE):  
         case (NODE_REFPURPOSE):  
         case (NODE_STRUCTNAME):  
         case (NODE_TEXT):  
         case (NODE_USERINPUT):  
         case (NODE_VARNAME):  
                 pnode_printmclose(p, sv);  
                 break;                  break;
         case (NODE_REFNAME):          case NODE_ESCAPE:
                 /*          case NODE_TERM:
                  * If we're in the NAME macro and we have multiple          case NODE_TEXT:
                  * <refname> macros in sequence, then print out a                  /* Accept more arguments to the previous macro. */
                  * trailing comma before the newline.                  return;
                  */          case NODE_FOOTNOTE:
                 if (NULL != pn->parent &&                  f->parastate = PARA_HAVE;
                         NODE_REFNAMEDIV == pn->parent->node &&                  macro_line(f, "Bc");
                         NULL != TAILQ_NEXT(pn, child) &&  
                         NODE_REFNAME == TAILQ_NEXT(pn, child)->node)  
                         fputs(" ,", stdout);  
                 pnode_printmclose(p, sv);  
                 break;                  break;
         case (NODE_PROGRAMLISTING):          case NODE_GLOSSTERM:
                 /* FALLTHROUGH */                  f->parastate = PARA_HAVE;
         case (NODE_SCREEN):  
                 assert(p->newln);  
                 puts(".Ed");  
                 p->newln = 1;  
                 break;                  break;
           case NODE_INFORMALEQUATION:
                   macro_line(f, "EN");
                   macro_line(f, "Ed");
                   break;
           case NODE_INLINEEQUATION:
                   macro_line(f, "EN");
                   break;
           case NODE_LITERAL:
                   if (n->parent != NULL && n->parent->node == NODE_QUOTE)
                           /* nothing */;
                   else if (was_impl) {
                           f->flags &= ~FMT_NOSPC;
                           macro_open(f, "Sc");
                   } else
                           f->flags &= ~FMT_IMPL;
                   break;
           case NODE_MEMBER:
                   if ((nn = TAILQ_NEXT(n, child)) != NULL &&
                       nn->node != NODE_MEMBER)
                           nn = NULL;
                   switch (f->linestate) {
                   case LINE_TEXT:
                           if (nn != NULL)
                                   print_text(f, ",", 0);
                           break;
                   case LINE_MACRO:
                           if (nn != NULL)
                                   macro_addarg(f, ",", ARG_SPACE);
                           macro_close(f);
                           break;
                   case LINE_NEW:
                           break;
                   }
                   break;
           case NODE_MML_MROW:
           case NODE_MML_MI:
           case NODE_MML_MN:
           case NODE_MML_MO:
                   if (TAILQ_EMPTY(&n->childq))
                           break;
                   fputs(" } ", stdout);
                   break;
           case NODE_PARA:
                   if (f->parastate == PARA_MID)
                           f->parastate = PARA_WANT;
                   break;
           case NODE_QUOTE:
                   if ((nc = TAILQ_FIRST(&n->childq)) != NULL &&
                       nc->node == NODE_FILENAME &&
                       TAILQ_NEXT(nc, child) == NULL)
                           /* nothing */;
                   else if (was_impl) {
                           f->flags &= ~FMT_NOSPC;
                           macro_open(f, "Dc");
                   } else
                           f->flags &= ~FMT_IMPL;
                   break;
           case NODE_PREFACE:
           case NODE_SECTION:
           case NODE_APPENDIX:
           case NODE_LEGALNOTICE:
           case NODE_NOTE:
           case NODE_TIP:
           case NODE_CAUTION:
           case NODE_WARNING:
                   f->level--;
                   break;
           case NODE_BLOCKQUOTE:
           case NODE_LITERALLAYOUT:
           case NODE_PROGRAMLISTING:
           case NODE_SCREEN:
           case NODE_SYNOPSIS:
                   f->parastate = PARA_HAVE;
                   macro_line(f, "Ed");
                   break;
           case NODE_TITLE:
           case NODE_SUBTITLE:
                   f->parastate = PARA_WANT;
                   break;
         default:          default:
                 break;                  break;
         }          }
           f->flags &= ~FMT_ARG;
 }  }
   
 /*  void
  * Loop around the read buffer until we've drained it of all data.  ptree_print_mdoc(struct ptree *tree)
  * Invoke the parser context with each buffer fill.  
  */  
 static int  
 readfile(XML_Parser xp, int fd,  
         char *b, size_t bsz, const char *fn)  
 {  {
         struct parse     p;          struct format    formatter;
         int              rc;  
         ssize_t          ssz;  
   
         memset(&p, 0, sizeof(struct parse));          formatter.level = 0;
           formatter.linestate = LINE_NEW;
         p.b = malloc(p.bsz = p.mbsz = 1024);          formatter.parastate = PARA_HAVE;
         p.fname = fn;          pnode_printprologue(&formatter, tree->root);
         p.xml = xp;          pnode_print(&formatter, tree->root);
           if (formatter.linestate != LINE_NEW)
         XML_SetCharacterDataHandler(xp, xml_char);                  putchar('\n');
         XML_SetElementHandler(xp, xml_elem_start, xml_elem_end);  
         XML_SetUserData(xp, &p);  
   
         while ((ssz = read(fd, b, bsz)) >= 0) {  
                 if (0 == (rc = XML_Parse(xp, b, ssz, 0 == ssz)))  
                         fprintf(stderr, "%s: %s\n", fn,  
                                 XML_ErrorString  
                                 (XML_GetErrorCode(xp)));  
                 else if ( ! p.stop && ssz > 0)  
                         continue;  
                 /*  
                  * Exit when we've read all or errors have occured  
                  * during the parse sequence.  
                  */  
                 p.newln = 1;  
                 pnode_printprologue(&p, p.root);  
                 pnode_print(&p, p.root);  
                 pnode_free(p.root);  
                 free(p.b);  
                 return(0 != rc && ! p.stop);  
         }  
   
         /* Read error has occured. */  
         perror(fn);  
         pnode_free(p.root);  
         free(p.b);  
         return(0);  
 }  
   
 int  
 main(int argc, char *argv[])  
 {  
         XML_Parser       xp;  
         const char      *fname;  
         char            *buf;  
         int              fd, rc;  
   
         fname = "-";  
         xp = NULL;  
         buf = NULL;  
         rc = 0;  
   
         if (-1 != getopt(argc, argv, ""))  
                 return(EXIT_FAILURE);  
   
         argc -= optind;  
         argv += optind;  
   
         if (argc > 1)  
                 return(EXIT_FAILURE);  
         else if (argc > 0)  
                 fname = argv[0];  
   
         /* Read from stdin or a file. */  
         fd = 0 == strcmp(fname, "-") ?  
                 STDIN_FILENO : open(fname, O_RDONLY, 0);  
   
         /*  
          * Open file for reading.  
          * Allocate a read buffer.  
          * Create the parser context.  
          * Dive directly into the parse.  
          */  
         if (-1 == fd)  
                 perror(fname);  
         else if (NULL == (buf = malloc(4096)))  
                 perror(NULL);  
         else if (NULL == (xp = XML_ParserCreate(NULL)))  
                 perror(NULL);  
         else if ( ! readfile(xp, fd, buf, 4096, fname))  
                 rc = 1;  
   
         XML_ParserFree(xp);  
         free(buf);  
         if (STDIN_FILENO != fd)  
                 close(fd);  
         return(rc ? EXIT_SUCCESS : EXIT_FAILURE);  
 }  }

Legend:
Removed from v.1.27  
changed lines
  Added in v.1.132

CVSweb