home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / utils / file / managers / git-4.3 / git-4 / git-4.3.7 / src / history.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-07-08  |  52.2 KB  |  2,023 lines

  1. /* History.c -- standalone history library */
  2.  
  3. /* Copyright (C) 1989, 1992 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. #define READLINE_LIBRARY
  27.  
  28. #ifdef HAVE_CONFIG_H
  29. #include <config.h>
  30. #endif
  31.  
  32. #include <stdio.h>
  33. #include <sys/types.h>
  34. #include "file.h"
  35. #include "xio.h"
  36. #include <fcntl.h>
  37.  
  38. #if defined (HAVE_STDLIB_H)
  39. #  include <stdlib.h>
  40. #else
  41. #  include "ansi_stdlib.h"
  42. #endif /* HAVE_STDLIB_H */
  43.  
  44. #if defined (HAVE_UNISTD_H)
  45. #  include <unistd.h>
  46. #endif
  47.  
  48. #include "xstring.h"
  49.  
  50. #include <errno.h>
  51.  
  52. /* Not all systems declare ERRNO in errno.h... and some systems #define it! */
  53. #if !defined (errno)
  54. extern int errno;
  55. #endif /* !errno */
  56.  
  57. #include "history.h"
  58.  
  59. #include "xmalloc.h"
  60.  
  61. #define STREQ(a, b)     (((a)[0] == (b)[0]) && (strcmp ((a), (b)) == 0))
  62. #define STREQN(a, b, n) (((a)[0] == (b)[0]) && (strncmp ((a), (b), (n)) == 0))
  63.  
  64. #ifndef savestring
  65. #  ifndef strcpy
  66. extern char *strcpy ();
  67. #  endif
  68. #define savestring(x) strcpy (xmalloc (1 + strlen (x)), (x))
  69. #endif
  70.  
  71. #ifndef whitespace
  72. #define whitespace(c) (((c) == ' ') || ((c) == '\t'))
  73. #endif
  74.  
  75. #ifndef digit
  76. #define digit(c)  ((c) >= '0' && (c) <= '9')
  77. #endif
  78.  
  79. #ifndef digit_value
  80. #define digit_value(c) ((c) - '0')
  81. #endif
  82.  
  83. #ifndef member
  84. #  ifndef strchr
  85. extern char *strchr ();
  86. #  endif
  87. #define member(c, s) ((c) ? ((char *)strchr ((s), (c)) != (char *)NULL) : 0)
  88. #endif
  89.  
  90. /* Possible history errors passed to hist_error. */
  91. #define EVENT_NOT_FOUND 0
  92. #define BAD_WORD_SPEC   1
  93. #define SUBST_FAILED    2
  94. #define BAD_MODIFIER    3
  95.  
  96. static char error_pointer;
  97.  
  98. static char *subst_lhs;
  99. static char *subst_rhs;
  100. static int subst_lhs_len = 0;
  101. static int subst_rhs_len = 0;
  102.  
  103. static char *get_history_word_specifier ();
  104.  
  105. #if defined (SHELL)
  106. extern char *single_quote ();
  107. #endif
  108.  
  109. /* **************************************************************** */
  110. /*                                                                  */
  111. /*                      History Functions                           */
  112. /*                                                                  */
  113. /* **************************************************************** */
  114.  
  115. /* An array of HIST_ENTRY.  This is where we store the history. */
  116. static HIST_ENTRY **the_history = (HIST_ENTRY **)NULL;
  117.  
  118. /* Non-zero means that we have enforced a limit on the amount of
  119.    history that we save. */
  120. int history_stifled = 0;
  121.  
  122. /* If HISTORY_STIFLED is non-zero, then this is the maximum number of
  123.    entries to remember. */
  124. int max_input_history;
  125.  
  126. /* The current location of the interactive history pointer.  Just makes
  127.    life easier for outside callers. */
  128. static int history_offset = 0;
  129.  
  130. /* The number of strings currently stored in the input_history list. */
  131. int history_length = 0;
  132.  
  133. /* The current number of slots allocated to the input_history. */
  134. static int history_size = 0;
  135.  
  136. /* The number of slots to increase the_history by. */
  137. #define DEFAULT_HISTORY_GROW_SIZE 50
  138.  
  139. /* The character that represents the start of a history expansion
  140.    request.  This is usually `!'. */
  141. char history_expansion_char = '!';
  142.  
  143. /* The character that invokes word substitution if found at the start of
  144.    a line.  This is usually `^'. */
  145. char history_subst_char = '^';
  146.  
  147. /* During tokenization, if this character is seen as the first character
  148.    of a word, then it, and all subsequent characters upto a newline are
  149.    ignored.  For a Bourne shell, this should be '#'.  Bash special cases
  150.    the interactive comment character to not be a comment delimiter. */
  151. char history_comment_char = '\0';
  152.  
  153. /* The list of characters which inhibit the expansion of text if found
  154.    immediately following history_expansion_char. */
  155. char *history_no_expand_chars = " \t\n\r=";
  156.  
  157. /* The logical `base' of the history array.  It defaults to 1. */
  158. int history_base = 1;
  159.  
  160. /* Return the current HISTORY_STATE of the history. */
  161. HISTORY_STATE *
  162. history_get_history_state ()
  163. {
  164.   HISTORY_STATE *state;
  165.  
  166.   state = (HISTORY_STATE *)xmalloc (sizeof (HISTORY_STATE));
  167.   state->entries = the_history;
  168.   state->offset = history_offset;
  169.   state->length = history_length;
  170.   state->size = history_size;
  171.  
  172.   return (state);
  173. }
  174.  
  175. /* Set the state of the current history array to STATE. */
  176. void
  177. history_set_history_state (state)
  178.      HISTORY_STATE *state;
  179. {
  180.   the_history = state->entries;
  181.   history_offset = state->offset;
  182.   history_length = state->length;
  183.   history_size = state->size;
  184. }
  185.  
  186. /* Begin a session in which the history functions might be used.  This
  187.    initializes interactive variables. */
  188. void
  189. using_history ()
  190. {
  191.   history_offset = history_length;
  192. }
  193.  
  194. /* Return the number of bytes that the primary history entries are using.
  195.    This just adds up the lengths of the_history->lines. */
  196. int
  197. history_total_bytes ()
  198. {
  199.   register int i, result;
  200.  
  201.   result = 0;
  202.  
  203.   for (i = 0; the_history && the_history[i]; i++)
  204.     result += strlen (the_history[i]->line);
  205.  
  206.   return (result);
  207. }
  208.  
  209. /* Place STRING at the end of the history list.  The data field
  210.    is  set to NULL. */
  211. void
  212. add_history (string)
  213.      char *string;
  214. {
  215.   HIST_ENTRY *temp;
  216.  
  217.   if (history_stifled && (history_length == max_input_history))
  218.     {
  219.       register int i;
  220.  
  221.       /* If the history is stifled, and history_length is zero,
  222.          and it equals max_input_history, we don't save items. */
  223.       if (history_length == 0)
  224.         return;
  225.  
  226.       /* If there is something in the slot, then remove it. */
  227.       if (the_history[0])
  228.         {
  229.           free (the_history[0]->line);
  230.           free (the_history[0]);
  231.         }
  232.  
  233.       /* Copy the rest of the entries, moving down one slot. */
  234.       for (i = 0; i < history_length; i++)
  235.         the_history[i] = the_history[i + 1];
  236.  
  237.       history_base++;
  238.  
  239.     }
  240.   else
  241.     {
  242.       if (!history_size)
  243.         {
  244.           history_size = DEFAULT_HISTORY_GROW_SIZE;
  245.           the_history = (HIST_ENTRY **)xmalloc (history_size * sizeof (HIST_ENTRY *));
  246.           history_length = 1;
  247.  
  248.         }
  249.       else
  250.         {
  251.           if (history_length == (history_size - 1))
  252.             {
  253.               history_size += DEFAULT_HISTORY_GROW_SIZE;
  254.               the_history = (HIST_ENTRY **)
  255.                 xrealloc (the_history, history_size * sizeof (HIST_ENTRY *));
  256.             }
  257.           history_length++;
  258.         }
  259.     }
  260.  
  261.   temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  262.   temp->line = savestring (string);
  263.   temp->data = (char *)NULL;
  264.  
  265.   the_history[history_length] = (HIST_ENTRY *)NULL;
  266.   the_history[history_length - 1] = temp;
  267. }
  268.  
  269. /* Make the history entry at WHICH have LINE and DATA.  This returns
  270.    the old entry so you can dispose of the data.  In the case of an
  271.    invalid WHICH, a NULL pointer is returned. */
  272. HIST_ENTRY *
  273. replace_history_entry (which, line, data)
  274.      int which;
  275.      char *line;
  276.      char *data;
  277. {
  278.   HIST_ENTRY *temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  279.   HIST_ENTRY *old_value;
  280.  
  281.   if (which >= history_length)
  282.     return ((HIST_ENTRY *)NULL);
  283.  
  284.   old_value = the_history[which];
  285.  
  286.   temp->line = savestring (line);
  287.   temp->data = data;
  288.   the_history[which] = temp;
  289.  
  290.   return (old_value);
  291. }
  292.  
  293. /* Returns the magic number which says what history element we are
  294.    looking at now.  In this implementation, it returns history_offset. */
  295. int
  296. where_history ()
  297. {
  298.   return (history_offset);
  299. }
  300.  
  301. /* Search the history for STRING, starting at history_offset.
  302.    If DIRECTION < 0, then the search is through previous entries, else
  303.    through subsequent.  If ANCHORED is non-zero, the string must
  304.    appear at the beginning of a history line, otherwise, the string
  305.    may appear anywhere in the line.  If the string is found, then
  306.    current_history () is the history entry, and the value of this
  307.    function is the offset in the line of that history entry that the
  308.    string was found in.  Otherwise, nothing is changed, and a -1 is
  309.    returned. */
  310.  
  311. #define ANCHORED_SEARCH 1
  312. #define NON_ANCHORED_SEARCH 0
  313.  
  314. static int
  315. history_search_internal (string, direction, anchored)
  316.      char *string;
  317.      int direction, anchored;
  318. {
  319.   register int i, reverse;
  320.   register char *line;
  321.   register int line_index;
  322.   int string_len;
  323.  
  324.   i = history_offset;
  325.   reverse = (direction < 0);
  326.  
  327.   /* Take care of trivial cases first. */
  328.  
  329.   if (!history_length || ((i == history_length) && !reverse))
  330.     return (-1);
  331.  
  332.   if (reverse && (i == history_length))
  333.     i--;
  334.  
  335. #define NEXT_LINE() do { if (reverse) i--; else i++; } while (0)
  336.  
  337.   string_len = strlen (string);
  338.   while (1)
  339.     {
  340.       /* Search each line in the history list for STRING. */
  341.  
  342.       /* At limit for direction? */
  343.       if ((reverse && i < 0) || (!reverse && i == history_length))
  344.         return (-1);
  345.  
  346.       line = the_history[i]->line;
  347.       line_index = strlen (line);
  348.  
  349.       /* If STRING is longer than line, no match. */
  350.       if (string_len > line_index)
  351.         {
  352.           NEXT_LINE ();
  353.           continue;
  354.         }
  355.  
  356.       /* Handle anchored searches first. */
  357.       if (anchored == ANCHORED_SEARCH)
  358.         {
  359.           if (STREQN (string, line, string_len))
  360.             {
  361.               history_offset = i;
  362.               return (0);
  363.             }
  364.  
  365.           NEXT_LINE ();
  366.           continue;
  367.         }
  368.  
  369.       /* Do substring search. */
  370.       if (reverse)
  371.         {
  372.           line_index -= string_len;
  373.  
  374.           while (line_index >= 0)
  375.             {
  376.               if (STREQN (string, line + line_index, string_len))
  377.                 {
  378.                   history_offset = i;
  379.                   return (line_index);
  380.                 }
  381.               line_index--;
  382.             }
  383.         }
  384.       else
  385.         {
  386.           register int limit = line_index - string_len + 1;
  387.           line_index = 0;
  388.  
  389.           while (line_index < limit)
  390.             {
  391.               if (STREQN (string, line + line_index, string_len))
  392.                 {
  393.                   history_offset = i;
  394.                   return (line_index);
  395.                 }
  396.               line_index++;
  397.             }
  398.         }
  399.       NEXT_LINE ();
  400.     }
  401. }
  402.  
  403. /* Do a non-anchored search for STRING through the history in DIRECTION. */
  404. int
  405. history_search (string, direction)
  406.      char *string;
  407.      int direction;
  408. {
  409.   return (history_search_internal (string, direction, NON_ANCHORED_SEARCH));
  410. }
  411.  
  412. /* Do an anchored search for string through the history in DIRECTION. */
  413. int
  414. history_search_prefix (string, direction)
  415.      char *string;
  416.      int direction;
  417. {
  418.   return (history_search_internal (string, direction, ANCHORED_SEARCH));
  419. }
  420.  
  421. /* Remove history element WHICH from the history.  The removed
  422.    element is returned to you so you can free the line, data,
  423.    and containing structure. */
  424. HIST_ENTRY *
  425. remove_history (which)
  426.      int which;
  427. {
  428.   HIST_ENTRY *return_value;
  429.  
  430.   if (which >= history_length || !history_length)
  431.     return_value = (HIST_ENTRY *)NULL;
  432.   else
  433.     {
  434.       register int i;
  435.       return_value = the_history[which];
  436.  
  437.       for (i = which; i < history_length; i++)
  438.         the_history[i] = the_history[i + 1];
  439.  
  440.       history_length--;
  441.     }
  442.  
  443.   return (return_value);
  444. }
  445.  
  446. /* Stifle the history list, remembering only MAX number of lines. */
  447. void
  448. stifle_history (max)
  449.      int max;
  450. {
  451.   if (max < 0)
  452.     max = 0;
  453.  
  454.   if (history_length > max)
  455.     {
  456.       register int i, j;
  457.  
  458.       /* This loses because we cannot free the data. */
  459.       for (i = 0; i < (history_length - max); i++)
  460.         {
  461.           free (the_history[i]->line);
  462.           free (the_history[i]);
  463.         }
  464.  
  465.       history_base = i;
  466.       for (j = 0, i = history_length - max; j < max; i++, j++)
  467.         the_history[j] = the_history[i];
  468.       the_history[j] = (HIST_ENTRY *)NULL;
  469.       history_length = j;
  470.     }
  471.  
  472.   history_stifled = 1;
  473.   max_input_history = max;
  474. }
  475.  
  476. /* Stop stifling the history.  This returns the previous amount the history
  477.  was stifled by.  The value is positive if the history was stifled, negative
  478.  if it wasn't. */
  479. int
  480. unstifle_history ()
  481. {
  482.   int result = max_input_history;
  483.  
  484.   if (history_stifled)
  485.     {
  486.       result = -result;
  487.       history_stifled = 0;
  488.     }
  489.  
  490.   return (result);
  491. }
  492.  
  493. /* Return the string that should be used in the place of this
  494.    filename.  This only matters when you don't specify the
  495.    filename to read_history (), or write_history (). */
  496. static char *
  497. history_filename (filename)
  498.      char *filename;
  499. {
  500.   char *return_val = filename ? savestring (filename) : (char *)NULL;
  501.  
  502.   if (!return_val)
  503.     {
  504.       char *home;
  505.       int home_len;
  506.  
  507.       home = getenv ("HOME");
  508.  
  509.       if (!home)
  510.         home = ".";
  511.  
  512.       home_len = strlen (home);
  513.       /* strlen(".history") == 8 */
  514.       return_val = xmalloc (2 + home_len + 8);
  515.  
  516.       strcpy (return_val, home);
  517.       return_val[home_len] = '/';
  518.       strcpy (return_val + home_len + 1, ".history");
  519.     }
  520.  
  521.   return (return_val);
  522. }
  523.  
  524. /* Add the contents of FILENAME to the history list, a line at a time.
  525.    If FILENAME is NULL, then read from ~/.history.  Returns 0 if
  526.    successful, or errno if not. */
  527. int
  528. read_history (filename)
  529.      char *filename;
  530. {
  531.   return (read_history_range (filename, 0, -1));
  532. }
  533.  
  534. /* Read a range of lines from FILENAME, adding them to the history list.
  535.    Start reading at the FROM'th line and end at the TO'th.  If FROM
  536.    is zero, start at the beginning.  If TO is less than FROM, read
  537.    until the end of the file.  If FILENAME is NULL, then read from
  538.    ~/.history.  Returns 0 if successful, or errno if not. */
  539. int
  540. read_history_range (filename, from, to)
  541.      char *filename;
  542.      int from, to;
  543. {
  544.   register int line_start, line_end;
  545.   char *input, *buffer = (char *)NULL;
  546.   int file, current_line;
  547.   struct stat finfo;
  548.  
  549.   input = history_filename (filename);
  550.   file = open (input, O_RDONLY, 0666);
  551.  
  552.   if ((file < 0) || (xfstat (file, &finfo) == -1))
  553.     goto error_and_exit;
  554.  
  555.   buffer = xmalloc ((int)finfo.st_size + 1);
  556.  
  557.   if (read (file, buffer, finfo.st_size) != finfo.st_size)
  558.     {
  559.   error_and_exit:
  560.       if (file >= 0)
  561.         close (file);
  562.  
  563.       if (input)
  564.         free (input);
  565.  
  566.       if (buffer)
  567.         free (buffer);
  568.  
  569.       return (errno);
  570.     }
  571.  
  572.   close (file);
  573.  
  574.   /* Set TO to larger than end of file if negative. */
  575.   if (to < 0)
  576.     to = finfo.st_size;
  577.  
  578.   /* Start at beginning of file, work to end. */
  579.   line_start = line_end = current_line = 0;
  580.  
  581.   /* Skip lines until we are at FROM. */
  582.   while (line_start < finfo.st_size && current_line < from)
  583.     {
  584.       for (line_end = line_start; line_end < finfo.st_size; line_end++)
  585.         if (buffer[line_end] == '\n')
  586.           {
  587.             current_line++;
  588.             line_start = line_end + 1;
  589.             if (current_line == from)
  590.               break;
  591.           }
  592.     }
  593.  
  594.   /* If there are lines left to gobble, then gobble them now. */
  595.   for (line_end = line_start; line_end < finfo.st_size; line_end++)
  596.     if (buffer[line_end] == '\n')
  597.       {
  598.         buffer[line_end] = '\0';
  599.  
  600.         if (buffer[line_start])
  601.           add_history (buffer + line_start);
  602.  
  603.         current_line++;
  604.  
  605.         if (current_line >= to)
  606.           break;
  607.  
  608.         line_start = line_end + 1;
  609.       }
  610.  
  611.   if (input)
  612.     free (input);
  613.  
  614.   if (buffer)
  615.     free (buffer);
  616.  
  617.   return (0);
  618. }
  619.  
  620. /* Truncate the history file FNAME, leaving only LINES trailing lines.
  621.    If FNAME is NULL, then use ~/.history. */
  622. int
  623. history_truncate_file (fname, lines)
  624.      char *fname;
  625.      register int lines;
  626. {
  627.   register int i;
  628.   int file, chars_read;
  629.   char *buffer = (char *)NULL, *filename;
  630.   struct stat finfo;
  631.  
  632.   filename = history_filename (fname);
  633.   file = open (filename, O_RDONLY, 0666);
  634.  
  635.   if (file == -1 || xfstat (file, &finfo) == -1)
  636.     goto truncate_exit;
  637.  
  638.   buffer = xmalloc ((int)finfo.st_size + 1);
  639.   chars_read = read (file, buffer, finfo.st_size);
  640.   close (file);
  641.  
  642.   if (chars_read <= 0)
  643.     goto truncate_exit;
  644.  
  645.   /* Count backwards from the end of buffer until we have passed
  646.      LINES lines. */
  647.   for (i = chars_read - 1; lines && i; i--)
  648.     {
  649.       if (buffer[i] == '\n')
  650.         lines--;
  651.     }
  652.  
  653.   /* If this is the first line, then the file contains exactly the
  654.      number of lines we want to truncate to, so we don't need to do
  655.      anything.  It's the first line if we don't find a newline between
  656.      the current value of i and 0.  Otherwise, write from the start of
  657.      this line until the end of the buffer. */
  658.   for ( ; i; i--)
  659.     if (buffer[i] == '\n')
  660.       {
  661.         i++;
  662.         break;
  663.       }
  664.  
  665.   /* Write only if there are more lines in the file than we want to
  666.      truncate to. */
  667.   if (i && ((file = open (filename, O_WRONLY|O_TRUNC, 0666)) != -1))
  668.     {
  669.       write (file, buffer + i, finfo.st_size - i);
  670.       close (file);
  671.     }
  672.  
  673.  truncate_exit:
  674.   if (buffer)
  675.     free (buffer);
  676.  
  677.   free (filename);
  678.   return 0;
  679. }
  680.  
  681. #define HISTORY_APPEND 0
  682. #define HISTORY_OVERWRITE 1
  683.  
  684. /* Workhorse function for writing history.  Writes NELEMENT entries
  685.    from the history list to FILENAME.  OVERWRITE is non-zero if you
  686.    wish to replace FILENAME with the entries. */
  687. static int
  688. history_do_write (filename, nelements, overwrite)
  689.      char *filename;
  690.      int nelements, overwrite;
  691. {
  692.   register int i;
  693.   char *output = history_filename (filename);
  694.   int file, mode;
  695.  
  696.   mode = overwrite ? O_WRONLY | O_CREAT | O_TRUNC : O_WRONLY | O_APPEND;
  697.  
  698.   if ((file = open (output, mode, 0666)) == -1)
  699.     {
  700.       if (output)
  701.         free (output);
  702.  
  703.       return (errno);
  704.     }
  705.  
  706.   if (nelements > history_length)
  707.     nelements = history_length;
  708.  
  709.   /* Build a buffer of all the lines to write, and write them in one syscall.
  710.      Suggested by Peter Ho (peter@robosts.oxford.ac.uk). */
  711.   {
  712.     register int j = 0;
  713.     int buffer_size = 0;
  714.     char *buffer;
  715.  
  716.     /* Calculate the total number of bytes to write. */
  717.     for (i = history_length - nelements; i < history_length; i++)
  718.       buffer_size += 1 + strlen (the_history[i]->line);
  719.  
  720.     /* Allocate the buffer, and fill it. */
  721.     buffer = xmalloc (buffer_size);
  722.  
  723.     for (i = history_length - nelements; i < history_length; i++)
  724.       {
  725.         strcpy (buffer + j, the_history[i]->line);
  726.         j += strlen (the_history[i]->line);
  727.         buffer[j++] = '\n';
  728.       }
  729.  
  730.     write (file, buffer, buffer_size);
  731.     free (buffer);
  732.   }
  733.  
  734.   close (file);
  735.  
  736.   if (output)
  737.     free (output);
  738.  
  739.   return (0);
  740. }
  741.  
  742. /* Append NELEMENT entries to FILENAME.  The entries appended are from
  743.    the end of the list minus NELEMENTs up to the end of the list. */
  744. int
  745. append_history (nelements, filename)
  746.      int nelements;
  747.      char *filename;
  748. {
  749.   return (history_do_write (filename, nelements, HISTORY_APPEND));
  750. }
  751.  
  752. /* Overwrite FILENAME with the current history.  If FILENAME is NULL,
  753.    then write the history list to ~/.history.  Values returned
  754.    are as in read_history ().*/
  755. int
  756. write_history (filename)
  757.      char *filename;
  758. {
  759.   return (history_do_write (filename, history_length, HISTORY_OVERWRITE));
  760. }
  761.  
  762. /* Return the history entry at the current position, as determined by
  763.    history_offset.  If there is no entry there, return a NULL pointer. */
  764. HIST_ENTRY *
  765. current_history ()
  766. {
  767.   if ((history_offset == history_length) || !the_history)
  768.     return ((HIST_ENTRY *)NULL);
  769.   else
  770.     return (the_history[history_offset]);
  771. }
  772.  
  773. /* Back up history_offset to the previous history entry, and return
  774.    a pointer to that entry.  If there is no previous entry then return
  775.    a NULL pointer. */
  776. HIST_ENTRY *
  777. previous_history ()
  778. {
  779.   if (!history_offset)
  780.     return ((HIST_ENTRY *)NULL);
  781.   else
  782.     return (the_history[--history_offset]);
  783. }
  784.  
  785. /* Move history_offset forward to the next history entry, and return
  786.    a pointer to that entry.  If there is no next entry then return a
  787.    NULL pointer. */
  788. HIST_ENTRY *
  789. next_history ()
  790. {
  791.   if (history_offset == history_length)
  792.     return ((HIST_ENTRY *)NULL);
  793.   else
  794.     return (the_history[++history_offset]);
  795. }
  796.  
  797. /* Return the current history array.  The caller has to be carefull, since this
  798.    is the actual array of data, and could be bashed or made corrupt easily.
  799.    The array is terminated with a NULL pointer. */
  800. HIST_ENTRY **
  801. history_list ()
  802. {
  803.   return (the_history);
  804. }
  805.  
  806. /* Return the history entry which is logically at OFFSET in the history array.
  807.    OFFSET is relative to history_base. */
  808. HIST_ENTRY *
  809. history_get (offset)
  810.      int offset;
  811. {
  812.   int local_index = offset - history_base;
  813.  
  814.   if (local_index >= history_length ||
  815.       local_index < 0 ||
  816.       !the_history)
  817.     return ((HIST_ENTRY *)NULL);
  818.   return (the_history[local_index]);
  819. }
  820.  
  821. /* Search for STRING in the history list.  DIR is < 0 for searching
  822.    backwards.  POS is an absolute index into the history list at
  823.    which point to begin searching. */
  824. int
  825. history_search_pos (string, dir, pos)
  826.      char *string;
  827.      int dir, pos;
  828. {
  829.   int ret, old = where_history ();
  830.   history_set_pos (pos);
  831.   if (history_search (string, dir) == -1)
  832.     {
  833.       history_set_pos (old);
  834.       return (-1);
  835.     }
  836.   ret = where_history ();
  837.   history_set_pos (old);
  838.   return ret;
  839. }
  840.  
  841. /* Make the current history item be the one at POS, an absolute index.
  842.    Returns zero if POS is out of range, else non-zero. */
  843. int
  844. history_set_pos (pos)
  845.      int pos;
  846. {
  847.   if (pos > history_length || pos < 0 || !the_history)
  848.     return (0);
  849.   history_offset = pos;
  850.   return (1);
  851. }
  852.  
  853.  
  854. /* **************************************************************** */
  855. /*                                                                  */
  856. /*                      History Expansion                           */
  857. /*                                                                  */
  858. /* **************************************************************** */
  859.  
  860. /* Hairy history expansion on text, not tokens.  This is of general
  861.    use, and thus belongs in this library. */
  862.  
  863. /* The last string searched for in a !?string? search. */
  864. static char *search_string = (char *)NULL;
  865.  
  866. /* Return the event specified at TEXT + OFFSET modifying OFFSET to
  867.    point to after the event specifier.  Just a pointer to the history
  868.    line is returned; NULL is returned in the event of a bad specifier.
  869.    You pass STRING with *INDEX equal to the history_expansion_char that
  870.    begins this specification.
  871.    DELIMITING_QUOTE is a character that is allowed to end the string
  872.    specification for what to search for in addition to the normal
  873.    characters `:', ` ', `\t', `\n', and sometimes `?'.
  874.    So you might call this function like:
  875.    line = get_history_event ("!echo:p", &index, 0);  */
  876. char *
  877. get_history_event (string, caller_index, delimiting_quote)
  878.      char *string;
  879.      int *caller_index;
  880.      int delimiting_quote;
  881. {
  882.   register int i = *caller_index;
  883.   register char c;
  884.   HIST_ENTRY *entry;
  885.   int which, sign = 1;
  886.   int local_index, search_mode, substring_okay = 0;
  887.   char *temp;
  888.  
  889.   /* The event can be specified in a number of ways.
  890.  
  891.      !!   the previous command
  892.      !n   command line N
  893.      !-n  current command-line minus N
  894.      !str the most recent command starting with STR
  895.      !?str[?]
  896.           the most recent command containing STR
  897.  
  898.      All values N are determined via HISTORY_BASE. */
  899.  
  900.   if (string[i] != history_expansion_char)
  901.     return ((char *)NULL);
  902.  
  903.   /* Move on to the specification. */
  904.   i++;
  905.  
  906. #define RETURN_ENTRY(e, w) \
  907.         return ((e = history_get (w)) ? e->line : (char *)NULL)
  908.  
  909.   /* Handle !! case. */
  910.   if (string[i] == history_expansion_char)
  911.     {
  912.       i++;
  913.       which = history_base + (history_length - 1);
  914.       *caller_index = i;
  915.       RETURN_ENTRY (entry, which);
  916.     }
  917.  
  918.   /* Hack case of numeric line specification. */
  919.   if (string[i] == '-')
  920.     {
  921.       sign = -1;
  922.       i++;
  923.     }
  924.  
  925.   if (digit (string[i]))
  926.     {
  927.       /* Get the extent of the digits and compute the value. */
  928.       for (which = 0; digit (string[i]); i++)
  929.         which = (which * 10) + digit_value (string[i]);
  930.  
  931.       *caller_index = i;
  932.  
  933.       if (sign < 0)
  934.         which = (history_length + history_base) - which;
  935.  
  936.       RETURN_ENTRY (entry, which);
  937.     }
  938.  
  939.   /* This must be something to search for.  If the spec begins with
  940.      a '?', then the string may be anywhere on the line.  Otherwise,
  941.      the string must be found at the start of a line. */
  942.   if (string[i] == '?')
  943.     {
  944.       substring_okay++;
  945.       i++;
  946.     }
  947.  
  948.   /* Only a closing `?' or a newline delimit a substring search string. */
  949.   for (local_index = i; (c = string[i]); i++)
  950.     if ((!substring_okay && (whitespace (c) || c == ':' ||
  951. #if defined (SHELL)
  952.           member (c, ";&()|<>") ||
  953. #endif /* SHELL */
  954.           string[i] == delimiting_quote)) ||
  955.         string[i] == '\n' ||
  956.         (substring_okay && string[i] == '?'))
  957.       break;
  958.  
  959.   temp = xmalloc (1 + (i - local_index));
  960.   strncpy (temp, &string[local_index], (i - local_index));
  961.   temp[i - local_index] = '\0';
  962.  
  963.   if (substring_okay && string[i] == '?')
  964.     i++;
  965.  
  966.   *caller_index = i;
  967.  
  968. #define FAIL_SEARCH() \
  969.   do { history_offset = history_length; free (temp) ; return (char *)NULL; } while (0)
  970.  
  971.   search_mode = substring_okay ? NON_ANCHORED_SEARCH : ANCHORED_SEARCH;
  972.   while (1)
  973.     {
  974.       local_index = history_search_internal (temp, -1, search_mode);
  975.  
  976.       if (local_index < 0)
  977.         FAIL_SEARCH ();
  978.  
  979.       if (local_index == 0 || substring_okay)
  980.         {
  981.           entry = current_history ();
  982.           history_offset = history_length;
  983.         
  984.           /* If this was a substring search, then remember the
  985.              string that we matched for word substitution. */
  986.           if (substring_okay)
  987.             {
  988.               if (search_string)
  989.                 free (search_string);
  990.               search_string = temp;
  991.             }
  992.           else
  993.             free (temp);
  994.           return (entry->line);
  995.         }
  996.  
  997.       if (history_offset)
  998.         history_offset--;
  999.       else
  1000.         FAIL_SEARCH ();
  1001.     }
  1002. #undef FAIL_SEARCH
  1003. #undef RETURN_ENTRY
  1004. }
  1005. #if defined (SHELL)
  1006. /* Function for extracting single-quoted strings.  Used for inhibiting
  1007.    history expansion within single quotes. */
  1008.  
  1009. /* Extract the contents of STRING as if it is enclosed in single quotes.
  1010.    SINDEX, when passed in, is the offset of the character immediately
  1011.    following the opening single quote; on exit, SINDEX is left pointing
  1012.    to the closing single quote. */
  1013. static void
  1014. rl_string_extract_single_quoted (string, sindex)
  1015.      char *string;
  1016.      int *sindex;
  1017. {
  1018.   register int i = *sindex;
  1019.  
  1020.   while (string[i] && string[i] != '\'')
  1021.     i++;
  1022.  
  1023.   *sindex = i;
  1024. }
  1025.  
  1026. static char *
  1027. quote_breaks (s)
  1028.      char *s;
  1029. {
  1030.   register char *p, *r;
  1031.   char *ret;
  1032.   int len = 3;
  1033.  
  1034.   for (p = s; p && *p; p++, len++)
  1035.     {
  1036.       if (*p == '\'')
  1037.         len += 3;
  1038.       else if (whitespace (*p) || *p == '\n')
  1039.         len += 2;
  1040.     }
  1041.  
  1042.   r = ret = xmalloc (len);
  1043.   *r++ = '\'';
  1044.   for (p = s; p && *p; )
  1045.     {
  1046.       if (*p == '\'')
  1047.         {
  1048.           *r++ = '\'';
  1049.           *r++ = '\\';
  1050.           *r++ = '\'';
  1051.           *r++ = '\'';
  1052.           p++;
  1053.         }
  1054.       else if (whitespace (*p) || *p == '\n')
  1055.         {
  1056.           *r++ = '\'';
  1057.           *r++ = *p++;
  1058.           *r++ = '\'';
  1059.         }
  1060.       else
  1061.         *r++ = *p++;
  1062.     }
  1063.   *r++ = '\'';
  1064.   *r = '\0';
  1065.   return ret;
  1066. }
  1067. #endif /* SHELL */
  1068.  
  1069. static char *
  1070. hist_error(s, start, current, errtype)
  1071.       char *s;
  1072.       int start, current, errtype;
  1073. {
  1074.   char *temp, *emsg;
  1075.   int ll, elen;
  1076.  
  1077.   ll = current - start;
  1078.  
  1079.   switch (errtype)
  1080.     {
  1081.     case EVENT_NOT_FOUND:
  1082.       emsg = "event not found";
  1083.       elen = 15;
  1084.       break;
  1085.     case BAD_WORD_SPEC:
  1086.       emsg = "bad word specifier";
  1087.       elen = 18;
  1088.       break;
  1089.     case SUBST_FAILED:
  1090.       emsg = "substitution failed";
  1091.       elen = 19;
  1092.       break;
  1093.     case BAD_MODIFIER:
  1094.       emsg = "unrecognized history modifier";
  1095.       elen = 29;
  1096.       break;
  1097.     default:
  1098.       emsg = "unknown expansion error";
  1099.       elen = 23;
  1100.       break;
  1101.     }
  1102.  
  1103.   temp = xmalloc (ll + elen + 3);
  1104.   strncpy (temp, s + start, ll);
  1105.   temp[ll] = ':';
  1106.   temp[ll + 1] = ' ';
  1107.   strcpy (temp + ll + 2, emsg);
  1108.   return (temp);
  1109. }
  1110.  
  1111. /* Get a history substitution string from STR starting at *IPTR
  1112.    and return it.  The length is returned in LENPTR.
  1113.  
  1114.    A backslash can quote the delimiter.  If the string is the
  1115.    empty string, the previous pattern is used.  If there is
  1116.    no previous pattern for the lhs, the last history search
  1117.    string is used.
  1118.  
  1119.    If IS_RHS is 1, we ignore empty strings and set the pattern
  1120.    to "" anyway.  subst_lhs is not changed if the lhs is empty;
  1121.    subst_rhs is allowed to be set to the empty string. */
  1122.  
  1123. static char *
  1124. get_subst_pattern (str, iptr, delimiter, is_rhs, lenptr)
  1125.      char *str;
  1126.      int *iptr, delimiter, is_rhs, *lenptr;
  1127. {
  1128.   register int si, i, j, k;
  1129.   char *s = (char *) NULL;
  1130.  
  1131.   i = *iptr;
  1132.  
  1133.   for (si = i; str[si] && str[si] != delimiter; si++)
  1134.     if (str[si] == '\\' && str[si + 1] == delimiter)
  1135.       si++;
  1136.  
  1137.   if (si > i || is_rhs)
  1138.     {
  1139.       s = xmalloc (si - i + 1);
  1140.       for (j = 0, k = i; k < si; j++, k++)
  1141.         {
  1142.           /* Remove a backslash quoting the search string delimiter. */
  1143.           if (str[k] == '\\' && str[k + 1] == delimiter)
  1144.             k++;
  1145.           s[j] = str[k];
  1146.         }
  1147.       s[j] = '\0';
  1148.       if (lenptr)
  1149.         *lenptr = j;
  1150.     }
  1151.  
  1152.   i = si;
  1153.   if (str[i])
  1154.     i++;
  1155.   *iptr = i;
  1156.  
  1157.   return s;
  1158. }
  1159.  
  1160. static void
  1161. postproc_subst_rhs ()
  1162. {
  1163.   char *new;
  1164.   int i, j, new_size;
  1165.  
  1166.   new = xmalloc (new_size = subst_rhs_len + subst_lhs_len);
  1167.   for (i = j = 0; i < subst_rhs_len; i++)
  1168.     {
  1169.       if (subst_rhs[i] == '&')
  1170.         {
  1171.           if (j + subst_lhs_len >= new_size)
  1172.             new = xrealloc (new, (new_size = new_size * 2 + subst_lhs_len));
  1173.           strcpy (new + j, subst_lhs);
  1174.           j += subst_lhs_len;
  1175.         }
  1176.       else
  1177.         {
  1178.           /* a single backslash protects the `&' from lhs interpolation */
  1179.           if (subst_rhs[i] == '\\' && subst_rhs[i + 1] == '&')
  1180.             i++;
  1181.           if (j >= new_size)
  1182.             new = xrealloc (new, new_size *= 2);
  1183.           new[j++] = subst_rhs[i];
  1184.         }
  1185.     }
  1186.   new[j] = '\0';
  1187.   free (subst_rhs);
  1188.   subst_rhs = new;
  1189.   subst_rhs_len = j;
  1190. }
  1191.  
  1192. /* Expand the bulk of a history specifier starting at STRING[START].
  1193.    Returns 0 if everything is OK, -1 if an error occurred, and 1
  1194.    if the `p' modifier was supplied and the caller should just print
  1195.    the returned string.  Returns the new index into string in
  1196.    *END_INDEX_PTR, and the expanded specifier in *RET_STRING. */
  1197. static int
  1198. history_expand_internal (string, start, end_index_ptr, ret_string, current_line)
  1199.      char *string;
  1200.      int start, *end_index_ptr;
  1201.      char **ret_string;
  1202.      char *current_line;        /* for !# */
  1203. {
  1204.   int i, n, starting_index;
  1205.   int substitute_globally, want_quotes, print_only;
  1206.   char *event, *temp, *result, *tstr, *t, c, *word_spec;
  1207.   int result_len;
  1208.  
  1209.   result = xmalloc (result_len = 128);
  1210.  
  1211.   i = start;
  1212.  
  1213.   /* If it is followed by something that starts a word specifier,
  1214.      then !! is implied as the event specifier. */
  1215.  
  1216.   if (member (string[i + 1], ":$*%^"))
  1217.     {
  1218.       char fake_s[3];
  1219.       int fake_i = 0;
  1220.       i++;
  1221.       fake_s[0] = fake_s[1] = history_expansion_char;
  1222.       fake_s[2] = '\0';
  1223.       event = get_history_event (fake_s, &fake_i, 0);
  1224.     }
  1225.   else if (string[i + 1] == '#')
  1226.     {
  1227.       i += 2;
  1228.       event = current_line;
  1229.     }
  1230.   else
  1231.     {
  1232.       int quoted_search_delimiter = 0;
  1233.  
  1234.       /* If the character before this `!' is a double or single
  1235.          quote, then this expansion takes place inside of the
  1236.          quoted string.  If we have to search for some text ("!foo"),
  1237.          allow the delimiter to end the search string. */
  1238.       if (i && (string[i - 1] == '\'' || string[i - 1] == '"'))
  1239.         quoted_search_delimiter = string[i - 1];
  1240.       event = get_history_event (string, &i, quoted_search_delimiter);
  1241.     }
  1242.           
  1243.   if (!event)
  1244.     {
  1245.       *ret_string = hist_error (string, start, i, EVENT_NOT_FOUND);
  1246.       free (result);
  1247.       return (-1);
  1248.     }
  1249.  
  1250.   /* If a word specifier is found, then do what that requires. */
  1251.   starting_index = i;
  1252.   word_spec = get_history_word_specifier (string, event, &i);
  1253.  
  1254.   /* There is no such thing as a `malformed word specifier'.  However,
  1255.      it is possible for a specifier that has no match.  In that case,
  1256.      we complain. */
  1257.   if (word_spec == (char *)&error_pointer)
  1258.     {
  1259.       *ret_string = hist_error (string, starting_index, i, BAD_WORD_SPEC);
  1260.       free (result);
  1261.       return (-1);
  1262.     }
  1263.  
  1264.   /* If no word specifier, than the thing of interest was the event. */
  1265.   if (!word_spec)
  1266.     temp = savestring (event);
  1267.   else
  1268.     {
  1269.       temp = savestring (word_spec);
  1270.       free (word_spec);
  1271.     }
  1272.  
  1273.   /* Perhaps there are other modifiers involved.  Do what they say. */
  1274.   want_quotes = substitute_globally = print_only = 0;
  1275.   starting_index = i;
  1276.  
  1277.   while (string[i] == ':')
  1278.     {
  1279.       c = string[i + 1];
  1280.  
  1281.       if (c == 'g')
  1282.         {
  1283.           substitute_globally = 1;
  1284.           i++;
  1285.           c = string[i + 1];
  1286.         }
  1287.  
  1288.       switch (c)
  1289.         {
  1290.         default:
  1291.           *ret_string = hist_error (string, i+1, i+2, BAD_MODIFIER);
  1292.           free (result);
  1293.           free (temp);
  1294.           return -1;
  1295.  
  1296. #if defined (SHELL)
  1297.         case 'q':
  1298.           want_quotes = 'q';
  1299.           break;
  1300.  
  1301.         case 'x':
  1302.           want_quotes = 'x';
  1303.           break;
  1304. #endif /* SHELL */
  1305.  
  1306.           /* :p means make this the last executed line.  So we
  1307.              return an error state after adding this line to the
  1308.              history. */
  1309.         case 'p':
  1310.           print_only++;
  1311.           break;
  1312.  
  1313.           /* :t discards all but the last part of the pathname. */
  1314.         case 't':
  1315.           tstr = strrchr (temp, '/');
  1316.           if (tstr)
  1317.             {
  1318.               tstr++;
  1319.               t = savestring (tstr);
  1320.               free (temp);
  1321.               temp = t;
  1322.             }
  1323.           break;
  1324.  
  1325.           /* :h discards the last part of a pathname. */
  1326.         case 'h':
  1327.           tstr = strrchr (temp, '/');
  1328.           if (tstr)
  1329.             *tstr = '\0';
  1330.           break;
  1331.  
  1332.           /* :r discards the suffix. */
  1333.         case 'r':
  1334.           tstr = strrchr (temp, '.');
  1335.           if (tstr)
  1336.             *tstr = '\0';
  1337.           break;
  1338.  
  1339.           /* :e discards everything but the suffix. */
  1340.         case 'e':
  1341.           tstr = strrchr (temp, '.');
  1342.           if (tstr)
  1343.             {
  1344.               t = savestring (tstr);
  1345.               free (temp);
  1346.               temp = t;
  1347.             }
  1348.           break;
  1349.  
  1350.         /* :s/this/that substitutes `that' for the first
  1351.            occurrence of `this'.  :gs/this/that substitutes `that'
  1352.            for each occurrence of `this'.  :& repeats the last
  1353.            substitution.  :g& repeats the last substitution
  1354.            globally. */
  1355.  
  1356.         case '&':
  1357.         case 's':
  1358.           {
  1359.             char *new_event, *t;
  1360.             int delimiter, failed, si, l_temp;
  1361.  
  1362.             if (c == 's')
  1363.               {
  1364.                 if (i + 2 < (int)strlen (string))
  1365.                   delimiter = string[i + 2];
  1366.                 else
  1367.                   break;        /* no search delimiter */
  1368.  
  1369.                 i += 3;
  1370.  
  1371.                 t = get_subst_pattern (string, &i, delimiter, 0, &subst_lhs_len);
  1372.                 /* An empty substitution lhs with no previous substitution
  1373.                    uses the last search string as the lhs. */
  1374.                 if (t)
  1375.                   {
  1376.                     if (subst_lhs)
  1377.                       free (subst_lhs);
  1378.                     subst_lhs = t;
  1379.                   }
  1380.                 else if (!subst_lhs)
  1381.                   {
  1382.                     if (search_string && *search_string)
  1383.                       {
  1384.                         subst_lhs = savestring (search_string);
  1385.                         subst_lhs_len = strlen (subst_lhs);
  1386.                       }
  1387.                     else
  1388.                       {
  1389.                         subst_lhs = (char *) NULL;
  1390.                         subst_lhs_len = 0;
  1391.                       }
  1392.                   }
  1393.  
  1394.                 /* If there is no lhs, the substitution can't succeed. */
  1395.                 if (subst_lhs_len == 0)
  1396.                   {
  1397.                     *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
  1398.                     free (result);
  1399.                     free (temp);
  1400.                     return -1;
  1401.                   }
  1402.  
  1403.                 if (subst_rhs)
  1404.                   free (subst_rhs);
  1405.                 subst_rhs = get_subst_pattern (string, &i, delimiter, 1, &subst_rhs_len);
  1406.  
  1407.                 /* If `&' appears in the rhs, it's supposed to be replaced
  1408.                    with the lhs. */
  1409.                 if (member ('&', subst_rhs))
  1410.                   postproc_subst_rhs ();
  1411.               }
  1412.             else
  1413.               i += 2;
  1414.  
  1415.             l_temp = strlen (temp);
  1416.             /* Ignore impossible cases. */
  1417.             if (subst_lhs_len > l_temp)
  1418.               {
  1419.                 *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
  1420.                 free (result);
  1421.                 free (temp);
  1422.                 return (-1);
  1423.               }
  1424.  
  1425.             /* Find the first occurrence of THIS in TEMP. */
  1426.             si = 0;
  1427.             for (failed = 1; (si + subst_lhs_len) <= l_temp; si++)
  1428.               if (STREQN (temp+si, subst_lhs, subst_lhs_len))
  1429.                 {
  1430.                   int len = subst_rhs_len - subst_lhs_len + l_temp;
  1431.                   new_event = xmalloc (1 + len);
  1432.                   strncpy (new_event, temp, si);
  1433.                   strncpy (new_event + si, subst_rhs, subst_rhs_len);
  1434.                   strncpy (new_event + si + subst_rhs_len,
  1435.                            temp + si + subst_lhs_len,
  1436.                            l_temp - (si + subst_lhs_len));
  1437.                   new_event[len] = '\0';
  1438.                   free (temp);
  1439.                   temp = new_event;
  1440.  
  1441.                   failed = 0;
  1442.  
  1443.                   if (substitute_globally)
  1444.                     {
  1445.                       si += subst_rhs_len;
  1446.                       l_temp = strlen (temp);
  1447.                       substitute_globally++;
  1448.                       continue;
  1449.                     }
  1450.                   else
  1451.                     break;
  1452.                 }
  1453.  
  1454.             if (substitute_globally > 1)
  1455.               {
  1456.                 substitute_globally = 0;
  1457.                 continue;       /* don't want to increment i */
  1458.               }
  1459.  
  1460.             if (failed == 0)
  1461.               continue;         /* don't want to increment i */
  1462.  
  1463.             *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
  1464.             free (result);
  1465.             free (temp);
  1466.             return (-1);
  1467.           }
  1468.         }
  1469.       i += 2;
  1470.     }
  1471.   /* Done with modfiers. */
  1472.   /* Believe it or not, we have to back the pointer up by one. */
  1473.   --i;
  1474.  
  1475. #if defined (SHELL)
  1476.   if (want_quotes)
  1477.     {
  1478.       char *x;
  1479.  
  1480.       if (want_quotes == 'q')
  1481.         x = single_quote (temp);
  1482.       else if (want_quotes == 'x')
  1483.         x = quote_breaks (temp);
  1484.       else
  1485.         x = savestring (temp);
  1486.  
  1487.       free (temp);
  1488.       temp = x;
  1489.     }
  1490. #endif /* SHELL */
  1491.  
  1492.   n = strlen (temp);
  1493.   if (n > result_len)
  1494.     result = xrealloc (result, n + 1);
  1495.   strcpy (result, temp);
  1496.   free (temp);
  1497.  
  1498.   *end_index_ptr = i;
  1499.   *ret_string = result;
  1500.   return (print_only);
  1501. }
  1502.  
  1503. /* Expand the string STRING, placing the result into OUTPUT, a pointer
  1504.    to a string.  Returns:
  1505.  
  1506.   -1) If there was an error in expansion.
  1507.    0) If no expansions took place (or, if the only change in
  1508.       the text was the de-slashifying of the history expansion
  1509.       character)
  1510.    1) If expansions did take place
  1511.    2) If the `p' modifier was given and the caller should print the result
  1512.  
  1513.   If an error ocurred in expansion, then OUTPUT contains a descriptive
  1514.   error message. */
  1515.  
  1516. #define ADD_STRING(s) \
  1517.         do \
  1518.           { \
  1519.             int sl = strlen (s); \
  1520.             j += sl; \
  1521.             while (j >= result_len) \
  1522.               result = xrealloc (result, result_len += 128); \
  1523.             strcpy (result + j - sl, s); \
  1524.           } \
  1525.         while (0)
  1526.  
  1527. #define ADD_CHAR(c) \
  1528.         do \
  1529.           { \
  1530.             if (j >= result_len) \
  1531.               result = xrealloc (result, result_len += 64); \
  1532.             result[j++] = c; \
  1533.             result[j] = '\0'; \
  1534.           } \
  1535.         while (0)
  1536.  
  1537. int
  1538. history_expand (hstring, output)
  1539.      char *hstring;
  1540.      char **output;
  1541. {
  1542.   register int j;
  1543.   int i, r, l, passc, cc, modified, eindex, only_printing;
  1544.   char *string;
  1545.  
  1546.   /* The output string, and its length. */
  1547.   int result_len;
  1548.   char *result;
  1549.  
  1550.   /* Used when adding the string. */
  1551.   char *temp;
  1552.  
  1553.   /* Setting the history expansion character to 0 inhibits all
  1554.      history expansion. */
  1555.   if (history_expansion_char == 0)
  1556.     {
  1557.       *output = savestring (hstring);
  1558.       return (0);
  1559.     }
  1560.     
  1561.   /* Prepare the buffer for printing error messages. */
  1562.   result = xmalloc (result_len = 256);
  1563.   result[0] = '\0';
  1564.  
  1565.   only_printing = modified = 0;
  1566.   l = strlen (hstring);
  1567.  
  1568.   /* Grovel the string.  Only backslash can quote the history escape
  1569.      character.  We also handle arg specifiers. */
  1570.  
  1571.   /* Before we grovel forever, see if the history_expansion_char appears
  1572.      anywhere within the text. */
  1573.  
  1574.   /* The quick substitution character is a history expansion all right.  That
  1575.      is to say, "^this^that^" is equivalent to "!!:s^this^that^", and in fact,
  1576.      that is the substitution that we do. */
  1577.   if (hstring[0] == history_subst_char)
  1578.     {
  1579.       string = xmalloc (l + 5);
  1580.  
  1581.       string[0] = string[1] = history_expansion_char;
  1582.       string[2] = ':';
  1583.       string[3] = 's';
  1584.       strcpy (string + 4, hstring);
  1585.       l += 4;
  1586.     }
  1587.   else
  1588.     {
  1589.       string = hstring;
  1590.       /* If not quick substitution, still maybe have to do expansion. */
  1591.  
  1592.       /* `!' followed by one of the characters in history_no_expand_chars
  1593.          is NOT an expansion. */
  1594.       for (i = 0; string[i]; i++)
  1595.         {
  1596.           cc = string[i + 1];
  1597.           if (string[i] == history_expansion_char)
  1598.             {
  1599.               if (!cc || member (cc, history_no_expand_chars))
  1600.                 continue;
  1601. #if defined (SHELL)
  1602.               /* The shell uses ! as a pattern negation character
  1603.                  in globbing [...] expressions, so let those pass
  1604.                  without expansion. */
  1605.               else if (i > 0 && (string[i - 1] == '[') &&
  1606.                        member (']', string + i + 1))
  1607.                 continue;
  1608. #endif /* SHELL */
  1609.               else
  1610.                 break;
  1611.             }
  1612. #if defined (SHELL)
  1613.           else if (string[i] == '\'')
  1614.             {
  1615.               /* If this is bash, single quotes inhibit history expansion. */
  1616.               i++;
  1617.               rl_string_extract_single_quoted (string, &i);
  1618.             }
  1619.           else if (string[i] == '\\')
  1620.             {
  1621.               /* If this is bash, allow backslashes to quote single
  1622.                  quotes and
  1623.                  the history expansion character. */
  1624.               if (cc == '\'' || cc == history_expansion_char)
  1625.                 i++;
  1626.             }
  1627. #endif /* SHELL */
  1628.         }
  1629.           
  1630.       if (string[i] != history_expansion_char)
  1631.         {
  1632.           free (result);
  1633.           *output = savestring (string);
  1634.           return (0);
  1635.         }
  1636.     }
  1637.  
  1638.   /* Extract and perform the substitution. */
  1639.   for (passc = i = j = 0; i < l; i++)
  1640.     {
  1641.       int tchar = string[i];
  1642.  
  1643.       if (passc)
  1644.         {
  1645.           passc = 0;
  1646.           ADD_CHAR (tchar);
  1647.           continue;
  1648.         }
  1649.  
  1650.       if (tchar == history_expansion_char)
  1651.         tchar = -3;
  1652.  
  1653.       switch (tchar)
  1654.         {
  1655.         default:
  1656.           ADD_CHAR (string[i]);
  1657.           break;
  1658.  
  1659.         case '\\':
  1660.           passc++;
  1661.           ADD_CHAR (tchar);
  1662.           break;
  1663.  
  1664. #if defined (SHELL)
  1665.         case '\'':
  1666.           {
  1667.             /* If this is bash, single quotes inhibit history expansion. */
  1668.             int quote, slen;
  1669.  
  1670.             quote = i++;
  1671.             rl_string_extract_single_quoted (string, &i);
  1672.  
  1673.             slen = i - quote + 2;
  1674.             temp = xmalloc (slen);
  1675.             strncpy (temp, string + quote, slen);
  1676.             temp[slen - 1] = '\0';
  1677.             ADD_STRING (temp);
  1678.             free (temp);
  1679.             break;
  1680.           }
  1681. #endif /* SHELL */
  1682.  
  1683.         case -3:                /* history_expansion_char */
  1684.           cc = string[i + 1];
  1685.  
  1686.           /* If the history_expansion_char is followed by one of the
  1687.              characters in history_no_expand_chars, then it is not a
  1688.              candidate for expansion of any kind. */
  1689.           if (member (cc, history_no_expand_chars))
  1690.             {
  1691.               ADD_CHAR (string[i]);
  1692.               break;
  1693.             }
  1694.  
  1695. #if defined (NO_BANG_HASH_MODIFIERS)
  1696.           /* There is something that is listed as a `word specifier' in csh
  1697.              documentation which means `the expanded text to this point'.
  1698.              That is not a word specifier, it is an event specifier.  If we
  1699.              don't want to allow modifiers with `!#', just stick the current
  1700.              output line in again. */
  1701.           if (cc == '#')
  1702.             {
  1703.               if (result)
  1704.                 {
  1705.                   temp = xmalloc (1 + strlen (result));
  1706.                   strcpy (temp, result);
  1707.                   ADD_STRING (temp);
  1708.                   free (temp);
  1709.                 }
  1710.               i++;
  1711.               break;
  1712.             }
  1713. #endif
  1714.  
  1715.           r = history_expand_internal (string, i, &eindex, &temp, result);
  1716.           if (r < 0)
  1717.             {
  1718.               *output = temp;
  1719.               free (result);
  1720.               if (string != hstring)
  1721.                 free (string);
  1722.               return -1;
  1723.             }
  1724.           else
  1725.             {
  1726.               if (temp)
  1727.                 {
  1728.                   modified++;
  1729.                   if (*temp)
  1730.                     ADD_STRING (temp);
  1731.                   free (temp);
  1732.                 }
  1733.               only_printing = r == 1;
  1734.               i = eindex;
  1735.             }
  1736.           break;
  1737.         }
  1738.     }
  1739.  
  1740.   *output = result;
  1741.   if (string != hstring)
  1742.     free (string);
  1743.  
  1744.   if (only_printing)
  1745.     {
  1746.       add_history (result);
  1747.       return (2);
  1748.     }
  1749.  
  1750.   return (modified != 0);
  1751. }
  1752.  
  1753. /* Return a consed string which is the word specified in SPEC, and found
  1754.    in FROM.  NULL is returned if there is no spec.  The address of
  1755.    ERROR_POINTER is returned if the word specified cannot be found.
  1756.    CALLER_INDEX is the offset in SPEC to start looking; it is updated
  1757.    to point to just after the last character parsed. */
  1758. static char *
  1759. get_history_word_specifier (spec, from, caller_index)
  1760.      char *spec, *from;
  1761.      int *caller_index;
  1762. {
  1763.   register int i = *caller_index;
  1764.   int first, last;
  1765.   int expecting_word_spec = 0;
  1766.   char *result;
  1767.  
  1768.   /* The range of words to return doesn't exist yet. */
  1769.   first = last = 0;
  1770.   result = (char *)NULL;
  1771.  
  1772.   /* If we found a colon, then this *must* be a word specification.  If
  1773.      it isn't, then it is an error. */
  1774.   if (spec[i] == ':')
  1775.     {
  1776.       i++;
  1777.       expecting_word_spec++;
  1778.     }
  1779.  
  1780.   /* Handle special cases first. */
  1781.  
  1782.   /* `%' is the word last searched for. */
  1783.   if (spec[i] == '%')
  1784.     {
  1785.       *caller_index = i + 1;
  1786.       return (search_string ? savestring (search_string) : savestring (""));
  1787.     }
  1788.  
  1789.   /* `*' matches all of the arguments, but not the command. */
  1790.   if (spec[i] == '*')
  1791.     {
  1792.       *caller_index = i + 1;
  1793.       result = history_arg_extract (1, '$', from);
  1794.       return (result ? result : savestring (""));
  1795.     }
  1796.  
  1797.   /* `$' is last arg. */
  1798.   if (spec[i] == '$')
  1799.     {
  1800.       *caller_index = i + 1;
  1801.       return (history_arg_extract ('$', '$', from));
  1802.     }
  1803.  
  1804.   /* Try to get FIRST and LAST figured out. */
  1805.  
  1806.   if (spec[i] == '-')
  1807.     first = 0;
  1808.   else if (spec[i] == '^')
  1809.     first = 1;
  1810.   else if (digit (spec[i]) && expecting_word_spec)
  1811.     {
  1812.       for (first = 0; digit (spec[i]); i++)
  1813.         first = (first * 10) + digit_value (spec[i]);
  1814.     }
  1815.   else
  1816.     return ((char *)NULL);      /* no valid `first' for word specifier */
  1817.  
  1818.   if (spec[i] == '^' || spec[i] == '*')
  1819.     {
  1820.       last = (spec[i] == '^') ? 1 : '$';        /* x* abbreviates x-$ */
  1821.       i++;
  1822.     }
  1823.   else if (spec[i] != '-')
  1824.     last = first;
  1825.   else
  1826.     {
  1827.       i++;
  1828.  
  1829.       if (digit (spec[i]))
  1830.         {
  1831.           for (last = 0; digit (spec[i]); i++)
  1832.             last = (last * 10) + digit_value (spec[i]);
  1833.         }
  1834.       else if (spec[i] == '$')
  1835.         {
  1836.           i++;
  1837.           last = '$';
  1838.         }
  1839.       else if (!spec[i] || spec[i] == ':')  /* could be modifier separator */
  1840.         last = -1;              /* x- abbreviates x-$ omitting word `$' */
  1841.     }
  1842.  
  1843.   *caller_index = i;
  1844.  
  1845.   if (last >= first || last == '$' || last < 0)
  1846.     result = history_arg_extract (first, last, from);
  1847.  
  1848.   return (result ? result : (char *)&error_pointer);
  1849. }
  1850.  
  1851. /* Extract the args specified, starting at FIRST, and ending at LAST.
  1852.    The args are taken from STRING.  If either FIRST or LAST is < 0,
  1853.    then make that arg count from the right (subtract from the number of
  1854.    tokens, so that FIRST = -1 means the next to last token on the line).
  1855.    If LAST is `$' the last arg from STRING is used. */
  1856. char *
  1857. history_arg_extract (first, last, string)
  1858.      int first, last;
  1859.      char *string;
  1860. {
  1861.   register int i, len;
  1862.   char *result = (char *)NULL;
  1863.   int size = 0, offset = 0;
  1864.   char **list;
  1865.  
  1866.   /* XXX - think about making history_tokenize return a struct array,
  1867.      each struct in array being a string and a length to avoid the
  1868.      calls to strlen below. */
  1869.   if ((list = history_tokenize (string)) == NULL)
  1870.     return ((char *)NULL);
  1871.  
  1872.   for (len = 0; list[len]; len++)
  1873.     ;
  1874.  
  1875.   if (last < 0)
  1876.     last = len + last - 1;
  1877.  
  1878.   if (first < 0)
  1879.     first = len + first - 1;
  1880.  
  1881.   if (last == '$')
  1882.     last = len - 1;
  1883.  
  1884.   if (first == '$')
  1885.     first = len - 1;
  1886.  
  1887.   last++;
  1888.  
  1889.   if (first > len || last > len || first < 0 || last < 0)
  1890.     result = ((char *)NULL);
  1891.   else
  1892.     {
  1893.       for (size = 0, i = first; i < last; i++)
  1894.         size += strlen (list[i]) + 1;
  1895.       result = xmalloc (size + 1);
  1896.  
  1897.       for (i = first; i < last; i++)
  1898.         {
  1899.           strcpy (result + offset, list[i]);
  1900.           offset += strlen (list[i]);
  1901.           if (i + 1 < last)
  1902.             {
  1903.               result[offset++] = ' ';
  1904.               result[offset] = 0;
  1905.             }
  1906.         }
  1907.     }
  1908.  
  1909.   for (i = 0; i < len; i++)
  1910.     free (list[i]);
  1911.   free (list);
  1912.  
  1913.   return (result);
  1914. }
  1915.  
  1916. #define slashify_in_quotes "\\`\"$"
  1917.  
  1918. /* Return an array of tokens, much as the shell might.  The tokens are
  1919.    parsed out of STRING. */
  1920. char **
  1921. history_tokenize (string)
  1922.      char *string;
  1923. {
  1924.   char **result = (char **)NULL;
  1925.   register int i, start, result_index, size;
  1926.   int len;
  1927.  
  1928.   i = result_index = size = 0;
  1929.  
  1930.   /* Get a token, and stuff it into RESULT.  The tokens are split
  1931.      exactly where the shell would split them. */
  1932.   while (string[i])
  1933.     {
  1934.       int delimiter = 0;
  1935.  
  1936.       /* Skip leading whitespace. */
  1937.       for (; string[i] && whitespace (string[i]); i++)
  1938.         ;
  1939.       if (!string[i] || string[i] == history_comment_char)
  1940.         return (result);
  1941.  
  1942.       start = i;
  1943.       
  1944.       if (member (string[i], "()\n"))
  1945.         {
  1946.           i++;
  1947.           goto got_token;
  1948.         }
  1949.  
  1950.       if (member (string[i], "<>;&|$"))
  1951.         {
  1952.           int peek = string[i + 1];
  1953.  
  1954.           if (peek == string[i] && peek != '$')
  1955.             {
  1956.               if (peek == '<' && string[i + 2] == '-')
  1957.                 i++;
  1958.               i += 2;
  1959.               goto got_token;
  1960.             }
  1961.           else
  1962.             {
  1963.               if ((peek == '&' && (string[i] == '>' || string[i] == '<')) ||
  1964.                   ((peek == '>') && (string[i] == '&')) ||
  1965.                   ((peek == '(') && (string[i] == '$')))
  1966.                 {
  1967.                   i += 2;
  1968.                   goto got_token;
  1969.                 }
  1970.             }
  1971.           if (string[i] != '$')
  1972.             {
  1973.               i++;
  1974.               goto got_token;
  1975.             }
  1976.         }
  1977.  
  1978.       /* Get word from string + i; */
  1979.  
  1980.       if (member (string[i], "\"'`"))
  1981.         delimiter = string[i++];
  1982.  
  1983.       for (; string[i]; i++)
  1984.         {
  1985.           if (string[i] == '\\' && string[i + 1] == '\n')
  1986.             {
  1987.               i++;
  1988.               continue;
  1989.             }
  1990.  
  1991.           if (string[i] == '\\' && delimiter != '\'' &&
  1992.               (delimiter != '"' || member (string[i], slashify_in_quotes)))
  1993.             {
  1994.               i++;
  1995.               continue;
  1996.             }
  1997.  
  1998.           if (delimiter && string[i] == delimiter)
  1999.             {
  2000.               delimiter = 0;
  2001.               continue;
  2002.             }
  2003.  
  2004.           if (!delimiter && (member (string[i], " \t\n;&()|<>")))
  2005.             break;
  2006.  
  2007.           if (!delimiter && member (string[i], "\"'`"))
  2008.             delimiter = string[i];
  2009.         }
  2010.     got_token:
  2011.  
  2012.       len = i - start;
  2013.       if (result_index + 2 >= size)
  2014.         result = (char **)xrealloc (result, ((size += 10) * sizeof (char *)));
  2015.       result[result_index] = xmalloc (1 + len);
  2016.       strncpy (result[result_index], string + start, len);
  2017.       result[result_index][len] = '\0';
  2018.       result[++result_index] = (char *)NULL;
  2019.     }
  2020.  
  2021.   return (result);
  2022. }
  2023.