code:
/* html.h -- declarations for html-related utilities.
   $Id: html.h,v 1.12 2011-04-06 21:20:24 gray Exp $

   Copyright (C) 1999, 2000, 2002, 2004, 2007, 2008
   Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#ifndef HTML_H
#define HTML_H

/* A stack of font tags.  */
typedef struct hstack
{
  struct hstack *next;
  char *tag;
  char *attribs;
} HSTACK;

/* Nonzero if we have output a title, from @titlefont or @settitle.  */
extern int html_title_written;

/* Filename to which to write list of index entries, and stream for them */
extern char *internal_links_filename;
extern FILE *internal_links_stream;

/* Perform the <head> output.  */
extern void html_output_head (void);

/* Escape &<>.  */
extern char *escape_string (char *);

/* Open or close TAG according to START_OR_END.  */
extern void insert_html_tag (int start_or_end, char *tag);

/* Output HTML <link> to NODE, plus extra ATTRIBUTES.  */
extern void add_link (char *nodename, char *attributes);

/* Escape URL-special characters.  */
extern char *escaped_anchor_name (const char *name);
extern void add_escaped_anchor_name (char *name, int old);

/* See html.c.  */
extern void add_anchor_name (char *nodename, int href);
extern void add_url_name (char *nodename, int href);
extern void add_nodename_to_filename (char *nodename, int href);
extern char *nodename_to_filename (char *nodename);
extern int rollback_empty_tag (char *tag);

extern void insert_html_tag_with_attribute (int start_or_end, char *tag, char *format, ...) TEXINFO_PRINTFLIKE(3,4);

#endif /* !HTML_H */


code:
/* index.c -- indexing for Texinfo.
   $Id: index.c,v 1.27 2008-05-19 18:26:48 karl Exp $

   Copyright (C) 1998, 1999, 2002, 2003, 2004, 2007, 2008
   Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#include "system.h"
#include "mbswidth.h"
#include "files.h"
#include "footnote.h"
#include "html.h"
#include "index.h"
#include "lang.h"
#include "macro.h"
#include "sectioning.h"
#include "toc.h"
#include "xml.h"

/* Nonzero means that we are in the middle of printing an index. */
int printing_index = 0;

/* The number of defined indices. */
int defined_indices = 0;

/* This is the order of the index.  */
int index_counter = 0;

/* Stuff for defining commands on the fly. */
COMMAND **user_command_array = NULL;
int user_command_array_len = 0;

INDEX_ALIST **name_index_alist = NULL;

/* An array of pointers.  Each one is for a different index.  The @synindex
   command changes which array slot is pointed to by a given index.  */
static INDEX_ELT **the_indices = NULL;

/* How to compare index entries for sorting.  May be set to strcoll.  */
static int (*index_compare_fn) (const char *a, const char *b) = mbscasecmp;

/* Find which element in the known list of indices has this name.
   Returns -1 if NAME isn't found. */
static int
find_index_offset (char *name)
{
  int i;
  for (i = 0; i < defined_indices; i++)
    if (name_index_alist[i] && STREQ (name, name_index_alist[i]->name))
      return i;
  return -1;
}

/* Return a pointer to the entry of (name . index) for this name.
   Return NULL if the index doesn't exist. */
static INDEX_ALIST *
find_index (char *name)
{
  int offset = find_index_offset (name);
  if (offset > -1)
    return name_index_alist[offset];
  else
    return NULL;
}

/* User-defined commands, which happens only from user-defined indexes.
   Used to initialize the builtin indices, too.  */
static void
define_user_command (char *name, COMMAND_FUNCTION (*proc), int needs_braces_p)
{
  int slot = user_command_array_len;
  user_command_array_len++;

  if (!user_command_array)
    user_command_array = xmalloc (1 * sizeof (COMMAND *));

  user_command_array = xrealloc (user_command_array,
                            (1 + user_command_array_len) * sizeof (COMMAND *));

  user_command_array[slot] = xmalloc (sizeof (COMMAND));
  user_command_array[slot]->name = xstrdup (name);
  user_command_array[slot]->proc = proc;
  user_command_array[slot]->argument_in_braces = needs_braces_p;
}

/* Please release me, let me go... */
static void
free_index (INDEX_ELT *index)
{
  INDEX_ELT *temp;

  while ((temp = index))
    {
      free (temp->entry);
      free (temp->entry_text);
      /* Do not free the node, because we already freed the tag table,
         which freed all the node names.  */
      /* free (temp->node); */
      index = index->next;
      free (temp);
    }
}

/* Flush an index by name.  This will delete the list of entries that
   would be written by a @printindex command for this index. */
static void
undefindex (char *name)
{
  int i;
  int which = find_index_offset (name);

  /* The index might have already been freed if this was the target of
     an @synindex.  */
  if (which < 0 || !name_index_alist[which])
    return;

  i = name_index_alist[which]->read_index;

  free_index (the_indices[i]);
  the_indices[i] = NULL;

  free (name_index_alist[which]->name);
  free (name_index_alist[which]);
  name_index_alist[which] = NULL;
}

