source: history.c @ d9fe25a

release-1.10release-1.8release-1.9
Last change on this file since d9fe25a was 25891a8, checked in by David Benjamin <davidben@mit.edu>, 13 years ago
Add a unit test for owl_history Also fix an off-by-one error in bounding the history size. May as well have those semantics be coherent and testable.
  • Property mode set to 100644
File size: 1.6 KB
Line 
1#include "owl.h"
2
3void owl_history_init(owl_history *h)
4{
5  g_queue_init(&h->hist);
6  h->cur = h->hist.tail;        /* current position in history */
7  h->partial = false;           /* is the 0th element is partially composed? */
8}
9
10void owl_history_cleanup(owl_history *h)
11{
12  g_queue_foreach(&h->hist, (GFunc)g_free, NULL);
13  g_queue_clear(&h->hist);
14}
15
16const char *owl_history_get_prev(owl_history *h)
17{
18  if (!h) return NULL;
19
20  if (h->cur == NULL || g_list_previous(h->cur) == NULL) return NULL;
21
22  h->cur = g_list_previous(h->cur);
23  return h->cur->data;
24}
25
26const char *owl_history_get_next(owl_history *h)
27{
28  if (!h) return NULL;
29
30  if (h->cur == NULL || g_list_next(h->cur) == NULL) return NULL;
31
32  h->cur = g_list_next(h->cur);
33  return h->cur->data;
34}
35
36void owl_history_store(owl_history *h, const char *line, bool partial)
37{
38  if (!h) return;
39
40  owl_history_reset(h);
41
42  /* check if the line is the same as the last */
43  if (!partial && !g_queue_is_empty(&h->hist) &&
44      strcmp(line, g_queue_peek_tail(&h->hist)) == 0)
45    return;
46
47  /* if we've reached the max history size, pop off the last element */
48  if (g_queue_get_length(&h->hist) >= OWL_HISTORYSIZE)
49    g_free(g_queue_pop_head(&h->hist));
50
51  /* add the new line */
52  g_queue_push_tail(&h->hist, g_strdup(line));
53  h->partial = partial;
54  h->cur = h->hist.tail;
55}
56
57void owl_history_reset(owl_history *h)
58{
59  if (!h) return;
60
61  /* if partial is set, remove the first entry first */
62  if (h->partial) {
63    g_free(g_queue_pop_tail(&h->hist));
64    h->partial = false;
65  }
66
67  h->cur = h->hist.tail;
68}
69
70int owl_history_is_touched(const owl_history *h)
71{
72  if (!h) return(0);
73  return h->cur != NULL && g_list_next(h->cur) != NULL;
74}
Note: See TracBrowser for help on using the repository browser.