#include "llvm/LineEditor/LineEditor.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstdio>
#ifdef HAVE_LIBEDIT
#include <histedit.h>
#endif
using namespace llvm;
std::string LineEditor::getDefaultHistoryPath(StringRef ProgName) {
SmallString<32> Path;
if (sys::path::home_directory(Path)) {
sys::path::append(Path, "." + ProgName + "-history");
return std::string(Path.str());
}
return std::string();
}
LineEditor::CompleterConcept::~CompleterConcept() = default;
LineEditor::ListCompleterConcept::~ListCompleterConcept() = default;
std::string LineEditor::ListCompleterConcept::getCommonPrefix(
const std::vector<Completion> &Comps) {
assert(!Comps.empty());
std::string CommonPrefix = Comps[0].TypedText;
for (std::vector<Completion>::const_iterator I = Comps.begin() + 1,
E = Comps.end();
I != E; ++I) {
size_t Len = std::min(CommonPrefix.size(), I->TypedText.size());
size_t CommonLen = 0;
for (; CommonLen != Len; ++CommonLen) {
if (CommonPrefix[CommonLen] != I->TypedText[CommonLen])
break;
}
CommonPrefix.resize(CommonLen);
}
return CommonPrefix;
}
LineEditor::CompletionAction
LineEditor::ListCompleterConcept::complete(StringRef Buffer, size_t Pos) const {
CompletionAction Action;
std::vector<Completion> Comps = getCompletions(Buffer, Pos);
if (Comps.empty()) {
Action.Kind = CompletionAction::AK_ShowCompletions;
return Action;
}
std::string CommonPrefix = getCommonPrefix(Comps);
if (CommonPrefix.empty()) {
Action.Kind = CompletionAction::AK_ShowCompletions;
for (const Completion &Comp : Comps)
Action.Completions.push_back(Comp.DisplayText);
} else {
Action.Kind = CompletionAction::AK_Insert;
Action.Text = CommonPrefix;
}
return Action;
}
LineEditor::CompletionAction LineEditor::getCompletionAction(StringRef Buffer,
size_t Pos) const {
if (!Completer) {
CompletionAction Action;
Action.Kind = CompletionAction::AK_ShowCompletions;
return Action;
}
return Completer->complete(Buffer, Pos);
}
#ifdef HAVE_LIBEDIT
struct LineEditor::InternalData {
LineEditor *LE;
History *Hist;
EditLine *EL;
unsigned PrevCount;
std::string ContinuationOutput;
FILE *Out;
};
namespace {
const char *ElGetPromptFn(EditLine *EL) {
LineEditor::InternalData *Data;
if (el_get(EL, EL_CLIENTDATA, &Data) == 0)
return Data->LE->getPrompt().c_str();
return "> ";
}
unsigned char ElCompletionFn(EditLine *EL, int ch) {
LineEditor::InternalData *Data;
if (el_get(EL, EL_CLIENTDATA, &Data) == 0) {
if (!Data->ContinuationOutput.empty()) {
FILE *Out = Data->Out;
::fwrite(Data->ContinuationOutput.c_str(),
Data->ContinuationOutput.size(), 1, Out);
std::string Prevs(Data->PrevCount, '\02');
::el_push(EL, const_cast<char *>(Prevs.c_str()));
Data->ContinuationOutput.clear();
return CC_REFRESH;
}
const LineInfo *LI = ::el_line(EL);
LineEditor::CompletionAction Action = Data->LE->getCompletionAction(
StringRef(LI->buffer, LI->lastchar - LI->buffer),
LI->cursor - LI->buffer);
switch (Action.Kind) {
case LineEditor::CompletionAction::AK_Insert:
::el_insertstr(EL, Action.Text.c_str());
return CC_REFRESH;
case LineEditor::CompletionAction::AK_ShowCompletions:
if (Action.Completions.empty()) {
return CC_REFRESH_BEEP;
} else {
::el_push(EL, const_cast<char *>("\05\t"));
raw_string_ostream OS(Data->ContinuationOutput);
OS << "\n";
for (std::vector<std::string>::iterator I = Action.Completions.begin(),
E = Action.Completions.end();
I != E; ++I) {
OS << *I << "\n";
}
OS << Data->LE->getPrompt()
<< StringRef(LI->buffer, LI->lastchar - LI->buffer);
Data->PrevCount = LI->lastchar - LI->cursor;
return CC_REFRESH;
}
}
}
return CC_ERROR;
}
}
LineEditor::LineEditor(StringRef ProgName, StringRef HistoryPath, FILE *In,
FILE *Out, FILE *Err)
: Prompt((ProgName + "> ").str()), HistoryPath(std::string(HistoryPath)),
Data(new InternalData) {
if (HistoryPath.empty())
this->HistoryPath = getDefaultHistoryPath(ProgName);
Data->LE = this;
Data->Out = Out;
Data->Hist = ::history_init();
assert(Data->Hist);
Data->EL = ::el_init(ProgName.str().c_str(), In, Out, Err);
assert(Data->EL);
::el_set(Data->EL, EL_PROMPT, ElGetPromptFn);
::el_set(Data->EL, EL_EDITOR, "emacs");
::el_set(Data->EL, EL_HIST, history, Data->Hist);
::el_set(Data->EL, EL_ADDFN, "tab_complete", "Tab completion function",
ElCompletionFn);
::el_set(Data->EL, EL_BIND, "\t", "tab_complete", NULL);
::el_set(Data->EL, EL_BIND, "^r", "em-inc-search-prev",
NULL); ::el_set(Data->EL, EL_BIND, "^w", "ed-delete-prev-word",
NULL); ::el_set(Data->EL, EL_BIND, "\033[3~", "ed-delete-next-char",
NULL); ::el_set(Data->EL, EL_CLIENTDATA, Data.get());
HistEvent HE;
::history(Data->Hist, &HE, H_SETSIZE, 800);
::history(Data->Hist, &HE, H_SETUNIQUE, 1);
loadHistory();
}
LineEditor::~LineEditor() {
saveHistory();
::history_end(Data->Hist);
::el_end(Data->EL);
::fwrite("\n", 1, 1, Data->Out);
}
void LineEditor::saveHistory() {
if (!HistoryPath.empty()) {
HistEvent HE;
::history(Data->Hist, &HE, H_SAVE, HistoryPath.c_str());
}
}
void LineEditor::loadHistory() {
if (!HistoryPath.empty()) {
HistEvent HE;
::history(Data->Hist, &HE, H_LOAD, HistoryPath.c_str());
}
}
Optional<std::string> LineEditor::readLine() const {
int LineLen = 0;
const char *Line = ::el_gets(Data->EL, &LineLen);
if (!Line || LineLen == 0)
return Optional<std::string>();
while (LineLen > 0 &&
(Line[LineLen - 1] == '\n' || Line[LineLen - 1] == '\r'))
--LineLen;
HistEvent HE;
if (LineLen > 0)
::history(Data->Hist, &HE, H_ENTER, Line);
return std::string(Line, LineLen);
}
#else
struct LineEditor::InternalData {
FILE *In;
FILE *Out;
};
LineEditor::LineEditor(StringRef ProgName, StringRef HistoryPath, FILE *In,
FILE *Out, FILE *Err)
: Prompt((ProgName + "> ").str()), Data(new InternalData) {
Data->In = In;
Data->Out = Out;
}
LineEditor::~LineEditor() {
::fwrite("\n", 1, 1, Data->Out);
}
void LineEditor::saveHistory() {}
void LineEditor::loadHistory() {}
Optional<std::string> LineEditor::readLine() const {
::fprintf(Data->Out, "%s", Prompt.c_str());
std::string Line;
do {
char Buf[64];
char *Res = ::fgets(Buf, sizeof(Buf), Data->In);
if (!Res) {
if (Line.empty())
return Optional<std::string>();
else
return Line;
}
Line.append(Buf);
} while (Line.empty() ||
(Line[Line.size() - 1] != '\n' && Line[Line.size() - 1] != '\r'));
while (!Line.empty() &&
(Line[Line.size() - 1] == '\n' || Line[Line.size() - 1] == '\r'))
Line.resize(Line.size() - 1);
return Line;
}
#endif