forked from TuxForge/archie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autocomplete.c
67 lines (54 loc) · 1.63 KB
/
autocomplete.c
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
#include "archium.h"
void cache_pacman_commands(void) {
if (cached_commands) {
return;
}
FILE *fp;
char path[1035];
int command_count = 0;
fp = popen("pacman -Ssq", "r");
if (fp == NULL) {
fprintf(stderr, "\033[1;31mFailed to run command\033[0m\n");
exit(EXIT_FAILURE);
}
while (fgets(path, sizeof(path), fp) != NULL) {
command_count++;
cached_commands = realloc(cached_commands, sizeof(char *) * (command_count + 1));
path[strcspn(path, "\n")] = 0;
cached_commands[command_count - 1] = strdup(path);
}
pclose(fp);
const char *custom_cmds[] = {"check", "info", "s"};
for (int i = 0; i < 3; i++) {
command_count++;
cached_commands = realloc(cached_commands, sizeof(char *) * (command_count + 1));
cached_commands[command_count - 1] = strdup(custom_cmds[i]);
}
if (cached_commands) {
cached_commands[command_count] = NULL;
}
}
char *command_generator(const char *text, int state) {
static int list_index, len;
if (!cached_commands) {
cache_pacman_commands();
}
if (!state) {
list_index = 0;
len = strlen(text);
}
while (cached_commands && cached_commands[list_index]) {
const char *name = cached_commands[list_index];
list_index++;
if (strncmp(name, text, len) == 0) {
return strdup(name);
}
}
return NULL;
}
char **command_completion(const char *text, int start, int end) {
(void)start;
(void)end;
rl_attempted_completion_over = 1;
return rl_completion_matches(text, command_generator);
}