Rocco Rutte:
[apps/madmutt.git] / history.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  *
5  * This file is part of mutt-ng, see http://www.muttng.org/.
6  * It's licensed under the GNU General Public License,
7  * please see the file GPL in the top level source directory.
8  */
9
10 #if HAVE_CONFIG_H
11 # include "config.h"
12 #endif
13
14 #include "mutt.h"
15 #include "history.h"
16 #include "lib/mem.h"
17
18 /* global vars used for the string-history routines */
19
20 struct history {
21   char **hist;
22   short cur;
23   short last;
24 };
25
26 static struct history History[HC_LAST];
27 static int OldSize = 0;
28
29 static void init_history (struct history *h)
30 {
31   int i;
32
33   if (OldSize) {
34     if (h->hist) {
35       for (i = 0; i < OldSize; i++)
36         mem_free (&h->hist[i]);
37       mem_free (&h->hist);
38     }
39   }
40
41   if (HistSize)
42     h->hist = mem_calloc (HistSize, sizeof (char *));
43
44   h->cur = 0;
45   h->last = 0;
46 }
47
48 void mutt_init_history (void)
49 {
50   history_class_t hclass;
51
52   if (HistSize == OldSize)
53     return;
54
55   for (hclass = HC_FIRST; hclass < HC_LAST; hclass++)
56     init_history (&History[hclass]);
57
58   OldSize = HistSize;
59 }
60
61 void mutt_history_add (history_class_t hclass, const char *s)
62 {
63   int prev;
64   struct history *h = &History[hclass];
65
66   if (!HistSize)
67     return;                     /* disabled */
68
69   if (*s) {
70     prev = h->last - 1;
71     if (prev < 0)
72       prev = HistSize - 1;
73     if (!h->hist[prev] || str_cmp (h->hist[prev], s) != 0) {
74       str_replace (&h->hist[h->last++], s);
75       if (h->last > HistSize - 1)
76         h->last = 0;
77     }
78   }
79   h->cur = h->last;             /* reset to the last entry */
80 }
81
82 char *mutt_history_next (history_class_t hclass)
83 {
84   int next;
85   struct history *h = &History[hclass];
86
87   if (!HistSize)
88     return ("");                /* disabled */
89
90   next = h->cur + 1;
91   if (next > HistSize - 1)
92     next = 0;
93   h->cur = h->hist[next] ? next : 0;
94   return (h->hist[h->cur] ? h->hist[h->cur] : "");
95 }
96
97 char *mutt_history_prev (history_class_t hclass)
98 {
99   int prev;
100   struct history *h = &History[hclass];
101
102   if (!HistSize)
103     return ("");                /* disabled */
104
105   prev = h->cur - 1;
106   if (prev < 0) {
107     prev = HistSize - 1;
108     while (prev > 0 && h->hist[prev] == NULL)
109       prev--;
110   }
111   if (h->hist[prev])
112     h->cur = prev;
113   return (h->hist[h->cur] ? h->hist[h->cur] : "");
114 }