62 lines
1.7 KiB
C
Raw Normal View History

2025-01-04 07:40:31 +00:00
// Written by retoor@molodetz.nl
// This source code provides command-line input functionalities with autocomplete and history features using readline library functionalities. It allows users to complete commands and manage input history.
// External includes:
// - <readline/readline.h>
// - <readline/history.h>
// MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction.
2025-01-04 05:00:03 +00:00
#include <readline/readline.h>
#include <readline/history.h>
#define HISTORY_FILE "~/.calpaca_history"
2025-01-04 07:40:31 +00:00
bool line_initialized = false;
2025-01-04 05:00:03 +00:00
2025-01-04 07:40:31 +00:00
char* line_command_generator(const char* text, int state) {
2025-01-04 05:00:03 +00:00
static int list_index, len;
2025-01-04 07:40:31 +00:00
const char* commands[] = {"help", "exit", "list", "review", "refactor", "obfuscate", NULL};
2025-01-04 05:00:03 +00:00
if (!state) {
list_index = 0;
len = strlen(text);
}
while (commands[list_index]) {
2025-01-04 07:40:31 +00:00
const char* command = commands[list_index++];
2025-01-04 05:00:03 +00:00
if (strncmp(command, text, len) == 0) {
2025-01-04 07:40:31 +00:00
return strdup(command);
2025-01-04 05:00:03 +00:00
}
}
2025-01-04 07:40:31 +00:00
return NULL;
2025-01-04 05:00:03 +00:00
}
2025-01-04 07:40:31 +00:00
char** line_command_completion(const char* text, int start, int end) {
2025-01-04 05:00:03 +00:00
rl_attempted_completion_over = 1;
return rl_completion_matches(text, line_command_generator);
}
2025-01-04 07:40:31 +00:00
void line_init() {
if (!line_initialized) {
2025-01-04 05:00:03 +00:00
rl_attempted_completion_function = line_command_completion;
line_initialized = true;
2025-01-04 07:40:31 +00:00
read_history(HISTORY_FILE);
2025-01-04 05:00:03 +00:00
}
}
2025-01-04 07:40:31 +00:00
char* line_read(char* prefix) {
char* data = readline(prefix);
if (!(data && *data)) {
2025-01-04 05:00:03 +00:00
return NULL;
}
return data;
}
2025-01-04 07:40:31 +00:00
void line_add_history(char* data) {
2025-01-04 05:00:03 +00:00
read_history(HISTORY_FILE);
add_history(data);
write_history(HISTORY_FILE);
}