1 /* bashhist.c -- bash interface to the GNU history library. */
3 /* Copyright (C) 1993-2004 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
12 Bash is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 You should have received a copy of the GNU General Public License along
18 with Bash; see the file COPYING. If not, write to the Free Software
19 Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
25 #if defined (HAVE_UNISTD_H)
27 # include <sys/types.h>
32 #include "bashtypes.h"
36 #include "posixstat.h"
44 #include "parser.h" /* for the struct dstack stuff. */
45 #include "pathexp.h" /* for the struct ignorevar stuff */
46 #include "bashhist.h" /* matching prototypes and declarations */
47 #include "builtins/common.h"
49 #include <readline/history.h>
50 #include <glob/glob.h>
51 #include <glob/strmatch.h>
53 #if defined (READLINE)
54 # include "bashline.h"
55 extern int rl_done, rl_dispatching; /* should really include readline.h */
62 static int histignore_item_func __P((struct ign *));
63 static int check_history_control __P((char *));
64 static void hc_erasedups __P((char *));
65 static void really_add_history __P((char *));
67 static struct ignorevar histignore =
73 (sh_iv_item_func_t *)histignore_item_func,
76 #define HIGN_EXPAND 0x01
78 /* Declarations of bash history variables. */
79 /* Non-zero means to remember lines typed to the shell on the history
80 list. This is different than the user-controlled behaviour; this
81 becomes zero when we read lines from a file, for example. */
82 int remember_on_history = 1;
84 /* The number of lines that Bash has added to this history session. The
85 difference between the number of the top element in the history list
86 (offset from history_base) and the number of lines in the history file.
87 Appending this session's history to the history file resets this to 0. */
88 int history_lines_this_session;
90 /* The number of lines that Bash has read from the history file. */
91 int history_lines_in_file;
93 #if defined (BANG_HISTORY)
94 /* Non-zero means do no history expansion on this line, regardless
95 of what history_expansion says. */
96 int history_expansion_inhibited;
99 /* With the old default, every line was saved in the history individually.
100 I.e., if the user enters:
105 Each line will be individually saved in the history.
112 If the variable command_oriented_history is set, multiple lines
113 which form one command will be saved as one history entry.
124 The user can then recall the whole command all at once instead
125 of just being able to recall one line at a time.
127 This is now enabled by default.
129 int command_oriented_history = 1;
131 /* Set to 1 if the first line of a possibly-multi-line command was saved
132 in the history list. Managed by maybe_add_history(), but global so
133 the history-manipluating builtins can see it. */
134 int current_command_first_line_saved = 0;
136 /* Non-zero means to store newlines in the history list when using
137 command_oriented_history rather than trying to use semicolons. */
140 /* Non-zero means to append the history to the history file at shell
141 exit, even if the history has been stifled. */
142 int force_append_history;
144 /* A nit for picking at history saving. Flags have the following values:
146 Value == 0 means save all lines parsed by the shell on the history.
147 Value & HC_IGNSPACE means save all lines that do not start with a space.
148 Value & HC_IGNDUPS means save all lines that do not match the last
150 Value & HC_ERASEDUPS means to remove all other matching lines from the
151 history list before saving the latest line. */
154 /* Set to 1 if the last command was added to the history list successfully
155 as a separate history entry; set to 0 if the line was ignored or added
156 to a previous entry as part of command-oriented-history processing. */
157 int hist_last_line_added;
159 /* Set to 1 if builtins/history.def:push_history added the last history
161 int hist_last_line_pushed;
163 #if defined (READLINE)
164 /* If non-zero, and readline is being used, the user is offered the
165 chance to re-edit a failed history expansion. */
166 int history_reediting;
168 /* If non-zero, and readline is being used, don't directly execute a
169 line with history substitution. Reload it into the editing buffer
170 instead and let the user further edit and confirm with a newline. */
173 #endif /* READLINE */
175 /* Non-zero means to not save function definitions in the history list. */
176 int dont_save_function_defs;
178 /* Variables declared in other files used here. */
179 extern int current_command_line_count;
181 extern struct dstack dstack;
183 static int bash_history_inhibit_expansion __P((char *, int));
184 #if defined (READLINE)
185 static void re_edit __P((char *));
187 static int history_expansion_p __P((char *));
188 static int shell_comment __P((char *));
189 static int should_expand __P((char *));
190 static HIST_ENTRY *last_history_entry __P((void));
191 static char *expand_histignore_pattern __P((char *));
192 static int history_should_ignore __P((char *));
194 /* Is the history expansion starting at string[i] one that should not
197 bash_history_inhibit_expansion (string, i)
201 /* The shell uses ! as a pattern negation character in globbing [...]
202 expressions, so let those pass without expansion. */
203 if (i > 0 && (string[i - 1] == '[') && member (']', string + i + 1))
205 /* The shell uses ! as the indirect expansion character, so let those
206 expansions pass as well. */
207 else if (i > 1 && string[i - 1] == '{' && string[i - 2] == '$' &&
208 member ('}', string + i + 1))
210 #if defined (EXTENDED_GLOB)
211 else if (extended_glob && i > 1 && string[i+1] == '(' && member (')', string + i + 2))
219 bash_initialize_history ()
221 history_quotes_inhibit_expansion = 1;
222 history_search_delimiter_chars = ";&()|<>";
223 history_inhibit_expansion_function = bash_history_inhibit_expansion;
224 #if defined (BANG_HISTORY)
225 sv_histchars ("histchars");
230 bash_history_reinit (interact)
233 #if defined (BANG_HISTORY)
234 history_expansion = interact != 0;
235 history_expansion_inhibited = 1;
237 remember_on_history = interact != 0;
238 history_inhibit_expansion_function = bash_history_inhibit_expansion;
242 bash_history_disable ()
244 remember_on_history = 0;
245 #if defined (BANG_HISTORY)
246 history_expansion_inhibited = 1;
251 bash_history_enable ()
253 remember_on_history = 1;
254 #if defined (BANG_HISTORY)
255 history_expansion_inhibited = 0;
257 history_inhibit_expansion_function = bash_history_inhibit_expansion;
258 sv_history_control ("HISTCONTROL");
259 sv_histignore ("HISTIGNORE");
262 /* Load the history list from the history file. */
269 /* Truncate history file for interactive shells which desire it.
270 Note that the history file is automatically truncated to the
271 size of HISTSIZE if the user does not explicitly set the size
273 set_if_not ("HISTFILESIZE", get_string_value ("HISTSIZE"));
274 sv_histsize ("HISTFILESIZE");
276 /* Read the history in HISTFILE into the history list. */
277 hf = get_string_value ("HISTFILE");
279 if (hf && *hf && stat (hf, &buf) == 0)
283 history_lines_in_file = where_history ();
287 #ifdef INCLUDE_UNUSED
288 /* Write the existing history out to the history file. */
295 hf = get_string_value ("HISTFILE");
296 if (hf && *hf && stat (hf, &buf) == 0)
298 /* Append only the lines that occurred this session to
302 if (history_lines_this_session < where_history () || force_append_history)
303 append_history (history_lines_this_session, hf);
307 sv_histsize ("HISTFILESIZE");
313 maybe_append_history (filename)
319 result = EXECUTION_SUCCESS;
320 if (history_lines_this_session && (history_lines_this_session < where_history ()))
322 /* If the filename was supplied, then create it if necessary. */
323 if (stat (filename, &buf) == -1 && errno == ENOENT)
325 fd = open (filename, O_WRONLY|O_CREAT, 0600);
328 builtin_error (_("%s: cannot create: %s"), filename, strerror (errno));
329 return (EXECUTION_FAILURE);
333 result = append_history (history_lines_this_session, filename);
334 history_lines_in_file += history_lines_this_session;
335 history_lines_this_session = 0;
340 /* If this is an interactive shell, then append the lines executed
341 this session to the history file. */
343 maybe_save_shell_history ()
350 if (history_lines_this_session)
352 hf = get_string_value ("HISTFILE");
356 /* If the file doesn't exist, then create it. */
357 if (stat (hf, &buf) == -1)
360 file = open (hf, O_CREAT | O_TRUNC | O_WRONLY, 0600);
365 /* Now actually append the lines if the history hasn't been
366 stifled. If the history has been stifled, rewrite the
369 if (history_lines_this_session <= where_history () || force_append_history)
371 result = append_history (history_lines_this_session, hf);
372 history_lines_in_file += history_lines_this_session;
376 result = write_history (hf);
377 history_lines_in_file = history_lines_this_session;
379 history_lines_this_session = 0;
381 sv_histsize ("HISTFILESIZE");
387 #if defined (READLINE)
388 /* Tell readline () that we have some text for it to edit. */
393 if (bash_input.type == st_stdin)
396 #endif /* READLINE */
398 /* Return 1 if this line needs history expansion. */
400 history_expansion_p (line)
405 for (s = line; *s; s++)
406 if (*s == history_expansion_char || *s == history_subst_char)
411 /* Do pre-processing on LINE. If PRINT_CHANGES is non-zero, then
412 print the results of expanding the line if there were any changes.
413 If there is an error, return NULL, otherwise the expanded line is
414 returned. If ADDIT is non-zero the line is added to the history
415 list after history expansion. ADDIT is just a suggestion;
416 REMEMBER_ON_HISTORY can veto, and does.
417 Right now this does history expansion. */
419 pre_process_line (line, print_changes, addit)
421 int print_changes, addit;
430 # if defined (BANG_HISTORY)
431 /* History expand the line. If this results in no errors, then
432 add that line to the history if ADDIT is non-zero. */
433 if (!history_expansion_inhibited && history_expansion && history_expansion_p (line))
435 expanded = history_expand (line, &history_value);
442 internal_error ("%s", history_value);
443 #if defined (READLINE)
444 else if (hist_verify == 0 || expanded == 2)
448 fprintf (stderr, "%s\n", history_value);
451 /* If there was an error, return NULL. */
452 if (expanded < 0 || expanded == 2) /* 2 == print only */
454 # if defined (READLINE)
455 if (expanded == 2 && rl_dispatching == 0 && *history_value)
457 if (expanded == 2 && *history_value)
458 # endif /* !READLINE */
459 maybe_add_history (history_value);
461 free (history_value);
463 # if defined (READLINE)
464 /* New hack. We can allow the user to edit the
465 failed history expansion. */
466 if (history_reediting && expanded < 0 && rl_done)
468 # endif /* READLINE */
469 return ((char *)NULL);
472 # if defined (READLINE)
473 if (hist_verify && expanded == 1)
475 re_edit (history_value);
476 return ((char *)NULL);
481 /* Let other expansions know that return_value can be free'ed,
482 and that a line has been added to the history list. Note
483 that we only add lines that have something in them. */
485 return_value = history_value;
487 # endif /* BANG_HISTORY */
489 if (addit && remember_on_history && *return_value)
490 maybe_add_history (return_value);
494 return_value = savestring (line);
497 return (return_value);
500 /* Return 1 if the first non-whitespace character in LINE is a `#', indicating
501 * that the line is a shell comment. */
508 for (p = line; p && *p && whitespace (*p); p++)
510 return (p && *p == '#');
513 #ifdef INCLUDE_UNUSED
514 /* Remove shell comments from LINE. A `#' and anything after it is a comment.
515 This isn't really useful yet, since it doesn't handle quoting. */
517 filter_comments (line)
522 for (p = line; p && *p && *p != '#'; p++)
530 /* Check LINE against what HISTCONTROL says to do. Returns 1 if the line
531 should be saved; 0 if it should be discarded. */
533 check_history_control (line)
539 if (history_control == 0)
542 /* ignorespace or ignoreboth */
543 if ((history_control & HC_IGNSPACE) && *line == ' ')
546 /* ignoredups or ignoreboth */
547 if (history_control & HC_IGNDUPS)
550 temp = previous_history ();
552 r = (temp == 0 || STREQ (temp->line, line) == 0);
563 /* Remove all entries matching LINE from the history list. Triggered when
564 HISTCONTROL includes `erasedups'. */
573 while (temp = previous_history ())
575 if (STREQ (temp->line, line))
577 r = where_history ();
584 /* Add LINE to the history list, handling possibly multi-line compound
585 commands. We note whether or not we save the first line of each command
586 (which is usually the entire command and history entry), and don't add
587 the second and subsequent lines of a multi-line compound command if we
588 didn't save the first line. We don't usually save shell comment lines in
589 compound commands in the history, because they could have the effect of
590 commenting out the rest of the command when the entire command is saved as
591 a single history entry (when COMMAND_ORIENTED_HISTORY is enabled). If
592 LITERAL_HISTORY is set, we're saving lines in the history with embedded
593 newlines, so it's OK to save comment lines. We also make sure to save
594 multiple-line quoted strings or other constructs. */
596 maybe_add_history (line)
599 hist_last_line_added = 0;
601 /* Don't use the value of history_control to affect the second
602 and subsequent lines of a multi-line command (old code did
603 this only when command_oriented_history is enabled). */
604 if (current_command_line_count > 1)
606 if (current_command_first_line_saved &&
607 (literal_history || dstack.delimiter_depth != 0 || shell_comment (line) == 0))
608 bash_add_history (line);
612 /* This is the first line of a (possible multi-line) command. Note whether
613 or not we should save the first line and remember it. */
614 current_command_first_line_saved = check_add_history (line, 0);
617 /* Just check LINE against HISTCONTROL and HISTIGNORE and add it to the
618 history if it's OK. Used by `history -s' as well as maybe_add_history().
619 Returns 1 if the line was saved in the history, 0 otherwise. */
621 check_add_history (line, force)
625 if (check_history_control (line) && history_should_ignore (line) == 0)
627 /* We're committed to saving the line. If the user has requested it,
628 remove other matching lines from the history. */
629 if (history_control & HC_ERASEDUPS)
634 really_add_history (line);
638 bash_add_history (line);
644 /* Add a line to the history list.
645 The variable COMMAND_ORIENTED_HISTORY controls the style of history
646 remembering; when non-zero, and LINE is not the first line of a
647 complete parser construct, append LINE to the last history line instead
648 of adding it as a new line. */
650 bash_add_history (line)
653 int add_it, offset, curlen;
654 HIST_ENTRY *current, *old;
655 char *chars_to_add, *new_line;
658 if (command_oriented_history && current_command_line_count > 1)
660 chars_to_add = literal_history ? "\n" : history_delimiting_chars ();
663 current = previous_history ();
667 /* If the previous line ended with an escaped newline (escaped
668 with backslash, but otherwise unquoted), then remove the quoted
669 newline, since that is what happens when the line is parsed. */
670 curlen = strlen (current->line);
672 if (dstack.delimiter_depth == 0 && current->line[curlen - 1] == '\\' &&
673 current->line[curlen - 2] != '\\')
675 current->line[curlen - 1] = '\0';
680 new_line = (char *)xmalloc (1
683 + strlen (chars_to_add));
684 sprintf (new_line, "%s%s%s", current->line, chars_to_add, line);
685 offset = where_history ();
686 old = replace_history_entry (offset, new_line, current->data);
690 free_history_entry (old);
697 really_add_history (line);
703 really_add_history (line)
706 hist_last_line_added = 1;
707 hist_last_line_pushed = 0;
709 history_lines_this_session++;
716 return (remember_on_history ? history_base + where_history () : 1);
725 for (p = s; p && *p; p++)
736 histignore_item_func (ign)
739 if (should_expand (ign->val))
740 ign->flags |= HIGN_EXPAND;
745 setup_history_ignore (varname)
748 setup_ignore_patterns (&histignore);
752 last_history_entry ()
757 he = previous_history ();
767 he = last_history_entry ();
769 return ((char *)NULL);
774 expand_histignore_pattern (pat)
780 phe = last_history_entry ();
782 if (phe == (HIST_ENTRY *)0)
783 return (savestring (pat));
785 ret = strcreplace (pat, '&', phe->line, 1);
790 /* Return 1 if we should not put LINE into the history according to the
791 patterns in HISTIGNORE. */
793 history_should_ignore (line)
796 register int i, match;
799 if (histignore.num_ignores == 0)
802 for (i = match = 0; i < histignore.num_ignores; i++)
804 if (histignore.ignores[i].flags & HIGN_EXPAND)
805 npat = expand_histignore_pattern (histignore.ignores[i].val);
807 npat = histignore.ignores[i].val;
809 match = strmatch (npat, line, FNMATCH_EXTFLAG) != FNM_NOMATCH;
811 if (histignore.ignores[i].flags & HIGN_EXPAND)