Debian Codegraph @

libsrc/readline/history.c

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