1/* histexamp.c - history library example program. */ 2 3/* Copyright (C) 1987-2009 Free Software Foundation, Inc. 4 5 This file is part of the GNU Readline Library (Readline), a library for 6 reading lines of text with interactive input and history editing. 7 8 Readline 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. 12 13 Readline 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. 17 18 You should have received a copy of the GNU General Public License 19 along with Readline. If not, see <http://www.gnu.org/licenses/>. 20*/ 21 22#include <stdio.h> 23 24#ifdef READLINE_LIBRARY 25# include "history.h" 26#else 27# include <readline/history.h> 28#endif 29 30#include <unistd.h> 31#include <stdlib.h> 32#include <string.h> 33 34int 35main (argc, argv) 36 int argc; 37 char **argv; 38{ 39 char line[1024], *t; 40 int len, done; 41 42 line[0] = 0; 43 done = 0; 44 45 using_history (); 46 while (!done) 47 { 48 printf ("history$ "); 49 fflush (stdout); 50 t = fgets (line, sizeof (line) - 1, stdin); 51 if (t && *t) 52 { 53 len = strlen (t); 54 if (t[len - 1] == '\n') 55 t[len - 1] = '\0'; 56 } 57 58 if (!t) 59 strcpy (line, "quit"); 60 61 if (line[0]) 62 { 63 char *expansion; 64 int result; 65 66 using_history (); 67 68 result = history_expand (line, &expansion); 69 if (result) 70 fprintf (stderr, "%s\n", expansion); 71 72 if (result < 0 || result == 2) 73 { 74 free (expansion); 75 continue; 76 } 77 78 add_history (expansion); 79 strncpy (line, expansion, sizeof (line) - 1); 80 free (expansion); 81 } 82 83 if (strcmp (line, "quit") == 0) 84 done = 1; 85 else if (strcmp (line, "save") == 0) 86 write_history ("history_file"); 87 else if (strcmp (line, "read") == 0) 88 read_history ("history_file"); 89 else if (strcmp (line, "list") == 0) 90 { 91 register HIST_ENTRY **the_list; 92 register int i; 93 time_t tt; 94 char timestr[128]; 95 96 the_list = history_list (); 97 if (the_list) 98 for (i = 0; the_list[i]; i++) 99 { 100 tt = history_get_time (the_list[i]); 101 if (tt) 102 strftime (timestr, sizeof (timestr), "%a %R", localtime(&tt)); 103 else 104 strcpy (timestr, "??"); 105 printf ("%d: %s: %s\n", i + history_base, timestr, the_list[i]->line); 106 } 107 } 108 else if (strncmp (line, "delete", 6) == 0) 109 { 110 int which; 111 if ((sscanf (line + 6, "%d", &which)) == 1) 112 { 113 HIST_ENTRY *entry = remove_history (which); 114 if (!entry) 115 fprintf (stderr, "No such entry %d\n", which); 116 else 117 { 118 free (entry->line); 119 free (entry); 120 } 121 } 122 else 123 { 124 fprintf (stderr, "non-numeric arg given to `delete'\n"); 125 } 126 } 127 } 128} 129