Skip to content

Instantly share code, notes, and snippets.

@odeblic
Created February 13, 2023 12:10
Show Gist options
  • Save odeblic/6aabc8a656a5cd07d8af0b664a61cee3 to your computer and use it in GitHub Desktop.
Save odeblic/6aabc8a656a5cd07d8af0b664a61cee3 to your computer and use it in GitHub Desktop.
#include <readline/history.h>
#include <readline/readline.h>
#include <iostream>
#include <vector>
std::vector<std::string> commandList =
{
"start",
"status",
"stop",
"restart",
"kill",
"quit",
"show",
};
char * generate(char const * text, int state)
{
static size_t index{0};
if (state == 0)
{
index = 0;
}
std::cerr << "\033[36mCALL:\033[0m generate(text=\033[35m\"" << text << "\"\033[0m, state=\033[35m" << state << "\033[0m)" << std::endl;
auto const input = std::string(text);
char * possibleMatch{nullptr};
while (index < commandList.size() and possibleMatch == nullptr)
{
auto const& command = commandList[index];
if (command.size() >= input.size() and command.compare(0, input.size(), input) == 0)
{
possibleMatch = strdup(commandList[index].c_str());
}
index++;
}
return possibleMatch;
}
char * generate2(const char *text, int state)
{
static std::vector<std::string> matches;
static size_t match_index = 0;
if (state == 0) {
matches.clear();
match_index = 0;
std::string textstr(text);
for (auto word : commandList) {
if (word.size() >= textstr.size() &&
word.compare(0, textstr.size(), textstr) == 0) {
matches.push_back(word);
}
}
}
if (match_index >= matches.size()) {
return nullptr;
} else {
return strdup(matches[match_index++].c_str());
}
}
char ** complete(char const * text, int start, int end)
{
rl_attempted_completion_over = 1;
std::cerr << "\033[36mCALL:\033[0m complete(text=\033[35m\"" << text << "\"\033[0m, start=\033[35m" << start << "\033[0m, end=\033[35m" << end << "\033[0m)" << std::endl;
if (start > 0)
{
return nullptr;
}
return rl_completion_matches(text, generate);
}
int main(int argc, char *argv[])
{
std::cerr << "\033[34mSTART\033[0m" << std::endl;
rl_attempted_completion_function = complete;
while (true)
{
char * line = readline("> ");
if (line == nullptr)
{
std::cerr << "\033[31mNULL\033[0m" << std::endl;
break;
}
else if (*line)
{
add_history(line);
std::cerr << "\033[32mRECEIVED:\033[0m " << line << std::endl;
}
else
{
std::cerr << "\033[33mEMPTY\033[0m" << std::endl;
}
free(line);
}
std::cerr << "\033[34mSTOP\033[0m" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment