home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / ptx-0.4-src.tgz / ptx-0.4-src.tar / fsf / ptx / ptx.c < prev    next >
C/C++ Source or Header  |  1996-09-28  |  67KB  |  2,249 lines

  1. /* Permuted index for GNU, with keywords in their context.
  2.    Copyright (C) 1990, 1991, 1993 Free Software Foundation, Inc.
  3.    Francois Pinard <pinard@iro.umontreal.ca>, 1988.
  4.  
  5.    This program is free software; you can redistribute it and/or modify
  6.    it under the terms of the GNU General Public License as published by
  7.    the Free Software Foundation; either version 2, or (at your option)
  8.    any later version.
  9.  
  10.    This program is distributed in the hope that it will be useful, but
  11.    WITHOUT ANY WARRANTY; without even the implied warranty of
  12.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13.    General Public License for more details.
  14.  
  15.    You should have received a copy of the GNU General Public License
  16.    along with this program; if not, write to the Free Software
  17.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  18. */
  19.  
  20. #ifdef HAVE_CONFIG_H
  21. # include <config.h>
  22. #endif
  23.  
  24. static char *const copyright_string = "\
  25. This program is free software; you can redistribute it and/or modify\n\
  26. it under the terms of the GNU General Public License as published by\n\
  27. the Free Software Foundation; either version 2, or (at your option)\n\
  28. any later version.\n\
  29. \n\
  30. This program is distributed in the hope that it will be useful,\n\
  31. but WITHOUT ANY WARRANTY; without even the implied warranty of\n\
  32. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\
  33. GNU General Public License for more details.\n\
  34. \n\
  35. You should have received a copy of the GNU General Public License\n\
  36. along with this program; if not, write to the Free Software\n\
  37. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n";
  38.  
  39. /* Reallocation step when swallowing non regular files.  The value is not
  40.    the actual reallocation step, but its base two logarithm.  */
  41. #define SWALLOW_REALLOC_LOG 12
  42.  
  43. /* Imported from "regex.c".  */
  44. #define Sword 1
  45.  
  46. #if STDC_HEADERS
  47. # include <stdlib.h>
  48. # include <ctype.h>
  49. #else
  50. /* These definitions work, for all 256 characters.  */
  51. # define isspace(C) ((C) == ' ' || (C) == '\t' || (C) == '\n')
  52. # define isxdigit(C) \
  53.   (((unsigned char) (C) >= 'a' && (unsigned char) (C) <= 'f')        \
  54.    || ((unsigned char) (C) >= 'A' && (unsigned char) (C) <= 'F')    \
  55.    || ((unsigned char) (C) >= '0' && (unsigned char) (C) <= '9'))
  56. # define islower(C) ((unsigned char) (C) >= 'a' && (unsigned char) (C) <= 'z')
  57. # define isupper(C) ((unsigned char) (C) >= 'A' && (unsigned char) (C) <= 'Z')
  58. # define isalpha(C) (islower (C) || isupper (C))
  59. # define toupper(C) (islower (C) ? (C) - 'a' + 'A' : (C))
  60. #endif
  61.  
  62. #if !defined (isascii) || defined (STDC_HEADERS)
  63. # undef isascii
  64. # define isascii(C) 1
  65. #endif
  66.  
  67. #define ISXDIGIT(C) (isascii (C) && isxdigit (C))
  68. #define ISODIGIT(C) ((C) >= '0' && (C) <= '7')
  69. #define HEXTOBIN(C) ((C) >= 'a' && (C) <= 'f' ? (C)-'a'+10 \
  70.              : (C) >= 'A' && (C) <= 'F' ? (C)-'A'+10 : (C)-'0')
  71. #define OCTTOBIN(C) ((C) - '0')
  72.  
  73. #include <stdio.h>
  74. #include <fcntl.h>
  75. #include <sys/types.h>
  76. #include <sys/stat.h>
  77.   
  78. #if !defined(S_ISREG) && defined(S_IFREG)
  79. # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
  80. #endif
  81.  
  82. #if HAVE_STRING_H
  83. # include <string.h>
  84. #else
  85. # include <strings.h>
  86. # ifndef strchr
  87. #  define strchr index
  88. # endif
  89. # ifndef strrchr
  90. #  define strrchr rindex
  91. # endif
  92. #endif
  93.  
  94. #include <errno.h>
  95. #ifndef errno
  96. extern int errno;
  97. #endif
  98.  
  99. /* Some systems do not define EXIT_*, even with STDC_HEADERS.  */
  100. #ifndef EXIT_SUCCESS
  101. # define EXIT_SUCCESS 0
  102. #endif
  103. #ifndef EXIT_FAILURE
  104. # define EXIT_FAILURE 1
  105. #endif
  106.  
  107. #include "getopt.h"
  108. #include "bumpalloc.h"
  109. #include "diacrit.h"
  110. #include "regex.h"
  111.  
  112. #if __STDC__
  113. void *xmalloc (int);
  114. void *xrealloc (void *, int);
  115. #else
  116. void *xmalloc ();
  117. void *xrealloc ();
  118. #endif
  119.  
  120. /* Debugging the memory allocator.  */
  121.  
  122. #ifdef WITH_DMALLOC
  123. # define MALLOC_FUNC_CHECK
  124. # include <dmalloc.h>
  125. #endif
  126.  
  127. /* Global definitions.  */
  128.  
  129. /* The name this program was run with. */
  130. const char *program_name;
  131.  
  132. /* If non-zero, display usage information and exit.  */
  133. static int show_help = 0;
  134.  
  135. /* If non-zero, print the version on standard output and exit.  */
  136. static int show_version = 0;
  137.  
  138. /* Program options.  */
  139.  
  140. enum Format
  141. {
  142.   DUMB_FORMAT,            /* output for a dumb terminal */
  143.   ROFF_FORMAT,            /* output for `troff' or `nroff' */
  144.   TEX_FORMAT,            /* output for `TeX' or `LaTeX' */
  145.   UNKNOWN_FORMAT        /* output format still unknown */
  146. };
  147.  
  148. int gnu_extensions = 1;        /* trigger all GNU extensions */
  149. int auto_reference = 0;        /* references are `file_name:line_number:' */
  150. int input_reference = 0;    /* references at beginning of input lines */
  151. int right_reference = 0;    /* output references after right context  */
  152. int line_width = 72;        /* output line width in characters */
  153. int gap_size = 3;        /* number of spaces between output fields */
  154. const char *truncation_string = "/";
  155.                 /* string used to mark line truncations */
  156. const char *macro_name = "xx";    /* macro name for roff or TeX output */
  157. enum Format output_format = UNKNOWN_FORMAT;
  158.                 /* output format */
  159.  
  160. int ignore_case = 0;        /* fold lower to upper case for sorting */
  161. const char *context_regex_string = NULL;
  162.                 /* raw regex for end of context */
  163. const char *word_regex_string = NULL;
  164.                 /* raw regex for a keyword */
  165. const char *break_file = NULL;    /* name of the `Break characters' file */
  166. const char *only_file = NULL;    /* name of the `Only words' file */
  167. const char *ignore_file = NULL;    /* name of the `Ignore words' file */
  168.  
  169. /* A BLOCK delimit a region in memory of arbitrary size, like the copy of a
  170.    whole file.  A WORD is something smaller, its length should fit in a
  171.    short integer.  A WORD_TABLE may contain several WORDs.  */
  172.  
  173. typedef struct
  174.   {
  175.     char *start;        /* pointer to beginning of region */
  176.     char *end;            /* pointer to end + 1 of region */
  177.   }
  178. BLOCK;
  179.  
  180. typedef struct
  181.   {
  182.     char *start;        /* pointer to beginning of region */
  183.     short size;            /* length of the region */
  184.   }
  185. WORD;
  186.  
  187. typedef struct
  188.   {
  189.     WORD *start;        /* array of WORDs */
  190.     size_t length;        /* number of entries */
  191.   }
  192. WORD_TABLE;
  193.  
  194. /* Pattern description tables.  */
  195.  
  196. /* For each character, provide its folded equivalent.  */
  197. unsigned char folded_chars[CHAR_SET_SIZE];
  198.  
  199. /* For each character, indicate if it is part of a word.  */
  200. char syntax_table[CHAR_SET_SIZE];
  201. char *re_syntax_table = syntax_table;
  202.  
  203. /* Compiled regex for end of context.  */
  204. struct re_pattern_buffer *context_regex;
  205.  
  206. /* End of context pattern register indices.  */
  207. struct re_registers context_regs;
  208.  
  209. /* Compiled regex for a keyword.  */
  210. struct re_pattern_buffer *word_regex;
  211.  
  212. /* Keyword pattern register indices.  */
  213. struct re_registers word_regs;
  214.  
  215. /* A word characters fastmap is used only when no word regexp has been
  216.    provided.  A word is then made up of a sequence of one or more characters
  217.    allowed by the fastmap.  Contains !0 if character allowed in word.  Not
  218.    only this is faster in most cases, but it simplifies the implementation
  219.    of the Break files.  */
  220. char word_fastmap[CHAR_SET_SIZE];
  221.  
  222. /* Maximum length of any word read.  */
  223. int maximum_word_length;
  224.  
  225. /* Maximum width of any reference used.  */
  226. int reference_max_width;
  227.  
  228.  
  229. /* Ignore and Only word tables.  */
  230.  
  231. WORD_TABLE ignore_table;    /* table of words to ignore */
  232. WORD_TABLE only_table;        /* table of words to select */
  233.  
  234. #define ALLOC_NEW_WORD(table) \
  235.   BUMP_ALLOC ((table)->start, (table)->length, 8, WORD)
  236.  
  237. /* Source text table, and scanning macros.  */
  238.  
  239. int number_input_files;        /* number of text input files */
  240. int total_line_count;        /* total number of lines seen so far */
  241. const char **input_file_name;    /* array of text input file names */
  242. int *file_line_count;        /* array of `total_line_count' values at end */
  243.  
  244. BLOCK text_buffer;        /* file to study */
  245. char *text_buffer_maxend;    /* allocated end of text_buffer */
  246.  
  247. /* SKIP_NON_WHITE used only for getting or skipping the reference.  */
  248.  
  249. #define SKIP_NON_WHITE(cursor, limit)                    \
  250.   while (cursor < limit && !isspace(*cursor))                \
  251.     cursor++
  252.  
  253. #define SKIP_WHITE(cursor, limit)                    \
  254.   while (cursor < limit && isspace(*cursor))                \
  255.     cursor++
  256.  
  257. #define SKIP_WHITE_BACKWARDS(cursor, start)                \
  258.   while (cursor > start && isspace(cursor[-1]))                \
  259.     cursor--
  260.  
  261. #define SKIP_SOMETHING(cursor, limit)                    \
  262.   do                                    \
  263.     if (word_regex_string)                        \
  264.       {                                    \
  265.     int count;                            \
  266.     count = re_match (word_regex, cursor, limit - cursor, 0, NULL);    \
  267.     cursor += count <= 0 ? 1 : count;                \
  268.       }                                    \
  269.     else if (word_fastmap[(unsigned char) *cursor])            \
  270.       while (cursor < limit && word_fastmap[(unsigned char) *cursor])    \
  271.     cursor++;                            \
  272.     else                                \
  273.       cursor++;                                \
  274.   while (0)
  275.  
  276. /* Occurrences table.
  277.    
  278.    The `keyword' pointer provides the central word, which is surrounded
  279.    by a left context and a right context.  The `keyword' and `length'
  280.    field allow full 8-bit characters keys, even including NULs.  At other
  281.    places in this program, the name `keyafter' refers to the keyword
  282.    followed by its right context.
  283.    
  284.    The left context does not extend, towards the beginning of the file,
  285.    further than a distance given by the `left' value.  This value is
  286.    relative to the keyword beginning, it is usually negative.  This
  287.    insures that, except for white space, we will never have to backward
  288.    scan the source text, when it is time to generate the final output
  289.    lines.
  290.    
  291.    The right context, indirectly attainable through the keyword end, does
  292.    not extend, towards the end of the file, further than a distance given
  293.    by the `right' value.  This value is relative to the keyword
  294.    beginning, it is usually positive.
  295.    
  296.    When automatic references are used, the `reference' value is the
  297.    overall line number in all input files read so far, in this case, it
  298.    is of type (int).  When input references are used, the `reference'
  299.    value indicates the distance between the keyword beginning and the
  300.    start of the reference field, it is of type (DELTA) and usually
  301.    negative.  */
  302.  
  303. typedef short DELTA;        /* to hold displacement within one context */
  304.  
  305. typedef struct
  306.   {
  307.     WORD key;            /* description of the keyword */
  308.     DELTA left;            /* distance to left context start */
  309.     DELTA right;        /* distance to right context end */
  310.     int reference;        /* reference descriptor */
  311.   }
  312. OCCURS;
  313.  
  314. /* The various OCCURS tables are indexed by the language.  But the time
  315.    being, there is no such multiple language support.  */
  316.  
  317. OCCURS *occurs_table[1];    /* all words retained from the read text */
  318. size_t number_of_occurs[1];    /* number of used slots in occurs_table */
  319.  
  320. #define ALLOC_NEW_OCCURS(language) \
  321.   BUMP_ALLOC (occurs_table[language], number_of_occurs[language], 9, OCCURS)
  322.      
  323.  
  324. /* Communication among output routines.  */
  325.  
  326. /* Indicate if special output processing is requested for each character.  */
  327. char edited_flag[CHAR_SET_SIZE];
  328.  
  329. int half_line_width;        /* half of line width, reference excluded */
  330. int before_max_width;        /* maximum width of before field */
  331. int keyafter_max_width;        /* maximum width of keyword-and-after field */
  332. int truncation_string_length;    /* length of string used to flag truncation */
  333.  
  334. /* When context is limited by lines, wraparound may happen on final output:
  335.    the `head' pointer gives access to some supplementary left context which
  336.    will be seen at the end of the output line, the `tail' pointer gives
  337.    access to some supplementary right context which will be seen at the
  338.    beginning of the output line. */
  339.  
  340. BLOCK tail;            /* tail field */
  341. int tail_truncation;        /* flag truncation after the tail field */
  342.  
  343. BLOCK before;            /* before field */
  344. int before_truncation;        /* flag truncation before the before field */
  345.  
  346. BLOCK keyafter;            /* keyword-and-after field */
  347. int keyafter_truncation;    /* flag truncation after the keyafter field */
  348.  
  349. BLOCK head;            /* head field */
  350. int head_truncation;        /* flag truncation before the head field */
  351.  
  352. BLOCK reference;        /* reference field for input reference mode */
  353.  
  354. /* Miscellaneous routines.  */
  355.  
  356. /*------------------------------------------------------.
  357. | Duplicate string STRING, while evaluating \-escapes.  |
  358. `------------------------------------------------------*/
  359.  
  360. /* Loosely adapted from GNU shellutils printf.c code.  */
  361.  
  362. static char *
  363. copy_unescaped_string (const char *string)
  364. {
  365.   char *result;            /* allocated result */
  366.   char *cursor;            /* cursor in result */
  367.   int value;            /* value of \nnn escape */
  368.   int length;            /* length of \nnn escape */
  369.  
  370.   result = xmalloc (strlen (string) + 1);
  371.   cursor = result;
  372.  
  373.   while (*string)
  374.     if (*string == '\\')
  375.       {
  376.     string++;
  377.     switch (*string)
  378.       {
  379.       case 'x':        /* \xhhh escape, 3 chars maximum */
  380.         value = 0;
  381.         for (length = 0, string++;
  382.          length < 3 && ISXDIGIT (*string);
  383.          length++, string++)
  384.           value = value * 16 + HEXTOBIN (*string);
  385.         if (length == 0)
  386.           {
  387.         *cursor++ = '\\';
  388.         *cursor++ = 'x';
  389.           }
  390.         else
  391.           *cursor++ = value;
  392.         break;
  393.  
  394.       case '0':        /* \0ooo escape, 3 chars maximum */
  395.         value = 0;
  396.         for (length = 0, string++;
  397.          length < 3 && ISODIGIT (*string);
  398.          length++, string++)
  399.           value = value * 8 + OCTTOBIN (*string);
  400.         *cursor++ = value;
  401.         break;
  402.  
  403.       case 'a':        /* alert */
  404. #if __STDC__
  405.         *cursor++ = '\a';
  406. #else
  407.         *cursor++ = 7;
  408. #endif
  409.         string++;
  410.         break;
  411.  
  412.       case 'b':        /* backspace */
  413.         *cursor++ = '\b';
  414.         string++;
  415.         break;
  416.  
  417.       case 'c':        /* cancel the rest of the output */
  418.         while (*string)
  419.           string++;
  420.         break;
  421.  
  422.       case 'f':        /* form feed */
  423.         *cursor++ = '\f';
  424.         string++;
  425.         break;
  426.  
  427.       case 'n':        /* new line */
  428.         *cursor++ = '\n';
  429.         string++;
  430.         break;
  431.  
  432.       case 'r':        /* carriage return */
  433.         *cursor++ = '\r';
  434.         string++;
  435.         break;
  436.  
  437.       case 't':        /* horizontal tab */
  438.         *cursor++ = '\t';
  439.         string++;
  440.         break;
  441.  
  442.       case 'v':        /* vertical tab */
  443. #if __STDC__
  444.         *cursor++ = '\v';
  445. #else
  446.         *cursor++ = 11;
  447. #endif
  448.         string++;
  449.         break;
  450.  
  451.       default:
  452.         *cursor++ = '\\';
  453.         *cursor++ = *string++;
  454.         break;
  455.       }
  456.       }
  457.     else
  458.       *cursor++ = *string++;
  459.  
  460.   *cursor = '\0';
  461.   return result;
  462. }
  463.  
  464. /*-------------------------------------------------------------------.
  465. | Compile the regex represented by STRING, diagnose and abort if any |
  466. | error.  Returns the compiled regex structure.                 |
  467. `-------------------------------------------------------------------*/
  468.  
  469. static struct re_pattern_buffer *
  470. alloc_and_compile_regex (const char *string)
  471. {
  472.   struct re_pattern_buffer *pattern; /* newly allocated structure */
  473.   const char *message;        /* error message returned by regex.c */
  474.  
  475.   pattern = (struct re_pattern_buffer *)
  476.     xmalloc (sizeof (struct re_pattern_buffer));
  477.   memset (pattern, 0, sizeof (struct re_pattern_buffer));
  478.  
  479.   pattern->buffer = NULL;
  480.   pattern->allocated = 0;
  481.   pattern->translate = ignore_case ? (char *) folded_chars : NULL;
  482.   pattern->fastmap = (char *) xmalloc (CHAR_SET_SIZE);
  483.  
  484.   message = re_compile_pattern (string, strlen (string), pattern);
  485.   if (message)
  486.     error (1, 0, "%s (for regexp `%s')", message, string);
  487.  
  488.   /* The fastmap should be compiled before `re_match'.  The following
  489.      call is not mandatory, because `re_search' is always called sooner,
  490.      and it compiles the fastmap if this has not been done yet.  */
  491.      
  492.   re_compile_fastmap (pattern);
  493.  
  494.   /* Do not waste extra allocated space.  */
  495.  
  496.   if (pattern->allocated > pattern->used)
  497.     {
  498.       pattern->buffer
  499.     = (unsigned char *) xrealloc (pattern->buffer, pattern->used);
  500.       pattern->allocated = pattern->used;
  501.     }
  502.  
  503.   return pattern;
  504. }
  505.  
  506. /*------------------------------------------------------------------------.
  507. | This will initialize various tables for pattern match and compiles some |
  508. | regexps.                                  |
  509. `------------------------------------------------------------------------*/
  510.  
  511. static void
  512. initialize_regex (void)
  513. {
  514.   int character;        /* character value */
  515.  
  516.   /* Initialize the regex syntax table.  */
  517.  
  518.   for (character = 0; character < CHAR_SET_SIZE; character++)
  519.     syntax_table[character] = isalpha (character) ? Sword : 0;
  520.  
  521.   /* Initialize the case folding table.  */
  522.  
  523.   if (ignore_case)
  524.     for (character = 0; character < CHAR_SET_SIZE; character++)
  525.       folded_chars[character] = toupper (character);
  526.  
  527.   /* Unless the user already provided a description of the end of line or
  528.      end of sentence sequence, select an end of line sequence to compile.
  529.      If the user provided an empty definition, thus disabling end of line
  530.      or sentence feature, make it NULL to speed up tests.  If GNU
  531.      extensions are enabled, use end of sentence like in GNU emacs.  If
  532.      disabled, use end of lines.  */
  533.  
  534.   if (context_regex_string)
  535.     {
  536.       if (!*context_regex_string)
  537.     context_regex_string = NULL;
  538.     }
  539.   else if (gnu_extensions && !input_reference)
  540.     context_regex_string = "[.?!][]\"')}]*\\($\\|\t\\|  \\)[ \t\n]*";
  541.   else
  542.     context_regex_string = "\n";
  543.  
  544.   if (context_regex_string)
  545.     context_regex = alloc_and_compile_regex (context_regex_string);
  546.  
  547.   /* If the user has already provided a non-empty regexp to describe
  548.      words, compile it.  Else, unless this has already been done through
  549.      a user provided Break character file, construct a fastmap of
  550.      characters that may appear in a word.  If GNU extensions enabled,
  551.      include only letters of the underlying character set.  If disabled,
  552.      include almost everything, even punctuations; stop only on white
  553.      space.  */
  554.  
  555.   if (word_regex_string && *word_regex_string)
  556.     word_regex = alloc_and_compile_regex (word_regex_string);
  557.   else if (!break_file)
  558.     if (gnu_extensions)
  559.       {
  560.  
  561.     /* Simulate \w+.  */
  562.  
  563.     for (character = 0; character < CHAR_SET_SIZE; character++)
  564.       word_fastmap[character] = isalpha (character);
  565.       }
  566.     else
  567.       {
  568.  
  569.     /* Simulate [^ \t\n]+.  */
  570.  
  571.     memset (word_fastmap, 1, CHAR_SET_SIZE);
  572.     word_fastmap[' '] = 0;
  573.     word_fastmap['\t'] = 0;
  574.     word_fastmap['\n'] = 0;
  575.       }
  576. }
  577.  
  578. /*------------------------------------------------------------------------.
  579. | This routine will attempt to swallow a whole file name FILE_NAME into a |
  580. | contiguous region of memory and return a description of it into BLOCK.  |
  581. | Standard input is assumed whenever FILE_NAME is NULL, empty or "-".      |
  582. |                                       |
  583. | Previously, in some cases, white space compression was attempted while  |
  584. | inputting text.  This was defeating some regexps like default end of      |
  585. | sentence, which checks for two consecutive spaces.  If white space      |
  586. | compression is ever reinstated, it should be in output routines.      |
  587. `------------------------------------------------------------------------*/
  588.  
  589. static void
  590. swallow_file_in_memory (const char *file_name, BLOCK *block)
  591. {
  592.   int file_handle;        /* file descriptor number */
  593.   struct stat stat_block;    /* stat block for file */
  594.   int allocated_length;        /* allocated length of memory buffer */
  595.   int used_length;        /* used length in memory buffer */
  596.   int read_length;        /* number of character gotten on last read */
  597.  
  598.   /* As special cases, a file name which is NULL or "-" indicates standard
  599.      input, which is already opened.  In all other cases, open the file from
  600.      its name.  */ 
  601.  
  602.   if (!file_name || !*file_name || strcmp (file_name, "-") == 0)
  603.     file_handle = fileno (stdin);
  604.   else
  605.     if ((file_handle = open (file_name, O_RDONLY)) < 0)
  606.       error (1, errno, file_name);
  607.  
  608.   /* If the file is a plain, regular file, allocate the memory buffer all at
  609.      once and swallow the file in one blow.  In other cases, read the file
  610.      repeatedly in smaller chunks until we have it all, reallocating memory
  611.      once in a while, as we go.  */
  612.  
  613.   if (fstat (file_handle, &stat_block) < 0)
  614.     error (1, errno, file_name);
  615.  
  616.   if (S_ISREG (stat_block.st_mode))
  617.     {
  618.       block->start = (char *) xmalloc ((int) stat_block.st_size);
  619.  
  620.       if (read (file_handle, block->start, (int) stat_block.st_size)
  621.       != stat_block.st_size)
  622.     error (1, errno, file_name);
  623.  
  624.       block->end = block->start + stat_block.st_size;
  625.     }
  626.   else
  627.     {
  628.       block->start = (char *) xmalloc (1 << SWALLOW_REALLOC_LOG);
  629.       used_length = 0;
  630.       allocated_length = (1 << SWALLOW_REALLOC_LOG);
  631.  
  632.       while ((read_length = read (file_handle,
  633.                   block->start + used_length,
  634.                   allocated_length - used_length)) > 0)
  635.     {
  636.       used_length += read_length;
  637.       if (used_length == allocated_length)
  638.         {
  639.           allocated_length += (1 << SWALLOW_REALLOC_LOG);
  640.           block->start
  641.         = (char *) xrealloc (block->start, allocated_length);
  642.         }
  643.     }
  644.  
  645.       if (read_length < 0)
  646.     error (1, errno, file_name);
  647.  
  648.       block->end = block->start + used_length;
  649.     }
  650.  
  651.   /* Close the file, but only if it was not the standard input.  */
  652.  
  653.   if (file_handle != fileno (stdin))
  654.     close (file_handle);
  655. }
  656.  
  657. /* Sort and search routines.  */
  658.  
  659. /*--------------------------------------------------------------------------.
  660. | Compare two words, FIRST and SECOND, and return 0 if they are identical.  |
  661. | Return less than 0 if the first word goes before the second; return        |
  662. | greater than 0 if the first word goes after the second.            |
  663. |                                         |
  664. | If a word is indeed a prefix of the other, the shorter should go first.   |
  665. `--------------------------------------------------------------------------*/
  666.  
  667. static int
  668. compare_words (const void *void_first, const void *void_second)
  669. {
  670. #define first ((WORD *) void_first)
  671. #define second ((WORD *) void_second)
  672.   int length;            /* minimum of two lengths */
  673.   int counter;            /* cursor in words */
  674.   int value;            /* value of comparison */
  675.  
  676.   length = first->size < second->size ? first->size : second->size;
  677.  
  678.   if (ignore_case)
  679.     {
  680.       for (counter = 0; counter < length; counter++)
  681.     {
  682.       value = (folded_chars [(unsigned char) (first->start[counter])]
  683.            - folded_chars [(unsigned char) (second->start[counter])]);
  684.       if (value != 0)
  685.         return value;
  686.     }
  687.     }
  688.   else
  689.     {
  690.       for (counter = 0; counter < length; counter++)
  691.     {
  692.       value = ((unsigned char) first->start[counter]
  693.            - (unsigned char) second->start[counter]);
  694.       if (value != 0)
  695.         return value;
  696.     }
  697.     }
  698.  
  699.   return first->size - second->size;
  700. #undef first
  701. #undef second
  702. }
  703.  
  704. /*-----------------------------------------------------------------------.
  705. | Decides which of two OCCURS, FIRST or SECOND, should lexicographically |
  706. | go first.  In case of a tie, preserve the original order through a     |
  707. | pointer comparison.                             |
  708. `-----------------------------------------------------------------------*/
  709.  
  710. static int
  711. compare_occurs (const void *void_first, const void *void_second)
  712. {
  713. #define first ((OCCURS *) void_first)
  714. #define second ((OCCURS *) void_second)
  715.   int value;
  716.  
  717.   value = compare_words (&first->key, &second->key);
  718.   return value == 0 ? first->key.start - second->key.start : value;
  719. #undef first
  720. #undef second
  721. }
  722.  
  723. /*------------------------------------------------------------.
  724. | Return !0 if WORD appears in TABLE.  Uses a binary search.  |
  725. `------------------------------------------------------------*/
  726.  
  727. static int
  728. search_table (WORD *word, WORD_TABLE *table)
  729. {
  730.   int lowest;            /* current lowest possible index */
  731.   int highest;            /* current highest possible index */
  732.   int middle;            /* current middle index */
  733.   int value;            /* value from last comparison */
  734.  
  735.   lowest = 0;
  736.   highest = table->length - 1;
  737.   while (lowest <= highest)
  738.     {
  739.       middle = (lowest + highest) / 2;
  740.       value = compare_words (word, table->start + middle);
  741.       if (value < 0)
  742.     highest = middle - 1;
  743.       else if (value > 0)
  744.     lowest = middle + 1;
  745.       else
  746.     return 1;
  747.     }
  748.   return 0;
  749. }
  750.  
  751. /*---------------------------------------------------------------------.
  752. | Sort the whole occurs table in memory.  Presumably, `qsort' does not |
  753. | take intermediate copies or table elements, so the sort will be      |
  754. | stabilized throughout the comparison routine.                   |
  755. `---------------------------------------------------------------------*/
  756.  
  757. static void
  758. sort_found_occurs (void)
  759. {
  760.  
  761.   /* Only one language for the time being.  */
  762.  
  763.   qsort (occurs_table[0], number_of_occurs[0], sizeof (OCCURS),
  764.      compare_occurs);
  765. }
  766.  
  767. /* Parameter files reading routines.  */
  768.  
  769. /*----------------------------------------------------------------------.
  770. | Read a file named FILE_NAME, containing a set of break characters.    |
  771. | Build a content to the array word_fastmap in which all characters are |
  772. | allowed except those found in the file.  Characters may be repeated.  |
  773. `----------------------------------------------------------------------*/
  774.  
  775. static void
  776. digest_break_file (const char *file_name)
  777. {
  778.   BLOCK file_contents;        /* to receive a copy of the file */
  779.   char *cursor;            /* cursor in file copy */
  780.  
  781.   swallow_file_in_memory (file_name, &file_contents);
  782.  
  783.   /* Make the fastmap and record the file contents in it.  */
  784.  
  785.   memset (word_fastmap, 1, CHAR_SET_SIZE);
  786.   for (cursor = file_contents.start; cursor < file_contents.end; cursor++)
  787.     word_fastmap[(unsigned char) *cursor] = 0;
  788.  
  789.   if (!gnu_extensions)
  790.     {
  791.  
  792.       /* If GNU extensions are enabled, the only way to avoid newline as
  793.      a break character is to write all the break characters in the
  794.      file with no newline at all, not even at the end of the file.
  795.      If disabled, spaces, tabs and newlines are always considered as
  796.      break characters even if not included in the break file.  */
  797.  
  798.       word_fastmap[' '] = 0;
  799.       word_fastmap['\t'] = 0;
  800.       word_fastmap['\n'] = 0;
  801.     }
  802.  
  803.   /* Return the space of the file, which is no more required.  */
  804.  
  805.   free (file_contents.start);
  806. }
  807.  
  808. /*-----------------------------------------------------------------------.
  809. | Read a file named FILE_NAME, containing one word per line, then     |
  810. | construct in TABLE a table of WORD descriptors for them.  The routine     |
  811. | swallows the whole file in memory; this is at the expense of space     |
  812. | needed for newlines, which are useless; however, the reading is fast.     |
  813. `-----------------------------------------------------------------------*/
  814.  
  815. static void
  816. digest_word_file (const char *file_name, WORD_TABLE *table)
  817. {
  818.   BLOCK file_contents;        /* to receive a copy of the file */
  819.   char *cursor;            /* cursor in file copy */
  820.   char *word_start;        /* start of the current word */
  821.  
  822.   swallow_file_in_memory (file_name, &file_contents);
  823.  
  824.   table->start = NULL;
  825.   table->length = 0;
  826.  
  827.   /* Read the whole file.  */
  828.  
  829.   cursor = file_contents.start;
  830.   while (cursor < file_contents.end)
  831.     {
  832.  
  833.       /* Read one line, and save the word in contains.  */
  834.  
  835.       word_start = cursor;
  836.       while (cursor < file_contents.end && *cursor != '\n')
  837.     cursor++;
  838.  
  839.       /* Record the word in table if it is not empty.  */
  840.  
  841.       if (cursor > word_start)
  842.     {
  843.       ALLOC_NEW_WORD (table);
  844.       table->start[table->length].start = word_start;
  845.       table->start[table->length].size = cursor - word_start;
  846.       table->length++;
  847.     }
  848.  
  849.       /* This test allows for an incomplete line at end of file.  */
  850.  
  851.       if (cursor < file_contents.end)
  852.     cursor++;
  853.     }
  854.  
  855.   /* Finally, sort all the words read.  */
  856.  
  857.   qsort (table->start, table->length, (size_t) sizeof (WORD), compare_words);
  858. }
  859.  
  860. /* Keyword recognition and selection.  */
  861.  
  862. /*----------------------------------------------------------------------.
  863. | For each keyword in the source text, constructs an OCCURS structure.  |
  864. `----------------------------------------------------------------------*/
  865.  
  866. static void
  867. find_occurs_in_text (void)
  868. {
  869.   char *cursor;            /* for scanning the source text */
  870.   char *scan;            /* for scanning the source text also */
  871.   char *line_start;        /* start of the current input line */
  872.   char *line_scan;        /* newlines scanned until this point */
  873.   int reference_length;        /* length of reference in input mode */
  874.   WORD possible_key;        /* possible key, to ease searches */
  875.   OCCURS *occurs_cursor;    /* current OCCURS under construction */
  876.  
  877.   char *context_start;        /* start of left context */
  878.   char *context_end;        /* end of right context */
  879.   char *word_start;        /* start of word */
  880.   char *word_end;        /* end of word */
  881.   char *next_context_start;    /* next start of left context */
  882.  
  883.   /* reference_length is always used within `if (input_reference)'.
  884.      However, GNU C diagnoses that it may be used uninitialized.  The
  885.      following assignment is merely to shut it up.  */
  886.  
  887.   reference_length = 0;
  888.  
  889.   /* Tracking where lines start is helpful for reference processing.  In
  890.      auto reference mode, this allows counting lines.  In input reference
  891.      mode, this permits finding the beginning of the references.
  892.  
  893.      The first line begins with the file, skip immediately this very first
  894.      reference in input reference mode, to help further rejection any word
  895.      found inside it.  Also, unconditionally assigning these variable has
  896.      the happy effect of shutting up lint.  */
  897.  
  898.   line_start = text_buffer.start;
  899.   line_scan = line_start;
  900.   if (input_reference)
  901.     {
  902.       SKIP_NON_WHITE (line_scan, text_buffer.end);
  903.       reference_length = line_scan - line_start;
  904.       SKIP_WHITE (line_scan, text_buffer.end);
  905.     }
  906.  
  907.   /* Process the whole buffer, one line or one sentence at a time.  */
  908.  
  909.   for (cursor = text_buffer.start;
  910.        cursor < text_buffer.end;
  911.        cursor = next_context_start)
  912.     {
  913.  
  914.       /* `context_start' gets initialized before the processing of each
  915.      line, or once for the whole buffer if no end of line or sentence
  916.      sequence separator.  */
  917.  
  918.       context_start = cursor;
  919.  
  920.       /* If a end of line or end of sentence sequence is defined and
  921.      non-empty, `next_context_start' will be recomputed to be the end of
  922.      each line or sentence, before each one is processed.  If no such
  923.      sequence, then `next_context_start' is set at the end of the whole
  924.      buffer, which is then considered to be a single line or sentence.
  925.      This test also accounts for the case of an incomplete line or
  926.      sentence at the end of the buffer.  */
  927.  
  928.       if (context_regex_string
  929.       && (re_search (context_regex, cursor, text_buffer.end - cursor,
  930.              0, text_buffer.end - cursor, &context_regs)
  931.           >= 0))
  932.     next_context_start = cursor + context_regs.end[0];
  933.  
  934.       else
  935.     next_context_start = text_buffer.end;
  936.  
  937.       /* Include the separator into the right context, but not any suffix
  938.      white space in this separator; this insures it will be seen in
  939.      output and will not take more space than necessary.  */
  940.  
  941.       context_end = next_context_start;
  942.       SKIP_WHITE_BACKWARDS (context_end, context_start);
  943.  
  944.       /* Read and process a single input line or sentence, one word at a
  945.      time.  */
  946.  
  947.       while (1)
  948.     {
  949.       if (word_regex)
  950.  
  951.         /* If a word regexp has been compiled, use it to skip at the
  952.            beginning of the next word.  If there is no such word, exit
  953.            the loop.  */
  954.  
  955.         {
  956.           if (re_search (word_regex, cursor, context_end - cursor,
  957.                  0, context_end - cursor, &word_regs)
  958.           < 0)
  959.         break;
  960.           word_start = cursor + word_regs.start[0];
  961.           word_end = cursor + word_regs.end[0];
  962.         }
  963.       else
  964.  
  965.         /* Avoid re_search and use the fastmap to skip to the
  966.            beginning of the next word.  If there is no more word in
  967.            the buffer, exit the loop.  */
  968.  
  969.         {
  970.           scan = cursor;
  971.           while (scan < context_end
  972.              && !word_fastmap[(unsigned char) *scan])
  973.         scan++;
  974.  
  975.           if (scan == context_end)
  976.         break;
  977.  
  978.           word_start = scan;
  979.  
  980.           while (scan < context_end
  981.              && word_fastmap[(unsigned char) *scan])
  982.         scan++;
  983.  
  984.           word_end = scan;
  985.         }
  986.  
  987.       /* Skip right to the beginning of the found word.  */
  988.  
  989.       cursor = word_start;
  990.  
  991.       /* Skip any zero length word.  Just advance a single position,
  992.          then go fetch the next word.  */
  993.  
  994.       if (word_end == word_start)
  995.         {
  996.           cursor++;
  997.           continue;
  998.         }
  999.  
  1000.       /* This is a genuine, non empty word, so save it as a possible
  1001.          key.  Then skip over it.  Also, maintain the maximum length of
  1002.          all words read so far.  It is mandatory to take the maximum
  1003.          length of all words in the file, without considering if they
  1004.          are actually kept or rejected, because backward jumps at output
  1005.          generation time may fall in *any* word.  */
  1006.  
  1007.       possible_key.start = cursor;
  1008.       possible_key.size = word_end - word_start;
  1009.       cursor += possible_key.size;
  1010.  
  1011.       if (possible_key.size > maximum_word_length)
  1012.         maximum_word_length = possible_key.size;
  1013.  
  1014.       /* In input reference mode, update `line_start' from its previous
  1015.          value.  Count the lines just in case auto reference mode is
  1016.          also selected. If it happens that the word just matched is
  1017.          indeed part of a reference; just ignore it.  */
  1018.  
  1019.       if (input_reference)
  1020.         {
  1021.           while (line_scan < possible_key.start)
  1022.         if (*line_scan == '\n')
  1023.           {
  1024.             total_line_count++;
  1025.             line_scan++;
  1026.             line_start = line_scan;
  1027.             SKIP_NON_WHITE (line_scan, text_buffer.end);
  1028.             reference_length = line_scan - line_start;
  1029.           }
  1030.         else
  1031.           line_scan++;
  1032.           if (line_scan > possible_key.start)
  1033.         continue;
  1034.         }
  1035.  
  1036.       /* Ignore the word if an `Ignore words' table exists and if it is
  1037.          part of it.  Also ignore the word if an `Only words' table and
  1038.          if it is *not* part of it.
  1039.  
  1040.          It is allowed that both tables be used at once, even if this
  1041.          may look strange for now.  Just ignore a word that would appear
  1042.          in both.  If regexps are eventually implemented for these
  1043.          tables, the Ignore table could then reject words that would
  1044.          have been previously accepted by the Only table.  */
  1045.  
  1046.       if (ignore_file && search_table (&possible_key, &ignore_table))
  1047.         continue;
  1048.       if (only_file && !search_table (&possible_key, &only_table))
  1049.         continue;
  1050.  
  1051.       /* A non-empty word has been found.  First of all, insure
  1052.          proper allocation of the next OCCURS, and make a pointer to
  1053.          where it will be constructed.  */
  1054.  
  1055.       ALLOC_NEW_OCCURS (0);
  1056.       occurs_cursor = occurs_table[0] + number_of_occurs[0];
  1057.  
  1058.       /* Define the refence field, if any.  */
  1059.  
  1060.       if (auto_reference)
  1061.         {
  1062.  
  1063.           /* While auto referencing, update `line_start' from its
  1064.          previous value, counting lines as we go.  If input
  1065.          referencing at the same time, `line_start' has been
  1066.          advanced earlier, and the following loop is never really
  1067.          executed.  */
  1068.  
  1069.           while (line_scan < possible_key.start)
  1070.         if (*line_scan == '\n')
  1071.           {
  1072.             total_line_count++;
  1073.             line_scan++;
  1074.             line_start = line_scan;
  1075.             SKIP_NON_WHITE (line_scan, text_buffer.end);
  1076.           }
  1077.         else
  1078.           line_scan++;
  1079.  
  1080.           occurs_cursor->reference = total_line_count;
  1081.         }
  1082.       else if (input_reference)
  1083.         {
  1084.  
  1085.           /* If only input referencing, `line_start' has been computed
  1086.          earlier to detect the case the word matched would be part
  1087.          of the reference.  The reference position is simply the
  1088.          value of `line_start'.  */
  1089.  
  1090.           occurs_cursor->reference
  1091.         = (DELTA) (line_start - possible_key.start);
  1092.           if (reference_length > reference_max_width)
  1093.         reference_max_width = reference_length;
  1094.         }
  1095.  
  1096.       /* Exclude the reference from the context in simple cases.  */
  1097.  
  1098.       if (input_reference && line_start == context_start)
  1099.         {
  1100.           SKIP_NON_WHITE (context_start, context_end);
  1101.           SKIP_WHITE (context_start, context_end);
  1102.         }
  1103.  
  1104.       /* Completes the OCCURS structure.  */
  1105.  
  1106.       occurs_cursor->key = possible_key;
  1107.       occurs_cursor->left = context_start - possible_key.start;
  1108.       occurs_cursor->right = context_end - possible_key.start;
  1109.  
  1110.       number_of_occurs[0]++;
  1111.     }
  1112.     }
  1113. }
  1114.  
  1115. /* Formatting and actual output - service routines.  */
  1116.  
  1117. /*-----------------------------------------.
  1118. | Prints some NUMBER of spaces on stdout.  |
  1119. `-----------------------------------------*/
  1120.  
  1121. static void
  1122. print_spaces (int number)
  1123. {
  1124.   int counter;
  1125.  
  1126.   for (counter = number; counter > 0; counter--)
  1127.     putchar (' ');
  1128. }
  1129.  
  1130. /*-------------------------------------.
  1131. | Prints the field provided by FIELD.  |
  1132. `-------------------------------------*/
  1133.  
  1134. static void
  1135. print_field (BLOCK field)
  1136. {
  1137.   char *cursor;            /* Cursor in field to print */
  1138.   int character;        /* Current character */
  1139.   int base;            /* Base character, without diacritic */
  1140.   int diacritic;        /* Diacritic code for the character */
  1141.  
  1142.   /* Whitespace is not really compressed.  Instead, each white space
  1143.      character (tab, vt, ht etc.) is printed as one single space.  */
  1144.  
  1145.   for (cursor = field.start; cursor < field.end; cursor++)
  1146.     {
  1147.       character = (unsigned char) *cursor;
  1148.       if (edited_flag[character])
  1149.     {
  1150.  
  1151.       /* First check if this is a diacriticized character.
  1152.  
  1153.          This works only for TeX.  I do not know how diacriticized
  1154.          letters work with `roff'.  Please someone explain it to me!  */
  1155.  
  1156.       diacritic = todiac (character);
  1157.       if (diacritic != 0 && output_format == TEX_FORMAT)
  1158.         {
  1159.           base = tobase (character);
  1160.           switch (diacritic)
  1161.         {
  1162.  
  1163.         case 1:        /* Latin diphthongs */
  1164.           switch (base)
  1165.             {
  1166.             case 'o':
  1167.               printf ("\\oe{}");
  1168.               break;
  1169.  
  1170.             case 'O':
  1171.               printf ("\\OE{}");
  1172.               break;
  1173.  
  1174.             case 'a':
  1175.               printf ("\\ae{}");
  1176.               break;
  1177.  
  1178.             case 'A':
  1179.               printf ("\\AE{}");
  1180.               break;
  1181.  
  1182.             default:
  1183.               putchar (' ');
  1184.             }
  1185.           break;
  1186.  
  1187.         case 2:        /* Acute accent */
  1188.           printf ("\\'%s%c", (base == 'i' ? "\\" : ""), base);
  1189.           break;
  1190.  
  1191.         case 3:        /* Grave accent */
  1192.           printf ("\\`%s%c", (base == 'i' ? "\\" : ""), base);
  1193.           break;
  1194.  
  1195.         case 4:        /* Circumflex accent */
  1196.           printf ("\\^%s%c", (base == 'i' ? "\\" : ""), base);
  1197.           break;
  1198.  
  1199.         case 5:        /* Diaeresis */
  1200.           printf ("\\\"%s%c", (base == 'i' ? "\\" : ""), base);
  1201.           break;
  1202.  
  1203.         case 6:        /* Tilde accent */
  1204.           printf ("\\~%s%c", (base == 'i' ? "\\" : ""), base);
  1205.           break;
  1206.  
  1207.         case 7:        /* Cedilla */
  1208.           printf ("\\c{%c}", base);
  1209.           break;
  1210.  
  1211.         case 8:        /* Small circle beneath */
  1212.           switch (base)
  1213.             {
  1214.             case 'a':
  1215.               printf ("\\aa{}");
  1216.               break;
  1217.  
  1218.             case 'A':
  1219.               printf ("\\AA{}");
  1220.               break;
  1221.  
  1222.             default:
  1223.               putchar (' ');
  1224.             }
  1225.           break;
  1226.  
  1227.         case 9:        /* Strike through */
  1228.           switch (base)
  1229.             {
  1230.             case 'o':
  1231.               printf ("\\o{}");
  1232.               break;
  1233.  
  1234.             case 'O':
  1235.               printf ("\\O{}");
  1236.               break;
  1237.  
  1238.             default:
  1239.               putchar (' ');
  1240.             }
  1241.           break;
  1242.         }
  1243.         }
  1244.       else
  1245.  
  1246.         /* This is not a diacritic character, so handle cases which are
  1247.            really specific to `roff' or TeX.  All white space processing
  1248.            is done as the default case of this switch.  */
  1249.  
  1250.         switch (character)
  1251.           {
  1252.           case '"':
  1253.         /* In roff output format, double any quote.  */
  1254.         putchar ('"');
  1255.         putchar ('"');
  1256.         break;
  1257.  
  1258.           case '$':
  1259.           case '%':
  1260.           case '&':
  1261.           case '#':
  1262.           case '_':
  1263.         /* In TeX output format, precede these with a backslash.  */
  1264.         putchar ('\\');
  1265.         putchar (character);
  1266.         break;
  1267.  
  1268.           case '{':
  1269.           case '}':
  1270.         /* In TeX output format, precede these with a backslash and
  1271.            force mathematical mode.  */
  1272.         printf ("$\\%c$", character);
  1273.         break;
  1274.  
  1275.           case '\\':
  1276.         /* In TeX output mode, request production of a backslash.  */
  1277.         printf ("\\backslash{}");
  1278.         break;
  1279.  
  1280.           default:
  1281.         /* Any other flagged character produces a single space.  */
  1282.         putchar (' ');
  1283.           }
  1284.     }
  1285.       else
  1286.     putchar (*cursor);
  1287.     }
  1288. }
  1289.  
  1290. /* Formatting and actual output - planning routines.  */
  1291.  
  1292. /*--------------------------------------------------------------------.
  1293. | From information collected from command line options and input file |
  1294. | readings, compute and fix some output parameter values.          |
  1295. `--------------------------------------------------------------------*/
  1296.  
  1297. static void
  1298. fix_output_parameters (void)
  1299. {
  1300.   int file_index;        /* index in text input file arrays */
  1301.   int line_ordinal;        /* line ordinal value for reference */
  1302.   char ordinal_string[12];    /* edited line ordinal for reference */
  1303.   int reference_width;        /* width for the whole reference */
  1304.   int character;        /* character ordinal */
  1305.   const char *cursor;        /* cursor in some constant strings */
  1306.  
  1307.   /* In auto reference mode, the maximum width of this field is
  1308.      precomputed and subtracted from the overall line width.  Add one for
  1309.      the column which separate the file name from the line number.  */
  1310.  
  1311.   if (auto_reference)
  1312.     {
  1313.       reference_max_width = 0;
  1314.       for (file_index = 0; file_index < number_input_files; file_index++)
  1315.     {
  1316.       line_ordinal = file_line_count[file_index] + 1;
  1317.       if (file_index > 0)
  1318.         line_ordinal -= file_line_count[file_index - 1];
  1319.       sprintf (ordinal_string, "%d", line_ordinal);
  1320.       reference_width = strlen (ordinal_string);
  1321.       if (input_file_name[file_index])
  1322.         reference_width += strlen (input_file_name[file_index]);
  1323.       if (reference_width > reference_max_width)
  1324.         reference_max_width = reference_width;
  1325.     }
  1326.       reference_max_width++;
  1327.       reference.start = (char *) xmalloc (reference_max_width + 1);
  1328.     }
  1329.  
  1330.   /* If the reference appears to the left of the output line, reserve some
  1331.      space for it right away, including one gap size.  */
  1332.  
  1333.   if ((auto_reference || input_reference) && !right_reference)
  1334.     line_width -= reference_max_width + gap_size;
  1335.  
  1336.   /* The output lines, minimally, will contain from left to right a left
  1337.      context, a gap, and a keyword followed by the right context with no
  1338.      special intervening gap.  Half of the line width is dedicated to the
  1339.      left context and the gap, the other half is dedicated to the keyword
  1340.      and the right context; these values are computed once and for all here.
  1341.      There also are tail and head wrap around fields, used when the keyword
  1342.      is near the beginning or the end of the line, or when some long word
  1343.      cannot fit in, but leave place from wrapped around shorter words.  The
  1344.      maximum width of these fields are recomputed separately for each line,
  1345.      on a case by case basis.  It is worth noting that it cannot happen that
  1346.      both the tail and head fields are used at once.  */
  1347.  
  1348.   half_line_width = line_width / 2;
  1349.   before_max_width = half_line_width - gap_size;
  1350.   keyafter_max_width = half_line_width;
  1351.  
  1352.   /* If truncation_string is the empty string, make it NULL to speed up
  1353.      tests.  In this case, truncation_string_length will never get used, so
  1354.      there is no need to set it.  */
  1355.  
  1356.   if (truncation_string && *truncation_string)
  1357.     truncation_string_length = strlen (truncation_string);
  1358.   else
  1359.     truncation_string = NULL;
  1360.  
  1361.   if (gnu_extensions)
  1362.     {
  1363.  
  1364.       /* When flagging truncation at the left of the keyword, the
  1365.      truncation mark goes at the beginning of the before field,
  1366.      unless there is a head field, in which case the mark goes at the
  1367.      left of the head field.  When flagging truncation at the right
  1368.      of the keyword, the mark goes at the end of the keyafter field,
  1369.      unless there is a tail field, in which case the mark goes at the
  1370.      end of the tail field.  Only eight combination cases could arise
  1371.      for truncation marks:
  1372.  
  1373.      . None.
  1374.      . One beginning the before field.
  1375.      . One beginning the head field.
  1376.      . One ending the keyafter field.
  1377.      . One ending the tail field.
  1378.      . One beginning the before field, another ending the keyafter field.
  1379.      . One ending the tail field, another beginning the before field.
  1380.      . One ending the keyafter field, another beginning the head field. 
  1381.      
  1382.      So, there is at most two truncation marks, which could appear both
  1383.      on the left side of the center of the output line, both on the
  1384.      right side, or one on either side.  */
  1385.  
  1386.       before_max_width -= 2 * truncation_string_length;
  1387.       keyafter_max_width -= 2 * truncation_string_length;
  1388.     }
  1389.   else
  1390.     {
  1391.  
  1392.       /* I never figured out exactly how UNIX' ptx plans the output width
  1393.      of its various fields.  If GNU extensions are disabled, do not
  1394.      try computing the field widths correctly; instead, use the
  1395.      following formula, which does not completely imitate UNIX' ptx,
  1396.      but almost.  */
  1397.  
  1398.       keyafter_max_width -= 2 * truncation_string_length + 1;
  1399.     }
  1400.  
  1401.   /* Compute which characters need special output processing.  Initialize
  1402.      by flagging any white space character.  Some systems do not consider
  1403.      form feed as a space character, but we do.  */
  1404.  
  1405.   for (character = 0; character < CHAR_SET_SIZE; character++)
  1406.     edited_flag[character] = isspace (character);
  1407.   edited_flag['\f'] = 1;
  1408.  
  1409.   /* Complete the special character flagging according to selected output
  1410.      format.  */
  1411.  
  1412.   switch (output_format)
  1413.     {
  1414.     case UNKNOWN_FORMAT:
  1415.       /* Should never happen.  */
  1416.  
  1417.     case DUMB_FORMAT:
  1418.       break;
  1419.  
  1420.     case ROFF_FORMAT:
  1421.  
  1422.       /* `Quote' characters should be doubled.  */
  1423.  
  1424.       edited_flag['"'] = 1;
  1425.       break;
  1426.  
  1427.     case TEX_FORMAT:
  1428.  
  1429.       /* Various characters need special processing.  */
  1430.  
  1431.       for (cursor = "$%&#_{}\\"; *cursor; cursor++)
  1432.     edited_flag[*cursor] = 1;
  1433.  
  1434.       /* Any character with 8th bit set will print to a single space, unless
  1435.      it is diacriticized.  */
  1436.  
  1437.       for (character = 0200; character < CHAR_SET_SIZE; character++)
  1438.     edited_flag[character] = todiac (character) != 0;
  1439.       break;
  1440.     }
  1441. }
  1442.  
  1443. /*------------------------------------------------------------------.
  1444. | Compute the position and length of all the output fields, given a |
  1445. | pointer to some OCCURS.                        |
  1446. `------------------------------------------------------------------*/
  1447.  
  1448. static void
  1449. define_all_fields (OCCURS *occurs)
  1450. {
  1451.   int tail_max_width;        /* allowable width of tail field */
  1452.   int head_max_width;        /* allowable width of head field */
  1453.   char *cursor;            /* running cursor in source text */
  1454.   char *left_context_start;    /* start of left context */
  1455.   char *right_context_end;    /* end of right context */
  1456.   char *left_field_start;    /* conservative start for `head'/`before' */
  1457.   int file_index;        /* index in text input file arrays */
  1458.   const char *file_name;        /* file name for reference */
  1459.   int line_ordinal;        /* line ordinal for reference */
  1460.  
  1461.   /* Define `keyafter', start of left context and end of right context.
  1462.      `keyafter' starts at the saved position for keyword and extend to the
  1463.      right from the end of the keyword, eating separators or full words, but
  1464.      not beyond maximum allowed width for `keyafter' field or limit for the
  1465.      right context.  Suffix spaces will be removed afterwards.  */
  1466.  
  1467.   keyafter.start = occurs->key.start;
  1468.   keyafter.end = keyafter.start + occurs->key.size;
  1469.   left_context_start = keyafter.start + occurs->left;
  1470.   right_context_end = keyafter.start + occurs->right;
  1471.  
  1472.   cursor = keyafter.end;
  1473.   while (cursor < right_context_end
  1474.      && cursor <= keyafter.start + keyafter_max_width)
  1475.     {
  1476.       keyafter.end = cursor;
  1477.       SKIP_SOMETHING (cursor, right_context_end);
  1478.     }
  1479.   if (cursor <= keyafter.start + keyafter_max_width)
  1480.     keyafter.end = cursor;
  1481.  
  1482.   keyafter_truncation = truncation_string && keyafter.end < right_context_end;
  1483.  
  1484.   SKIP_WHITE_BACKWARDS (keyafter.end, keyafter.start);
  1485.  
  1486.   /* When the left context is wide, it might take some time to catch up from
  1487.      the left context boundary to the beginning of the `head' or `before'
  1488.      fields.  So, in this case, to speed the catchup, we jump back from the
  1489.      keyword, using some secure distance, possibly falling in the middle of
  1490.      a word.  A secure backward jump would be at least half the maximum
  1491.      width of a line, plus the size of the longest word met in the whole
  1492.      input.  We conclude this backward jump by a skip forward of at least
  1493.      one word.  In this manner, we should not inadvertently accept only part
  1494.      of a word.  From the reached point, when it will be time to fix the
  1495.      beginning of `head' or `before' fields, we will skip forward words or
  1496.      delimiters until we get sufficiently near.  */
  1497.  
  1498.   if (-occurs->left > half_line_width + maximum_word_length)
  1499.     {
  1500.       left_field_start
  1501.     = keyafter.start - (half_line_width + maximum_word_length);
  1502.       SKIP_SOMETHING (left_field_start, keyafter.start);
  1503.     }
  1504.   else
  1505.     left_field_start = keyafter.start + occurs->left;
  1506.  
  1507.   /* `before' certainly ends at the keyword, but not including separating
  1508.      spaces.  It starts after than the saved value for the left context, by
  1509.      advancing it until it falls inside the maximum allowed width for the
  1510.      before field.  There will be no prefix spaces either.  `before' only
  1511.      advances by skipping single separators or whole words. */
  1512.  
  1513.   before.start = left_field_start;
  1514.   before.end = keyafter.start;
  1515.   SKIP_WHITE_BACKWARDS (before.end, before.start);
  1516.  
  1517.   while (before.start + before_max_width < before.end)
  1518.     SKIP_SOMETHING (before.start, before.end);
  1519.  
  1520.   if (truncation_string)
  1521.     {
  1522.       cursor = before.start;
  1523.       SKIP_WHITE_BACKWARDS (cursor, text_buffer.start);
  1524.       before_truncation = cursor > left_context_start;
  1525.     }
  1526.   else
  1527.     before_truncation = 0;
  1528.  
  1529.   SKIP_WHITE (before.start, text_buffer.end);
  1530.  
  1531.   /* The tail could not take more columns than what has been left in the
  1532.      left context field, and a gap is mandatory.  It starts after the
  1533.      right context, and does not contain prefixed spaces.  It ends at
  1534.      the end of line, the end of buffer or when the tail field is full,
  1535.      whichever comes first.  It cannot contain only part of a word, and
  1536.      has no suffixed spaces.  */
  1537.  
  1538.   tail_max_width
  1539.     = before_max_width - (before.end - before.start) - gap_size;
  1540.  
  1541.   if (tail_max_width > 0)
  1542.     {
  1543.       tail.start = keyafter.end;
  1544.       SKIP_WHITE (tail.start, text_buffer.end);
  1545.  
  1546.       tail.end = tail.start;
  1547.       cursor = tail.end;
  1548.       while (cursor < right_context_end
  1549.          && cursor < tail.start + tail_max_width)
  1550.     {
  1551.       tail.end = cursor;
  1552.       SKIP_SOMETHING (cursor, right_context_end);
  1553.     }
  1554.  
  1555.       if (cursor < tail.start + tail_max_width)
  1556.     tail.end = cursor;
  1557.  
  1558.       if (tail.end > tail.start)
  1559.     {
  1560.       keyafter_truncation = 0;
  1561.       tail_truncation = truncation_string && tail.end < right_context_end;
  1562.     }
  1563.       else
  1564.     tail_truncation = 0;
  1565.  
  1566.       SKIP_WHITE_BACKWARDS (tail.end, tail.start);
  1567.     }
  1568.   else
  1569.     {
  1570.  
  1571.       /* No place left for a tail field.  */
  1572.  
  1573.       tail.start = NULL;
  1574.       tail.end = NULL;
  1575.       tail_truncation = 0;
  1576.     }
  1577.  
  1578.   /* `head' could not take more columns than what has been left in the right
  1579.      context field, and a gap is mandatory.  It ends before the left
  1580.      context, and does not contain suffixed spaces.  Its pointer is advanced
  1581.      until the head field has shrunk to its allowed width.  It cannot
  1582.      contain only part of a word, and has no suffixed spaces.  */
  1583.  
  1584.   head_max_width
  1585.     = keyafter_max_width - (keyafter.end - keyafter.start) - gap_size;
  1586.  
  1587.   if (head_max_width > 0)
  1588.     {
  1589.       head.end = before.start;
  1590.       SKIP_WHITE_BACKWARDS (head.end, text_buffer.start);
  1591.  
  1592.       head.start = left_field_start;
  1593.       while (head.start + head_max_width < head.end)
  1594.     SKIP_SOMETHING (head.start, head.end);
  1595.  
  1596.       if (head.end > head.start)
  1597.     {
  1598.       before_truncation = 0;
  1599.       head_truncation = (truncation_string
  1600.                  && head.start > left_context_start);
  1601.     }
  1602.       else
  1603.     head_truncation = 0;
  1604.  
  1605.       SKIP_WHITE (head.start, head.end);
  1606.     }
  1607.   else
  1608.     {
  1609.  
  1610.       /* No place left for a head field.  */
  1611.  
  1612.       head.start = NULL;
  1613.       head.end = NULL;
  1614.       head_truncation = 0;
  1615.     }
  1616.  
  1617.   if (auto_reference)
  1618.     {
  1619.  
  1620.       /* Construct the reference text in preallocated space from the file
  1621.      name and the line number.  Find out in which file the reference
  1622.      occurred.  Standard input yields an empty file name.  Insure line
  1623.      numbers are one based, even if they are computed zero based.  */
  1624.  
  1625.       file_index = 0;
  1626.       while (file_line_count[file_index] < occurs->reference)
  1627.     file_index++;
  1628.  
  1629.       file_name = input_file_name[file_index];
  1630.       if (!file_name)
  1631.     file_name = "";
  1632.  
  1633.       line_ordinal = occurs->reference + 1;
  1634.       if (file_index > 0)
  1635.     line_ordinal -= file_line_count[file_index - 1];
  1636.  
  1637.       sprintf (reference.start, "%s:%d", file_name, line_ordinal);
  1638.       reference.end = reference.start + strlen (reference.start);
  1639.     }
  1640.   else if (input_reference)
  1641.     {
  1642.  
  1643.       /* Reference starts at saved position for reference and extends right
  1644.      until some white space is met.  */
  1645.  
  1646.       reference.start = keyafter.start + (DELTA) occurs->reference;
  1647.       reference.end = reference.start;
  1648.       SKIP_NON_WHITE (reference.end, right_context_end);
  1649.     }
  1650. }
  1651.  
  1652. /* Formatting and actual output - control routines.  */
  1653.  
  1654. /*----------------------------------------------------------------------.
  1655. | Output the current output fields as one line for `troff' or `nroff'.  |
  1656. `----------------------------------------------------------------------*/
  1657.  
  1658. static void
  1659. output_one_roff_line (void)
  1660. {
  1661.   /* Output the `tail' field.  */
  1662.  
  1663.   printf (".%s \"", macro_name);
  1664.   print_field (tail);
  1665.   if (tail_truncation)
  1666.     printf ("%s", truncation_string);
  1667.   putchar ('"');
  1668.  
  1669.   /* Output the `before' field.  */
  1670.  
  1671.   printf (" \"");
  1672.   if (before_truncation)
  1673.     printf ("%s", truncation_string);
  1674.   print_field (before);
  1675.   putchar ('"');
  1676.  
  1677.   /* Output the `keyafter' field.  */
  1678.  
  1679.   printf (" \"");
  1680.   print_field (keyafter);
  1681.   if (keyafter_truncation)
  1682.     printf ("%s", truncation_string);
  1683.   putchar ('"');
  1684.  
  1685.   /* Output the `head' field.  */
  1686.  
  1687.   printf (" \"");
  1688.   if (head_truncation)
  1689.     printf ("%s", truncation_string);
  1690.   print_field (head);
  1691.   putchar ('"');
  1692.  
  1693.   /* Conditionally output the `reference' field.  */
  1694.  
  1695.   if (auto_reference || input_reference)
  1696.     {
  1697.       printf (" \"");
  1698.       print_field (reference);
  1699.       putchar ('"');
  1700.     }
  1701.  
  1702.   putchar ('\n');
  1703. }
  1704.  
  1705. /*---------------------------------------------------------.
  1706. | Output the current output fields as one line for `TeX'.  |
  1707. `---------------------------------------------------------*/
  1708.  
  1709. static void
  1710. output_one_tex_line (void)
  1711. {
  1712.   BLOCK key;            /* key field, isolated */
  1713.   BLOCK after;            /* after field, isolated */
  1714.   char *cursor;            /* running cursor in source text */
  1715.  
  1716.   printf ("\\%s ", macro_name);
  1717.   printf ("{");
  1718.   print_field (tail);
  1719.   printf ("}{");
  1720.   print_field (before);
  1721.   printf ("}{");
  1722.   key.start = keyafter.start;
  1723.   after.end = keyafter.end;
  1724.   cursor = keyafter.start;
  1725.   SKIP_SOMETHING (cursor, keyafter.end);
  1726.   key.end = cursor;
  1727.   after.start = cursor;
  1728.   print_field (key);
  1729.   printf ("}{");
  1730.   print_field (after);
  1731.   printf ("}{");
  1732.   print_field (head);
  1733.   printf ("}");
  1734.   if (auto_reference || input_reference)
  1735.     {
  1736.       printf ("{");
  1737.       print_field (reference);
  1738.       printf ("}");
  1739.     }
  1740.   printf ("\n");
  1741. }
  1742.  
  1743. /*-------------------------------------------------------------------.
  1744. | Output the current output fields as one line for a dumb terminal.  |
  1745. `-------------------------------------------------------------------*/
  1746.  
  1747. static void
  1748. output_one_dumb_line (void)
  1749. {
  1750.   if (!right_reference)
  1751.     if (auto_reference)
  1752.       {
  1753.  
  1754.         /* Output the `reference' field, in such a way that GNU emacs
  1755.            next-error will handle it.  The ending colon is taken from the
  1756.            gap which follows.  */
  1757.  
  1758.     print_field (reference);
  1759.     putchar (':');
  1760.     print_spaces (reference_max_width
  1761.               + gap_size
  1762.               - (reference.end - reference.start)
  1763.               - 1);
  1764.       }
  1765.     else
  1766.       {
  1767.  
  1768.     /* Output the `reference' field and its following gap.  */
  1769.  
  1770.     print_field (reference);
  1771.     print_spaces (reference_max_width
  1772.             + gap_size
  1773.             - (reference.end - reference.start));
  1774.       }
  1775.  
  1776.   if (tail.start < tail.end)
  1777.     {
  1778.       /* Output the `tail' field.  */
  1779.  
  1780.       print_field (tail);
  1781.       if (tail_truncation)
  1782.     printf ("%s", truncation_string);
  1783.  
  1784.       print_spaces (half_line_width - gap_size
  1785.             - (before.end - before.start)
  1786.             - (before_truncation ? truncation_string_length : 0)
  1787.             - (tail.end - tail.start)
  1788.             - (tail_truncation ? truncation_string_length : 0));
  1789.     }
  1790.   else
  1791.     print_spaces (half_line_width - gap_size
  1792.           - (before.end - before.start)
  1793.           - (before_truncation ? truncation_string_length : 0));
  1794.  
  1795.   /* Output the `before' field.  */
  1796.  
  1797.   if (before_truncation)
  1798.     printf ("%s", truncation_string);
  1799.   print_field (before);
  1800.  
  1801.   print_spaces (gap_size);
  1802.  
  1803.   /* Output the `keyafter' field.  */
  1804.  
  1805.   print_field (keyafter);
  1806.   if (keyafter_truncation)
  1807.     printf ("%s", truncation_string);
  1808.  
  1809.   if (head.start < head.end)
  1810.     {
  1811.       /* Output the `head' field.  */
  1812.  
  1813.       print_spaces (half_line_width
  1814.             - (keyafter.end - keyafter.start)
  1815.             - (keyafter_truncation ? truncation_string_length : 0)
  1816.             - (head.end - head.start)
  1817.             - (head_truncation ? truncation_string_length : 0));
  1818.       if (head_truncation)
  1819.     printf ("%s", truncation_string);
  1820.       print_field (head);
  1821.     }
  1822.   else
  1823.  
  1824.     if ((auto_reference || input_reference) && right_reference)
  1825.       print_spaces (half_line_width
  1826.             - (keyafter.end - keyafter.start)
  1827.             - (keyafter_truncation ? truncation_string_length : 0));
  1828.  
  1829.   if ((auto_reference || input_reference) && right_reference)
  1830.     {
  1831.       /* Output the `reference' field.  */
  1832.  
  1833.       print_spaces (gap_size);
  1834.       print_field (reference);
  1835.     }
  1836.  
  1837.   printf ("\n");
  1838. }
  1839.  
  1840. /*------------------------------------------------------------------------.
  1841. | Scan the whole occurs table and, for each entry, output one line in the |
  1842. | appropriate format.                              |
  1843. `------------------------------------------------------------------------*/
  1844.  
  1845. static void
  1846. generate_all_output (void)
  1847. {
  1848.   int occurs_index;        /* index of keyword entry being processed */
  1849.   OCCURS *occurs_cursor;    /* current keyword entry being processed */
  1850.  
  1851.  
  1852.   /* The following assignments are useful to provide default values in case
  1853.      line contexts or references are not used, in which case these variables
  1854.      would never be computed.  */
  1855.  
  1856.   tail.start = NULL;
  1857.   tail.end = NULL;
  1858.   tail_truncation = 0;
  1859.  
  1860.   head.start = NULL;
  1861.   head.end = NULL;
  1862.   head_truncation = 0;
  1863.  
  1864.  
  1865.   /* Loop over all keyword occurrences.  */
  1866.  
  1867.   occurs_cursor = occurs_table[0];
  1868.  
  1869.   for (occurs_index = 0; occurs_index < number_of_occurs[0]; occurs_index++)
  1870.     {
  1871.       /* Compute the exact size of every field and whenever truncation flags
  1872.      are present or not.  */
  1873.  
  1874.       define_all_fields (occurs_cursor);
  1875.  
  1876.       /* Produce one output line according to selected format.  */
  1877.  
  1878.       switch (output_format)
  1879.     {
  1880.     case UNKNOWN_FORMAT:
  1881.       /* Should never happen.  */
  1882.  
  1883.     case DUMB_FORMAT:
  1884.       output_one_dumb_line ();
  1885.       break;
  1886.  
  1887.     case ROFF_FORMAT:
  1888.       output_one_roff_line ();
  1889.       break;
  1890.  
  1891.     case TEX_FORMAT:
  1892.       output_one_tex_line ();
  1893.       break;
  1894.     }
  1895.  
  1896.       /* Advance the cursor into the occurs table.  */
  1897.  
  1898.       occurs_cursor++;
  1899.     }
  1900. }
  1901.  
  1902. /* Option decoding and main program.  */
  1903.  
  1904. /*------------------------------------------------------.
  1905. | Print program identification and options, then exit.  |
  1906. `------------------------------------------------------*/
  1907.  
  1908. static void
  1909. usage (int status)
  1910. {
  1911.   if (status != EXIT_SUCCESS)
  1912.     fprintf (stderr, "Try `%s --help' for more information.\n", program_name);
  1913.   else
  1914.     {
  1915.       printf ("\
  1916. Usage: %s [OPTION]... [INPUT]...   (without -G)\n\
  1917.   or:  %s -G [OPTION]... [INPUT [OUTPUT]]\n", program_name, program_name);
  1918.       printf ("\
  1919. Mandatory arguments to long options are mandatory for short options too.\n\
  1920. \n\
  1921.   -A, --auto-reference           output automatically generated references\n\
  1922.   -C, --copyright                display Copyright and copying conditions\n\
  1923.   -G, --traditional              behave more like System V `ptx'\n\
  1924.   -F, --flag-truncation=STRING   use STRING for flagging line truncations\n\
  1925.   -M, --macro-name=STRING        macro name to use instead of `xx'\n\
  1926.   -O, --format=roff              generate output as roff directives\n\
  1927.   -R, --right-side-refs          put references at right, not counted in -w\n\
  1928.   -S, --sentence-regexp=REGEXP   for end of lines or end of sentences\n\
  1929.   -T, --format=tex               generate output as TeX directives\n\
  1930.   -W, --word-regexp=REGEXP       use REGEXP to match each keyword\n\
  1931.   -b, --break-file=FILE          word break characters in this FILE\n\
  1932.   -f, --ignore-case              fold lower case to upper case for sorting\n\
  1933.   -g, --gap-size=NUMBER          gap size in columns between output fields\n\
  1934.   -i, --ignore-file=FILE         read ignore word list from FILE\n\
  1935.   -o, --only-file=FILE           read only word list from this FILE\n\
  1936.   -r, --references               first field of each line is a reference\n\
  1937.   -t, --typeset-mode               - not implemented -\n\
  1938.   -w, --width=NUMBER             output width in columns, reference excluded\n\
  1939.       --help                     display this help and exit\n\
  1940.       --version                  output version information and exit\n\
  1941. \n\
  1942. With no FILE or if FILE is -, read Standard Input.  `-F /' by default.\n");
  1943.     }
  1944.   exit (status);
  1945. }
  1946.  
  1947. /*----------------------------------------------------------------------.
  1948. | Main program.  Decode ARGC arguments passed through the ARGV array of |
  1949. | strings, then launch execution.                        |
  1950. `----------------------------------------------------------------------*/
  1951.  
  1952. /* Long options equivalences.  */
  1953. static const struct option long_options[] =
  1954. {
  1955.   {"auto-reference", no_argument, NULL, 'A'},
  1956.   {"break-file", required_argument, NULL, 'b'},
  1957.   {"copyright", no_argument, NULL, 'C'},
  1958.   {"flag-truncation", required_argument, NULL, 'F'},
  1959.   {"ignore-case", no_argument, NULL, 'f'},
  1960.   {"gap-size", required_argument, NULL, 'g'},
  1961.   {"help", no_argument, &show_help, 1},
  1962.   {"ignore-file", required_argument, NULL, 'i'},
  1963.   {"macro-name", required_argument, NULL, 'M'},
  1964.   {"only-file", required_argument, NULL, 'o'},
  1965.   {"references", no_argument, NULL, 'r'},
  1966.   {"right-side-refs", no_argument, NULL, 'R'},
  1967.   {"format", required_argument, NULL, 10},
  1968.   {"sentence-regexp", required_argument, NULL, 'S'},
  1969.   {"traditional", no_argument, NULL, 'G'},
  1970.   {"typeset-mode", no_argument, NULL, 't'},
  1971.   {"version", no_argument, &show_version, 1},
  1972.   {"width", required_argument, NULL, 'w'},
  1973.   {"word-regexp", required_argument, NULL, 'W'},
  1974.   {0, 0, 0, 0},
  1975. };
  1976.  
  1977. static char const* const format_args[] =
  1978. {
  1979.   "roff", "tex", 0
  1980. };
  1981.  
  1982. int
  1983. main (int argc, char *const argv[])
  1984. {
  1985.   int optchar;            /* argument character */
  1986.   extern int optind;        /* index of argument */
  1987.   extern char *optarg;        /* value or argument */
  1988.   int file_index;        /* index in text input file arrays */
  1989.  
  1990. #if STDC_HEADERS && HAVE_SETCHRCLASS
  1991.   setchrclass (NULL);
  1992. #endif
  1993.  
  1994.   /* Decode program options.  */
  1995.  
  1996.   program_name = strrchr (argv[0], '/');
  1997.   if (program_name == NULL)
  1998.     program_name = argv[0];
  1999.   else
  2000.     program_name++;
  2001.   
  2002.   while (optchar = getopt_long (argc, argv, "ACF:GM:ORS:TW:b:i:fg:o:trw:",
  2003.                 long_options, NULL),
  2004.      optchar != EOF)
  2005.     {
  2006.       switch (optchar)
  2007.     {
  2008.     default:
  2009.       usage (EXIT_FAILURE);
  2010.  
  2011.     case 0:
  2012.       break;
  2013.  
  2014.     case 'C':
  2015.       printf ("%s", copyright_string);
  2016.       exit (EXIT_SUCCESS);
  2017.  
  2018.     case 'G':
  2019.       gnu_extensions = 0;
  2020.       break;
  2021.  
  2022.     case 'b':
  2023.       break_file = optarg;
  2024.       break;
  2025.  
  2026.     case 'f':
  2027.       ignore_case = 1;
  2028.       break;
  2029.  
  2030.     case 'g':
  2031.       gap_size = atoi (optarg);
  2032.       break;
  2033.  
  2034.     case 'i':
  2035.       ignore_file = optarg;
  2036.       break;
  2037.  
  2038.     case 'o':
  2039.       only_file = optarg;
  2040.       break;
  2041.  
  2042.     case 'r':
  2043.       input_reference = 1;
  2044.       break;
  2045.  
  2046.     case 't':
  2047.       /* A decouvrir...  */
  2048.       break;
  2049.  
  2050.     case 'w':
  2051.       line_width = atoi (optarg);
  2052.       break;
  2053.  
  2054.     case 'A':
  2055.       auto_reference = 1;
  2056.       break;
  2057.  
  2058.     case 'F':
  2059.       truncation_string = copy_unescaped_string (optarg);
  2060.       break;
  2061.  
  2062.     case 'M':
  2063.       macro_name = optarg;
  2064.       break;
  2065.  
  2066.     case 'O':
  2067.       output_format = ROFF_FORMAT;
  2068.       break;
  2069.  
  2070.     case 'R':
  2071.       right_reference = 1;
  2072.       break;
  2073.  
  2074.     case 'S':
  2075.       context_regex_string = copy_unescaped_string (optarg);
  2076.       break;
  2077.  
  2078.     case 'T':
  2079.       output_format = TEX_FORMAT;
  2080.       break;
  2081.  
  2082.     case 'W':
  2083.       word_regex_string = copy_unescaped_string (optarg);
  2084.       break;
  2085.  
  2086.     case 10:
  2087.       switch (argmatch (optarg, format_args))
  2088.         {
  2089.         default:
  2090.           usage (EXIT_FAILURE);
  2091.  
  2092.         case 0:
  2093.           output_format = ROFF_FORMAT;
  2094.           break;
  2095.  
  2096.         case 1:
  2097.           output_format = TEX_FORMAT;
  2098.           break;
  2099.         }
  2100.     }
  2101.     }
  2102.  
  2103.   /* Process trivial options.  */
  2104.  
  2105.   if (show_help)
  2106.     usage (EXIT_SUCCESS);
  2107.  
  2108.   if (show_version)
  2109.     {
  2110.       printf ("GNU %s %s\n", PRODUCT, VERSION);
  2111.       exit (EXIT_SUCCESS);
  2112.     }
  2113.  
  2114.   /* Change the default Ignore file if one is defined.  */
  2115.  
  2116. #ifdef DEFAULT_IGNORE_FILE
  2117.   if (!ignore_file)
  2118.     ignore_file = DEFAULT_IGNORE_FILE;
  2119. #endif
  2120.  
  2121.   /* Process remaining arguments.  If GNU extensions are enabled, process
  2122.      all arguments as input parameters.  If disabled, accept at most two
  2123.      arguments, the second of which is an output parameter.  */
  2124.  
  2125.   if (optind == argc)
  2126.     {
  2127.  
  2128.       /* No more argument simply means: read standard input.  */
  2129.  
  2130.       input_file_name = (const char **) xmalloc (sizeof (const char *));
  2131.       file_line_count = (int *) xmalloc (sizeof (int));
  2132.       number_input_files = 1;
  2133.       input_file_name[0] = NULL;
  2134.     }
  2135.   else if (gnu_extensions)
  2136.     {
  2137.       number_input_files = argc - optind;
  2138.       input_file_name
  2139.     = (const char **) xmalloc (number_input_files * sizeof (const char *));
  2140.       file_line_count
  2141.     = (int *) xmalloc (number_input_files * sizeof (int));
  2142.  
  2143.       for (file_index = 0; file_index < number_input_files; file_index++)
  2144.     {
  2145.       input_file_name[file_index] = argv[optind];
  2146.       if (!*argv[optind] || strcmp (argv[optind], "-") == 0)
  2147.         input_file_name[0] = NULL;
  2148.       else
  2149.         input_file_name[0] = argv[optind];
  2150.       optind++;
  2151.     }
  2152.     }
  2153.   else
  2154.     {
  2155.  
  2156.       /* There is one necessary input file.  */
  2157.  
  2158.       number_input_files = 1;
  2159.       input_file_name = (const char **) xmalloc (sizeof (const char *));
  2160.       file_line_count = (int *) xmalloc (sizeof (int));
  2161.       if (!*argv[optind] || strcmp (argv[optind], "-") == 0)
  2162.     input_file_name[0] = NULL;
  2163.       else
  2164.     input_file_name[0] = argv[optind];
  2165.       optind++;
  2166.  
  2167.       /* Redirect standard output, only if requested.  */
  2168.  
  2169.       if (optind < argc)
  2170.     {
  2171.       fclose (stdout);
  2172.       if (fopen (argv[optind], "w") == NULL)
  2173.         error (1, errno, argv[optind]);
  2174.       optind++;
  2175.     }
  2176.  
  2177.       /* Diagnose any other argument as an error.  */
  2178.  
  2179.       if (optind < argc)
  2180.     usage (EXIT_FAILURE);
  2181.     }
  2182.  
  2183.   /* If the output format has not been explicitly selected, choose dumb
  2184.      terminal format if GNU extensions are enabled, else `roff' format.  */
  2185.  
  2186.   if (output_format == UNKNOWN_FORMAT)
  2187.     output_format = gnu_extensions ? DUMB_FORMAT : ROFF_FORMAT;
  2188.  
  2189.   /* Initialize the main tables.  */
  2190.  
  2191.   initialize_regex ();
  2192.  
  2193.   /* Read `Break character' file, if any.  */
  2194.  
  2195.   if (break_file)
  2196.     digest_break_file (break_file);
  2197.  
  2198.   /* Read `Ignore words' file and `Only words' files, if any.  If any of
  2199.      these files is empty, reset the name of the file to NULL, to avoid
  2200.      unnecessary calls to search_table. */
  2201.  
  2202.   if (ignore_file)
  2203.     {
  2204.       digest_word_file (ignore_file, &ignore_table);
  2205.       if (ignore_table.length == 0)
  2206.     ignore_file = NULL;
  2207.     }
  2208.  
  2209.   if (only_file)
  2210.     {
  2211.       digest_word_file (only_file, &only_table);
  2212.       if (only_table.length == 0)
  2213.     only_file = NULL;
  2214.     }
  2215.  
  2216.   /* Prepare to study all the input files.  */
  2217.  
  2218.   number_of_occurs[0] = 0;
  2219.   total_line_count = 0;
  2220.   maximum_word_length = 0;
  2221.   reference_max_width = 0;
  2222.  
  2223.   for (file_index = 0; file_index < number_input_files; file_index++)
  2224.     {
  2225.  
  2226.       /* Read the file in core, than study it.  */
  2227.  
  2228.       swallow_file_in_memory (input_file_name[file_index], &text_buffer);
  2229.       find_occurs_in_text ();
  2230.  
  2231.       /* Maintain for each file how many lines has been read so far when its
  2232.      end is reached.  Incrementing the count first is a simple kludge to
  2233.      handle a possible incomplete line at end of file.  */
  2234.  
  2235.       total_line_count++;
  2236.       file_line_count[file_index] = total_line_count;
  2237.     }
  2238.  
  2239.   /* Do the output process phase.  */
  2240.  
  2241.   sort_found_occurs ();
  2242.   fix_output_parameters ();
  2243.   generate_all_output ();
  2244.  
  2245.   /* All done.  */
  2246.  
  2247.   exit (EXIT_SUCCESS);
  2248. }
  2249.