1 //===-- LineEditor.cpp - line editor --------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/LineEditor/LineEditor.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/Config/config.h"
13 #include "llvm/Support/Path.h"
14 #include "llvm/Support/raw_ostream.h"
22 std::string LineEditor::getDefaultHistoryPath(StringRef ProgName) {
24 if (sys::path::home_directory(Path)) {
25 sys::path::append(Path, "." + ProgName + "-history");
31 LineEditor::CompleterConcept::~CompleterConcept() {}
32 LineEditor::ListCompleterConcept::~ListCompleterConcept() {}
34 std::string LineEditor::ListCompleterConcept::getCommonPrefix(
35 const std::vector<Completion> &Comps) {
36 assert(!Comps.empty());
38 std::string CommonPrefix = Comps[0].TypedText;
39 for (std::vector<Completion>::const_iterator I = Comps.begin() + 1,
42 size_t Len = std::min(CommonPrefix.size(), I->TypedText.size());
44 for (; CommonLen != Len; ++CommonLen) {
45 if (CommonPrefix[CommonLen] != I->TypedText[CommonLen])
48 CommonPrefix.resize(CommonLen);
53 LineEditor::CompletionAction
54 LineEditor::ListCompleterConcept::complete(StringRef Buffer, size_t Pos) const {
55 CompletionAction Action;
56 std::vector<Completion> Comps = getCompletions(Buffer, Pos);
58 Action.Kind = CompletionAction::AK_ShowCompletions;
62 std::string CommonPrefix = getCommonPrefix(Comps);
64 // If the common prefix is non-empty we can simply insert it. If there is a
65 // single completion, this will insert the full completion. If there is more
66 // than one, this might be enough information to jog the user's memory but if
67 // not the user can also hit tab again to see the completions because the
68 // common prefix will then be empty.
69 if (CommonPrefix.empty()) {
70 Action.Kind = CompletionAction::AK_ShowCompletions;
71 for (std::vector<Completion>::iterator I = Comps.begin(), E = Comps.end();
73 Action.Completions.push_back(I->DisplayText);
75 Action.Kind = CompletionAction::AK_Insert;
76 Action.Text = CommonPrefix;
82 LineEditor::CompletionAction LineEditor::getCompletionAction(StringRef Buffer,
85 CompletionAction Action;
86 Action.Kind = CompletionAction::AK_ShowCompletions;
90 return Completer->complete(Buffer, Pos);
95 // libedit-based implementation.
97 struct LineEditor::InternalData {
104 std::string ContinuationOutput;
109 static const char *ElGetPromptFn(EditLine *EL) {
110 LineEditor::InternalData *Data;
111 if (el_get(EL, EL_CLIENTDATA, &Data) == 0)
112 return Data->LE->getPrompt().c_str();
116 // Handles tab completion.
118 // This function is really horrible. But since the alternative is to get into
119 // the line editor business, here we are.
120 static unsigned char ElCompletionFn(EditLine *EL, int ch) {
121 LineEditor::InternalData *Data;
122 if (el_get(EL, EL_CLIENTDATA, &Data) == 0) {
123 if (!Data->ContinuationOutput.empty()) {
124 // This is the continuation of the AK_ShowCompletions branch below.
125 FILE *Out = Data->Out;
127 // Print the required output (see below).
128 ::fwrite(Data->ContinuationOutput.c_str(),
129 Data->ContinuationOutput.size(), 1, Out);
131 // Push a sequence of Ctrl-B characters to move the cursor back to its
132 // original position.
133 std::string Prevs(Data->PrevCount, '\02');
134 ::el_push(EL, const_cast<char *>(Prevs.c_str()));
136 Data->ContinuationOutput.clear();
141 const LineInfo *LI = ::el_line(EL);
142 LineEditor::CompletionAction Action = Data->LE->getCompletionAction(
143 StringRef(LI->buffer, LI->lastchar - LI->buffer),
144 LI->cursor - LI->buffer);
145 switch (Action.Kind) {
146 case LineEditor::CompletionAction::AK_Insert:
147 ::el_insertstr(EL, Action.Text.c_str());
150 case LineEditor::CompletionAction::AK_ShowCompletions:
151 if (Action.Completions.empty()) {
152 return CC_REFRESH_BEEP;
154 // Push a Ctrl-E and a tab. The Ctrl-E causes libedit to move the cursor
155 // to the end of the line, so that when we emit a newline we will be on
156 // a new blank line. The tab causes libedit to call this function again
157 // after moving the cursor. There doesn't seem to be anything we can do
158 // from here to cause libedit to move the cursor immediately. This will
159 // break horribly if the user has rebound their keys, so for now we do
160 // not permit user rebinding.
161 ::el_push(EL, const_cast<char *>("\05\t"));
163 // This assembles the output for the continuation block above.
164 raw_string_ostream OS(Data->ContinuationOutput);
166 // Move cursor to a blank line.
169 // Emit the completions.
170 for (std::vector<std::string>::iterator I = Action.Completions.begin(),
171 E = Action.Completions.end();
176 // Fool libedit into thinking nothing has changed. Reprint its prompt
177 // and the user input. Note that the cursor will remain at the end of
178 // the line after this.
179 OS << Data->LE->getPrompt()
180 << StringRef(LI->buffer, LI->lastchar - LI->buffer);
182 // This is the number of characters we need to tell libedit to go back:
183 // the distance between end of line and the original cursor position.
184 Data->PrevCount = LI->lastchar - LI->cursor;
193 LineEditor::LineEditor(StringRef ProgName, StringRef HistoryPath, FILE *In,
194 FILE *Out, FILE *Err)
195 : Prompt((ProgName + "> ").str()), HistoryPath(HistoryPath),
196 Data(new InternalData) {
197 if (HistoryPath.empty())
198 this->HistoryPath = getDefaultHistoryPath(ProgName);
203 Data->Hist = ::history_init();
206 Data->EL = ::el_init(ProgName.str().c_str(), In, Out, Err);
209 ::el_set(Data->EL, EL_PROMPT, ElGetPromptFn);
210 ::el_set(Data->EL, EL_EDITOR, "emacs");
211 ::el_set(Data->EL, EL_HIST, history, Data->Hist);
212 ::el_set(Data->EL, EL_ADDFN, "tab_complete", "Tab completion function",
214 ::el_set(Data->EL, EL_BIND, "\t", "tab_complete", NULL);
215 ::el_set(Data->EL, EL_BIND, "^r", "em-inc-search-prev",
216 NULL); // Cycle through backwards search, entering string
217 ::el_set(Data->EL, EL_BIND, "^w", "ed-delete-prev-word",
218 NULL); // Delete previous word, behave like bash does.
219 ::el_set(Data->EL, EL_BIND, "\033[3~", "ed-delete-next-char",
220 NULL); // Fix the delete key.
221 ::el_set(Data->EL, EL_CLIENTDATA, Data.get());
224 ::history(Data->Hist, &HE, H_SETSIZE, 800);
225 ::history(Data->Hist, &HE, H_SETUNIQUE, 1);
229 LineEditor::~LineEditor() {
232 ::history_end(Data->Hist);
234 ::fwrite("\n", 1, 1, Data->Out);
237 void LineEditor::saveHistory() {
238 if (!HistoryPath.empty()) {
240 ::history(Data->Hist, &HE, H_SAVE, HistoryPath.c_str());
244 void LineEditor::loadHistory() {
245 if (!HistoryPath.empty()) {
247 ::history(Data->Hist, &HE, H_LOAD, HistoryPath.c_str());
251 Optional<std::string> LineEditor::readLine() const {
252 // Call el_gets to prompt the user and read the user's input.
254 const char *Line = ::el_gets(Data->EL, &LineLen);
256 // Either of these may mean end-of-file.
257 if (!Line || LineLen == 0)
258 return Optional<std::string>();
260 // Strip any newlines off the end of the string.
261 while (LineLen > 0 &&
262 (Line[LineLen - 1] == '\n' || Line[LineLen - 1] == '\r'))
267 ::history(Data->Hist, &HE, H_ENTER, Line);
269 return std::string(Line, LineLen);
274 // Simple fgets-based implementation.
276 struct LineEditor::InternalData {
281 LineEditor::LineEditor(StringRef ProgName, StringRef HistoryPath, FILE *In,
282 FILE *Out, FILE *Err)
283 : Prompt((ProgName + "> ").str()), Data(new InternalData) {
288 LineEditor::~LineEditor() {
289 ::fwrite("\n", 1, 1, Data->Out);
292 void LineEditor::saveHistory() {}
293 void LineEditor::loadHistory() {}
295 Optional<std::string> LineEditor::readLine() const {
296 ::fprintf(Data->Out, "%s", Prompt.c_str());
301 char *Res = ::fgets(Buf, sizeof(Buf), Data->In);
304 return Optional<std::string>();
309 } while (Line.empty() ||
310 (Line[Line.size() - 1] != '\n' && Line[Line.size() - 1] != '\r'));
312 while (!Line.empty() &&
313 (Line[Line.size() - 1] == '\n' || Line[Line.size() - 1] == '\r'))
314 Line.resize(Line.size() - 1);