|
// 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.
|
|
|
|
#include <readline/readline.h>
|
|
#include <readline/history.h>
|
|
|
|
#define HISTORY_FILE "~/.calpaca_history"
|
|
|
|
bool line_initialized = false;
|
|
|
|
char* line_command_generator(const char* text, int state) {
|
|
static int list_index, len;
|
|
const char* commands[] = {"help", "exit", "list", "review", "refactor", "obfuscate", NULL};
|
|
|
|
if (!state) {
|
|
list_index = 0;
|
|
len = strlen(text);
|
|
}
|
|
|
|
while (commands[list_index]) {
|
|
const char* command = commands[list_index++];
|
|
if (strncmp(command, text, len) == 0) {
|
|
return strdup(command);
|
|
}
|
|
}
|
|
|
|
return NULL;
|
|
}
|
|
|
|
char** line_command_completion(const char* text, int start, int end) {
|
|
rl_attempted_completion_over = 1;
|
|
return rl_completion_matches(text, line_command_generator);
|
|
}
|
|
|
|
void line_init() {
|
|
if (!line_initialized) {
|
|
rl_attempted_completion_function = line_command_completion;
|
|
line_initialized = true;
|
|
read_history(HISTORY_FILE);
|
|
}
|
|
}
|
|
|
|
char* line_read(char* prefix) {
|
|
char* data = readline(prefix);
|
|
if (!(data && *data)) {
|
|
return NULL;
|
|
}
|
|
return data;
|
|
}
|
|
|
|
void line_add_history(char* data) {
|
|
read_history(HISTORY_FILE);
|
|
add_history(data);
|
|
write_history(HISTORY_FILE);
|
|
} |