Imported from ../bash-1.14.7.tar.gz.
[platform/upstream/bash.git] / lib / readline / examples / histexamp.c
1 main ()
2 {
3   char line[1024], *t;
4   int len, done = 0;
5
6   line[0] = 0;
7
8   using_history ();
9   while (!done)
10     {
11       printf ("history$ ");
12       fflush (stdout);
13       t = fgets (line, sizeof (line) - 1, stdin);
14       if (t && *t)
15         {
16           len = strlen (t);
17           if (t[len - 1] == '\n')
18             t[len - 1] = '\0';
19         }
20
21       if (!t)
22         strcpy (line, "quit");
23
24       if (line[0])
25         {
26           char *expansion;
27           int result;
28
29           using_history ();
30
31           result = history_expand (line, &expansion);
32           if (result)
33             fprintf (stderr, "%s\n", expansion);
34
35           if (result < 0 || result == 2)
36             {
37               free (expansion);
38               continue;
39             }
40
41           add_history (expansion);
42           strncpy (line, expansion, sizeof (line) - 1);
43           free (expansion);
44         }
45
46       if (strcmp (line, "quit") == 0)
47         done = 1;
48       else if (strcmp (line, "save") == 0)
49         write_history ("history_file");
50       else if (strcmp (line, "read") == 0)
51         read_history ("history_file");
52       else if (strcmp (line, "list") == 0)
53         {
54           register HIST_ENTRY **the_list;
55           register int i;
56
57           the_list = history_list ();
58           if (the_list)
59             for (i = 0; the_list[i]; i++)
60               printf ("%d: %s\n", i + history_base, the_list[i]->line);
61         }
62       else if (strncmp (line, "delete", 6) == 0)
63         {
64           int which;
65           if ((sscanf (line + 6, "%d", &which)) == 1)
66             {
67               HIST_ENTRY *entry = remove_history (which);
68               if (!entry)
69                 fprintf (stderr, "No such entry %d\n", which);
70               else
71                 {
72                   free (entry->line);
73                   free (entry);
74                 }
75             }
76           else
77             {
78               fprintf (stderr, "non-numeric arg given to `delete'\n");
79             }
80         }
81     }
82 }