spmenu/libs/history.c

89 lines
1.8 KiB
C
Raw Normal View History

void loadhistory(void) {
2023-05-08 23:00:45 +02:00
FILE *fp = NULL;
static size_t cap = 0;
size_t llen;
char *line;
2023-03-31 12:42:15 +02:00
// no history file, give up like i do with all things in life
2023-05-08 23:00:45 +02:00
if (!histfile) {
return;
}
2023-03-31 12:42:15 +02:00
// open history file, return if it failed
2023-05-08 23:00:45 +02:00
fp = fopen(histfile, "r");
if (!fp) {
2023-03-31 12:42:15 +02:00
fprintf(stderr, "spmenu: failed to open history file\n");
return;
}
2023-05-08 23:00:45 +02:00
for (;;) {
line = NULL;
llen = 0;
2023-03-31 12:42:15 +02:00
2023-05-08 23:00:45 +02:00
if (-1 == getline(&line, &llen, fp)) {
if (ferror(fp)) {
die("spmenu: failed to read history");
}
2023-03-31 12:42:15 +02:00
2023-05-08 23:00:45 +02:00
free(line);
break;
}
2023-03-31 12:42:15 +02:00
2023-05-08 23:00:45 +02:00
if (cap == histsz) {
cap += 64 * sizeof(char*);
history = realloc(history, cap);
if (!history) {
die("spmenu: failed to realloc memory");
}
}
strtok(line, "\n");
history[histsz] = line;
histsz++;
}
2023-03-31 12:42:15 +02:00
2023-05-08 23:00:45 +02:00
histpos = histsz;
2023-03-31 12:42:15 +02:00
2023-05-08 23:00:45 +02:00
if (fclose(fp)) {
die("spmenu: failed to close file %s", histfile);
}
2023-03-31 12:42:15 +02:00
}
void navigatehistfile(int dir) {
2023-05-08 23:00:45 +02:00
static char def[BUFSIZ];
char *p = NULL;
size_t len = 0;
2023-03-31 12:42:15 +02:00
2023-05-08 23:00:45 +02:00
if (!history || histpos + 1 == 0)
return;
2023-03-31 12:42:15 +02:00
2023-05-08 23:00:45 +02:00
if (histsz == histpos) {
strncpy(def, text, sizeof(def));
}
2023-03-31 12:42:15 +02:00
2023-05-08 23:00:45 +02:00
switch (dir) {
2023-03-31 12:42:15 +02:00
case 1:
if (histpos < histsz - 1) {
p = history[++histpos];
} else if (histpos == histsz - 1) {
p = def;
histpos++;
}
break;
case -1:
if (histpos > 0) {
p = history[--histpos];
}
break;
2023-05-08 23:00:45 +02:00
}
2023-03-31 12:42:15 +02:00
2023-05-08 23:00:45 +02:00
if (p == NULL) {
return;
}
2023-03-31 12:42:15 +02:00
2023-05-08 23:00:45 +02:00
len = MIN(strlen(p), BUFSIZ - 1);
strcpy(text, p);
text[len] = '\0';
cursor = len;
match();
2023-03-31 12:42:15 +02:00
}