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