1 /* histexpand.c -- history expansion. */
3 /* Copyright (C) 1989-2009 Free Software Foundation, Inc.
5 This file contains the GNU History Library (History), a set of
6 routines for managing the text of previously typed lines.
8 History 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 3 of the License, or
11 (at your option) any later version.
13 History is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with History. If not, see <http://www.gnu.org/licenses/>.
22 #define READLINE_LIBRARY
24 #if defined (HAVE_CONFIG_H)
30 #if defined (HAVE_STDLIB_H)
33 # include "ansi_stdlib.h"
34 #endif /* HAVE_STDLIB_H */
36 #if defined (HAVE_UNISTD_H)
38 # include <sys/types.h>
51 #define HISTORY_WORD_DELIMITERS " \t\n;&()|<>"
52 #define HISTORY_QUOTE_CHARACTERS "\"'`"
54 #define slashify_in_quotes "\\`\"$"
56 typedef int _hist_search_func_t PARAMS((const char *, int));
58 static char error_pointer;
60 static char *subst_lhs;
61 static char *subst_rhs;
62 static int subst_lhs_len;
63 static int subst_rhs_len;
65 static char *get_history_word_specifier PARAMS((char *, char *, int *));
66 static int history_tokenize_word PARAMS((const char *, int));
67 static char **history_tokenize_internal PARAMS((const char *, int, int *));
68 static char *history_substring PARAMS((const char *, int, int));
69 static void freewords PARAMS((char **, int));
70 static char *history_find_word PARAMS((char *, int));
72 static char *quote_breaks PARAMS((char *));
74 /* Variables exported by this file. */
75 /* The character that represents the start of a history expansion
76 request. This is usually `!'. */
77 char history_expansion_char = '!';
79 /* The character that invokes word substitution if found at the start of
80 a line. This is usually `^'. */
81 char history_subst_char = '^';
83 /* During tokenization, if this character is seen as the first character
84 of a word, then it, and all subsequent characters upto a newline are
85 ignored. For a Bourne shell, this should be '#'. Bash special cases
86 the interactive comment character to not be a comment delimiter. */
87 char history_comment_char = '\0';
89 /* The list of characters which inhibit the expansion of text if found
90 immediately following history_expansion_char. */
91 char *history_no_expand_chars = " \t\n\r=";
93 /* If set to a non-zero value, single quotes inhibit history expansion.
95 int history_quotes_inhibit_expansion = 0;
97 /* Used to split words by history_tokenize_internal. */
98 char *history_word_delimiters = HISTORY_WORD_DELIMITERS;
100 /* If set, this points to a function that is called to verify that a
101 particular history expansion should be performed. */
102 rl_linebuf_func_t *history_inhibit_expansion_function;
104 /* **************************************************************** */
106 /* History Expansion */
108 /* **************************************************************** */
110 /* Hairy history expansion on text, not tokens. This is of general
111 use, and thus belongs in this library. */
113 /* The last string searched for by a !?string? search. */
114 static char *search_string;
116 /* The last string matched by a !?string? search. */
117 static char *search_match;
119 /* Return the event specified at TEXT + OFFSET modifying OFFSET to
120 point to after the event specifier. Just a pointer to the history
121 line is returned; NULL is returned in the event of a bad specifier.
122 You pass STRING with *INDEX equal to the history_expansion_char that
123 begins this specification.
124 DELIMITING_QUOTE is a character that is allowed to end the string
125 specification for what to search for in addition to the normal
126 characters `:', ` ', `\t', `\n', and sometimes `?'.
127 So you might call this function like:
128 line = get_history_event ("!echo:p", &index, 0); */
130 get_history_event (string, caller_index, delimiting_quote)
133 int delimiting_quote;
138 int which, sign, local_index, substring_okay;
139 _hist_search_func_t *search_func;
142 /* The event can be specified in a number of ways.
144 !! the previous command
146 !-n current command-line minus N
147 !str the most recent command starting with STR
149 the most recent command containing STR
151 All values N are determined via HISTORY_BASE. */
155 if (string[i] != history_expansion_char)
156 return ((char *)NULL);
158 /* Move on to the specification. */
164 #define RETURN_ENTRY(e, w) \
165 return ((e = history_get (w)) ? e->line : (char *)NULL)
167 /* Handle !! case. */
168 if (string[i] == history_expansion_char)
171 which = history_base + (history_length - 1);
173 RETURN_ENTRY (entry, which);
176 /* Hack case of numeric line specification. */
177 if (string[i] == '-')
183 if (_rl_digit_p (string[i]))
185 /* Get the extent of the digits and compute the value. */
186 for (which = 0; _rl_digit_p (string[i]); i++)
187 which = (which * 10) + _rl_digit_value (string[i]);
192 which = (history_length + history_base) - which;
194 RETURN_ENTRY (entry, which);
197 /* This must be something to search for. If the spec begins with
198 a '?', then the string may be anywhere on the line. Otherwise,
199 the string must be found at the start of a line. */
200 if (string[i] == '?')
206 /* Only a closing `?' or a newline delimit a substring search string. */
207 for (local_index = i; c = string[i]; i++)
209 #if defined (HANDLE_MULTIBYTE)
210 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
215 memset (&ps, 0, sizeof (mbstate_t));
216 /* These produce warnings because we're passing a const string to a
217 function that takes a non-const string. */
218 _rl_adjust_point ((char *)string, i, &ps);
219 if ((v = _rl_get_char_len ((char *)string + i, &ps)) > 1)
226 #endif /* HANDLE_MULTIBYTE */
227 if ((!substring_okay && (whitespace (c) || c == ':' ||
228 (history_search_delimiter_chars && member (c, history_search_delimiter_chars)) ||
229 string[i] == delimiting_quote)) ||
231 (substring_okay && string[i] == '?'))
235 which = i - local_index;
236 temp = (char *)xmalloc (1 + which);
238 strncpy (temp, string + local_index, which);
241 if (substring_okay && string[i] == '?')
246 #define FAIL_SEARCH() \
248 history_offset = history_length; free (temp) ; return (char *)NULL; \
251 /* If there is no search string, try to use the previous search string,
252 if one exists. If not, fail immediately. */
253 if (*temp == '\0' && substring_okay)
258 temp = savestring (search_string);
264 search_func = substring_okay ? history_search : history_search_prefix;
267 local_index = (*search_func) (temp, -1);
272 if (local_index == 0 || substring_okay)
274 entry = current_history ();
275 history_offset = history_length;
277 /* If this was a substring search, then remember the
278 string that we matched for word substitution. */
281 FREE (search_string);
282 search_string = temp;
285 search_match = history_find_word (entry->line, local_index);
290 return (entry->line);
302 /* Function for extracting single-quoted strings. Used for inhibiting
303 history expansion within single quotes. */
305 /* Extract the contents of STRING as if it is enclosed in single quotes.
306 SINDEX, when passed in, is the offset of the character immediately
307 following the opening single quote; on exit, SINDEX is left pointing
308 to the closing single quote. */
310 hist_string_extract_single_quoted (string, sindex)
316 for (i = *sindex; string[i] && string[i] != '\''; i++)
326 register char *p, *r;
330 for (p = s; p && *p; p++, len++)
334 else if (whitespace (*p) || *p == '\n')
338 r = ret = (char *)xmalloc (len);
340 for (p = s; p && *p; )
350 else if (whitespace (*p) || *p == '\n')
365 hist_error(s, start, current, errtype)
367 int start, current, errtype;
373 ll = current - start;
377 case EVENT_NOT_FOUND:
378 emsg = "event not found";
382 emsg = "bad word specifier";
386 emsg = "substitution failed";
390 emsg = "unrecognized history modifier";
394 emsg = "no previous substitution";
398 emsg = "unknown expansion error";
403 temp = (char *)xmalloc (ll + elen + 3);
404 strncpy (temp, s + start, ll);
407 strcpy (temp + ll + 2, emsg);
411 /* Get a history substitution string from STR starting at *IPTR
412 and return it. The length is returned in LENPTR.
414 A backslash can quote the delimiter. If the string is the
415 empty string, the previous pattern is used. If there is
416 no previous pattern for the lhs, the last history search
419 If IS_RHS is 1, we ignore empty strings and set the pattern
420 to "" anyway. subst_lhs is not changed if the lhs is empty;
421 subst_rhs is allowed to be set to the empty string. */
424 get_subst_pattern (str, iptr, delimiter, is_rhs, lenptr)
426 int *iptr, delimiter, is_rhs, *lenptr;
428 register int si, i, j, k;
430 #if defined (HANDLE_MULTIBYTE)
437 #if defined (HANDLE_MULTIBYTE)
438 memset (&ps, 0, sizeof (mbstate_t));
439 _rl_adjust_point (str, i, &ps);
442 for (si = i; str[si] && str[si] != delimiter; si++)
443 #if defined (HANDLE_MULTIBYTE)
444 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
447 if ((v = _rl_get_char_len (str + si, &ps)) > 1)
449 else if (str[si] == '\\' && str[si + 1] == delimiter)
453 #endif /* HANDLE_MULTIBYTE */
454 if (str[si] == '\\' && str[si + 1] == delimiter)
457 if (si > i || is_rhs)
459 s = (char *)xmalloc (si - i + 1);
460 for (j = 0, k = i; k < si; j++, k++)
462 /* Remove a backslash quoting the search string delimiter. */
463 if (str[k] == '\\' && str[k + 1] == delimiter)
481 postproc_subst_rhs ()
486 new = (char *)xmalloc (new_size = subst_rhs_len + subst_lhs_len);
487 for (i = j = 0; i < subst_rhs_len; i++)
489 if (subst_rhs[i] == '&')
491 if (j + subst_lhs_len >= new_size)
492 new = (char *)xrealloc (new, (new_size = new_size * 2 + subst_lhs_len));
493 strcpy (new + j, subst_lhs);
498 /* a single backslash protects the `&' from lhs interpolation */
499 if (subst_rhs[i] == '\\' && subst_rhs[i + 1] == '&')
502 new = (char *)xrealloc (new, new_size *= 2);
503 new[j++] = subst_rhs[i];
512 /* Expand the bulk of a history specifier starting at STRING[START].
513 Returns 0 if everything is OK, -1 if an error occurred, and 1
514 if the `p' modifier was supplied and the caller should just print
515 the returned string. Returns the new index into string in
516 *END_INDEX_PTR, and the expanded specifier in *RET_STRING. */
518 history_expand_internal (string, start, end_index_ptr, ret_string, current_line)
520 int start, *end_index_ptr;
522 char *current_line; /* for !# */
524 int i, n, starting_index;
525 int substitute_globally, subst_bywords, want_quotes, print_only;
526 char *event, *temp, *result, *tstr, *t, c, *word_spec;
528 #if defined (HANDLE_MULTIBYTE)
531 memset (&ps, 0, sizeof (mbstate_t));
534 result = (char *)xmalloc (result_len = 128);
538 /* If it is followed by something that starts a word specifier,
539 then !! is implied as the event specifier. */
541 if (member (string[i + 1], ":$*%^"))
546 fake_s[0] = fake_s[1] = history_expansion_char;
548 event = get_history_event (fake_s, &fake_i, 0);
550 else if (string[i + 1] == '#')
553 event = current_line;
557 int quoted_search_delimiter = 0;
559 /* If the character before this `!' is a double or single
560 quote, then this expansion takes place inside of the
561 quoted string. If we have to search for some text ("!foo"),
562 allow the delimiter to end the search string. */
563 #if defined (HANDLE_MULTIBYTE)
564 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
567 l = _rl_find_prev_mbchar (string, i, MB_FIND_ANY);
569 /* XXX - original patch had i - 1 ??? If i == 0 it would fail. */
570 if (i && (ch == '\'' || ch == '"'))
571 quoted_search_delimiter = ch;
574 #endif /* HANDLE_MULTIBYTE */
575 if (i && (string[i - 1] == '\'' || string[i - 1] == '"'))
576 quoted_search_delimiter = string[i - 1];
578 event = get_history_event (string, &i, quoted_search_delimiter);
583 *ret_string = hist_error (string, start, i, EVENT_NOT_FOUND);
588 /* If a word specifier is found, then do what that requires. */
590 word_spec = get_history_word_specifier (string, event, &i);
592 /* There is no such thing as a `malformed word specifier'. However,
593 it is possible for a specifier that has no match. In that case,
595 if (word_spec == (char *)&error_pointer)
597 *ret_string = hist_error (string, starting_index, i, BAD_WORD_SPEC);
602 /* If no word specifier, than the thing of interest was the event. */
603 temp = word_spec ? savestring (word_spec) : savestring (event);
606 /* Perhaps there are other modifiers involved. Do what they say. */
607 want_quotes = substitute_globally = subst_bywords = print_only = 0;
610 while (string[i] == ':')
614 if (c == 'g' || c == 'a')
616 substitute_globally = 1;
630 *ret_string = hist_error (string, i+1, i+2, BAD_MODIFIER);
643 /* :p means make this the last executed line. So we
644 return an error state after adding this line to the
650 /* :t discards all but the last part of the pathname. */
652 tstr = strrchr (temp, '/');
656 t = savestring (tstr);
662 /* :h discards the last part of a pathname. */
664 tstr = strrchr (temp, '/');
669 /* :r discards the suffix. */
671 tstr = strrchr (temp, '.');
676 /* :e discards everything but the suffix. */
678 tstr = strrchr (temp, '.');
681 t = savestring (tstr);
687 /* :s/this/that substitutes `that' for the first
688 occurrence of `this'. :gs/this/that substitutes `that'
689 for each occurrence of `this'. :& repeats the last
690 substitution. :g& repeats the last substitution
697 int delimiter, failed, si, l_temp, ws, we;
701 if (i + 2 < (int)strlen (string))
703 #if defined (HANDLE_MULTIBYTE)
704 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
706 _rl_adjust_point (string, i + 2, &ps);
707 if (_rl_get_char_len (string + i + 2, &ps) > 1)
710 delimiter = string[i + 2];
713 #endif /* HANDLE_MULTIBYTE */
714 delimiter = string[i + 2];
717 break; /* no search delimiter */
721 t = get_subst_pattern (string, &i, delimiter, 0, &subst_lhs_len);
722 /* An empty substitution lhs with no previous substitution
723 uses the last search string as the lhs. */
731 if (search_string && *search_string)
733 subst_lhs = savestring (search_string);
734 subst_lhs_len = strlen (subst_lhs);
738 subst_lhs = (char *) NULL;
744 subst_rhs = get_subst_pattern (string, &i, delimiter, 1, &subst_rhs_len);
746 /* If `&' appears in the rhs, it's supposed to be replaced
748 if (member ('&', subst_rhs))
749 postproc_subst_rhs ();
754 /* If there is no lhs, the substitution can't succeed. */
755 if (subst_lhs_len == 0)
757 *ret_string = hist_error (string, starting_index, i, NO_PREV_SUBST);
763 l_temp = strlen (temp);
764 /* Ignore impossible cases. */
765 if (subst_lhs_len > l_temp)
767 *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
773 /* Find the first occurrence of THIS in TEMP. */
774 /* Substitute SUBST_RHS for SUBST_LHS in TEMP. There are three
777 1. substitute_globally == subst_bywords == 0
778 2. substitute_globally == 1 && subst_bywords == 0
779 3. substitute_globally == 0 && subst_bywords == 1
781 In the first case, we substitute for the first occurrence only.
782 In the second case, we substitute for every occurrence.
783 In the third case, we tokenize into words and substitute the
784 first occurrence of each word. */
787 for (failed = 1; (si + subst_lhs_len) <= l_temp; si++)
789 /* First skip whitespace and find word boundaries if
790 we're past the end of the word boundary we found
792 if (subst_bywords && si > we)
794 for (; temp[si] && whitespace (temp[si]); si++)
797 we = history_tokenize_word (temp, si);
800 if (STREQN (temp+si, subst_lhs, subst_lhs_len))
802 int len = subst_rhs_len - subst_lhs_len + l_temp;
803 new_event = (char *)xmalloc (1 + len);
804 strncpy (new_event, temp, si);
805 strncpy (new_event + si, subst_rhs, subst_rhs_len);
806 strncpy (new_event + si + subst_rhs_len,
807 temp + si + subst_lhs_len,
808 l_temp - (si + subst_lhs_len));
809 new_event[len] = '\0';
815 if (substitute_globally)
817 /* Reported to fix a bug that causes it to skip every
818 other match when matching a single character. Was
819 si += subst_rhs_len previously. */
820 si += subst_rhs_len - 1;
821 l_temp = strlen (temp);
822 substitute_globally++;
825 else if (subst_bywords)
828 l_temp = strlen (temp);
836 if (substitute_globally > 1)
838 substitute_globally = 0;
839 continue; /* don't want to increment i */
843 continue; /* don't want to increment i */
845 *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
853 /* Done with modfiers. */
854 /* Believe it or not, we have to back the pointer up by one. */
861 if (want_quotes == 'q')
862 x = sh_single_quote (temp);
863 else if (want_quotes == 'x')
864 x = quote_breaks (temp);
866 x = savestring (temp);
874 result = (char *)xrealloc (result, n + 2);
875 strcpy (result, temp);
879 *ret_string = result;
883 /* Expand the string STRING, placing the result into OUTPUT, a pointer
884 to a string. Returns:
886 -1) If there was an error in expansion.
887 0) If no expansions took place (or, if the only change in
888 the text was the de-slashifying of the history expansion
890 1) If expansions did take place
891 2) If the `p' modifier was given and the caller should print the result
893 If an error ocurred in expansion, then OUTPUT contains a descriptive
896 #define ADD_STRING(s) \
899 int sl = strlen (s); \
901 if (j >= result_len) \
903 while (j >= result_len) \
905 result = (char *)xrealloc (result, result_len); \
907 strcpy (result + j - sl, s); \
911 #define ADD_CHAR(c) \
914 if (j >= result_len - 1) \
915 result = (char *)xrealloc (result, result_len += 64); \
922 history_expand (hstring, output)
927 int i, r, l, passc, cc, modified, eindex, only_printing, dquote;
930 /* The output string, and its length. */
934 #if defined (HANDLE_MULTIBYTE)
939 /* Used when adding the string. */
945 /* Setting the history expansion character to 0 inhibits all
946 history expansion. */
947 if (history_expansion_char == 0)
949 *output = savestring (hstring);
953 /* Prepare the buffer for printing error messages. */
954 result = (char *)xmalloc (result_len = 256);
957 only_printing = modified = 0;
958 l = strlen (hstring);
960 /* Grovel the string. Only backslash and single quotes can quote the
961 history escape character. We also handle arg specifiers. */
963 /* Before we grovel forever, see if the history_expansion_char appears
964 anywhere within the text. */
966 /* The quick substitution character is a history expansion all right. That
967 is to say, "^this^that^" is equivalent to "!!:s^this^that^", and in fact,
968 that is the substitution that we do. */
969 if (hstring[0] == history_subst_char)
971 string = (char *)xmalloc (l + 5);
973 string[0] = string[1] = history_expansion_char;
976 strcpy (string + 4, hstring);
981 #if defined (HANDLE_MULTIBYTE)
982 memset (&ps, 0, sizeof (mbstate_t));
986 /* If not quick substitution, still maybe have to do expansion. */
988 /* `!' followed by one of the characters in history_no_expand_chars
989 is NOT an expansion. */
990 for (i = dquote = 0; string[i]; i++)
992 #if defined (HANDLE_MULTIBYTE)
993 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
996 v = _rl_get_char_len (string + i, &ps);
1003 #endif /* HANDLE_MULTIBYTE */
1006 /* The history_comment_char, if set, appearing at the beginning
1007 of a word signifies that the rest of the line should not have
1008 history expansion performed on it.
1009 Skip the rest of the line and break out of the loop. */
1010 if (history_comment_char && string[i] == history_comment_char &&
1011 (i == 0 || member (string[i - 1], history_word_delimiters)))
1017 else if (string[i] == history_expansion_char)
1019 if (cc == 0 || member (cc, history_no_expand_chars))
1021 /* If the calling application has set
1022 history_inhibit_expansion_function to a function that checks
1023 for special cases that should not be history expanded,
1024 call the function and skip the expansion if it returns a
1026 else if (history_inhibit_expansion_function &&
1027 (*history_inhibit_expansion_function) (string, i))
1032 /* Shell-like quoting: allow backslashes to quote double quotes
1033 inside a double-quoted string. */
1034 else if (dquote && string[i] == '\\' && cc == '"')
1036 /* More shell-like quoting: if we're paying attention to single
1037 quotes and letting them quote the history expansion character,
1038 then we need to pay attention to double quotes, because single
1039 quotes are not special inside double-quoted strings. */
1040 else if (history_quotes_inhibit_expansion && string[i] == '"')
1042 dquote = 1 - dquote;
1044 else if (dquote == 0 && history_quotes_inhibit_expansion && string[i] == '\'')
1046 /* If this is bash, single quotes inhibit history expansion. */
1048 hist_string_extract_single_quoted (string, &i);
1050 else if (history_quotes_inhibit_expansion && string[i] == '\\')
1052 /* If this is bash, allow backslashes to quote single
1053 quotes and the history expansion character. */
1054 if (cc == '\'' || cc == history_expansion_char)
1060 if (string[i] != history_expansion_char)
1063 *output = savestring (string);
1068 /* Extract and perform the substitution. */
1069 for (passc = dquote = i = j = 0; i < l; i++)
1071 int tchar = string[i];
1080 #if defined (HANDLE_MULTIBYTE)
1081 if (MB_CUR_MAX > 1 && rl_byte_oriented == 0)
1086 memset (mb, 0, sizeof (mb));
1087 for (k = 0; k < MB_LEN_MAX; k++)
1090 memset (&ps, 0, sizeof (mbstate_t));
1091 if (_rl_get_char_len (mb, &ps) == -2)
1096 if (strlen (mb) > 1)
1102 #endif /* HANDLE_MULTIBYTE */
1104 if (tchar == history_expansion_char)
1106 else if (tchar == history_comment_char)
1112 ADD_CHAR (string[i]);
1121 dquote = 1 - dquote;
1127 /* If history_quotes_inhibit_expansion is set, single quotes
1128 inhibit history expansion. */
1129 if (dquote == 0 && history_quotes_inhibit_expansion)
1134 hist_string_extract_single_quoted (string, &i);
1136 slen = i - quote + 2;
1137 temp = (char *)xmalloc (slen);
1138 strncpy (temp, string + quote, slen);
1139 temp[slen - 1] = '\0';
1144 ADD_CHAR (string[i]);
1148 case -2: /* history_comment_char */
1149 if (i == 0 || member (string[i - 1], history_word_delimiters))
1151 temp = (char *)xmalloc (l - i + 1);
1152 strcpy (temp, string + i);
1158 ADD_CHAR (string[i]);
1161 case -3: /* history_expansion_char */
1164 /* If the history_expansion_char is followed by one of the
1165 characters in history_no_expand_chars, then it is not a
1166 candidate for expansion of any kind. */
1167 if (cc == 0 || member (cc, history_no_expand_chars) ||
1168 (history_inhibit_expansion_function && (*history_inhibit_expansion_function) (string, i)))
1170 ADD_CHAR (string[i]);
1174 #if defined (NO_BANG_HASH_MODIFIERS)
1175 /* There is something that is listed as a `word specifier' in csh
1176 documentation which means `the expanded text to this point'.
1177 That is not a word specifier, it is an event specifier. If we
1178 don't want to allow modifiers with `!#', just stick the current
1179 output line in again. */
1184 temp = (char *)xmalloc (1 + strlen (result));
1185 strcpy (temp, result);
1194 r = history_expand_internal (string, i, &eindex, &temp, result);
1199 if (string != hstring)
1212 only_printing = r == 1;
1220 if (string != hstring)
1226 add_history (result);
1231 return (modified != 0);
1234 /* Return a consed string which is the word specified in SPEC, and found
1235 in FROM. NULL is returned if there is no spec. The address of
1236 ERROR_POINTER is returned if the word specified cannot be found.
1237 CALLER_INDEX is the offset in SPEC to start looking; it is updated
1238 to point to just after the last character parsed. */
1240 get_history_word_specifier (spec, from, caller_index)
1244 register int i = *caller_index;
1246 int expecting_word_spec = 0;
1249 /* The range of words to return doesn't exist yet. */
1251 result = (char *)NULL;
1253 /* If we found a colon, then this *must* be a word specification. If
1254 it isn't, then it is an error. */
1258 expecting_word_spec++;
1261 /* Handle special cases first. */
1263 /* `%' is the word last searched for. */
1266 *caller_index = i + 1;
1267 return (search_match ? savestring (search_match) : savestring (""));
1270 /* `*' matches all of the arguments, but not the command. */
1273 *caller_index = i + 1;
1274 result = history_arg_extract (1, '$', from);
1275 return (result ? result : savestring (""));
1278 /* `$' is last arg. */
1281 *caller_index = i + 1;
1282 return (history_arg_extract ('$', '$', from));
1285 /* Try to get FIRST and LAST figured out. */
1289 else if (spec[i] == '^')
1294 else if (_rl_digit_p (spec[i]) && expecting_word_spec)
1296 for (first = 0; _rl_digit_p (spec[i]); i++)
1297 first = (first * 10) + _rl_digit_value (spec[i]);
1300 return ((char *)NULL); /* no valid `first' for word specifier */
1302 if (spec[i] == '^' || spec[i] == '*')
1304 last = (spec[i] == '^') ? 1 : '$'; /* x* abbreviates x-$ */
1307 else if (spec[i] != '-')
1313 if (_rl_digit_p (spec[i]))
1315 for (last = 0; _rl_digit_p (spec[i]); i++)
1316 last = (last * 10) + _rl_digit_value (spec[i]);
1318 else if (spec[i] == '$')
1324 else if (!spec[i] || spec[i] == ':')
1325 /* check against `:' because there could be a modifier separator */
1328 /* csh seems to allow anything to terminate the word spec here,
1329 leaving it as an abbreviation. */
1331 last = -1; /* x- abbreviates x-$ omitting word `$' */
1336 if (last >= first || last == '$' || last < 0)
1337 result = history_arg_extract (first, last, from);
1339 return (result ? result : (char *)&error_pointer);
1342 /* Extract the args specified, starting at FIRST, and ending at LAST.
1343 The args are taken from STRING. If either FIRST or LAST is < 0,
1344 then make that arg count from the right (subtract from the number of
1345 tokens, so that FIRST = -1 means the next to last token on the line).
1346 If LAST is `$' the last arg from STRING is used. */
1348 history_arg_extract (first, last, string)
1352 register int i, len;
1357 /* XXX - think about making history_tokenize return a struct array,
1358 each struct in array being a string and a length to avoid the
1359 calls to strlen below. */
1360 if ((list = history_tokenize (string)) == NULL)
1361 return ((char *)NULL);
1363 for (len = 0; list[len]; len++)
1367 last = len + last - 1;
1370 first = len + first - 1;
1380 if (first >= len || last > len || first < 0 || last < 0 || first > last)
1381 result = ((char *)NULL);
1384 for (size = 0, i = first; i < last; i++)
1385 size += strlen (list[i]) + 1;
1386 result = (char *)xmalloc (size + 1);
1389 for (i = first, offset = 0; i < last; i++)
1391 strcpy (result + offset, list[i]);
1392 offset += strlen (list[i]);
1395 result[offset++] = ' ';
1401 for (i = 0; i < len; i++)
1409 history_tokenize_word (string, ind)
1419 if (member (string[i], "()\n"))
1425 if (member (string[i], "<>;&|$"))
1427 int peek = string[i + 1];
1429 if (peek == string[i] && peek != '$')
1431 if (peek == '<' && string[i + 2] == '-')
1433 else if (peek == '<' && string[i + 2] == '<')
1440 if ((peek == '&' && (string[i] == '>' || string[i] == '<')) ||
1441 (peek == '>' && string[i] == '&') ||
1442 (peek == '(' && (string[i] == '>' || string[i] == '<')) || /* ) */
1443 (peek == '(' && string[i] == '$')) /* ) */
1450 if (string[i] != '$')
1457 /* Get word from string + i; */
1459 if (member (string[i], HISTORY_QUOTE_CHARACTERS))
1460 delimiter = string[i++];
1462 for (; string[i]; i++)
1464 if (string[i] == '\\' && string[i + 1] == '\n')
1470 if (string[i] == '\\' && delimiter != '\'' &&
1471 (delimiter != '"' || member (string[i], slashify_in_quotes)))
1477 if (delimiter && string[i] == delimiter)
1483 if (!delimiter && (member (string[i], history_word_delimiters)))
1486 if (!delimiter && member (string[i], HISTORY_QUOTE_CHARACTERS))
1487 delimiter = string[i];
1494 history_substring (string, start, end)
1499 register char *result;
1502 result = (char *)xmalloc (len + 1);
1503 strncpy (result, string + start, len);
1508 /* Parse STRING into tokens and return an array of strings. If WIND is
1509 not -1 and INDP is not null, we also want the word surrounding index
1510 WIND. The position in the returned array of strings is returned in
1513 history_tokenize_internal (string, wind, indp)
1518 register int i, start, result_index, size;
1520 /* If we're searching for a string that's not part of a word (e.g., " "),
1521 make sure we set *INDP to a reasonable value. */
1522 if (indp && wind != -1)
1525 /* Get a token, and stuff it into RESULT. The tokens are split
1526 exactly where the shell would split them. */
1527 for (i = result_index = size = 0, result = (char **)NULL; string[i]; )
1529 /* Skip leading whitespace. */
1530 for (; string[i] && whitespace (string[i]); i++)
1532 if (string[i] == 0 || string[i] == history_comment_char)
1537 i = history_tokenize_word (string, start);
1539 /* If we have a non-whitespace delimiter character (which would not be
1540 skipped by the loop above), use it and any adjacent delimiters to
1541 make a separate field. Any adjacent white space will be skipped the
1542 next time through the loop. */
1543 if (i == start && history_word_delimiters)
1546 while (string[i] && member (string[i], history_word_delimiters))
1550 /* If we are looking for the word in which the character at a
1551 particular index falls, remember it. */
1552 if (indp && wind != -1 && wind >= start && wind < i)
1553 *indp = result_index;
1555 if (result_index + 2 >= size)
1556 result = (char **)xrealloc (result, ((size += 10) * sizeof (char *)));
1558 result[result_index++] = history_substring (string, start, i);
1559 result[result_index] = (char *)NULL;
1565 /* Return an array of tokens, much as the shell might. The tokens are
1566 parsed out of STRING. */
1568 history_tokenize (string)
1571 return (history_tokenize_internal (string, -1, (int *)NULL));
1574 /* Free members of WORDS from START to an empty string */
1576 freewords (words, start)
1582 for (i = start; words[i]; i++)
1586 /* Find and return the word which contains the character at index IND
1587 in the history line LINE. Used to save the word matched by the
1588 last history !?string? search. */
1590 history_find_word (line, ind)
1597 words = history_tokenize_internal (line, ind, &wind);
1598 if (wind == -1 || words == 0)
1601 freewords (words, 0);
1603 return ((char *)NULL);
1606 for (i = 0; i < wind; i++)
1608 freewords (words, wind + 1);