libcubescript/tools/edit_linenoise.hh

86 lines
2.1 KiB
C++
Raw Permalink Normal View History

#ifdef CS_REPL_USE_LINENOISE
#ifdef OSTD_PLATFORM_POSIX
#ifndef CS_REPL_HAS_EDIT
#define CS_REPL_HAS_EDIT
/* use the bundled linenoise library, default */
#include <errno.h>
#include <ctype.h>
#include <signal.h>
2017-01-30 19:38:11 +01:00
#include <optional>
#include <ostd/string.hh>
#include "linenoise.hh"
2017-02-13 18:10:40 +01:00
static cs_state *ln_cs = nullptr;
2016-09-11 23:33:02 +02:00
2017-06-19 20:13:54 +02:00
inline void ln_complete(char const *buf, linenoiseCompletions *lc) {
2017-02-16 19:07:22 +01:00
ostd::string_range cmd = get_complete_cmd(buf);
for (auto id: ln_cs->get_idents()) {
if (!id->is_command()) {
continue;
}
2017-02-16 19:07:22 +01:00
ostd::string_range idname = id->get_name();
if (idname.size() <= cmd.size()) {
continue;
}
if (idname.slice(0, cmd.size()) == cmd) {
linenoiseAddCompletion(lc, idname.data());
}
}
}
2017-06-19 20:13:54 +02:00
inline char *ln_hint(char const *buf, int *color, int *bold) {
2017-02-13 18:10:40 +01:00
cs_command *cmd = get_hint_cmd(*ln_cs, buf);
if (!cmd) {
return nullptr;
}
2017-01-30 01:18:55 +01:00
std::string args = " [";
fill_cmd_args(args, cmd->get_args());
args += ']';
*color = 35;
*bold = 1;
char *ret = new char[args.size() + 1];
memcpy(ret, args.data(), args.size() + 1);
return ret;
}
2017-06-19 20:13:54 +02:00
inline void ln_hint_free(void *hint) {
delete[] static_cast<char *>(hint);
}
2017-06-19 20:13:54 +02:00
inline void init_lineedit(cs_state &cs, ostd::string_range) {
/* sensible default history size */
linenoiseHistorySetMaxLen(1000);
2016-09-11 23:33:02 +02:00
ln_cs = &cs;
linenoiseSetCompletionCallback(ln_complete);
linenoiseSetHintsCallback(ln_hint);
linenoiseSetFreeHintsCallback(ln_hint_free);
}
2017-06-19 20:13:54 +02:00
inline std::optional<std::string> read_line(cs_state &, cs_svar *pr) {
auto line = linenoise(pr->get_value().data());
if (!line) {
/* linenoise traps ctrl-c, detect it and let the user exit */
if (errno == EAGAIN) {
raise(SIGINT);
2017-01-30 19:38:11 +01:00
return std::nullopt;
}
2017-01-30 01:18:55 +01:00
return std::string{};
}
2017-01-30 01:18:55 +01:00
std::string ret = line;
linenoiseFree(line);
2017-01-25 01:57:33 +01:00
return std::move(ret);
}
2017-06-19 20:13:54 +02:00
inline void add_history(cs_state &, ostd::string_range line) {
2017-01-30 01:18:55 +01:00
/* backed by std::string so it's terminated */
linenoiseHistoryAdd(line.data());
}
#endif
#endif
#endif