summary refs log tree commit diff stats
path: root/src/common/history.c
blob: 1cd6b50826e7ba9bd7d87a8fd7c5aa281e955a22 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/* X-Chat
 * Copyright (C) 1998 Peter Zelezny.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */

#include <string.h>
#include <stdlib.h>
#include "history.h"

void
history_add (struct history *his, char *text)
{
	if (his->lines[his->realpos])
		free (his->lines[his->realpos]);
	his->lines[his->realpos] = strdup (text);
	his->realpos++;
	if (his->realpos == HISTORY_SIZE)
		his->realpos = 0;
	his->pos = his->realpos;
}

void
history_free (struct history *his)
{
	int i;
	for (i = 0; i < HISTORY_SIZE; i++)
	{
		if (his->lines[i])
		{
			free (his->lines[i]);
			his->lines[i] = 0;
		}
	}
}

char *
history_down (struct history *his)
{
	int next;

	if (his->pos == his->realpos)	/* allow down only after up */
		return 0;
	if (his->realpos == 0)
	{
		if (his->pos == HISTORY_SIZE - 1)
		{
			his->pos = 0;
			return "";
		}
	} else
	{
		if (his->pos == his->realpos - 1)
		{
			his->pos++;
			return "";
		}
	}

	next = 0;
	if (his->pos < HISTORY_SIZE - 1)
		next = his->pos + 1;

	if (his->lines[next])
	{
		his->pos = next;
		return his->lines[his->pos];
	}

	return 0;
}

char *
history_up (struct history *his, char *current_text)
{
	int next;

	if (his->realpos == HISTORY_SIZE - 1)
	{
		if (his->pos == 0)
			return 0;
	} else
	{
		if (his->pos == his->realpos + 1)
			return 0;
	}

	next = HISTORY_SIZE - 1;
	if (his->pos != 0)
		next = his->pos - 1;

	if (his->lines[next])
	{
		if
		(
			current_text[0] && strcmp(current_text, his->lines[next]) &&
			(!his->lines[his->pos] || strcmp(current_text, his->lines[his->pos])) &&
			(!his->lines[his->realpos] || strcmp(current_text, his->lines[his->pos]))
		)
		{
			history_add (his, current_text);
		}
		
		his->pos = next;
		return his->lines[his->pos];
	}

	return 0;
}