/* Add the arguments to the current index command to the index NAME.  */
static void
index_add_arg (char *name)
{
  int which;
  char *index_entry;
  INDEX_ALIST *tem;

  tem = find_index (name);

  which = tem ? tem->write_index : -1;

  if (macro_expansion_output_stream && !executing_string)
    append_to_expansion_output (input_text_offset + 1);

  get_rest_of_line (0, &index_entry);
  ignore_blank_line ();

  if (macro_expansion_output_stream && !executing_string)
    {
      char *index_line = xmalloc (strlen (index_entry) + 2);
      sprintf (index_line, "%s\n", index_entry);
      me_execute_string_keep_state (index_line, NULL);
      free (index_line);
    }

  if (which < 0)
    {
      line_error (_("Unknown index `%s'"), name);
      free (index_entry);
    }
  else
    {
      INDEX_ELT *new = xmalloc (sizeof (INDEX_ELT));

      index_counter++;

      /* Get output line number updated before doing anything.  */
      if (!html && !xml)
        flush_output ();

      new->next = the_indices[which];
      new->entry = NULL;
      new->entry_text = index_entry;
      /* Since footnotes are handled at the very end of the document,
         node name in the non-split HTML outputs always show the last
         node.  We artificially make it ``Footnotes''.  */
      if (html && !splitting && already_outputting_pending_notes)
        new->node = xstrdup (_("Footnotes"));
      else
        new->node = current_node ? current_node : xstrdup ("");
      if (!html && !xml && no_headers)
        {
          new->section = current_sectioning_number ();
          if (strlen (new->section) == 0)
            new->section_name = current_sectioning_name ();
          else
            new->section_name = "";
        }
      else
        {
          new->section = NULL;
          new->section_name = NULL;
        }
      new->code = tem->code;
      new->defining_line = line_number - 1;
      new->output_line = no_headers ? output_line_number : node_line_number;
      /* We need to make a copy since input_filename may point to
         something that goes away, for example, inside a macro.
         (see the findexerr test).  */
      new->defining_file = xstrdup (input_filename);

      if (html && splitting)
        {
          if (current_output_filename && *current_output_filename)
            new->output_file = filename_part (current_output_filename);
          else
            new->output_file = xstrdup ("");
        }
      else
        new->output_file = NULL;

      new->entry_number = index_counter;
      the_indices[which] = new;

#if 0
      /* The index breaks if there are colons in the entry.
         -- This is true, but it's too painful to force changing index
         entries to use `colon', and too confusing for users.  The real
         fix is to change Info support to support arbitrary characters
         in node names, and we're not ready to do that.  --karl,
         19mar02.  */
      if (strchr (new->entry_text, ':'))
        warning (_("Info cannot handle `:' in index entry `%s'"),
                 new->entry_text);
#endif

      if (html)
        {
          /* Anchor.  */
          int removed_empty_elt = 0;

          /* We must put the anchor outside the
 and
 blocks.  */
          if (rollback_empty_tag ("dl"))
            removed_empty_elt = 1;
          else if (rollback_empty_tag ("ul"))
            removed_empty_elt = 2;

          add_word ("", index_counter);

          if (removed_empty_elt == 1)
            add_html_block_elt_args ("\n
");
          else if (removed_empty_elt == 2)
            add_html_block_elt_args ("\n
");
        }
    }

  if (xml)
    xml_insert_indexterm (index_entry, name);
}

/* The function which user defined index commands call. */
static void
gen_index (void)
{
  char *name = xstrdup (command);
  if (strlen (name) >= strlen ("index"))
    name[strlen (name) - strlen ("index")] = 0;
  index_add_arg (name);
  free (name);
}

/* Define an index known as NAME.  We assign the slot number.
   If CODE is nonzero, make this a code index. */
static void
defindex (char *name, int code)
{
  int i, slot;

  /* If it already exists, flush it. */
  undefindex (name);

  /* Try to find an empty slot. */
  slot = -1;
  for (i = 0; i < defined_indices; i++)
    if (!name_index_alist[i])
      {
        slot = i;
        break;
      }

  if (slot < 0)
    { /* No such luck.  Make space for another index. */
      slot = defined_indices;
      defined_indices++;

      name_index_alist = (INDEX_ALIST **)
        xrealloc (name_index_alist, (1 + defined_indices)
                                    * sizeof (INDEX_ALIST *));
      the_indices = (INDEX_ELT **)
        xrealloc (the_indices, (1 + defined_indices) * sizeof (INDEX_ELT *));
    }

  /* We have a slot.  Start assigning. */
  name_index_alist[slot] = xmalloc (sizeof (INDEX_ALIST));
  name_index_alist[slot]->name = xstrdup (name);
  name_index_alist[slot]->read_index = slot;
  name_index_alist[slot]->write_index = slot;
  name_index_alist[slot]->code = code;

  the_indices[slot] = NULL;
}

/* Define an index NAME, implicitly @code if CODE is nonzero.  */
static void
top_defindex (char *name, int code)
{
  char *temp;

  temp = xmalloc (1 + strlen (name) + strlen ("index"));
  sprintf (temp, "%sindex", name);
  define_user_command (temp, gen_index, 0);
  defindex (name, code);
  free (temp);
}

/* Set up predefined indices.  */
void
init_indices (void)
{
  int i;

  /* Create the default data structures. */

  /* Initialize data space. */
  if (!the_indices)
    {
      the_indices = xmalloc ((1 + defined_indices) * sizeof (INDEX_ELT *));
      the_indices[defined_indices] = NULL;

      name_index_alist = xmalloc ((1 + defined_indices)
                                  * sizeof (INDEX_ALIST *));
      name_index_alist[defined_indices] = NULL;
    }

  /* If there were existing indices, get rid of them now. */
  for (i = 0; i < defined_indices; i++)
    {
      if (name_index_alist[i])
        { /* Suppose we're called with two input files, and the first
             does a @synindex pg cp.  Then, when we get here to start
             the second file, the "pg" element won't get freed by
             undefindex (because it's pointing to "cp").  So free it
             here; otherwise, when we try to define the pg index again
             just below, it will still point to cp.  */
          undefindex (name_index_alist[i]->name);

          /* undefindex sets all this to null in some cases.  */
          if (name_index_alist[i])
            {
              free (name_index_alist[i]->name);
              free (name_index_alist[i]);
              name_index_alist[i] = NULL;
            }
        }
    }

  /* Add the default indices. */
  top_defindex ("cp", 0);           /* cp is the only non-code index.  */
  top_defindex ("fn", 1);
  top_defindex ("ky", 1);
  top_defindex ("pg", 1);
  top_defindex ("tp", 1);
  top_defindex ("vr", 1);
}

/* Given an index name, return the offset in the_indices of this index,
   or -1 if there is no such index. */
static int
translate_index (char *name)
{
  INDEX_ALIST *which = find_index (name);

  if (which)
    return which->read_index;
  else
    return -1;
}

/* Return the index list which belongs to NAME. */
INDEX_ELT *
index_list (char *name)
{
  int which = translate_index (name);
  if (which < 0)
    return (INDEX_ELT *) -1;
  else
    return the_indices[which];
}

/* Define a new index command.  Arg is name of index. */
static void
gen_defindex (int code)
{
  char *name;
  get_rest_of_line (0, &name);

  if (find_index (name))
    {
      line_error (_("Index `%s' already exists"), name);
    }
  else
    {
      char *temp = xmalloc (strlen (name) + sizeof ("index"));
      sprintf (temp, "%sindex", name);
      define_user_command (temp, gen_index, 0);
      defindex (name, code);
      free (temp);
    }

  free (name);
}

void
cm_defindex (void)
{
  gen_defindex (0);
}

void
cm_defcodeindex (void)
{
  gen_defindex (1);
}

/* Expects 2 args, on the same line.  Both are index abbreviations.
   Make the first one be a synonym for the second one, i.e. make the
   first one have the same index as the second one. */
void
cm_synindex (void)
{
  int source, target;
  char *abbrev1, *abbrev2;

  skip_whitespace ();
  get_until_in_line (0, " ", &abbrev1);
  target = find_index_offset (abbrev1);
  skip_whitespace ();
  get_until_in_line (0, " ", &abbrev2);
  source = find_index_offset (abbrev2);
  if (source < 0 || target < 0)
    {
      line_error (_("Unknown index `%s' and/or `%s' in @synindex"),
                  abbrev1, abbrev2);
    }
  else
    {
      if (xml && !docbook)
        xml_synindex (abbrev1, abbrev2);
      else
        name_index_alist[target]->write_index
          = name_index_alist[source]->write_index;
    }

  free (abbrev1);
  free (abbrev2);
}

void
cm_pindex (void)                    /* Pinhead index. */
{
  index_add_arg ("pg");
}

void
cm_vindex (void)                    /* Variable index. */
{
  index_add_arg ("vr");
}

void
cm_kindex (void)                    /* Key index. */
{
  index_add_arg ("ky");
}

void
cm_cindex (void)                    /* Concept index. */
{
  index_add_arg ("cp");
}

void
cm_findex (void)                    /* Function index. */
{
  index_add_arg ("fn");
}

void
cm_tindex (void)                    /* Data Type index. */
{
  index_add_arg ("tp");
}

static int
index_element_compare (const void *element1, const void *element2)
{
  INDEX_ELT **elt1 = (INDEX_ELT **) element1;
  INDEX_ELT **elt2 = (INDEX_ELT **) element2;

  return index_compare_fn ((*elt1)->entry, (*elt2)->entry);
}

/* Force all index entries to be unique. */
static void
make_index_entries_unique (INDEX_ELT **array, int count)
{
  int i, j;
  INDEX_ELT **copy;
  int counter = 1;

  copy = xmalloc ((1 + count) * sizeof (INDEX_ELT *));

  for (i = 0, j = 0; i < count; i++)
    {
      if (i == (count - 1)
          || array[i]->node != array[i + 1]->node
          || !STREQ (array[i]->entry, array[i + 1]->entry))
        copy[j++] = array[i];
      else
        {
          free (array[i]->entry);
          free (array[i]->entry_text);
          free (array[i]);
        }
    }
  copy[j] = NULL;

  /* Now COPY contains only unique entries.  Duplicated entries in the
     original array have been freed.  Replace the current array with
     the copy, fixing the NEXT pointers. */
  for (i = 0; copy[i]; i++)
    {
      copy[i]->next = copy[i + 1];

      /* Fix entry names which are the same.  They point to different nodes,
         so we make the entry name unique. */
      if (copy[i+1]
          && STREQ (copy[i]->entry, copy[i + 1]->entry)
          && !html)
        {
          char *new_entry_name;

          new_entry_name = xmalloc (10 + strlen (copy[i]->entry));
          sprintf (new_entry_name, "%s <%d>", copy[i]->entry, counter);
          free (copy[i]->entry);
          copy[i]->entry = new_entry_name;
          counter++;
        }
      else
        counter = 1;

      array[i] = copy[i];
    }
  array[i] = NULL;

  /* Free the storage used only by COPY. */
  free (copy);
}

/* Sort the index passed in INDEX, returning an array of pointers to
   elements.  The array is terminated with a NULL pointer.  */

static INDEX_ELT **
sort_index (INDEX_ELT *index)
{
  INDEX_ELT **array;
  INDEX_ELT *temp;
  int count = 0;
  int save_line_number = line_number;
  char *save_input_filename = input_filename;
  int save_html = html;

  /* Pretend we are in non-HTML mode, for the purpose of getting the
     expanded index entry that lacks any markup and other HTML escape
     characters which could produce a wrong sort order.  */
  /* fixme: html: this still causes some markup, such as non-ASCII
     characters @AE{} etc., to sort incorrectly.  */
  html = 0;

  for (temp = index, count = 0; temp; temp = temp->next, count++)
    ;
  /* We have the length, now we can allocate an array. */
  array = xmalloc ((count + 1) * sizeof (INDEX_ELT *));

  for (temp = index, count = 0; temp; temp = temp->next, count++)
    {
      /* Allocate new memory for the return array, since parts of the
         original INDEX get freed.  Otherwise, if the document calls
         @printindex twice on the same index, with duplicate entries,
         we'll have garbage the second time.  There are cleaner ways to
         deal, but this will suffice for now.  */
      array[count] = xmalloc (sizeof (INDEX_ELT));
      *(array[count]) = *(temp);  /* struct assignment, hope it's ok */

      /* Adjust next pointers to use the new memory.  */
      if (count > 0)
        array[count-1]->next = array[count];

      /* Set line number and input filename to the source line for this
         index entry, as this expansion finds any errors.  */
      line_number = array[count]->defining_line;
      input_filename = array[count]->defining_file;

      /* If this particular entry should be printed as a "code" index,
         then expand it as @code{entry}, i.e., as in fixed-width font.  */
      array[count]->entry = expansion (temp->entry_text, array[count]->code);
    }
  array[count] = NULL;    /* terminate the array. */

  line_number = save_line_number;
  input_filename = save_input_filename;
  html = save_html;

#ifdef HAVE_STRCOLL
  /* This is not perfect.  We should set (then restore) the locale to the
     documentlanguage, so strcoll operates according to the document's
     locale, not the user's.  For now, I'm just going to assume that
     those few new documents which use @documentlanguage will be
     processed in the appropriate locale.  In any case, don't use
     strcoll in the C (aka POSIX) locale, that is the ASCII ordering.  */
  if (language_code != en)
    {
      char *lang_env = getenv ("LANG");
      if (lang_env && !STREQ (lang_env, "C") && !STREQ (lang_env, "POSIX"))
        index_compare_fn = strcoll;
    }
#endif /* HAVE_STRCOLL */

  /* Sort the array. */
  qsort (array, count, sizeof (INDEX_ELT *), index_element_compare);

  /* Remove duplicate entries.  */
  make_index_entries_unique (array, count);

  /* Replace the original index with the sorted one, in case the
     document wants to print it again.  If the index wasn't empty.  */
  if (index)
    *index = **array;

  return array;
}

/* Return the number of times that the byte CH occurs in the LEN bytes
   starting at STR.  Multibyte strings are not taken into account, which
   is incorrect, but we need this for @tie; see more comments below.  */

static int
count_strn_chars (const char *str, int len, int ch)
{
  int count = 0;
  int i;

  for (i = 0; i < len; i++)
    if (str[i] == ch)
      count++;

  return count;
}

static void
insert_index_output_line_no (int line_number, int output_line_number_len)
{
  int last_column, out_line_no_width;
  int str_size = output_line_number_len + strlen (_("(line )"))
    + sizeof (NULL);
  char *out_line_no_str = (char *) xmalloc (str_size + 1);

  /* Do not translate ``(line NNN)'' below for !no_headers case (Info output),
     because it's something like the ``* Menu'' strings.  For plaintext output
     it should be translated though.  */
  sprintf (out_line_no_str,
      no_headers ? _("(line %*d)") : "(line %*d)",
      output_line_number_len, line_number);

  {
    int i = output_paragraph_offset;
    while (0  fill_column)
    {
      insert ('\n');
      last_column = 0;
    }

  while (last_column + out_line_no_width < fill_column)
    {
      insert (' ');
      last_column++;
    }

  insert_string (out_line_no_str);
  insert ('\n');

  free (out_line_no_str);
}

/* Takes one arg, a short name of an index to print.
   Outputs a menu of the sorted elements of the index. */
void
cm_printindex (void)
{
  char *index_name;
  get_rest_of_line (0, &index_name);

  /* get_rest_of_line increments the line number by one,
     so to make warnings/errors point to the correct line,
     we decrement the line_number again.  */
  if (!handling_delayed_writes)
    line_number--;

  if (xml)
    {
      xml_insert_element (PRINTINDEX, START);
      if (! docbook)
	insert_string (index_name);
      xml_insert_element (PRINTINDEX, END);
    }
  else if (!handling_delayed_writes)
    {
      int command_len = sizeof ("@ ") + strlen (command) + strlen (index_name);
      char *index_command = xmalloc (command_len + 1);

      close_paragraph ();
      sprintf (index_command, "@%s %s", command, index_name);
      register_delayed_write (index_command);
      free (index_command);
    }
  else
    {
      int item;
      INDEX_ELT *index;
      INDEX_ELT *last_index = 0;
      INDEX_ELT **array;
      unsigned line_length;
      char *line;
      int saved_inhibit_paragraph_indentation = inhibit_paragraph_indentation;
      int saved_filling_enabled = filling_enabled;
      int saved_line_number = line_number;
      char *saved_input_filename = input_filename;
      unsigned output_line_number_len;
      FILE *saved_output_stream = output_stream;

      index = index_list (index_name);
      if (index == (INDEX_ELT *)-1)
        {
          line_error (_("Unknown index `%s' in @printindex"), index_name);
          free (index_name);
          return;
        }

      /* Do this before sorting, so execute_string is in the good environment */
      if (xml && docbook)
        xml_begin_index ();

      /* Do this before sorting, so execute_string in index_element_compare
         will give the same results as when we actually print.  */
      printing_index = 1;
      filling_enabled = 0;
      inhibit_paragraph_indentation = 1;
      xml_sort_index = 1;
      array = sort_index (index);
      xml_sort_index = 0;
      close_paragraph ();
      if (html)
        add_html_block_elt_args ("
",
                                 index_name);
      else if (!no_headers && !docbook)
        { /* Info.  Add magic cookie for info readers (to treat this
             menu differently), and the usual start-of-menu.  */
          add_char ('\0');
          add_word ("\010[index");
          add_char ('\0');
          add_word ("\010]\n");
          add_word ("* Menu:\n\n");
        }

      me_inhibit_expansion++;

      /* This will probably be enough.  */
      line_length = 100;
      line = xmalloc (line_length);

      {
        char *max_output_line_number = (char *) xmalloc (25 * sizeof (char));

        if (no_headers)
          sprintf (max_output_line_number, "%d", output_line_number);
        else
          {
            INDEX_ELT *tmp_entry = index;
            unsigned tmp = 0;
            for (tmp_entry = index; tmp_entry; tmp_entry = tmp_entry->next)
              tmp = tmp_entry->output_line > tmp ? tmp_entry->output_line : tmp;
            sprintf (max_output_line_number, "%d", tmp);
          }

        output_line_number_len = strlen (max_output_line_number);
        free (max_output_line_number);
      }

      for (item = 0; (index = array[item]); item++)
        {
          /* A pathological document might have an index entry outside of any
             node.  Don't crash; try using the section name instead.  */
          char *index_node = index->node;

          line_number = index->defining_line;
          input_filename = index->defining_file;

          if ((!index_node || !*index_node) && html)
            index_node = toc_find_section_of_node (index_node);

          if (!index_node || !*index_node)
            {
              line_error (_("Entry for index `%s' outside of any node"),
                          index_name);
              if (html || !no_headers)
                index_node = (char *) _("(outside of any node)");
            }

          if (html)
            {
              /* For HTML, we need to expand and HTML-escape the
                 original entry text, at the same time.  Consider
                 @cindex J@"urgen.  We want Jüurgen.  We can't
                 expand and then escape since we'll end up with
                 J&uuml;rgen.  We can't escape and then expand
                 because then `expansion' will see J@"urgen, and
                 @"urgen is not a command.  */
              char *html_entry =
                maybe_escaped_expansion (index->entry_text, index->code, 1);

              add_html_block_elt_args ("\n
output_file) ? index->output_file : "");
              add_escaped_anchor_name (index->entry_text, 0);
              add_word_args ("-%d\">%s: ", index->entry_number,
                  html_entry);
              free (html_entry);

              add_word ("node && *index->node)
                {
                  /* Ensure any non-macros in the node name are expanded.  */
                  char *expanded_index;

                  in_fixed_width_font++;
                  expanded_index = expansion (index_node, 0);
                  in_fixed_width_font--;
                  add_anchor_name (expanded_index, 1);
		  expanded_index = escape_string (expanded_index);
                  add_word_args ("\">%s", expanded_index);
                  free (expanded_index);
                }
              else if (STREQ (index_node, _("(outside of any node)")))
                {
                  add_anchor_name (index_node, 1);
                  add_word_args ("\">%s", index_node);
                }
              else
                /* If we use the section instead of the (missing) node, then
                   index_node already includes all we need except the #.  */
                add_word_args ("#%s", index_node);

              add_html_block_elt ("
");

              if (internal_links_stream)
                {
                  char *escaped = escaped_anchor_name (index->entry_text);
                  fprintf (internal_links_stream, "%s#index-%s-%d\t%s\t%s\n",
                      (splitting && index->output_file) ? index->output_file : "",
                      escaped, index->entry_number, index_name,
                      index->entry_text);
                  free (escaped);
                }
            }
          else if (xml && docbook)
            {
	      /* Let DocBook processor generate the index. */
            }
          else
            {
#define MIN_ENTRY_COLUMNS 37
	      /* Make sure there is enough space even if index->entry has zero
		 width. */
              unsigned new_length = strlen (index->entry) + MIN_ENTRY_COLUMNS;

              if (new_length < 50) /* minimum length used below */
                new_length = 50;
              new_length += strlen (index_node) + 7; /* * : .\n\0 */

              if (new_length > line_length)
                {
                  line_length = new_length;
                  line = xrealloc (line, line_length);
                }
              /* Print the entry, nicely formatted.  We've already
                 expanded any commands in index->entry, including any
                 implicit @code.  Thus, can't call execute_string, since
                 @@ has turned into @. */
              if (!no_headers)
                {
                  int nspaces;
		  int width = mbswidth (index->entry, 0);

		  /* Unfortunately, our @tie{} / @w{ } magic is an
                     unprintable character, and so mbswidth doesn't
                     count it.  If that byte value occurs in a multibyte
                     string, we'd lose, but at least it's only a
                     question of minor formatting, not functionality.  */
		  width += count_strn_chars (index->entry,
                                    strlen (index->entry), NON_BREAKING_SPACE);

		  nspaces = -(strlen (index->entry)
                              + (MIN_ENTRY_COLUMNS - width));
                  sprintf (line, "* %*s  ",
                           width < MIN_ENTRY_COLUMNS ? nspaces : 0,
			   index->entry);
                  line[2 + strlen (index->entry)] = ':';
                  insert_string (line);
                  /* Expand any non-macros in the node name.  */
                  in_fixed_width_font++;
                  execute_string ("%s. ", index_node);
                  insert_index_output_line_no (index->output_line,
                      output_line_number_len);
                  in_fixed_width_font--;
                }
              else
                {
                  /* With --no-headers, the @node lines are gone, so
                     there's little sense in referring to them in the
                     index.  Instead, output the number or name of the
                     section that corresponds to that node.  */
                  sprintf (line, "%-*s ", number_sections ? 46 : 1,
                           index->entry);
                  line[strlen (index->entry)] = ':';
                  insert_string (line);

                  if (strlen (index->section) > 0)
                    { /* We got your number.  */
                      insert_string ((char *) _("See "));
                      insert_string (index->section);
                    }
                  else
                    { /* Sigh, index in an @unnumbered. :-\  */
                      insert_string ("\n          ");
                      insert_string ((char *) _("See "));
                      insert_string ("``");
                      insert_string (expansion (index->section_name, 0));
                      insert_string ("''");
                    }

                  insert_string (". ");
                  insert_index_output_line_no (index->output_line,
                      output_line_number_len);
                }
            }

          /* Prevent `output_paragraph' from growing to the size of the
             whole index.  */
          flush_output ();
          last_index = index;
        }

      free (line);

      me_inhibit_expansion--;
      printing_index = 0;

      close_single_paragraph ();
      filling_enabled = saved_filling_enabled;
      inhibit_paragraph_indentation = saved_inhibit_paragraph_indentation;
      input_filename = saved_input_filename;
      line_number = saved_line_number;

      if (html)
        add_html_block_elt ("
");
      else if (xml && docbook)
        xml_end_index ();
    }

  free (index_name);
  /* Re-increment the line number, because get_rest_of_line
     left us looking at the next line after the command.  */
  line_number++;
}

repo_name: mthl/texinfo

license: mit


code:
/* index.h -- declarations for index.c.
   $Id: index.h,v 1.6 2007-09-26 20:53:40 karl Exp $

   Copyright (C) 1998, 1999, 2007 Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#ifndef INDEX_H
#define INDEX_H

#include "makeinfo.h"
#include "cmds.h"

extern int printing_index;
extern int defined_indices;
extern int index_counter;

/* User commands are only new indices.  (Macros are handled separately.)  */
extern COMMAND **user_command_array;
extern int user_command_array_len;

/* An index element... */
typedef struct index_elt
{
  struct index_elt *next;
  char *entry;                  /* The index entry itself, after expansion. */
  char *entry_text;             /* The original, non-expanded entry text. */
  char *node;                   /* The node from whence it came. */
  char *section;                /* Current section number we are in, */
  char *section_name;           /* ... and its title.  */
  int code;                     /* Nonzero means add `@code{...}' when
                                   printing this element. */
  int defining_line;            /* Line number where this entry was written. */
  int output_line;              /* And line number where it is in the output. */
  char *defining_file;          /* Source file for defining_line. */
  char *output_file;            /* Output file for output_line. */
  int entry_number;             /* Entry number.  */
} INDEX_ELT;

/* A list of short-names for each index.
   There are two indices into the the_indices array.
   * read_index is the index that points to the list of index
     entries that we will find if we ask for the list of entries for
     this name.
   * write_index is the index that points to the list of index entries
     that we will add new entries to.

   Initially, read_index and write_index are the same, but the
   @syncodeindex and @synindex commands can change the list we add
   entries to.

   For example, after the commands
     @cindex foo
     @defindex ii
     @synindex cp ii
     @cindex bar

   the cp index will contain the entry `foo', and the new ii
   index will contain the entry `bar'.  This is consistent with the
   way texinfo.tex handles the same situation.

   In addition, for each index, it is remembered whether that index is
   a code index or not.  Code indices have @code{} inserted around the
   first word when they are printed with printindex. */
typedef struct
{
  char *name;
  int read_index;   /* index entries for `name' */
  int write_index;  /* store index entries here, @synindex can change it */
  int code;
} INDEX_ALIST;

extern INDEX_ALIST **name_index_alist;

/* Initialize all indices.  */
extern void init_indices (void);

INDEX_ELT *index_list (char *name);

#endif /* !INDEX_H */


code:
/* insertion.c -- insertions for Texinfo.
   $Id: insertion.c,v 1.72 2009-01-01 07:24:57 olegkat Exp $

   Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
   2007, 2008 Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#include "system.h"
#include "cmds.h"
#include "defun.h"
#include "float.h"
#include "html.h"
#include "insertion.h"
#include "macro.h"
#include "makeinfo.h"
#include "multi.h"
#include "xml.h"

/* Must match list in insertion.h.  */
static char *insertion_type_names[] =
{
  "cartouche", "copying", "defcv", "deffn", "defivar", "defmac",
  "defmethod", "defop", "defopt", "defspec", "deftp", "deftypecv",
  "deftypefn", "deftypefun", "deftypeivar", "deftypemethod",
  "deftypeop", "deftypevar", "deftypevr", "defun", "defvar", "defvr",
  "detailmenu", "direntry", "display", "documentdescription",
  "enumerate", "example", "float", "flushleft", "flushright", "format",
  "ftable", "group", "ifclear", "ifdocbook", "ifhtml", "ifinfo",
  "ifnotdocbook", "ifnothtml", "ifnotinfo", "ifnotplaintext", "ifnottex",
  "ifnotxml", "ifplaintext", "ifset", "iftex", "ifxml", "itemize", "lisp",
  "menu", "multitable", "quotation", "raggedcenter", "raggedleft",
  "raggedright", "rawdocbook", "rawhtml", "rawtex",
  "rawxml", "smalldisplay", "smallexample", "smallformat", "smalllisp",
  "verbatim", "table", "tex", "vtable", "titlepage", "bad_type"
};

/* All nested environments.  */
INSERTION_ELT *insertion_stack = NULL;

/* How deeply we're nested.  */
int insertion_level = 0;

/* Set to 1 if we've processed (commentary) text in a @menu that
   wasn't part of a menu item.  */
int had_menu_commentary;

/* How to examine menu lines.  */
int in_detailmenu = 0;

/* Whether to examine menu lines.  */
int in_menu = 0;

/* Set to 1 if
 is written in normal context.
   Used for menu and itemize. */
int in_paragraph = 0;

/* Since an insertion is already in the stack before we reach the switch
   statement, we cannot use is_in_insertion_of_type (always returns true.) Also
   making it return the level found, and comparing it with the current level is
   no use, due to the order of stack.  */
static int float_active = 0;

/* Unsetting escape_html blindly causes text inside @html/etc. to be escaped if
   used within a rmacro.  */
static int raw_output_block = 0;

/* Non-zero if a
 element has a
 element in it.  We use this when
   deciding whether to insert a
 or not.  */
static int html_deflist_has_term = 0;

const char default_item_function[] = { "@bullet" };

void
init_insertion_stack (void)
{
  insertion_stack = NULL;
}

/* Return the type of the current insertion. */
static enum insertion_type
current_insertion_type (void)
{
  return insertion_level ? insertion_stack->insertion : bad_type;
}

/* Return the string which is the function to wrap around items, or NULL
   if we're not in an environment where @item is ok.  */
static char *
current_item_function (void)
{
  int done = 0;
  INSERTION_ELT *elt = insertion_stack;

  /* Skip down through the stack until we find an insertion with an
     itemize function defined, i.e., skip conditionals, @cartouche, etc.  */
  while (!done && elt)
    {
      switch (elt->insertion)
        {
        /* This list should match the one in cm_item.  */
        case ifclear:
        case ifhtml:
        case ifinfo:
        case ifnothtml:
        case ifnotinfo:
        case ifnotplaintext:
        case ifnottex:
	case ifnotxml:
        case ifplaintext:
        case ifset:
        case iftex:
	case ifxml:
        case rawdocbook:
        case rawhtml:
        case rawxml:
        case rawtex:
        case tex:
        case cartouche:
          elt = elt->next;
          break;

        default:
          done = 1;
        }
    }

  /* item_function usually gets assigned the empty string.  */
  return done && (*elt->item_function) ? elt->item_function : NULL;
}

/* Parse the item marker function off the input.  If result is just "@",
   change it to "@ ", since "@" by itself is not a command.  This makes
   "@ ", "@\t", and "@\n" all the same, but their default meanings are
   the same anyway, and let's not worry about supporting redefining them.  */
char *
get_item_function (void)
{
  char *item_function;
  char *item_loc;

  get_rest_of_line (0, &item_function);

  /* If the document erroneously says
       @itemize @bullet @item foobar
     it's nicer to give an error up front than repeat `@bullet expected
     braces' until we get a segmentation fault.  */
  item_loc = strstr (item_function, "@item");
  if (item_loc)
    {
      line_error (_("@item not allowed in argument to @itemize"));
      *item_loc = 0;
    }

  /* If we hit the end of text in get_rest_of_line, backing up
     input pointer will cause the last character of the last line
     be pushed back onto the input, which is wrong.  */
  if (input_text_offset < input_text_length)
    backup_input_pointer ();

  if (STREQ (item_function, "@"))
    {
      free (item_function);
      item_function = xstrdup ("@ ");
    }

  return item_function;
}

 /* Push the state of the current insertion on the stack. */
static void
push_insertion (enum insertion_type type, char *item_function)
{
  INSERTION_ELT *new = xmalloc (sizeof (INSERTION_ELT));

  new->item_function = item_function;
  new->filling_enabled = filling_enabled;
  new->indented_fill = indented_fill;
  new->insertion = type;
  new->line_number = line_number;
  new->filename = xstrdup (input_filename);
  new->inhibited = inhibit_paragraph_indentation;
  new->in_fixed_width_font = in_fixed_width_font;
  new->next = insertion_stack;
  insertion_stack = new;
  insertion_level++;
}

 /* Pop the value on top of the insertion stack into the
    global variables. */
void
pop_insertion (void)
{
  INSERTION_ELT *temp = insertion_stack;

  if (temp == NULL)
    return;

  in_fixed_width_font = temp->in_fixed_width_font;
  inhibit_paragraph_indentation = temp->inhibited;
  filling_enabled = temp->filling_enabled;
  indented_fill = temp->indented_fill;
  if (temp->item_function == default_item_function)
    temp->item_function = NULL;
  else
    free_and_clear (&(temp->item_function));
  free_and_clear (&(temp->filename));
  insertion_stack = insertion_stack->next;
  free (temp);
  insertion_level--;
}

 /* Return a pointer to the print name of this
    enumerated type. */
static const char *
insertion_type_pname (enum insertion_type type)
{
  if ((int) type < (int) bad_type)
  {
    if (type == rawdocbook)
      return "docbook";
    else if (type == rawhtml)
      return "html";
    else if (type == rawxml)
      return "xml";
    else if (type == rawtex)
      return "tex";
    else
      return insertion_type_names[(int) type];
  }
  else
    return _("Broken-Type in insertion_type_pname");
}

/* Return the insertion_type associated with NAME.
   If the type is not one of the known ones, return BAD_TYPE. */
enum insertion_type
find_type_from_name (char *name)
{
  int index = 0;
  while (index < (int) bad_type)
    {
      if (STREQ (name, insertion_type_names[index]))
        return (enum insertion_type) index;
      if (index == rawdocbook && STREQ (name, "docbook"))
        return rawdocbook;
      if (index == rawhtml && STREQ (name, "html"))
        return rawhtml;
      if (index == rawxml && STREQ (name, "xml"))
        return rawxml;
      if (index == rawtex && STREQ (name, "tex"))
        return rawtex;
      index++;
    }
  return bad_type;
}

/* Simple function to query insertion_stack to see if we are inside a given
   insertion type. */
int
is_in_insertion_of_type (int type)
{
  INSERTION_ELT *temp = insertion_stack;

  if (!insertion_level)
    return 0;

  while (temp)
    {
      if (temp->insertion == type)
        return 1;
      temp = temp->next;
    }

  return 0;
}

static int
defun_insertion (enum insertion_type type)
{
  return 0
     || (type == defcv)
     || (type == deffn)
     || (type == defivar)
     || (type == defmac)
     || (type == defmethod)
     || (type == defop)
     || (type == defopt)
     || (type == defspec)
     || (type == deftp)
     || (type == deftypecv)
     || (type == deftypefn)
     || (type == deftypefun)
     || (type == deftypeivar)
     || (type == deftypemethod)
     || (type == deftypeop)
     || (type == deftypevar)
     || (type == deftypevr)
     || (type == defun)
     || (type == defvar)
     || (type == defvr)
  ;
}

/* MAX_NS is the maximum nesting level for enumerations.  I picked 100
   which seemed reasonable.  This doesn't control the number of items,
   just the number of nested lists. */
#define max_stack_depth 100
#define ENUM_DIGITS 1
#define ENUM_ALPHA  2
typedef struct {
  int enumtype;
  int enumval;
} DIGIT_ALPHA;

DIGIT_ALPHA enumstack[max_stack_depth];
int enumstack_offset = 0;
int current_enumval = 1;
int current_enumtype = ENUM_DIGITS;
char *enumeration_arg = NULL;

static void
start_enumerating (int at, int type)
{
  if ((enumstack_offset + 1) == max_stack_depth)
    {
      line_error (_("Enumeration stack overflow"));
      return;
    }
  enumstack[enumstack_offset].enumtype = current_enumtype;
  enumstack[enumstack_offset].enumval = current_enumval;
  enumstack_offset++;
  current_enumval = at;
  current_enumtype = type;
}

static void
stop_enumerating (void)
{
  --enumstack_offset;
  if (enumstack_offset < 0)
    enumstack_offset = 0;

  current_enumval = enumstack[enumstack_offset].enumval;
  current_enumtype = enumstack[enumstack_offset].enumtype;
}

/* Place a letter or digits into the output stream. */
static void
enumerate_item (void)
{
  char temp[10];

  if (current_enumtype == ENUM_ALPHA)
    {
      if (current_enumval == ('z' + 1) || current_enumval == ('Z' + 1))
        {
          current_enumval = ((current_enumval - 1) == 'z' ? 'a' : 'A');
          warning (_("lettering overflow, restarting at %c"), current_enumval);
        }
      sprintf (temp, "%c. ", current_enumval);
    }
  else
    sprintf (temp, "%d. ", current_enumval);

  indent (current_output_column () + (current_indent - strlen (temp)));
  add_word (temp);
  current_enumval++;
}

static void
enum_html (void)
{
  char type;
  int start;

  if (isdigit (*enumeration_arg))
    {
      type = '1';
      start = atoi (enumeration_arg);
    }
  else if (isupper (*enumeration_arg))
    {
      type = 'A';
      start = *enumeration_arg - 'A' + 1;
    }
  else
    {
      type = 'a';
      start = *enumeration_arg - 'a' + 1;
    }

  add_html_block_elt_args ("
\n", type, start);
}

/* Conditionally parse based on the current command name. */
void
command_name_condition (void)
{
  char *discarder = xmalloc (8 + strlen (command));

  sprintf (discarder, "\n%cend %s", COMMAND_PREFIX, command);
  discard_until (discarder);
  discard_until ("\n");

  free (discarder);
}

/* This is where the work for all the "insertion" style
   commands is done.  A huge switch statement handles the
   various setups, and generic code is on both sides. */
void
begin_insertion (enum insertion_type type)
{
  int no_discard = 0;

  if (defun_insertion (type))
    {
      push_insertion (type, xstrdup (""));
      no_discard++;
    }
  else
    {
      push_insertion (type, get_item_function ());
    }

  switch (type)
    {
    case menu:
      if (!no_headers)
        close_paragraph ();

      filling_enabled = no_indent = 0;
      inhibit_paragraph_indentation = 1;

      if (html)
        {
          had_menu_commentary = 1;
        }
      else if (!no_headers && !xml)
        add_word ("* Menu:\n");

      if (xml)
        xml_insert_element (MENU, START);
      else
        in_fixed_width_font++;

      next_menu_item_number = 1;
      in_menu++;
      no_discard++;
      break;

    case detailmenu:
      if (!in_menu)
        {
          if (!no_headers)
            close_paragraph ();

          filling_enabled = no_indent = 0;
          inhibit_paragraph_indentation = 1;

          no_discard++;
        }

      if (xml)
        {
          xml_insert_element (DETAILMENU, START);
          skip_whitespace_and_newlines ();
        }
      else
        in_fixed_width_font++;

      in_detailmenu++;
      break;

    case direntry:
      close_single_paragraph ();
      filling_enabled = no_indent = 0;
      inhibit_paragraph_indentation = 1;
      add_word ("START-INFO-DIR-ENTRY\n");

      /* The zsh manual, maybe others, wrongly indents the * line of the
         direntry in the source.  Ignore that whitespace.  */
      skip_whitespace_and_newlines ();
      no_discard++;
      break;

    case documentdescription:
      {
        char *desc;
        int start_of_end;
        int save_fixed_width;

        discard_until ("\n"); /* ignore the @documentdescription line */
        start_of_end = get_until ("\n@end documentdescription", &desc);
        save_fixed_width = in_fixed_width_font;

        in_fixed_width_font = 0;
        document_description = expansion (desc, 0);
        free (desc);

        in_fixed_width_font = save_fixed_width;
        input_text_offset = start_of_end; /* go back to the @end to match */
      }
      break;

    case copying:
        /* Save the copying text away for @insertcopying,
           typically used on the back of the @titlepage (for TeX) and
           the Top node (for info/html).  */
      if (input_text[input_text_offset] != '\n')
        discard_until ("\n"); /* ignore remainder of @copying line */

        input_text_offset = get_until ("\n@end copying", &copying_text);
        canon_white (copying_text);

      /* For info, output the copying text right away, so it will end up
         in the header of the Info file, before the first node, and thus
         get copied automatically to all the split files.  For xml, also
         output it right away since xml output is never split.
         For html, we output it specifically in html_output_head.
         For plain text, there's no way to hide it, so the author must
         use @insertcopying in the desired location.  */
      if (docbook)
	{
	  if (!xml_in_bookinfo)
	    {
	      xml_insert_element (BOOKINFO, START);
	      xml_in_bookinfo = 1;
	    }
          xml_insert_element (LEGALNOTICE, START);
	}

      if (!html && !no_headers)
        cm_insert_copying ();

      if (docbook)
        xml_insert_element (LEGALNOTICE, END);
      break;

    case quotation:
      /* @quotation does filling (@display doesn't).  */
      if (html)
        add_html_block_elt ("
\n");
      else
        {
          /* with close_single_paragraph, we get no blank line above
             within @copying.  */
          close_paragraph ();
          last_char_was_newline = no_indent = 0;
          indented_fill = filling_enabled = 1;
          inhibit_paragraph_indentation = 1;
          current_indent += default_indentation_increment;
        }
      if (xml)
        xml_insert_quotation (insertion_stack->item_function, START);
      else if (strlen(insertion_stack->item_function))
        execute_string ("@b{%s:} ", insertion_stack->item_function);
      break;

    case example:
    case smallexample:
    case lisp:
    case smalllisp:
      in_fixed_width_font++;
      /* fall through */

      /* Like @example but no fixed width font. */
    case display:
    case smalldisplay:
      /* Like @display but without indentation. */
    case smallformat:
    case format:
      close_single_paragraph ();
      inhibit_paragraph_indentation = 1;
      filling_enabled = 0;
      last_char_was_newline = 0;

      if (html)
        /* Kludge alert: if
 is followed by a newline, IE3,
           mozilla, maybe others render an extra blank line before the
           pre-formatted block.  So don't output a newline.  */
        add_html_block_elt_args ("
", command);

      if (type != format && type != smallformat)
        {
          current_indent += example_indentation_increment;
          if (html)
            {
              /* Since we didn't put \n after
, we need to insert
                 the indentation by hand.  */
              int i;
              for (i = current_indent; i > 0; i--)
                add_char (' ');
            }
        }
      break;

    case multitable:
      do_multitable ();
      break;

    case table:
    case ftable:
    case vtable:
    case itemize:
      close_single_paragraph ();
      current_indent += default_indentation_increment;
      filling_enabled = indented_fill = 1;
#if defined (INDENT_PARAGRAPHS_IN_TABLE)
      inhibit_paragraph_indentation = 0;
#else
      inhibit_paragraph_indentation = 1;
#endif /* !INDENT_PARAGRAPHS_IN_TABLE */

      /* Make things work for losers who forget the itemize syntax. */
      if (type == itemize)
        {
          if (!(*insertion_stack->item_function))
            {
              free (insertion_stack->item_function);
              insertion_stack->item_function = (char *) default_item_function;
            }
        }

      if (!*insertion_stack->item_function)
        {
          line_error (_("%s requires an argument: the formatter for %citem"),
                      insertion_type_pname (type), COMMAND_PREFIX);
        }

      if (html)
        {
          if (type == itemize)
            {
              add_html_block_elt ("
\n");
              in_paragraph = 0;
            }
          else
            { /* We are just starting, so this

                 has no
 children yet.  */
              html_deflist_has_term = 0;
              add_html_block_elt ("
\n");
            }
        }
      if (xml)
        xml_begin_table (type, insertion_stack->item_function);

      while (input_text[input_text_offset] == '\n'
          && input_text[input_text_offset+1] == '\n')
        {
          line_number++;
          input_text_offset++;
        }

      break;

    case enumerate:
      close_single_paragraph ();
      no_indent = 0;
#if defined (INDENT_PARAGRAPHS_IN_TABLE)
      inhibit_paragraph_indentation = 0;
#else
      inhibit_paragraph_indentation = 1;
#endif /* !INDENT_PARAGRAPHS_IN_TABLE */

      current_indent += default_indentation_increment;
      filling_enabled = indented_fill = 1;

      if (html)
        {
          enum_html ();
          in_paragraph = 0;
        }

      if (xml)
        xml_begin_enumerate (enumeration_arg);

      if (isdigit (*enumeration_arg))
        start_enumerating (atoi (enumeration_arg), ENUM_DIGITS);
      else
        start_enumerating (*enumeration_arg, ENUM_ALPHA);
      break;

      /* @group produces no output in info. */
    case group:
      /* Only close the paragraph if we are not inside of an
         @example-like environment. */
      if (xml)
        xml_insert_element (GROUP, START);
      else if (!insertion_stack->next
          || (insertion_stack->next->insertion != display
              && insertion_stack->next->insertion != smalldisplay
              && insertion_stack->next->insertion != example
              && insertion_stack->next->insertion != smallexample
              && insertion_stack->next->insertion != lisp
              && insertion_stack->next->insertion != smalllisp
              && insertion_stack->next->insertion != format
              && insertion_stack->next->insertion != smallformat
              && insertion_stack->next->insertion != flushleft
              && insertion_stack->next->insertion != flushright))
        close_single_paragraph ();
      break;

    case cartouche:
      if (html)
	add_html_block_elt ("

\n");
      if (in_menu)
        no_discard++;
      break;

    case floatenv:
      /* Cannot nest floats, so complain.  */
      if (float_active)
        {
          line_error (_("%cfloat environments cannot be nested"), COMMAND_PREFIX);
          pop_insertion ();
          break;
        }

      float_active++;

      { /* Collect data about this float.  */
        /* Example: @float [FLOATTYPE][,XREFLABEL][,POSITION] */
        char floattype[200] = "";
        char xreflabel[200] = "";
        char position[200]  = "";
        char *text;
        char *caption;
        char *shortcaption;
        int start_of_end;
        int save_line_number = line_number;
        int save_input_text_offset = input_text_offset;
        int i;

        if (strlen (insertion_stack->item_function) > 0)
          {
            int i = 0, t = 0, c = 0;
            while (insertion_stack->item_function[i])
              {
                if (insertion_stack->item_function[i] == ',')
                  {
                    switch (t)
                      {
                      case 0:
                        floattype[c] = '\0';
                        break;
                      case 1:
                        xreflabel[c] = '\0';
                        break;
                      case 2:
                        position[c] = '\0';
                        break;
                      }
                    c = 0;
                    t++;
                    i++;
                    continue;
                  }

                switch (t)
                  {
                  case 0:
                    floattype[c] = insertion_stack->item_function[i];
                    break;
                  case 1:
                    xreflabel[c] = insertion_stack->item_function[i];
                    break;
                  case 2:
                    position[c] = insertion_stack->item_function[i];
                    break;
                  }
                c++;
                i++;
              }
          }

        skip_whitespace_and_newlines ();

        start_of_end = get_until ("\n@end float", &text);

        /* Get also the @caption.  */
        i = search_forward_until_pos ("\n@caption{",
            save_input_text_offset, start_of_end);
        if (i > -1)
          {
            input_text_offset = i + sizeof ("\n@caption{") - 1;
            get_until_in_braces ("\n@end float", &caption);
            input_text_offset = save_input_text_offset;
          }
        else
          caption = "";

        /* ... and the @shortcaption.  */
        i = search_forward_until_pos ("\n@shortcaption{",
            save_input_text_offset, start_of_end);
        if (i > -1)
          {
            input_text_offset = i + sizeof ("\n@shortcaption{") - 1;
            get_until_in_braces ("\n@end float", &shortcaption);
            input_text_offset = save_input_text_offset;
          }
        else
          shortcaption = "";

        canon_white (xreflabel);
        canon_white (floattype);
        canon_white (position);
        canon_white (caption);
        canon_white (shortcaption);

        add_new_float (xstrdup (xreflabel),
            xstrdup (caption), xstrdup (shortcaption),
            xstrdup (floattype), xstrdup (position));

        /* Move to the start of the @float so the contents get processed as
           usual.  */
        input_text_offset = save_input_text_offset;
        line_number = save_line_number;
      }

      if (html)
        add_html_block_elt ("
\n");
      else if (docbook)
        xml_insert_element (FLOAT, START);
      else if (xml)
        {
          xml_insert_element_with_attribute (FLOAT, START,
              "name=\"%s\"", current_float_id ());

          xml_insert_element (FLOATTYPE, START);
          execute_string ("%s", current_float_type ());
          xml_insert_element (FLOATTYPE, END);

          xml_insert_element (FLOATPOS, START);
          execute_string ("%s", current_float_position ());
          xml_insert_element (FLOATPOS, END);
        }
      else
        { /* Info */
          close_single_paragraph ();
          inhibit_paragraph_indentation = 1;
        }

      /* Anchor now.  Note that XML documents get their
         anchors with <float name="anchor"> tag.  */
      if ((!xml || docbook) && strlen (current_float_id ()) > 0)
        execute_string ("@anchor{%s}", current_float_id ());

      break;

      /* Insertions that are no-ops in info, but do something in TeX. */
    case ifclear:
    case ifdocbook:
    case ifhtml:
    case ifinfo:
    case ifnotdocbook:
    case ifnothtml:
    case ifnotinfo:
    case ifnotplaintext:
    case ifnottex:
    case ifnotxml:
    case ifplaintext:
    case ifset:
    case iftex:
    case ifxml:
    case rawtex:
      if (in_menu)
        no_discard++;
      break;

    case rawdocbook:
    case rawhtml:
    case rawxml:
      raw_output_block++;

      if (raw_output_block > 0)
        {
          xml_no_para = 1;
          escape_html = 0;
          xml_keep_space++;
        }

      {
        /* Some deuglification for improved readability.  */
        extern int xml_in_para;
        if (xml && !xml_in_para && xml_indentation_increment > 0)
          add_char ('\n');
      }

      break;

    case defcv:
    case deffn:
    case defivar:
    case defmac:
    case defmethod:
    case defop:
    case defopt:
    case defspec:
    case deftp:
    case deftypecv:
    case deftypefn:
    case deftypefun:
    case deftypeivar:
    case deftypemethod:
    case deftypeop:
    case deftypevar:
    case deftypevr:
    case defun:
    case defvar:
    case defvr:
      inhibit_paragraph_indentation = 1;
      filling_enabled = indented_fill = 1;
      current_indent += default_indentation_increment;
      no_indent = 0;
      if (xml)
	xml_begin_definition ();
      break;

    case flushleft:
      close_single_paragraph ();
      inhibit_paragraph_indentation = 1;
      filling_enabled = indented_fill = no_indent = 0;
      if (html)
        add_html_block_elt ("
");
      break;

    case flushright:
      close_single_paragraph ();
      filling_enabled = indented_fill = no_indent = 0;
      inhibit_paragraph_indentation = 1;
      force_flush_right++;
      if (html)
        add_html_block_elt ("
");
      break;

    case raggedcenter:
      close_single_paragraph ();
      filling_enabled = indented_fill = 1;
      no_indent = inhibit_paragraph_indentation = 1;
      if (html)
        add_html_block_elt ("
");
      break;

    case raggedleft:
      close_single_paragraph ();
      filling_enabled = indented_fill = 1;
      no_indent = inhibit_paragraph_indentation = 1;
      if (html)
        add_html_block_elt ("
");
      break;

    case raggedright:
      close_single_paragraph ();
      filling_enabled = indented_fill = 1;
      no_indent = inhibit_paragraph_indentation = 0;
      if (html)
        add_html_block_elt ("
");
      break;

    case titlepage:
      xml_insert_element (TITLEPAGE, START);
      break;

    default:
      line_error ("begin_insertion internal error: type=%d", type);
    }

  if (!no_discard)
    discard_until ("\n");
}

/* Try to end the insertion with the specified TYPE.  With a value of
   `bad_type', TYPE gets translated to match the value currently on top
   of the stack.  Otherwise, if TYPE doesn't match the top of the
   insertion stack, give error. */
static void
end_insertion (enum insertion_type type)
{
  enum insertion_type temp_type;

  if (!insertion_level)
    return;

  temp_type = current_insertion_type ();

  if (type == bad_type)
    type = temp_type;

  if (type != temp_type)
    {
      line_error
        (_("`@end' expected `%s', but saw `%s'"),
         insertion_type_pname (temp_type), insertion_type_pname (type));
      return;
    }

  pop_insertion ();

  if (xml)
    {
      switch (type)
        {
        case ifinfo:
        case documentdescription:
          break;
        case quotation:
          xml_insert_quotation ("", END);
          break;
        case example:
          xml_insert_element (EXAMPLE, END);
          if (docbook && current_insertion_type () == floatenv)
            xml_insert_element (FLOATEXAMPLE, END);
          break;
        case smallexample:
          xml_insert_element (SMALLEXAMPLE, END);
          if (docbook && current_insertion_type () == floatenv)
            xml_insert_element (FLOATEXAMPLE, END);
          break;
        case lisp:
          xml_insert_element (LISP, END);
          if (docbook && current_insertion_type () == floatenv)
            xml_insert_element (FLOATEXAMPLE, END);
          break;
        case smalllisp:
          xml_insert_element (SMALLLISP, END);
          if (docbook && current_insertion_type () == floatenv)
            xml_insert_element (FLOATEXAMPLE, END);
          break;
        case cartouche:
          xml_insert_element (CARTOUCHE, END);
          break;
        case format:
	  if (docbook && xml_in_bookinfo && xml_in_abstract)
	    {
	      xml_insert_element (ABSTRACT, END);
	      xml_in_abstract = 0;
	    }
	  else
	    xml_insert_element (FORMAT, END);
          break;
        case smallformat:
          xml_insert_element (SMALLFORMAT, END);
          break;
        case display:
          xml_insert_element (DISPLAY, END);
          break;
        case smalldisplay:
          xml_insert_element (SMALLDISPLAY, END);
          break;
        case table:
        case ftable:
        case vtable:
        case itemize:
          xml_end_table (type);
          break;
        case enumerate:
          xml_end_enumerate ();
          break;
        case group:
          xml_insert_element (GROUP, END);
          break;
	case titlepage:
	  xml_insert_element (TITLEPAGE, END);
	  break;
        }
    }
  switch (type)
    {
      /* Insertions which have no effect on paragraph formatting. */
    case copying:
      line_number--;
      break;

    case ifclear:
    case ifdocbook:
    case ifinfo:
    case ifhtml:
    case ifnotdocbook:
    case ifnothtml:
    case ifnotinfo:
    case ifnotplaintext:
    case ifnottex:
    case ifnotxml:
    case ifplaintext:
    case ifset:
    case iftex:
    case ifxml:
    case rawtex:
    case titlepage:
      break;

    case rawdocbook:
    case rawhtml:
    case rawxml:
      raw_output_block--;

      if (raw_output_block <= 0)
        {
          xml_no_para = 0;
          escape_html = 1;
          xml_keep_space--;
        }

      if ((xml || html)
	  && output_paragraph_offset > 0
	  && output_paragraph[output_paragraph_offset-1] == '\n')
        output_paragraph_offset--;
      break;

    case detailmenu:
      if (xml)
        xml_insert_element (DETAILMENU, END);

      in_detailmenu--;          /* No longer hacking menus. */
      if (!in_menu)
        {
          if (!no_headers)
            close_insertion_paragraph ();
        }
      break;

    case direntry:              /* Eaten if html. */
      insert_string ("END-INFO-DIR-ENTRY\n\n");
      close_insertion_paragraph ();
      break;

    case documentdescription:
      if (xml)
        insert_string (document_description);
        xml_insert_element (DOCUMENTDESCRIPTION, END);
      break;

    case menu:
      in_menu--;                /* No longer hacking menus. */
      if (html && !no_headers)
        add_html_block_elt ("
\n");
      else if (!no_headers && !xml)
        close_insertion_paragraph ();
      break;

    case multitable:
      end_multitable ();
      break;

    case enumerate:
      stop_enumerating ();
      close_insertion_paragraph ();
      current_indent -= default_indentation_increment;
      if (html)
        add_html_block_elt ("
\n");
      break;

    case flushleft:
      if (html)
        add_html_block_elt ("
\n");
      close_insertion_paragraph ();
      break;

    case cartouche:
      if (html)
	add_html_block_elt ("

\n");
      close_insertion_paragraph ();
      break;

    case group:
      if (!xml || docbook)
        close_insertion_paragraph ();
      break;

    case floatenv:
      if (xml)
        xml_insert_element (FLOAT, END);
      else
        {
          if (html)
            add_html_block_elt ("
");
          else
            close_paragraph ();

          no_indent = 1;

          /* Legend:
               1) @float Foo,lbl & no caption:    Foo 1.1
               2) @float Foo & no caption:        Foo
               3) @float ,lbl & no caption:       1.1
               4) @float & no caption:                    */

          if (!xml && !html)
            indent (current_indent);

          if (strlen (current_float_type ()))
            execute_string ("%s", current_float_type ());

          if (strlen (current_float_id ()) > 0)
            {
              if (strlen (current_float_type ()) > 0)
                add_char (' ');

              add_word (current_float_number ());
            }

          if (strlen (current_float_title ()) > 0)
            {
              if (strlen (current_float_type ()) > 0
                  || strlen (current_float_id ()) > 0)
                insert_string (": ");

              execute_string ("%s", current_float_title ());
            }

          /* Indent the following paragraph. */
          inhibit_paragraph_indentation = 0;

          if (html)
            add_word ("

\n");
          else
            close_paragraph ();
        }
      float_active--;
      break;

    case format:
    case smallformat:
    case display:
    case smalldisplay:
    case example:
    case smallexample:
    case lisp:
    case smalllisp:
    case quotation:
      /* @format and @smallformat are the only fixed_width insertion
         without a change in indentation. */
      if (type != format && type != smallformat && type != quotation)
        current_indent -= example_indentation_increment;
      else if (type == quotation && !html)
        current_indent -= default_indentation_increment;

      if (html)
        { /* The complex code in close_paragraph that kills whitespace
             does not function here, since we've inserted non-whitespace
             (the </whatever>) before it.  The indentation already got
             inserted at the end of the last example line, so we have to
             delete it, or browsers wind up showing an extra blank line.
             Furthermore, if we're inside indented environments, we
             might have arbitrarily much indentation, so remove it all.  */
          kill_self_indent (-1);
          add_html_block_elt (type == quotation
              ? "
\n" : "
\n");
        }

      /* The ending of one of these insertions always marks the
         start of a new paragraph, except for the XML output. */
      if (!xml || docbook)
        close_insertion_paragraph ();

      /*
 closes paragraph without messing with
.  */
      if (html && type != quotation)
          paragraph_is_open = 0;
      break;

    case table:
    case ftable:
    case vtable:
      current_indent -= default_indentation_increment;
      if (html)
        add_html_block_elt ("
\n");
      close_insertion_paragraph ();
      break;

    case itemize:
      current_indent -= default_indentation_increment;
      if (html)
        add_html_block_elt ("
\n");
      close_insertion_paragraph ();
      break;

    case flushright:
      force_flush_right--;
      if (html)
        add_html_block_elt ("
\n");
      close_insertion_paragraph ();
      break;

    case raggedcenter:
    case raggedleft:
    case raggedright:
      if (html)
        add_html_block_elt ("
\n");
      close_insertion_paragraph ();
      break;

    /* Handle the @defun insertions with this default clause. */
    default:
      {
        int base_type;

        if (type < defcv || type > defvr)
          line_error ("end_insertion internal error: type=%d", type);

        base_type = get_base_type (type);
        switch (base_type)
          {
          case deffn:
          case defvr:
          case deftp:
          case deftypecv:
          case deftypefn:
          case deftypevr:
          case defcv:
          case defop:
          case deftypemethod:
          case deftypeop:
          case deftypeivar:
            if (html)
              {
                if (paragraph_is_open)
                  add_html_block_elt ("
");
                /* close the div and blockquote which has been opened in defun.c */
                if (!rollback_empty_tag ("blockquote"))
                  add_html_block_elt ("
");
                add_html_block_elt ("
\n");
              }
	    if (xml)
	      xml_end_definition ();
            break;
          } /* switch (base_type)... */

        current_indent -= default_indentation_increment;
        close_insertion_paragraph ();
      }
      break;

    }

  if (current_indent < 0)
    line_error ("end_insertion internal error: current indent=%d",
                current_indent);
}

/* Insertions cannot cross certain boundaries, such as node beginnings.  In
   code that creates such boundaries, you should call `discard_insertions'
   before doing anything else.  It prints the errors for you, and cleans up
   the insertion stack.

   With nonzero SPECIALS_OK argument, allows unmatched
   @if... conditionals, otherwise not.  This is because conditionals can
   cross node boundaries.  Always happens with the @top node, for example.  */
void
discard_insertions (int specials_ok)
{
  int real_line_number = line_number;
  while (insertion_stack)
    {
      if (specials_ok
          && ((ifclear <= insertion_stack->insertion
               && insertion_stack->insertion <= iftex)
              || insertion_stack->insertion == rawdocbook
              || insertion_stack->insertion == rawhtml
              || insertion_stack->insertion == rawxml
              || insertion_stack->insertion == rawtex))
        break;
      else
        {
          const char *offender = insertion_type_pname (insertion_stack->insertion);

          file_line_error (insertion_stack->filename,
                           insertion_stack->line_number,
                           _("No matching `%cend %s'"), COMMAND_PREFIX,
                           offender);
          pop_insertion ();
        }
    }
  line_number = real_line_number;
}

/* Insertion (environment) commands.  */

void
cm_quotation (void)
{
  /* We start the blockquote element in the insertion.  */
  begin_insertion (quotation);
}

void
cm_example (void)
{
  if (docbook && current_insertion_type () == floatenv)
    xml_begin_docbook_float (FLOATEXAMPLE);

  if (xml)
    {
      /* Rollback previous newlines.  These occur between
         </para> and <example>.  */
      if (output_paragraph_offset > 0
	  && output_paragraph[output_paragraph_offset-1] == '\n')
        output_paragraph_offset--;

      xml_insert_element (EXAMPLE, START);

      /* Make sure example text is starting on a new line
         for improved readability.  */
      if (docbook)
        add_char ('\n');
    }

  begin_insertion (example);
}

void
cm_smallexample (void)
{
  if (docbook && current_insertion_type () == floatenv)
    xml_begin_docbook_float (FLOATEXAMPLE);

  if (xml)
    {
      /* See cm_example comments about newlines.  */
      if (output_paragraph_offset > 0
	  && output_paragraph[output_paragraph_offset-1] == '\n')
        output_paragraph_offset--;
      xml_insert_element (SMALLEXAMPLE, START);
      if (docbook)
        add_char ('\n');
    }

  begin_insertion (smallexample);
}

void
cm_lisp (void)
{
  if (docbook && current_insertion_type () == floatenv)
    xml_begin_docbook_float (FLOATEXAMPLE);

  if (xml)
    {
      /* See cm_example comments about newlines.  */
      if (output_paragraph_offset > 0
	  && output_paragraph[output_paragraph_offset-1] == '\n')
        output_paragraph_offset--;
      xml_insert_element (LISP, START);
      if (docbook)
        add_char ('\n');
    }

  begin_insertion (lisp);
}

void
cm_smalllisp (void)
{
  if (docbook && current_insertion_type () == floatenv)
    xml_begin_docbook_float (FLOATEXAMPLE);

  if (xml)
    {
      /* See cm_example comments about newlines.  */
      if (output_paragraph_offset > 0
	  && output_paragraph[output_paragraph_offset-1] == '\n')
        output_paragraph_offset--;
      xml_insert_element (SMALLLISP, START);
      if (docbook)
        add_char ('\n');
    }

  begin_insertion (smalllisp);
}

void
cm_cartouche (void)
{
  if (docbook && current_insertion_type () == floatenv)
    xml_begin_docbook_float (CARTOUCHE);

  if (xml)
    xml_insert_element (CARTOUCHE, START);
  begin_insertion (cartouche);
}

void
cm_copying (void)
{
  begin_insertion (copying);
}

/* Not an insertion, despite the name, but it goes with cm_copying.  */
void
cm_insert_copying (void)
{
  if (!copying_text)
    {
      warning ("@copying not used before %s", command);
      return;
    }

  /* It is desirable that @copying is set early in the input file.  For
     Info output, we write the copying text out right away, and thus it
     may well be the first thing in the output, and we want the file
     header first.  The special case in add_char has to check for
     executing_string, so it won't be effective.  Thus, do it explicitly.  */
  output_head ();
  execute_string ("%s", copying_text);

  if (!xml && !html)
    {
      add_word ("\n\n");
      /* Update output_position so that the node positions in the tag
         tables will take account of the copying text.  */
      flush_output ();
    }
}

void
cm_format (void)
{
  if (xml)
    {
      if (docbook && xml_in_bookinfo)
	{
	  xml_insert_element (ABSTRACT, START);
	  xml_in_abstract = 1;
	}
      else
        {
          /* See cm_example comments about newlines.  */
          if (output_paragraph_offset > 0
	      && output_paragraph[output_paragraph_offset-1] == '\n')
            output_paragraph_offset--;
          xml_insert_element (FORMAT, START);
          if (docbook)
            add_char ('\n');
        }
    }
  begin_insertion (format);
}

void
cm_smallformat (void)
{
  if (xml)
    {
      /* See cm_example comments about newlines.  */
      if (output_paragraph_offset > 0
	  && output_paragraph[output_paragraph_offset-1] == '\n')
        output_paragraph_offset--;
      xml_insert_element (SMALLFORMAT, START);
      if (docbook)
        add_char ('\n');
    }

  begin_insertion (smallformat);
}

void
cm_display (void)
{
  if (xml)
    {
      /* See cm_example comments about newlines.  */
      if (output_paragraph_offset > 0
	  && output_paragraph[output_paragraph_offset-1] == '\n')
        output_paragraph_offset--;
      xml_insert_element (DISPLAY, START);
      if (docbook)
        add_char ('\n');
    }

  begin_insertion (display);
}

void
cm_smalldisplay (void)
{
  if (xml)
    {
      /* See cm_example comments about newlines.  */
      if (output_paragraph_offset > 0
	  && output_paragraph[output_paragraph_offset-1] == '\n')
        output_paragraph_offset--;
      xml_insert_element (SMALLDISPLAY, START);
      if (docbook)
        add_char ('\n');
    }

  begin_insertion (smalldisplay);
}

void
cm_direntry (void)
{
  if (html || xml || no_headers)
    command_name_condition ();
  else
    begin_insertion (direntry);
}

void
cm_documentdescription (void)
{
  if (html)
    begin_insertion (documentdescription);

  else if (xml)
    {
      xml_insert_element (DOCUMENTDESCRIPTION, START);
      begin_insertion (documentdescription);
    }

  else
    command_name_condition ();
}

void
cm_itemize (void)
{
  begin_insertion (itemize);
}

/* Start an enumeration insertion of type TYPE.  If the user supplied
   no argument on the line, then use DEFAULT_STRING as the initial string. */
static void
do_enumeration (enum insertion_type type, char *default_string)
{
  get_until_in_line (0, ".", &enumeration_arg);
  canon_white (enumeration_arg);

  if (!*enumeration_arg)
    {
      free (enumeration_arg);
      enumeration_arg = xstrdup (default_string);
    }

  if (!isdigit (*enumeration_arg) && !isletter (*enumeration_arg))
    {
      warning (_("%s requires letter or digit"), insertion_type_pname (type));

      switch (type)
        {
        case enumerate:
          default_string = "1";
          break;
        }
      enumeration_arg = xstrdup (default_string);
    }
  begin_insertion (type);
}

void
cm_enumerate (void)
{
  do_enumeration (enumerate, "1");
}

/* Handle verbatim environment:
    find_end_verbatim == 0:  process until end of file
    find_end_verbatim != 0:  process until 'COMMAND_PREFIXend verbatim'
                             or end of file

   No indentation is inserted: this is verbatim after all.
   If you want indentation, enclose @verbatim in @example.

   Thus, we cannot simply copy the input to the output, since the
   verbatim environment may be encapsulated in an @example environment,
   for example. */

void
handle_verbatim_environment (int find_end_verbatim)
{
  int character;
  int seen_end = 0;
  int save_filling_enabled = filling_enabled;
  int save_inhibit_paragraph_indentation = inhibit_paragraph_indentation;

  if (!insertion_stack)
    close_single_paragraph (); /* no blank lines if not at outer level */
  inhibit_paragraph_indentation = 1;
  filling_enabled = 0;
  in_fixed_width_font++;
  last_char_was_newline = 0;

  if (html)
    { /* If inside @example, we'll be preceded by the indentation
         already.  Browsers will ignore those spaces because we're about
         to start another
 (don't ask me).  So, wipe them out for
         cleanliness, and re-insert.  */
      int i;
      kill_self_indent (default_indentation_increment);
      add_html_block_elt ("
");
      for (i = current_indent; i > 0; i--)
        add_char (' ');
    }
  else if (xml)
    {
      xml_insert_element (VERBATIM, START);
    }

  if (find_end_verbatim)
    { /* Ignore the remainder of the @verbatim line.  */
      char *junk;
      get_rest_of_line (0, &junk);
      free (junk);
    }

  while (input_text_offset < input_text_length)
    {
      character = curchar ();

      if (character == '\n')
        line_number++;

      /* Assume no newlines in END_VERBATIM. */
      else if (find_end_verbatim && (character == COMMAND_PREFIX) /* @ */
          && (input_text_length - input_text_offset > sizeof (END_VERBATIM))
          && !strncmp (&input_text[input_text_offset+1], END_VERBATIM,
                       sizeof (END_VERBATIM)-1))
        {
          input_text_offset += sizeof (END_VERBATIM);
          seen_end = 1;
          break;
        }

      if (html && character == '&' && escape_html)
        add_word ("&");
      else if (html && character == '<' && escape_html)
        add_word ("<");
      else
        add_char (character);

      input_text_offset++;
    }

  if (find_end_verbatim && !seen_end)
    warning (_("end of file inside verbatim block"));

  if (html)
    { /* See comments in example case above.  */
      kill_self_indent (default_indentation_increment);
      add_word ("
");
    }
  else if (xml)
    {
      xml_insert_element (VERBATIM, END);
    }

  in_fixed_width_font--;
  filling_enabled = save_filling_enabled;
  inhibit_paragraph_indentation = save_inhibit_paragraph_indentation;
}

void
cm_verbatim (void)
{
  handle_verbatim_environment (1);
}

void
cm_table (void)
{
  begin_insertion (table);
}

void
cm_multitable (void)
{
  begin_insertion (multitable); /* @@ */
}

void
cm_ftable (void)
{
  begin_insertion (ftable);
}

void
cm_vtable (void)
{
  begin_insertion (vtable);
}

void
cm_group (void)
{
  begin_insertion (group);
}

/* Insert raw HTML (no escaping of `<' etc.). */
void
cm_html (int arg)
{
  if (process_html)
    begin_insertion (rawhtml);
  else
    command_name_condition ();
}

void
cm_xml (int arg)
{
  if (process_xml)
    begin_insertion (rawxml);
  else
    command_name_condition ();
}

void
cm_docbook (int arg)
{
  if (process_docbook)
    begin_insertion (rawdocbook);
  else
    command_name_condition ();
}

void
cm_ifdocbook (void)
{
  if (process_docbook)
    begin_insertion (ifdocbook);
  else
    command_name_condition ();
}

void
cm_ifnotdocbook (void)
{
  if (!process_docbook)
    begin_insertion (ifnotdocbook);
  else
    command_name_condition ();
}

void
cm_ifhtml (void)
{
  if (process_html)
    begin_insertion (ifhtml);
  else
    command_name_condition ();
}

void
cm_ifnothtml (void)
{
  if (!process_html)
    begin_insertion (ifnothtml);
  else
    command_name_condition ();
}

void
cm_ifinfo (void)
{
  if (process_info)
    begin_insertion (ifinfo);
  else
    command_name_condition ();
}

void
cm_ifnotinfo (void)
{
  if (!process_info)
    begin_insertion (ifnotinfo);
  else
    command_name_condition ();
}

void
cm_ifplaintext (void)
{
  if (process_plaintext)
    begin_insertion (ifplaintext);
  else
    command_name_condition ();
}

void
cm_ifnotplaintext (void)
{
  if (!process_plaintext)
    begin_insertion (ifnotplaintext);
  else
    command_name_condition ();
}

void
cm_tex (void)
{
  if (process_tex)
    begin_insertion (rawtex);
  else
    command_name_condition ();
}

void
cm_iftex (void)
{
  if (process_tex)
    begin_insertion (iftex);
  else
    command_name_condition ();
}

void
cm_ifnottex (void)
{
  if (!process_tex)
    begin_insertion (ifnottex);
  else
    command_name_condition ();
}

void
cm_ifxml (void)
{
  if (process_xml)
    begin_insertion (ifxml);
  else
    command_name_condition ();
}

void
cm_ifnotxml (void)
{
  if (!process_xml)
    begin_insertion (ifnotxml);
  else
    command_name_condition ();
}

/* Generic xrefable block with a caption.  */
void
cm_float (void)
{
  begin_insertion (floatenv);
}

void
cm_caption (int arg)
{
  char *temp;

  /* This is a no_op command for most formats, as we handle it during @float
     insertion.  For XML though, we handle it here to keep document structure
     as close as possible, to the Texinfo source.  */

  /* Everything is already handled at START.  */
  if (arg == END)
    return;

  /* Check if it's mislocated.  */
  if (current_insertion_type () != floatenv)
    line_error (_("@%s not meaningful outside `@float' environment"), command);

  get_until_in_braces ("\n@end float", &temp);

  if (xml)
    {
      int elt = STREQ (command, "shortcaption") ? SHORTCAPTION : CAPTION;
      xml_insert_element (elt, START);
      if (!docbook)
        execute_string ("%s", temp);
      xml_insert_element (elt, END);
    }

  free (temp);
}

/* Begin an insertion where the lines are not filled or indented. */
void
cm_flushleft (void)
{
  begin_insertion (flushleft);
}

/* Begin an insertion where the lines are not filled, and each line is
   forced to the right-hand side of the page. */
void
cm_flushright (void)
{
  begin_insertion (flushright);
}

void
cm_menu (void)
{
  if (current_node == NULL && !macro_expansion_output_stream)
    {
      warning (_("@menu seen before first @node, creating `Top' node"));
      warning (_("perhaps your @top node should be wrapped in @ifnottex rather than @ifinfo?"));
      /* Include @top command so we can construct the implicit node tree.  */
      execute_string ("@node top\n@top Top\n");
    }
  begin_insertion (menu);
}

void
cm_detailmenu (void)
{
  if (current_node == NULL && !macro_expansion_output_stream)
    { /* Problems anyway, @detailmenu should always be inside @menu.  */
      warning (_("@detailmenu seen before first node, creating `Top' node"));
      execute_string ("@node top\n@top Top\n");
    }
  begin_insertion (detailmenu);
}

void
cm_raggedcenter (void)
{
  begin_insertion (raggedcenter);
}

void
cm_raggedleft (void)
{
  begin_insertion (raggedleft);
}

void
cm_raggedright (void)
{
  begin_insertion (raggedright);
}

/* Title page commands. */

void
cm_titlepage (void)
{
  titlepage_cmd_present = 1;
  if (xml && !docbook)
    begin_insertion (titlepage);
  else
    command_name_condition ();
}

void
cm_author (void)
{
  char *rest;
  get_rest_of_line (1, &rest);

  if (is_in_insertion_of_type (quotation))
    {
      if (html)
        add_word_args ("— %s", rest);
      else if (docbook)
        {
          /* FIXME Ideally, we should use an attribution element,
             but they are supposed to be at the start of quotation
             blocks.  So to avoid looking ahead mess, let's just
             use mdash like HTML for now.  */
          xml_insert_entity ("mdash");
          add_word (rest);
        }
      else if (xml)
        {
          xml_insert_element (AUTHOR, START);
          add_word (rest);
          xml_insert_element (AUTHOR, END);
        }
      else
        add_word_args ("-- %s", rest);
    }
  else if (is_in_insertion_of_type (titlepage))
    {
      if (xml && !docbook)
        {
          xml_insert_element (AUTHOR, START);
          add_word (rest);
          xml_insert_element (AUTHOR, END);
        }
    }
  else
    line_error (_("@%s not meaningful outside `@titlepage' and `@quotation' environments"),
        command);

  free (rest);
}

void
cm_titlepage_cmds (void)
{
  char *rest;

  get_rest_of_line (1, &rest);

  if (!is_in_insertion_of_type (titlepage))
    line_error (_("@%s not meaningful outside `@titlepage' environment"),
        command);

  if (xml && !docbook)
    {
      int elt = 0;

      if (STREQ (command, "title"))
        elt = BOOKTITLE;
      else if (STREQ (command, "subtitle"))
        elt = BOOKSUBTITLE;

      xml_insert_element (elt, START);
      add_word (rest);
      xml_insert_element (elt, END);
    }

    free (rest);
}

/* End existing insertion block. */
void
cm_end (void)
{
  char *temp;
  enum insertion_type type;

  get_rest_of_line (0, &temp);

  if (!insertion_level)
    {
      line_error (_("Unmatched `%c%s'"), COMMAND_PREFIX, command);
      return;
    }

  if (temp[0] == 0)
    line_error (_("`%c%s' needs something after it"), COMMAND_PREFIX, command);

  type = find_type_from_name (temp);

  if (type == bad_type)
    {
      line_error (_("Bad argument `%s' to `@%s', using `%s'"),
           temp, command, insertion_type_pname (current_insertion_type ()));
    }
  if (xml && type == menu) /* fixme */
    {
      xml_end_menu ();
    }
  end_insertion (type);
  free (temp);
}

/* @itemx, @item. */

static int itemx_flag = 0;

/* Return whether CMD takes a brace-delimited {arg}.  */
int
command_needs_braces (char *cmd)
{
  int i;
  for (i = 0; command_table[i].name; i++)
    {
      if (STREQ (command_table[i].name, cmd))
        return command_table[i].argument_in_braces == BRACE_ARGS;
    }

  return 0; /* macro or alias */
}

void
cm_item (void)
{
  char *rest_of_line, *item_func;

  /* Can only hack "@item" while inside of an insertion. */
  if (insertion_level)
    {
      INSERTION_ELT *stack = insertion_stack;
      int original_input_text_offset;

      skip_whitespace ();
      original_input_text_offset = input_text_offset;

      get_rest_of_line (0, &rest_of_line);
      item_func = current_item_function ();

    /* Do the right thing depending on which insertion function is active. */
    switch_top:
      switch (stack->insertion)
        {
        case multitable:
          multitable_item ();
          /* Support text directly after the @item.  */
          if (*rest_of_line)
            {
              line_number--;
              input_text_offset = original_input_text_offset;
            }
          break;

        case ifclear:
        case ifhtml:
        case ifinfo:
        case ifnothtml:
        case ifnotinfo:
        case ifnotplaintext:
        case ifnottex:
	case ifnotxml:
        case ifplaintext:
        case ifset:
        case iftex:
	case ifxml:
        case rawdocbook:
        case rawhtml:
        case rawxml:
        case rawtex:
        case tex:
        case cartouche:
          stack = stack->next;
          if (!stack)
            goto no_insertion;
          else
            goto switch_top;
          break;

        case menu:
        case quotation:
        case example:
        case smallexample:
        case lisp:
        case smalllisp:
        case format:
        case smallformat:
        case display:
        case smalldisplay:
        case group:
          line_error (_("@%s not meaningful inside `@%s' block"),
                      command,
                      insertion_type_pname (current_insertion_type ()));
          break;

        case itemize:
        case enumerate:
          if (itemx_flag)
            {
              line_error (_("@itemx not meaningful inside `%s' block"),
                          insertion_type_pname (current_insertion_type ()));
            }
          else
            {
              if (html)
                add_html_block_elt ("
");
              else if (xml)
                xml_begin_item ();
              else
                {
                  start_paragraph ();
                  kill_self_indent (-1);
                  filling_enabled = indented_fill = 1;

                  if (current_item_function ())
                    {
                      indent (current_indent - 2);

                      /* The item marker can be given with or without
                         braces -- @bullet and @bullet{} are both ok.
                         Or it might be something that doesn't take
                         braces at all, such as "o" or "#" or "@ ".
                         Thus, only supply braces if the item marker is
                         a command, they haven't supplied braces
                         themselves, and we know it needs them.  */
                      if (item_func && *item_func)
                        {
                          if (*item_func == COMMAND_PREFIX
                              && item_func[strlen (item_func) - 1] != '}'
                              && command_needs_braces (item_func + 1))
                            execute_string ("%s{}", item_func);
                          else
                            execute_string ("%s", item_func);
                        }
                      insert (' ');
                    }
                  else
                    enumerate_item ();

                  /* Special hack.  This makes `close_paragraph' a no-op until
                     `start_paragraph' has been called. */
                  must_start_paragraph = 1;
                }

              /* Handle text directly after the @item.  */
              if (*rest_of_line)
                {
                  line_number--;
                  input_text_offset = original_input_text_offset;
                }
            }
          break;

        case table:
        case ftable:
        case vtable:
          if (html)
            { /* If nothing has been output since the last
,
                 remove the empty
 element.  Some browsers render
                 an extra empty line for

, which makes @itemx
                 conversion look ugly.  */
              rollback_empty_tag ("dd");

              /* Force the browser to render one blank line before
                 each new @item in a table.  But don't do that if
                 this is the first
 after the
, or if we are
                 converting @itemx.

                 Note that there are some browsers which ignore

                 in this context, but I cannot find any way to force
                 them all render exactly one blank line.  */
              if (!itemx_flag && html_deflist_has_term)
                add_html_block_elt ("
");

              /* We are about to insert a
, so this
 has a term.
                 Feel free to insert a
 next time. :)  */
              html_deflist_has_term = 1;

              add_html_block_elt ("
");
              if (item_func && *item_func)
                execute_string ("%s{%s}", item_func, rest_of_line);
              else
                execute_string ("%s", rest_of_line);

              if (current_insertion_type () == ftable)
                execute_string ("%cfindex %s\n", COMMAND_PREFIX, rest_of_line);

              if (current_insertion_type () == vtable)
                execute_string ("%cvindex %s\n", COMMAND_PREFIX, rest_of_line);

              add_html_block_elt ("
");
            }
          else if (xml) /* && docbook)*/ /* 05-08 */
            {
              xml_begin_table_item ();

              if (!docbook && current_insertion_type () == ftable)
                execute_string ("%cfindex %s\n", COMMAND_PREFIX, rest_of_line);

              if (!docbook && current_insertion_type () == vtable)
                execute_string ("%cvindex %s\n", COMMAND_PREFIX, rest_of_line);

              if (item_func && *item_func)
                execute_string ("%s{%s}", item_func, rest_of_line);
              else
                execute_string ("%s", rest_of_line);
              xml_continue_table_item ();
            }
          else
            {
              /* We need this to determine if we have two @item's in a row
                 (see test just below).  */
              static int last_item_output_position = 0;

              /* Get rid of extra characters. */
              kill_self_indent (-1);

              /* If we have one @item followed directly by another @item,
                 we need to insert a blank line.  This is not true for
                 @itemx, though.  */
              if (!itemx_flag && last_item_output_position == output_position)
                insert ('\n');

              /* `close_paragraph' almost does what we want.  The problem
                 is when paragraph_is_open, and last_char_was_newline, and
                 the last newline has been turned into a space, because
                 filling_enabled. I handle it here. */
              if (last_char_was_newline && filling_enabled &&
                  paragraph_is_open)
                insert ('\n');
              close_paragraph ();

#if defined (INDENT_PARAGRAPHS_IN_TABLE)
              /* Indent on a new line, but back up one indentation level. */
              {
                int save = inhibit_paragraph_indentation;
                inhibit_paragraph_indentation = 1;
                /* At this point, inserting any non-whitespace character will
                   force the existing indentation to be output. */
                add_char ('i');
                inhibit_paragraph_indentation = save;
              }
#else /* !INDENT_PARAGRAPHS_IN_TABLE */
              add_char ('i');
#endif /* !INDENT_PARAGRAPHS_IN_TABLE */

              output_paragraph_offset--;
              kill_self_indent (default_indentation_increment + 1);

              /* Add item's argument to the line. */
              filling_enabled = 0;
              if (item_func && *item_func)
                execute_string ("%s{%s}", item_func, rest_of_line);
              else
                execute_string ("%s", rest_of_line);

              if (current_insertion_type () == ftable)
                execute_string ("%cfindex %s\n", COMMAND_PREFIX, rest_of_line);
              else if (current_insertion_type () == vtable)
                execute_string ("%cvindex %s\n", COMMAND_PREFIX, rest_of_line);

              /* Start a new line, and let start_paragraph ()
                 do the indenting of it for you. */
              close_single_paragraph ();
              indented_fill = filling_enabled = 1;
              last_item_output_position = output_position;
            }
        }
      free (rest_of_line);
    }
  else
    {
    no_insertion:
      line_error (_("%c%s found outside of an insertion block"),
                  COMMAND_PREFIX, command);
    }
}

void
cm_itemx (void)
{
  itemx_flag++;
  cm_item ();
  itemx_flag--;
}

int headitem_flag = 0;

void
cm_headitem (void)
{
  headitem_flag = 1;
  cm_item ();
}