Nico Golde:
[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
17 /* global vars used for the string-history routines */
18
19 struct history {
20   char **hist;
21   short cur;
22   short last;
23 };
24
25 static struct history History[HC_LAST];
26 static int OldSize = 0;
27
28 static void init_history (struct history *h)
29 {
30   int i;
31
32   if (OldSize) {
33     if (h->hist) {
34       for (i = 0; i < OldSize; i++)
35         FREE (&h->hist[i]);
36       FREE (&h->hist);
37     }
38   }
39
40   if (HistSize)
41     h->hist = safe_calloc (HistSize, sizeof (char *));
42
43   h->cur = 0;
44   h->last = 0;
45 }
46
47 void mutt_init_history (void)
48 {
49   history_class_t hclass;
50
51   if (HistSize == OldSize)
52     return;
53
54   for (hclass = HC_FIRST; hclass < HC_LAST; hclass++)
55     init_history (&History[hclass]);
56
57   OldSize = HistSize;
58 }
59
60 void mutt_history_add (history_class_t hclass, const char *s)
61 {
62   int prev;
63   struct history *h = &History[hclass];
64
65   if (!HistSize)
66     return;                     /* disabled */
67
68   if (*s) {
69     prev = h->last - 1;
70     if (prev < 0)
71       prev = HistSize - 1;
72     if (!h->hist[prev] || mutt_strcmp (h->hist[prev], s) != 0) {
73       mutt_str_replace (&h->hist[h->last++], s);
74       if (h->last > HistSize - 1)
75         h->last = 0;
76     }
77   }
78   h->cur = h->last;             /* reset to the last entry */
79 }
80
81 char *mutt_history_next (history_class_t hclass)
82 {
83   int next;
84   struct history *h = &History[hclass];
85
86   if (!HistSize)
87     return ("");                /* disabled */
88
89   next = h->cur + 1;
90   if (next > HistSize - 1)
91     next = 0;
92   h->cur = h->hist[next] ? next : 0;
93   return (h->hist[h->cur] ? h->hist[h->cur] : "");
94 }
95
96 char *mutt_history_prev (history_class_t hclass)
97 {
98   int prev;
99   struct history *h = &History[hclass];
100
101   if (!HistSize)
102     return ("");                /* disabled */
103
104   prev = h->cur - 1;
105   if (prev < 0) {
106     prev = HistSize - 1;
107     while (prev > 0 && h->hist[prev] == NULL)
108       prev--;
109   }
110   if (h->hist[prev])
111     h->cur = prev;
112   return (h->hist[h->cur] ? h->hist[h->cur] : "");
113 }