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