home *** CD-ROM | disk | FTP | other *** search
/ Dream 52 / Amiga_Dream_52.iso / Atari / Gnu / gdb36p4s.zoo / readline / history.c < prev    next >
C/C++ Source or Header  |  1992-01-26  |  40KB  |  1,710 lines

  1. /* History.c -- standalone history library */
  2.  
  3. /* Copyright (C) 1989 Free Software Foundation, Inc.
  4.  
  5.    This file contains the GNU History Library (the Library), a set of
  6.    routines for managing the text of previously typed lines.
  7.  
  8.    The Library is free software; you can redistribute it and/or modify
  9.    it under the terms of the GNU General Public License as published by
  10.    the Free Software Foundation; either version 1, or (at your option)
  11.    any later version.
  12.  
  13.    The Library is distributed in the hope that it will be useful, but
  14.    WITHOUT ANY WARRANTY; without even the implied warranty of
  15.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  16.    General Public License for more details.
  17.  
  18.    The GNU General Public License is often shipped with GNU software, and
  19.    is generally kept in a file called COPYING or LICENSE.  If you do not
  20.    have a copy of the license, write to the Free Software Foundation,
  21.    675 Mass Ave, Cambridge, MA 02139, USA. */
  22.  
  23. /* The goal is to make the implementation transparent, so that you
  24.    don't have to know what data types are used, just what functions
  25.    you can call.  I think I have done that. */
  26.  
  27. /* Remove these declarations when we have a complete libgnu.a. */
  28. #if !defined (STATIC_MALLOC)
  29. extern char *xmalloc (), *xrealloc ();
  30. #else
  31. static char *xmalloc (), *xrealloc ();
  32. #endif
  33.  
  34. #include <stdio.h>
  35. #include <sys/types.h>
  36. #include <sys/file.h>
  37. #include <sys/stat.h>
  38. #include <fcntl.h>
  39.  
  40. #if defined (__GNUC__)
  41. #  define alloca __builtin_alloca
  42. #else
  43. #  if defined (sparc) || defined (HAVE_ALLOCA_H)
  44. #    include <alloca.h>
  45. #  else
  46. extern char *alloca ();
  47. #  endif /* sparc || HAVE_ALLOCA_H */
  48. #endif /* !__GNU_C__ */
  49.  
  50. #include "history.h"
  51.  
  52. #ifndef savestring
  53. #define savestring(x) (char *)strcpy (xmalloc (1 + strlen (x)), (x))
  54. #endif
  55.  
  56. #ifndef whitespace
  57. #define whitespace(c) (((c) == ' ') || ((c) == '\t'))
  58. #endif
  59.  
  60. #ifndef digit
  61. #define digit(c)  ((c) >= '0' && (c) <= '9')
  62. #endif
  63.  
  64. #ifndef member
  65. #define member(c, s) ((c) ? index ((s), (c)) : 0)
  66. #endif
  67.  
  68. /* **************************************************************** */
  69. /*                                    */
  70. /*            History Functions                */
  71. /*                                    */
  72. /* **************************************************************** */
  73.  
  74. /* An array of HIST_ENTRY.  This is where we store the history. */
  75. static HIST_ENTRY **the_history = (HIST_ENTRY **)NULL;
  76.  
  77. /* Non-zero means that we have enforced a limit on the amount of
  78.    history that we save. */
  79. int history_stifled = 0;
  80.  
  81. /* If HISTORY_STIFLED is non-zero, then this is the maximum number of
  82.    entries to remember. */
  83. int max_input_history;
  84.  
  85. /* The current location of the interactive history pointer.  Just makes
  86.    life easier for outside callers. */
  87. static int history_offset = 0;
  88.  
  89. /* The number of strings currently stored in the input_history list. */
  90. int history_length = 0;
  91.  
  92. /* The current number of slots allocated to the input_history. */
  93. static int history_size = 0;
  94.  
  95. /* The number of slots to increase the_history by. */
  96. #define DEFAULT_HISTORY_GROW_SIZE 50
  97.  
  98. /* The character that represents the start of a history expansion
  99.    request.  This is usually `!'. */
  100. char history_expansion_char = '!';
  101.  
  102. /* The character that invokes word substitution if found at the start of
  103.    a line.  This is usually `^'. */
  104. char history_subst_char = '^';
  105.  
  106. /* During tokenization, if this character is seen as the first character
  107.    of a word, then it, and all subsequent characters upto a newline are
  108.    ignored.  For a Bourne shell, this should be '#'.  Bash special cases
  109.    the interactive comment character to not be a comment delimiter. */
  110. char history_comment_char = '\0';
  111.  
  112. /* The list of characters which inhibit the expansion of text if found
  113.    immediately following history_expansion_char. */
  114. char *history_no_expand_chars = " \t\n\r=";
  115.  
  116. /* The logical `base' of the history array.  It defaults to 1. */
  117. int history_base = 1;
  118.  
  119. /* Begin a session in which the history functions might be used.  This
  120.    initializes interactive variables. */
  121. void
  122. using_history ()
  123. {
  124.   history_offset = history_length;
  125. }
  126.  
  127. /* Return the number of bytes that the primary history entries are using.
  128.    This just adds up the lengths of the_history->lines. */
  129. int
  130. history_total_bytes ()
  131. {
  132.   register int i, result;
  133.  
  134.   result = 0;
  135.  
  136.   for (i = 0; the_history && the_history[i]; i++)
  137.     result += strlen (the_history[i]->line);
  138.  
  139.   return (result);
  140. }
  141.  
  142. /* Place STRING at the end of the history list.  The data field
  143.    is  set to NULL. */
  144. void
  145. add_history (string)
  146.      char *string;
  147. {
  148.   HIST_ENTRY *temp;
  149.  
  150.   if (history_stifled && (history_length == max_input_history))
  151.     {
  152.       register int i;
  153.  
  154.       /* If the history is stifled, and history_length is zero,
  155.      and it equals max_input_history, we don't save items. */
  156.       if (!history_length)
  157.     return;
  158.  
  159.       /* If there is something in the slot, then remove it. */
  160.       if (the_history[0])
  161.     {
  162.       free (the_history[0]->line);
  163.       free (the_history[0]);
  164.     }
  165.  
  166.       for (i = 0; i < history_length; i++)
  167.     the_history[i] = the_history[i + 1];
  168.  
  169.       history_base++;
  170.  
  171.     }
  172.   else
  173.     {
  174.       if (!history_size)
  175.     {
  176.       the_history = (HIST_ENTRY **)
  177.         xmalloc ((history_size = DEFAULT_HISTORY_GROW_SIZE)
  178.              * sizeof (HIST_ENTRY *));
  179.       history_length = 1;
  180.  
  181.     }
  182.       else
  183.     {
  184.       if (history_length == (history_size - 1))
  185.         {
  186.           the_history = (HIST_ENTRY **)
  187.         xrealloc (the_history,
  188.               ((history_size += DEFAULT_HISTORY_GROW_SIZE)
  189.                * sizeof (HIST_ENTRY *)));
  190.       }
  191.       history_length++;
  192.     }
  193.     }
  194.  
  195.   temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  196.   temp->line = savestring (string);
  197.   temp->data = (char *)NULL;
  198.  
  199.   the_history[history_length] = (HIST_ENTRY *)NULL;
  200.   the_history[history_length - 1] = temp;
  201. }
  202.  
  203. /* Make the history entry at WHICH have LINE and DATA.  This returns
  204.    the old entry so you can dispose of the data.  In the case of an
  205.    invalid WHICH, a NULL pointer is returned. */
  206. HIST_ENTRY *
  207. replace_history_entry (which, line, data)
  208.      int which;
  209.      char *line;
  210.      char *data;
  211. {
  212.   HIST_ENTRY *temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  213.   HIST_ENTRY *old_value;
  214.  
  215.   if (which >= history_length)
  216.     return ((HIST_ENTRY *)NULL);
  217.  
  218.   old_value = the_history[which];
  219.  
  220.   temp->line = savestring (line);
  221.   temp->data = data;
  222.   the_history[which] = temp;
  223.  
  224.   return (old_value);
  225. }
  226.  
  227. /* Returns the magic number which says what history element we are
  228.    looking at now.  In this implementation, it returns history_offset. */
  229. int
  230. where_history ()
  231. {
  232.   return (history_offset);
  233. }
  234.  
  235. /* Search the history for STRING, starting at history_offset.
  236.    If DIRECTION < 0, then the search is through previous entries, else
  237.    through subsequent.  If ANCHORED is non-zero, the string must
  238.    appear at the beginning of a history line, otherwise, the string
  239.    may appear anywhere in the line.  If the string is found, then
  240.    current_history () is the history entry, and the value of this
  241.    function is the offset in the line of that history entry that the
  242.    string was found in.  Otherwise, nothing is changed, and a -1 is
  243.    returned. */
  244.  
  245. #define ANCHORED_SEARCH 1
  246. #define NON_ANCHORED_SEARCH 0
  247.  
  248. static int
  249. history_search_internal (string, direction, anchored)
  250.      char *string;
  251.      int direction, anchored;
  252. {
  253.   register int i = history_offset;
  254.   register int reverse = (direction < 0);
  255.   register char *line;
  256.   register int index;
  257.   int string_len = strlen (string);
  258.  
  259.   /* Take care of trivial cases first. */
  260.  
  261.   if (!history_length || ((i == history_length) && !reverse))
  262.     return (-1);
  263.  
  264.   if (reverse && (i == history_length))
  265.     i--;
  266.  
  267.   while (1)
  268.     {
  269.       /* Search each line in the history list for STRING. */
  270.  
  271.       /* At limit for direction? */
  272.       if ((reverse && i < 0) ||
  273.       (!reverse && i == history_length))
  274.     return (-1);
  275.  
  276.       line = the_history[i]->line;
  277.       index = strlen (line);
  278.  
  279.       /* If STRING is longer than line, no match. */
  280.       if (string_len > index)
  281.     goto next_line;
  282.  
  283.       /* Handle anchored searches first. */
  284.       if (anchored == ANCHORED_SEARCH)
  285.     {
  286.       if (strncmp (string, line, string_len) == 0)
  287.         {
  288.           history_offset = i;
  289.           return (0);
  290.         }
  291.  
  292.       goto next_line;
  293.     }
  294.  
  295.       /* Do substring search. */
  296.       if (reverse)
  297.     {
  298.       index -= string_len;
  299.  
  300.       while (index >= 0)
  301.         {
  302.           if (strncmp (string, line + index, string_len) == 0)
  303.         {
  304.           history_offset = i;
  305.           return (index);
  306.         }
  307.           index--;
  308.         }
  309.     }
  310.       else
  311.     {
  312.       register int limit = index - string_len + 1;
  313.       index = 0;
  314.  
  315.       while (index < limit)
  316.         {
  317.           if (strncmp (string, line + index, string_len) == 0)
  318.         {
  319.           history_offset = i;
  320.           return (index);
  321.         }
  322.           index++;
  323.         }
  324.     }
  325.     next_line:
  326.       if (reverse)
  327.     i--;
  328.       else
  329.     i++;
  330.     }
  331. }
  332.  
  333. /* Do a non-anchored search for STRING through the history in DIRECTION. */
  334. int
  335. history_search (string, direction)
  336.      char *string;
  337.      int direction;
  338. {
  339.   return (history_search_internal (string, direction, NON_ANCHORED_SEARCH));
  340. }
  341.  
  342. /* Do an anchored search for string through the history in DIRECTION. */
  343. int
  344. history_search_prefix (string, direction)
  345.      char *string;
  346.      int direction;
  347. {
  348.   return (history_search_internal (string, direction, ANCHORED_SEARCH));
  349. }
  350.  
  351. /* Remove history element WHICH from the history.  The removed
  352.    element is returned to you so you can free the line, data,
  353.    and containing structure. */
  354. HIST_ENTRY *
  355. remove_history (which)
  356.      int which;
  357. {
  358.   HIST_ENTRY *return_value;
  359.  
  360.   if (which >= history_length || !history_length)
  361.     return_value = (HIST_ENTRY *)NULL;
  362.   else
  363.     {
  364.       register int i;
  365.       return_value = the_history[which];
  366.  
  367.       for (i = which; i < history_length; i++)
  368.     the_history[i] = the_history[i + 1];
  369.  
  370.       history_length--;
  371.     }
  372.  
  373.   return (return_value);
  374. }
  375.  
  376. /* Stifle the history list, remembering only MAX number of lines. */
  377. void
  378. stifle_history (max)
  379.      int max;
  380. {
  381.   if (history_length > max)
  382.     {
  383.       register int i, j;
  384.  
  385.       /* This loses because we cannot free the data. */
  386.       for (i = 0; i < (history_length - max); i++)
  387.     {
  388.       free (the_history[i]->line);
  389.       free (the_history[i]);
  390.     }
  391.  
  392.       history_base = i;
  393.       for (j = 0, i = history_length - max; j < max; i++, j++)
  394.     the_history[j] = the_history[i];
  395.       the_history[j] = (HIST_ENTRY *)NULL;
  396.       history_length = j;
  397.     }
  398.  
  399.   history_stifled = 1;
  400.   max_input_history = max;
  401. }
  402.  
  403. /* Stop stifling the history.  This returns the previous amount the history
  404.  was stifled by.  The value is positive if the history was stifled, negative
  405.  if it wasn't. */
  406. int
  407. unstifle_history ()
  408. {
  409.   int result = max_input_history;
  410.  
  411.   if (history_stifled)
  412.     {
  413.       result = -result;
  414.       history_stifled = 0;
  415.     }
  416.  
  417.   return (result);
  418. }
  419.  
  420. /* Return the string that should be used in the place of this
  421.    filename.  This only matters when you don't specify the
  422.    filename to read_history (), or write_history (). */
  423. static char *
  424. history_filename (filename)
  425.      char *filename;
  426. {
  427.   char *return_val = filename ? savestring (filename) : (char *)NULL;
  428.  
  429.   if (!return_val)
  430.     {
  431.       char *home, *getenv ();
  432.  
  433.       home = getenv ("HOME");
  434.  
  435.       if (!home)
  436.     home = ".";
  437.  
  438.       return_val = (char *)xmalloc (2 + strlen (home) + strlen (".history"));
  439.  
  440.       sprintf (return_val, "%s/.history", home);
  441.     }
  442.  
  443.   return (return_val);
  444. }
  445.  
  446. /* Add the contents of FILENAME to the history list, a line at a time.
  447.    If FILENAME is NULL, then read from ~/.history.  Returns 0 if
  448.    successful, or errno if not. */
  449. int
  450. read_history (filename)
  451.      char *filename;
  452. {
  453.   return (read_history_range (filename, 0, -1));
  454. }
  455.  
  456. /* Read a range of lines from FILENAME, adding them to the history list.
  457.    Start reading at the FROM'th line and end at the TO'th.  If FROM
  458.    is zero, start at the beginning.  If TO is less than FROM, read
  459.    until the end of the file.  If FILENAME is NULL, then read from
  460.    ~/.history.  Returns 0 if successful, or errno if not. */
  461. int
  462. read_history_range (filename, from, to)
  463.      char *filename;
  464.      int from, to;
  465. {
  466.   register int line_start, line_end;
  467.   char *input, *buffer = (char *)NULL;
  468.   int file, current_line;
  469.   struct stat finfo;
  470.   extern int errno;
  471.  
  472.   input = history_filename (filename);
  473.   file = open (input, O_RDONLY, 0666);
  474.  
  475.   if ((file < 0) ||
  476.       (stat (input, &finfo) == -1))
  477.     goto error_and_exit;
  478.  
  479.   buffer = (char *)xmalloc (finfo.st_size + 1);
  480.  
  481.   if (read (file, buffer, finfo.st_size) != finfo.st_size)
  482.   error_and_exit:
  483.     {
  484.       if (file >= 0)
  485.     close (file);
  486.  
  487.       if (buffer)
  488.     free (buffer);
  489.  
  490.       return (errno);
  491.     }
  492.  
  493.   close (file);
  494.  
  495.   /* Set TO to larger than end of file if negative. */
  496.   if (to < 0)
  497.     to = finfo.st_size;
  498.  
  499.   /* Start at beginning of file, work to end. */
  500.   line_start = line_end = current_line = 0;
  501.  
  502.   /* Skip lines until we are at FROM. */
  503.   while (line_start < finfo.st_size && current_line < from)
  504.     {
  505.       for (line_end = line_start; line_end < finfo.st_size; line_end++)
  506.     if (buffer[line_end] == '\n')
  507.       {
  508.         current_line++;
  509.         line_start = line_end + 1;
  510.         if (current_line == from)
  511.           break;
  512.       }
  513.     }
  514.  
  515.   /* If there are lines left to gobble, then gobble them now. */
  516.   for (line_end = line_start; line_end < finfo.st_size; line_end++)
  517.     if (buffer[line_end] == '\n')
  518.       {
  519.     buffer[line_end] = '\0';
  520.  
  521.     if (buffer[line_start])
  522.       add_history (buffer + line_start);
  523.  
  524.     current_line++;
  525.  
  526.     if (current_line >= to)
  527.       break;
  528.  
  529.     line_start = line_end + 1;
  530.       }
  531.   return (0);
  532. }
  533.  
  534. /* Truncate the history file FNAME, leaving only LINES trailing lines.
  535.    If FNAME is NULL, then use ~/.history. */
  536. history_truncate_file (fname, lines)
  537.      char *fname;
  538.      register int lines;
  539. {
  540.   register int i;
  541.   int file;
  542.   char *buffer = (char *)NULL, *filename;
  543.   struct stat finfo;
  544.  
  545.   filename = history_filename (fname);
  546.   if (stat (filename, &finfo) == -1)
  547.     goto truncate_exit;
  548.  
  549.   file = open (filename, O_RDONLY, 0666);
  550.  
  551.   if (file == -1)
  552.     goto truncate_exit;
  553.  
  554.   buffer = (char *)xmalloc (finfo.st_size + 1);
  555.   read (file, buffer, finfo.st_size);
  556.   close (file);
  557.  
  558.   /* Count backwards from the end of buffer until we have passed
  559.      LINES lines. */
  560.   for (i = finfo.st_size; lines && i; i--)
  561.     {
  562.       if (buffer[i] == '\n')
  563.     lines--;
  564.     }
  565.  
  566.   /* If there are fewer lines in the file than we want to truncate to,
  567.      then we are all done. */
  568.   if (!i)
  569.     goto truncate_exit;
  570.  
  571.   /* Otherwise, write from the start of this line until the end of the
  572.      buffer. */
  573.   for (--i; i; i--)
  574.     if (buffer[i] == '\n')
  575.       {
  576.     i++;
  577.     break;
  578.       }
  579.  
  580.   file = open (filename, O_WRONLY | O_TRUNC | O_CREAT, 0666);
  581.   if (file == -1)
  582.     goto truncate_exit;
  583.  
  584.   write (file, buffer + i, finfo.st_size - i);
  585.   close (file);
  586.  
  587.  truncate_exit:
  588.   if (buffer)
  589.     free (buffer);
  590.  
  591.   free (filename);
  592. }
  593.  
  594. #define HISTORY_APPEND 0
  595. #define HISTORY_OVERWRITE 1
  596.  
  597. /* Workhorse function for writing history.  Writes NELEMENT entries
  598.    from the history list to FILENAME.  OVERWRITE is non-zero if you
  599.    wish to replace FILENAME with the entries. */
  600. static int
  601. history_do_write (filename, nelements, overwrite)
  602.      char *filename;
  603.      int nelements, overwrite;
  604. {
  605.   extern int errno;
  606.   register int i;
  607.   char *output = history_filename (filename);
  608.   int file, mode;
  609.   char cr = '\n';
  610.  
  611.   if (overwrite)
  612.     mode = O_WRONLY | O_CREAT | O_TRUNC;
  613.   else
  614.     mode = O_WRONLY | O_APPEND;
  615.  
  616.   if ((file = open (output, mode, 0666)) == -1)
  617.     return (errno);
  618.  
  619.   if (nelements > history_length)
  620.     nelements = history_length;
  621.  
  622.   for (i = history_length - nelements; i < history_length; i++)
  623.     {
  624.       if (write (file, the_history[i]->line, strlen (the_history[i]->line)) < 0)
  625.     break;
  626.       if (write (file, &cr, 1) < 0)
  627.     break;
  628.     }
  629.  
  630.   close (file);
  631.   return (0);
  632. }
  633.   
  634. /* Append NELEMENT entries to FILENAME.  The entries appended are from
  635.    the end of the list minus NELEMENTs up to the end of the list. */
  636. int
  637. append_history (nelements, filename)
  638.      int nelements;
  639.      char *filename;
  640. {
  641.   return (history_do_write (filename, nelements, HISTORY_APPEND));
  642. }
  643.  
  644. /* Overwrite FILENAME with the current history.  If FILENAME is NULL,
  645.    then write the history list to ~/.history.  Values returned
  646.    are as in read_history ().*/
  647. int
  648. write_history (filename)
  649.      char *filename;
  650. {
  651.   return (history_do_write (filename, history_length, HISTORY_OVERWRITE));
  652. }
  653.  
  654. /* Return the history entry at the current position, as determined by
  655.    history_offset.  If there is no entry there, return a NULL pointer. */
  656. HIST_ENTRY *
  657. current_history ()
  658. {
  659.   if ((history_offset == history_length) || !the_history)
  660.     return ((HIST_ENTRY *)NULL);
  661.   else
  662.     return (the_history[history_offset]);
  663. }
  664.  
  665. /* Back up history_offset to the previous history entry, and return
  666.    a pointer to that entry.  If there is no previous entry then return
  667.    a NULL pointer. */
  668. HIST_ENTRY *
  669. previous_history ()
  670. {
  671.   if (!history_offset)
  672.     return ((HIST_ENTRY *)NULL);
  673.   else
  674.     return (the_history[--history_offset]);
  675. }
  676.  
  677. /* Move history_offset forward to the next history entry, and return
  678.    a pointer to that entry.  If there is no next entry then return a
  679.    NULL pointer. */
  680. HIST_ENTRY *
  681. next_history ()
  682. {
  683.   if (history_offset == history_length)
  684.     return ((HIST_ENTRY *)NULL);
  685.   else
  686.     return (the_history[++history_offset]);
  687. }
  688.  
  689. /* Return the current history array.  The caller has to be carefull, since this
  690.    is the actual array of data, and could be bashed or made corrupt easily.
  691.    The array is terminated with a NULL pointer. */
  692. HIST_ENTRY **
  693. history_list ()
  694. {
  695.   return (the_history);
  696. }
  697.  
  698. /* Return the history entry which is logically at OFFSET in the history array.
  699.    OFFSET is relative to history_base. */
  700. HIST_ENTRY *
  701. history_get (offset)
  702.      int offset;
  703. {
  704.   int index = offset - history_base;
  705.  
  706.   if (index >= history_length ||
  707.       index < 0 ||
  708.       !the_history)
  709.     return ((HIST_ENTRY *)NULL);
  710.   return (the_history[index]);
  711. }
  712.  
  713. /* Search for STRING in the history list.  DIR is < 0 for searching
  714.    backwards.  POS is an absolute index into the history list at
  715.    which point to begin searching. */
  716. int
  717. history_search_pos (string, dir, pos)
  718.      char *string;
  719.      int dir, pos;
  720. {
  721.   int ret, old = where_history ();
  722.   history_set_pos (pos);
  723.   if (history_search (string, dir) == -1)
  724.     {
  725.       history_set_pos (old);
  726.       return (-1);
  727.     }
  728.   ret = where_history ();
  729.   history_set_pos (old);
  730.   return ret;
  731. }
  732.  
  733. /* Make the current history item be the one at POS, an absolute index.
  734.    Returns zero if POS is out of range, else non-zero. */
  735. int
  736. history_set_pos (pos)
  737.      int pos;
  738. {
  739.   if (pos > history_length || pos < 0 || !the_history)
  740.     return (0);
  741.   history_offset = pos;
  742.   return (1);
  743. }
  744.  
  745.  
  746. /* **************************************************************** */
  747. /*                                    */
  748. /*            History Expansion                */
  749. /*                                    */
  750. /* **************************************************************** */
  751.  
  752. /* Hairy history expansion on text, not tokens.  This is of general
  753.    use, and thus belongs in this library. */
  754.  
  755. /* The last string searched for in a !?string? search. */
  756. static char *search_string = (char *)NULL;
  757.  
  758. /* Return the event specified at TEXT + OFFSET modifying OFFSET to
  759.    point to after the event specifier.  Just a pointer to the history
  760.    line is returned; NULL is returned in the event of a bad specifier.
  761.    You pass STRING with *INDEX equal to the history_expansion_char that
  762.    begins this specification.
  763.    DELIMITING_QUOTE is a character that is allowed to end the string
  764.    specification for what to search for in addition to the normal
  765.    characters `:', ` ', `\t', `\n', and sometimes `?'.
  766.    So you might call this function like:
  767.    line = get_history_event ("!echo:p", &index, 0);  */
  768. char *
  769. get_history_event (string, caller_index, delimiting_quote)
  770.      char *string;
  771.      int *caller_index;
  772.      int delimiting_quote;
  773. {
  774.   register int i = *caller_index;
  775.   int which, sign = 1;
  776.   HIST_ENTRY *entry;
  777.  
  778.   /* The event can be specified in a number of ways.
  779.  
  780.      !!   the previous command
  781.      !n   command line N
  782.      !-n  current command-line minus N
  783.      !str the most recent command starting with STR
  784.      !?str[?]
  785.       the most recent command containing STR
  786.  
  787.      All values N are determined via HISTORY_BASE. */
  788.  
  789.   if (string[i] != history_expansion_char)
  790.     return ((char *)NULL);
  791.  
  792.   /* Move on to the specification. */
  793.   i++;
  794.  
  795.   /* Handle !! case. */
  796.   if (string[i] == history_expansion_char)
  797.     {
  798.       i++;
  799.       which = history_base + (history_length - 1);
  800.       *caller_index = i;
  801.       goto get_which;
  802.     }
  803.  
  804.   /* Hack case of numeric line specification. */
  805.  read_which:
  806.   if (string[i] == '-')
  807.     {
  808.       sign = -1;
  809.       i++;
  810.     }
  811.  
  812.   if (digit (string[i]))
  813.     {
  814.       int start = i;
  815.  
  816.       /* Get the extent of the digits. */
  817.       for (; digit (string[i]); i++);
  818.  
  819.       /* Get the digit value. */
  820.       sscanf (string + start, "%d", &which);
  821.  
  822.       *caller_index = i;
  823.  
  824.       if (sign < 0)
  825.     which = (history_length + history_base) - which;
  826.  
  827.     get_which:
  828.       if (entry = history_get (which))
  829.     return (entry->line);
  830.  
  831.       return ((char *)NULL);
  832.     }
  833.  
  834.   /* This must be something to search for.  If the spec begins with
  835.      a '?', then the string may be anywhere on the line.  Otherwise,
  836.      the string must be found at the start of a line. */
  837.   {
  838.     int index;
  839.     char *temp;
  840.     int substring_okay = 0;
  841.  
  842.     if (string[i] == '?')
  843.       {
  844.     substring_okay++;
  845.     i++;
  846.       }
  847.  
  848.     for (index = i; string[i]; i++)
  849.       if (whitespace (string[i]) ||
  850.       string[i] == '\n' ||
  851.       string[i] == ':' ||
  852.       (substring_okay && string[i] == '?') ||
  853.       string[i] == delimiting_quote)
  854.     break;
  855.  
  856.     temp = (char *)alloca (1 + (i - index));
  857.     strncpy (temp, &string[index], (i - index));
  858.     temp[i - index] = '\0';
  859.  
  860.     if (string[i] == '?')
  861.       i++;
  862.  
  863.     *caller_index = i;
  864.  
  865.   search_again:
  866.  
  867.     index = history_search_internal
  868.       (temp, -1, substring_okay ? NON_ANCHORED_SEARCH : ANCHORED_SEARCH);
  869.  
  870.     if (index < 0)
  871.     search_lost:
  872.       {
  873.     history_offset = history_length;
  874.     return ((char *)NULL);
  875.       }
  876.  
  877.     if (index == 0 || substring_okay)
  878.       {
  879.       search_won:
  880.     entry = current_history ();
  881.     history_offset = history_length;
  882.     
  883.     /* If this was a substring search, then remember the string that
  884.        we matched for word substitution. */
  885.     if (substring_okay)
  886.       {
  887.         if (search_string)
  888.           free (search_string);
  889.         search_string = savestring (temp);
  890.       }
  891.  
  892.     return (entry->line);
  893.       }
  894.  
  895.     if (history_offset)
  896.       history_offset--;
  897.     else
  898.       goto search_lost;
  899.     
  900.     goto search_again;
  901.   }
  902. }
  903.  
  904. /* Expand the string STRING, placing the result into OUTPUT, a pointer
  905.    to a string.  Returns:
  906.  
  907.    0) If no expansions took place (or, if the only change in
  908.       the text was the de-slashifying of the history expansion
  909.       character)
  910.    1) If expansions did take place
  911.   -1) If there was an error in expansion.
  912.  
  913.   If an error ocurred in expansion, then OUTPUT contains a descriptive
  914.   error message. */
  915. int
  916. history_expand (string, output)
  917.      char *string;
  918.      char **output;
  919. {
  920.   register int j, l = strlen (string);
  921.   int i, word_spec_error = 0;
  922.   int cc, modified = 0;
  923.   char *word_spec, *event;
  924.   int starting_index, only_printing = 0, substitute_globally = 0;
  925.  
  926.   char *get_history_word_specifier (), *rindex ();
  927.  
  928.   /* The output string, and its length. */
  929.   int len = 0;
  930.   char *result = (char *)NULL;
  931.  
  932.   /* Used in add_string; */
  933.   char *temp, tt[2], tbl[3];
  934.  
  935.   /* Prepare the buffer for printing error messages. */
  936.   result = (char *)xmalloc (len = 255);
  937.  
  938.   result[0] = tt[1] = tbl[2] = '\0';
  939.   tbl[0] = '\\';
  940.   tbl[1] = history_expansion_char;
  941.  
  942.   /* Grovel the string.  Only backslash can quote the history escape
  943.      character.  We also handle arg specifiers. */
  944.  
  945.   /* Before we grovel forever, see if the history_expansion_char appears
  946.      anywhere within the text. */
  947.  
  948.   /* The quick substitution character is a history expansion all right.  That
  949.      is to say, "^this^that^" is equivalent to "!!:s^this^that^", and in fact,
  950.      that is the substitution that we do. */
  951.   if (string[0] == history_subst_char)
  952.     {
  953.       char *format_string = (char *)alloca (10 + strlen (string));
  954.  
  955.       sprintf (format_string, "%c%c:s%s",
  956.            history_expansion_char, history_expansion_char,
  957.            string);
  958.       string = format_string;
  959.       l += 4;
  960.       goto grovel;
  961.     }
  962.  
  963.   /* If not quick substitution, still maybe have to do expansion. */
  964.  
  965.   /* `!' followed by one of the characters in history_no_expand_chars
  966.      is NOT an expansion. */
  967.   for (i = 0; string[i]; i++)
  968.     if (string[i] == history_expansion_char)
  969.       if (!string[i + 1] || member (string[i + 1], history_no_expand_chars))
  970.     continue;
  971.       else
  972.     goto grovel;
  973.  
  974.   free (result);
  975.   *output = savestring (string);
  976.   return (0);
  977.  
  978.  grovel:
  979.  
  980.   for (i = j = 0; i < l; i++)
  981.     {
  982.       int tchar = string[i];
  983.       if (tchar == history_expansion_char)
  984.     tchar = -3;
  985.  
  986.       switch (tchar)
  987.     {
  988.     case '\\':
  989.       if (string[i + 1] == history_expansion_char)
  990.         {
  991.           i++;
  992.           temp = tbl;
  993.           goto do_add;
  994.         }
  995.       else
  996.         goto add_char;
  997.  
  998.       /* case history_expansion_char: */
  999.     case -3:
  1000.       starting_index = i + 1;
  1001.       cc = string[i + 1];
  1002.  
  1003.       /* If the history_expansion_char is followed by one of the
  1004.          characters in history_no_expand_chars, then it is not a
  1005.          candidate for expansion of any kind. */
  1006.       if (member (cc, history_no_expand_chars))
  1007.         goto add_char;
  1008.  
  1009.       /* There is something that is listed as a `word specifier' in csh
  1010.          documentation which means `the expanded text to this point'.
  1011.          That is not a word specifier, it is an event specifier. */
  1012.  
  1013.       if (cc == '#')
  1014.         goto hack_pound_sign;
  1015.  
  1016.       /* If it is followed by something that starts a word specifier,
  1017.          then !! is implied as the event specifier. */
  1018.  
  1019.       if (member (cc, ":$*%^"))
  1020.         {
  1021.           char fake_s[3];
  1022.           int fake_i = 0;
  1023.           i++;
  1024.           fake_s[0] = fake_s[1] = history_expansion_char;
  1025.           fake_s[2] = '\0';
  1026.           event = get_history_event (fake_s, &fake_i, 0);
  1027.         }
  1028.       else
  1029.         {
  1030.           int quoted_search_delimiter = 0;
  1031.  
  1032.           /* If the character before this `!' is a double or single
  1033.          quote, then this expansion takes place inside of the
  1034.          quoted string.  If we have to search for some text ("!foo"),
  1035.          allow the delimiter to end the search string. */
  1036.           if (i && (string[i - 1] == '\'' || string[i - 1] == '"'))
  1037.         quoted_search_delimiter = string[i - 1];
  1038.  
  1039.           event = get_history_event (string, &i, quoted_search_delimiter);
  1040.         }
  1041.       
  1042.       if (!event)
  1043.       event_not_found:
  1044.         {
  1045.         int l = 1 + (i - starting_index);
  1046.  
  1047.         temp = (char *)alloca (1 + l);
  1048.         strncpy (temp, string + starting_index, l);
  1049.         temp[l - 1] = 0;
  1050.         sprintf (result, "%s: %s.", temp,
  1051.              word_spec_error ? "Bad word specifier" : "Event not found");
  1052.       error_exit:
  1053.         *output = result;
  1054.         return (-1);
  1055.       }
  1056.  
  1057.       /* If a word specifier is found, then do what that requires. */
  1058.       starting_index = i;
  1059.  
  1060.       word_spec = get_history_word_specifier (string, event, &i);
  1061.  
  1062.       /* There is no such thing as a `malformed word specifier'.  However,
  1063.          it is possible for a specifier that has no match.  In that case,
  1064.          we complain. */
  1065.       if (word_spec == (char *)-1)
  1066.       bad_word_spec:
  1067.       {
  1068.         word_spec_error++;
  1069.         goto event_not_found;
  1070.       }
  1071.  
  1072.       /* If no word specifier, than the thing of interest was the event. */
  1073.       if (!word_spec)
  1074.         temp = event;
  1075.       else
  1076.         {
  1077.           temp = (char *)alloca (1 + strlen (word_spec));
  1078.           strcpy (temp, word_spec);
  1079.           free (word_spec);
  1080.         }
  1081.  
  1082.       /* Perhaps there are other modifiers involved.  Do what they say. */
  1083.  
  1084.     hack_specials:
  1085.  
  1086.       if (string[i] == ':')
  1087.         {
  1088.           char *tstr;
  1089.  
  1090.           switch (string[i + 1])
  1091.         {
  1092.           /* :p means make this the last executed line.  So we
  1093.              return an error state after adding this line to the
  1094.              history. */
  1095.         case 'p':
  1096.           only_printing++;
  1097.           goto next_special;
  1098.  
  1099.           /* :t discards all but the last part of the pathname. */
  1100.         case 't':
  1101.           tstr = rindex (temp, '/');
  1102.           if (tstr)
  1103.             temp = ++tstr;
  1104.           goto next_special;
  1105.  
  1106.           /* :h discards the last part of a pathname. */
  1107.         case 'h':
  1108.           tstr = rindex (temp, '/');
  1109.           if (tstr)
  1110.             *tstr = '\0';
  1111.           goto next_special;
  1112.  
  1113.           /* :r discards the suffix. */
  1114.         case 'r':
  1115.           tstr = rindex (temp, '.');
  1116.           if (tstr)
  1117.             *tstr = '\0';
  1118.           goto next_special;
  1119.  
  1120.           /* :e discards everything but the suffix. */
  1121.         case 'e':
  1122.           tstr = rindex (temp, '.');
  1123.           if (tstr)
  1124.             temp = tstr;
  1125.           goto next_special;
  1126.  
  1127.           /* :s/this/that substitutes `this' for `that'. */
  1128.           /* :gs/this/that substitutes `this' for `that' globally. */
  1129.         case 'g':
  1130.           if (string[i + 2] == 's')
  1131.             {
  1132.               i++;
  1133.               substitute_globally = 1;
  1134.               goto substitute;
  1135.             }
  1136.           else
  1137.             
  1138.         case 's':
  1139.           substitute:
  1140.           {
  1141.             char *this, *that, *new_event;
  1142.             int delimiter = 0;
  1143.             int si, l_this, l_that, l_temp = strlen (temp);
  1144.  
  1145.             if (i + 2 < strlen (string))
  1146.               delimiter = string[i + 2];
  1147.  
  1148.             if (!delimiter)
  1149.               break;
  1150.  
  1151.             i += 3;
  1152.  
  1153.             /* Get THIS. */
  1154.             for (si = i; string[si] && string[si] != delimiter; si++);
  1155.             l_this = (si - i);
  1156.             this = (char *)alloca (1 + l_this);
  1157.             strncpy (this, string + i, l_this);
  1158.             this[l_this] = '\0';
  1159.  
  1160.             i = si;
  1161.             if (string[si])
  1162.               i++;
  1163.  
  1164.             /* Get THAT. */
  1165.             for (si = i; string[si] && string[si] != delimiter; si++);
  1166.             l_that = (si - i);
  1167.             that = (char *)alloca (1 + l_that);
  1168.             strncpy (that, string + i, l_that);
  1169.             that[l_that] = '\0';
  1170.  
  1171.             i = si;
  1172.             if (string[si]) i++;
  1173.  
  1174.             /* Ignore impossible cases. */
  1175.             if (l_this > l_temp)
  1176.               goto cant_substitute;
  1177.  
  1178.             /* Find the first occurrence of THIS in TEMP. */
  1179.             si = 0;
  1180.             for (; (si + l_this) <= l_temp; si++)
  1181.               if (strncmp (temp + si, this, l_this) == 0)
  1182.             {
  1183.               new_event =
  1184.                 (char *)alloca (1 + (l_that - l_this) + l_temp);
  1185.               strncpy (new_event, temp, si);
  1186.               strncpy (new_event + si, that, l_that);
  1187.               strncpy (new_event + si + l_that,
  1188.                    temp + si + l_this,
  1189.                    l_temp - (si + l_this));
  1190.               new_event[(l_that - l_this) + l_temp] = '\0';
  1191.               temp = new_event;
  1192.  
  1193.               if (substitute_globally)
  1194.                 {
  1195.                   si += l_that;
  1196.                   l_temp = strlen (temp);
  1197.                   substitute_globally++;
  1198.                   continue;
  1199.                 }
  1200.  
  1201.               goto hack_specials;
  1202.             }
  1203.  
  1204.           cant_substitute:
  1205.  
  1206.             if (substitute_globally > 1)
  1207.               {
  1208.             substitute_globally = 0;
  1209.             goto hack_specials;
  1210.               }
  1211.  
  1212.             goto event_not_found;
  1213.           }
  1214.  
  1215.           /* :# is the line so far.  Note that we have to
  1216.              alloca () it since RESULT could be realloc ()'ed
  1217.              below in add_string. */
  1218.         case '#':
  1219.         hack_pound_sign:
  1220.           if (result)
  1221.             {
  1222.               temp = (char *)alloca (1 + strlen (result));
  1223.               strcpy (temp, result);
  1224.             }
  1225.           else
  1226.             temp = "";
  1227.  
  1228.         next_special:
  1229.           i += 2;
  1230.           goto hack_specials;
  1231.         }
  1232.  
  1233.         }
  1234.       /* Believe it or not, we have to back the pointer up by one. */
  1235.       --i;
  1236.       goto add_string;
  1237.  
  1238.       /* A regular character.  Just add it to the output string. */
  1239.     default:
  1240.     add_char:
  1241.       tt[0] = string[i];
  1242.       temp = tt;
  1243.       goto do_add;
  1244.  
  1245.     add_string:
  1246.       modified++;
  1247.  
  1248.     do_add:
  1249.       j += strlen (temp);
  1250.       while (j > len)
  1251.         result = (char *)xrealloc (result, (len += 255));
  1252.  
  1253.       strcpy (result + (j - strlen (temp)), temp);
  1254.     }
  1255.     }
  1256.  
  1257.   *output = result;
  1258.  
  1259.   if (only_printing)
  1260.     {
  1261.       add_history (result);
  1262.       return (-1);
  1263.     }
  1264.  
  1265.   return (modified != 0);
  1266. }
  1267.  
  1268. /* Return a consed string which is the word specified in SPEC, and found
  1269.    in FROM.  NULL is returned if there is no spec.  -1 is returned if
  1270.    the word specified cannot be found.  CALLER_INDEX is the offset in
  1271.    SPEC to start looking; it is updated to point to just after the last
  1272.    character parsed. */
  1273. char *
  1274. get_history_word_specifier (spec, from, caller_index)
  1275.      char *spec, *from;
  1276.      int *caller_index;
  1277. {
  1278.   register int i = *caller_index;
  1279.   int first, last;
  1280.   int expecting_word_spec = 0;
  1281.   char *history_arg_extract ();
  1282.  
  1283.   /* The range of words to return doesn't exist yet. */
  1284.   first = last = 0;
  1285.  
  1286.   /* If we found a colon, then this *must* be a word specification.  If
  1287.      it isn't, then it is an error. */
  1288.   if (spec[i] == ':')
  1289.     i++, expecting_word_spec++;
  1290.  
  1291.   /* Handle special cases first. */
  1292.  
  1293.   /* `%' is the word last searched for. */
  1294.   if (spec[i] == '%')
  1295.     {
  1296.       *caller_index = i + 1;
  1297.       if (search_string)
  1298.     return (savestring (search_string));
  1299.       else
  1300.     return (savestring (""));
  1301.     }
  1302.  
  1303.   /* `*' matches all of the arguments, but not the command. */
  1304.   if (spec[i] == '*')
  1305.     {
  1306.       char *star_result;
  1307.  
  1308.       *caller_index = i + 1;
  1309.       star_result = history_arg_extract (1, '$', from);
  1310.  
  1311.       if (!star_result)
  1312.     star_result = savestring ("");
  1313.  
  1314.       return (star_result);
  1315.     }
  1316.  
  1317.   /* `$' is last arg. */
  1318.   if (spec[i] == '$')
  1319.     {
  1320.       *caller_index = i + 1;
  1321.       return (history_arg_extract ('$', '$', from));
  1322.     }
  1323.  
  1324.   /* Try to get FIRST and LAST figured out. */
  1325.   if (spec[i] == '-' || spec[i] == '^')
  1326.     {
  1327.       first = 1;
  1328.       goto get_last;
  1329.     }
  1330.  
  1331.  get_first:
  1332.   if (digit (spec[i]) && expecting_word_spec)
  1333.     {
  1334.       sscanf (spec + i, "%d", &first);
  1335.       for (; digit (spec[i]); i++);
  1336.     }
  1337.   else
  1338.     return ((char *)NULL);
  1339.  
  1340.  get_last:
  1341.   if (spec[i] == '^')
  1342.     {
  1343.       i++;
  1344.       last = 1;
  1345.       goto get_args;
  1346.     }
  1347.  
  1348.   if (spec[i] != '-')
  1349.     {
  1350.       last = first;
  1351.       goto get_args;
  1352.     }
  1353.  
  1354.   i++;
  1355.  
  1356.   if (digit (spec[i]))
  1357.     {
  1358.       sscanf (spec + i, "%d", &last);
  1359.       for (; digit (spec[i]); i++);
  1360.     }
  1361.   else
  1362.     if (spec[i] == '$')
  1363.       {
  1364.     i++;
  1365.     last = '$';
  1366.       }
  1367.  
  1368.  get_args:
  1369.   {
  1370.     char *result = (char *)NULL;
  1371.  
  1372.     *caller_index = i;
  1373.  
  1374.     if (last >= first)
  1375.       result = history_arg_extract (first, last, from);
  1376.  
  1377.     if (result)
  1378.       return (result);
  1379.     else
  1380.       return ((char *)-1);
  1381.   }
  1382. }
  1383.  
  1384. /* Extract the args specified, starting at FIRST, and ending at LAST.
  1385.    The args are taken from STRING.  If either FIRST or LAST is < 0,
  1386.    then make that arg count from the right (subtract from the number of
  1387.    tokens, so that FIRST = -1 means the next to last token on the line). */
  1388. char *
  1389. history_arg_extract (first, last, string)
  1390.      int first, last;
  1391.      char *string;
  1392. {
  1393.   register int i, len;
  1394.   char *result = (char *)NULL;
  1395.   int size = 0, offset = 0;
  1396.  
  1397.   char **history_tokenize (), **list;
  1398.  
  1399.   if (!(list = history_tokenize (string)))
  1400.     return ((char *)NULL);
  1401.  
  1402.   for (len = 0; list[len]; len++);
  1403.  
  1404.   if (last < 0)
  1405.     last = len + last - 1;
  1406.  
  1407.   if (first < 0)
  1408.     first = len + first - 1;
  1409.  
  1410.   if (last == '$')
  1411.     last = len - 1;
  1412.  
  1413.   if (first == '$')
  1414.     first = len - 1;
  1415.  
  1416.   last++;
  1417.  
  1418.   if (first > len || last > len || first < 0 || last < 0)
  1419.     result = ((char *)NULL);
  1420.   else
  1421.     {
  1422.       for (i = first; i < last; i++)
  1423.     {
  1424.       int l = strlen (list[i]);
  1425.  
  1426.       if (!result)
  1427.         result = (char *)xmalloc ((size = (2 + l)));
  1428.       else
  1429.         result = (char *)xrealloc (result, (size += (2 + l)));
  1430.       strcpy (result + offset, list[i]);
  1431.       offset += l;
  1432.       if (i + 1 < last)
  1433.         {
  1434.           strcpy (result + offset, " ");
  1435.           offset++;
  1436.         }
  1437.     }
  1438.     }
  1439.  
  1440.   for (i = 0; i < len; i++)
  1441.     free (list[i]);
  1442.  
  1443.   free (list);
  1444.  
  1445.   return (result);
  1446. }
  1447.  
  1448. #define slashify_in_quotes "\\`\"$"
  1449.  
  1450. /* Return an array of tokens, much as the shell might.  The tokens are
  1451.    parsed out of STRING. */
  1452. char **
  1453. history_tokenize (string)
  1454.      char *string;
  1455. {
  1456.   char **result = (char **)NULL;
  1457.   register int i, start, result_index, size;
  1458.   int len;
  1459.  
  1460.   i = result_index = size = 0;
  1461.  
  1462.   /* Get a token, and stuff it into RESULT.  The tokens are split
  1463.      exactly where the shell would split them. */
  1464.  get_token:
  1465.  
  1466.   /* Skip leading whitespace. */
  1467.   for (; string[i] && whitespace(string[i]); i++);
  1468.  
  1469.   start = i;
  1470.  
  1471.   if (!string[i] || string[i] == history_comment_char)
  1472.     return (result);
  1473.  
  1474.   if (member (string[i], "()\n"))
  1475.     {
  1476.       i++;
  1477.       goto got_token;
  1478.     }
  1479.  
  1480.   if (member (string[i], "<>;&|"))
  1481.     {
  1482.       int peek = string[i + 1];
  1483.  
  1484.       if (peek == string[i])
  1485.     {
  1486.       if (peek ==  '<')
  1487.         {
  1488.           if (string[1 + 2] == '-')
  1489.         i++;
  1490.           i += 2;
  1491.           goto got_token;
  1492.         }
  1493.  
  1494.       if (member (peek, ">:&|"))
  1495.         {
  1496.           i += 2;
  1497.           goto got_token;
  1498.         }
  1499.     }
  1500.       else
  1501.     {
  1502.       if ((peek == '&' &&
  1503.            (string[i] == '>' || string[i] == '<')) ||
  1504.           ((peek == '>') &&
  1505.            (string[i] == '&')))
  1506.         {
  1507.           i += 2;
  1508.           goto got_token;
  1509.         }
  1510.     }
  1511.       i++;
  1512.       goto got_token;
  1513.     }
  1514.  
  1515.   /* Get word from string + i; */
  1516.   {
  1517.     int delimiter = 0;
  1518.  
  1519.     if (member (string[i], "\"'`"))
  1520.       delimiter = string[i++];
  1521.  
  1522.     for (;string[i]; i++)
  1523.       {
  1524.     if (string[i] == '\\')
  1525.       {
  1526.         if (string[i + 1] == '\n')
  1527.           {
  1528.         i++;
  1529.         continue;
  1530.           }
  1531.         else
  1532.           {
  1533.         if (delimiter != '\'')
  1534.           if ((delimiter != '"') ||
  1535.               (member (string[i], slashify_in_quotes)))
  1536.             {
  1537.               i++;
  1538.               continue;
  1539.             }
  1540.           }
  1541.       }
  1542.  
  1543.     if (delimiter && string[i] == delimiter)
  1544.       {
  1545.         delimiter = 0;
  1546.         continue;
  1547.       }
  1548.  
  1549.     if (!delimiter && (member (string[i], " \t\n;&()|<>")))
  1550.       goto got_token;
  1551.  
  1552.     if (!delimiter && member (string[i], "\"'`"))
  1553.       {
  1554.         delimiter = string[i];
  1555.         continue;
  1556.       }
  1557.       }
  1558.     got_token:
  1559.  
  1560.     len = i - start;
  1561.     if (result_index + 2 >= size)
  1562.       {
  1563.     if (!size)
  1564.       result = (char **)xmalloc ((size = 10) * (sizeof (char *)));
  1565.     else
  1566.       result =
  1567.         (char **)xrealloc (result, ((size += 10) * (sizeof (char *))));
  1568.       }
  1569.     result[result_index] = (char *)xmalloc (1 + len);
  1570.     strncpy (result[result_index], string + start, len);
  1571.     result[result_index][len] = '\0';
  1572.     result_index++;
  1573.     result[result_index] = (char *)NULL;
  1574.   }
  1575.   if (string[i])
  1576.     goto get_token;
  1577.  
  1578.   return (result);
  1579. }
  1580.  
  1581. #if defined (STATIC_MALLOC)
  1582.  
  1583. /* **************************************************************** */
  1584. /*                                    */
  1585. /*            xmalloc and xrealloc ()                     */
  1586. /*                                    */
  1587. /* **************************************************************** */
  1588.  
  1589. static void memory_error_and_abort ();
  1590.  
  1591. static char *
  1592. xmalloc (bytes)
  1593.      int bytes;
  1594. {
  1595.   char *temp = (char *)malloc (bytes);
  1596.  
  1597.   if (!temp)
  1598.     memory_error_and_abort ();
  1599.   return (temp);
  1600. }
  1601.  
  1602. static char *
  1603. xrealloc (pointer, bytes)
  1604.      char *pointer;
  1605.      int bytes;
  1606. {
  1607.   char *temp;
  1608.  
  1609.   if (!pointer)
  1610.     temp = (char *)xmalloc (bytes);
  1611.   else
  1612.     temp = (char *)realloc (pointer, bytes);
  1613.  
  1614.   if (!temp)
  1615.     memory_error_and_abort ();
  1616.  
  1617.   return (temp);
  1618. }
  1619.  
  1620. static void
  1621. memory_error_and_abort ()
  1622. {
  1623.   fprintf (stderr, "history: Out of virtual memory!\n");
  1624.   abort ();
  1625. }
  1626. #endif /* STATIC_MALLOC */
  1627.  
  1628.  
  1629. /* **************************************************************** */
  1630. /*                                    */
  1631. /*                Test Code                */
  1632. /*                                    */
  1633. /* **************************************************************** */
  1634. #ifdef TEST
  1635. main ()
  1636. {
  1637.   char line[1024], *t;
  1638.   int done = 0;
  1639.  
  1640.   line[0] = 0;
  1641.  
  1642.   while (!done)
  1643.     {
  1644.       fprintf (stdout, "history%% ");
  1645.       t = gets (line);
  1646.  
  1647.       if (!t)
  1648.     strcpy (line, "quit");
  1649.  
  1650.       if (line[0])
  1651.     {
  1652.       char *expansion;
  1653.       int result;
  1654.  
  1655.       using_history ();
  1656.  
  1657.       result = history_expand (line, &expansion);
  1658.       strcpy (line, expansion);
  1659.       free (expansion);
  1660.       if (result)
  1661.         fprintf (stderr, "%s\n", line);
  1662.  
  1663.       if (result < 0)
  1664.         continue;
  1665.  
  1666.       add_history (line);
  1667.     }
  1668.  
  1669.       if (strcmp (line, "quit") == 0) done = 1;
  1670.       if (strcmp (line, "save") == 0) write_history (0);
  1671.       if (strcmp (line, "read") == 0) read_history (0);
  1672.       if (strcmp (line, "list") == 0)
  1673.     {
  1674.       register HIST_ENTRY **the_list = history_list ();
  1675.       register int i;
  1676.  
  1677.       if (the_list)
  1678.         for (i = 0; the_list[i]; i++)
  1679.           fprintf (stdout, "%d: %s\n", i + history_base, the_list[i]->line);
  1680.     }
  1681.       if (strncmp (line, "delete", strlen ("delete")) == 0)
  1682.     {
  1683.       int which;
  1684.       if ((sscanf (line + strlen ("delete"), "%d", &which)) == 1)
  1685.         {
  1686.           HIST_ENTRY *entry = remove_history (which);
  1687.           if (!entry)
  1688.         fprintf (stderr, "No such entry %d\n", which);
  1689.           else
  1690.         {
  1691.           free (entry->line);
  1692.           free (entry);
  1693.         }
  1694.         }
  1695.       else
  1696.         {
  1697.           fprintf (stderr, "non-numeric arg given to `delete'\n");
  1698.         }
  1699.     }
  1700.     }
  1701. }
  1702.  
  1703. #endif /* TEST */
  1704.  
  1705. /*
  1706. * Local variables:
  1707. * compile-command: "gcc -g -DTEST -o history history.c"
  1708. * end:
  1709. */
  1710.