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"
24 std::string
LineEditor::getDefaultHistoryPath(StringRef ProgName
) {
26 if (sys::path::home_directory(Path
)) {
27 sys::path::append(Path
, "." + ProgName
+ "-history");
33 LineEditor::CompleterConcept::~CompleterConcept() {}
34 LineEditor::ListCompleterConcept::~ListCompleterConcept() {}
36 std::string
LineEditor::ListCompleterConcept::getCommonPrefix(
37 const std::vector
<Completion
> &Comps
) {
38 assert(!Comps
.empty());
40 std::string CommonPrefix
= Comps
[0].TypedText
;
41 for (std::vector
<Completion
>::const_iterator I
= Comps
.begin() + 1,
44 size_t Len
= std::min(CommonPrefix
.size(), I
->TypedText
.size());
46 for (; CommonLen
!= Len
; ++CommonLen
) {
47 if (CommonPrefix
[CommonLen
] != I
->TypedText
[CommonLen
])
50 CommonPrefix
.resize(CommonLen
);
55 LineEditor::CompletionAction
56 LineEditor::ListCompleterConcept::complete(StringRef Buffer
, size_t Pos
) const {
57 CompletionAction Action
;
58 std::vector
<Completion
> Comps
= getCompletions(Buffer
, Pos
);
60 Action
.Kind
= CompletionAction::AK_ShowCompletions
;
64 std::string CommonPrefix
= getCommonPrefix(Comps
);
66 // If the common prefix is non-empty we can simply insert it. If there is a
67 // single completion, this will insert the full completion. If there is more
68 // than one, this might be enough information to jog the user's memory but if
69 // not the user can also hit tab again to see the completions because the
70 // common prefix will then be empty.
71 if (CommonPrefix
.empty()) {
72 Action
.Kind
= CompletionAction::AK_ShowCompletions
;
73 for (std::vector
<Completion
>::iterator I
= Comps
.begin(), E
= Comps
.end();
75 Action
.Completions
.push_back(I
->DisplayText
);
77 Action
.Kind
= CompletionAction::AK_Insert
;
78 Action
.Text
= CommonPrefix
;
84 LineEditor::CompletionAction
LineEditor::getCompletionAction(StringRef Buffer
,
87 CompletionAction Action
;
88 Action
.Kind
= CompletionAction::AK_ShowCompletions
;
92 return Completer
->complete(Buffer
, Pos
);
97 // libedit-based implementation.
99 struct LineEditor::InternalData
{
106 std::string ContinuationOutput
;
113 const char *ElGetPromptFn(EditLine
*EL
) {
114 LineEditor::InternalData
*Data
;
115 if (el_get(EL
, EL_CLIENTDATA
, &Data
) == 0)
116 return Data
->LE
->getPrompt().c_str();
120 // Handles tab completion.
122 // This function is really horrible. But since the alternative is to get into
123 // the line editor business, here we are.
124 unsigned char ElCompletionFn(EditLine
*EL
, int ch
) {
125 LineEditor::InternalData
*Data
;
126 if (el_get(EL
, EL_CLIENTDATA
, &Data
) == 0) {
127 if (!Data
->ContinuationOutput
.empty()) {
128 // This is the continuation of the AK_ShowCompletions branch below.
129 FILE *Out
= Data
->Out
;
131 // Print the required output (see below).
132 ::fwrite(Data
->ContinuationOutput
.c_str(),
133 Data
->ContinuationOutput
.size(), 1, Out
);
135 // Push a sequence of Ctrl-B characters to move the cursor back to its
136 // original position.
137 std::string
Prevs(Data
->PrevCount
, '\02');
138 ::el_push(EL
, const_cast<char *>(Prevs
.c_str()));
140 Data
->ContinuationOutput
.clear();
145 const LineInfo
*LI
= ::el_line(EL
);
146 LineEditor::CompletionAction Action
= Data
->LE
->getCompletionAction(
147 StringRef(LI
->buffer
, LI
->lastchar
- LI
->buffer
),
148 LI
->cursor
- LI
->buffer
);
149 switch (Action
.Kind
) {
150 case LineEditor::CompletionAction::AK_Insert
:
151 ::el_insertstr(EL
, Action
.Text
.c_str());
154 case LineEditor::CompletionAction::AK_ShowCompletions
:
155 if (Action
.Completions
.empty()) {
156 return CC_REFRESH_BEEP
;
158 // Push a Ctrl-E and a tab. The Ctrl-E causes libedit to move the cursor
159 // to the end of the line, so that when we emit a newline we will be on
160 // a new blank line. The tab causes libedit to call this function again
161 // after moving the cursor. There doesn't seem to be anything we can do
162 // from here to cause libedit to move the cursor immediately. This will
163 // break horribly if the user has rebound their keys, so for now we do
164 // not permit user rebinding.
165 ::el_push(EL
, const_cast<char *>("\05\t"));
167 // This assembles the output for the continuation block above.
168 raw_string_ostream
OS(Data
->ContinuationOutput
);
170 // Move cursor to a blank line.
173 // Emit the completions.
174 for (std::vector
<std::string
>::iterator I
= Action
.Completions
.begin(),
175 E
= Action
.Completions
.end();
180 // Fool libedit into thinking nothing has changed. Reprint its prompt
181 // and the user input. Note that the cursor will remain at the end of
182 // the line after this.
183 OS
<< Data
->LE
->getPrompt()
184 << StringRef(LI
->buffer
, LI
->lastchar
- LI
->buffer
);
186 // This is the number of characters we need to tell libedit to go back:
187 // the distance between end of line and the original cursor position.
188 Data
->PrevCount
= LI
->lastchar
- LI
->cursor
;
197 } // end anonymous namespace
199 LineEditor::LineEditor(StringRef ProgName
, StringRef HistoryPath
, FILE *In
,
200 FILE *Out
, FILE *Err
)
201 : Prompt((ProgName
+ "> ").str()), HistoryPath(HistoryPath
),
202 Data(new InternalData
) {
203 if (HistoryPath
.empty())
204 this->HistoryPath
= getDefaultHistoryPath(ProgName
);
209 Data
->Hist
= ::history_init();
212 Data
->EL
= ::el_init(ProgName
.str().c_str(), In
, Out
, Err
);
215 ::el_set(Data
->EL
, EL_PROMPT
, ElGetPromptFn
);
216 ::el_set(Data
->EL
, EL_EDITOR
, "emacs");
217 ::el_set(Data
->EL
, EL_HIST
, history
, Data
->Hist
);
218 ::el_set(Data
->EL
, EL_ADDFN
, "tab_complete", "Tab completion function",
220 ::el_set(Data
->EL
, EL_BIND
, "\t", "tab_complete", NULL
);
221 ::el_set(Data
->EL
, EL_BIND
, "^r", "em-inc-search-prev",
222 NULL
); // Cycle through backwards search, entering string
223 ::el_set(Data
->EL
, EL_BIND
, "^w", "ed-delete-prev-word",
224 NULL
); // Delete previous word, behave like bash does.
225 ::el_set(Data
->EL
, EL_BIND
, "\033[3~", "ed-delete-next-char",
226 NULL
); // Fix the delete key.
227 ::el_set(Data
->EL
, EL_CLIENTDATA
, Data
.get());
230 ::history(Data
->Hist
, &HE
, H_SETSIZE
, 800);
231 ::history(Data
->Hist
, &HE
, H_SETUNIQUE
, 1);
235 LineEditor::~LineEditor() {
238 ::history_end(Data
->Hist
);
240 ::fwrite("\n", 1, 1, Data
->Out
);
243 void LineEditor::saveHistory() {
244 if (!HistoryPath
.empty()) {
246 ::history(Data
->Hist
, &HE
, H_SAVE
, HistoryPath
.c_str());
250 void LineEditor::loadHistory() {
251 if (!HistoryPath
.empty()) {
253 ::history(Data
->Hist
, &HE
, H_LOAD
, HistoryPath
.c_str());
257 Optional
<std::string
> LineEditor::readLine() const {
258 // Call el_gets to prompt the user and read the user's input.
260 const char *Line
= ::el_gets(Data
->EL
, &LineLen
);
262 // Either of these may mean end-of-file.
263 if (!Line
|| LineLen
== 0)
264 return Optional
<std::string
>();
266 // Strip any newlines off the end of the string.
267 while (LineLen
> 0 &&
268 (Line
[LineLen
- 1] == '\n' || Line
[LineLen
- 1] == '\r'))
273 ::history(Data
->Hist
, &HE
, H_ENTER
, Line
);
275 return std::string(Line
, LineLen
);
278 #else // HAVE_LIBEDIT
280 // Simple fgets-based implementation.
282 struct LineEditor::InternalData
{
287 LineEditor::LineEditor(StringRef ProgName
, StringRef HistoryPath
, FILE *In
,
288 FILE *Out
, FILE *Err
)
289 : Prompt((ProgName
+ "> ").str()), Data(new InternalData
) {
294 LineEditor::~LineEditor() {
295 ::fwrite("\n", 1, 1, Data
->Out
);
298 void LineEditor::saveHistory() {}
299 void LineEditor::loadHistory() {}
301 Optional
<std::string
> LineEditor::readLine() const {
302 ::fprintf(Data
->Out
, "%s", Prompt
.c_str());
307 char *Res
= ::fgets(Buf
, sizeof(Buf
), Data
->In
);
310 return Optional
<std::string
>();
315 } while (Line
.empty() ||
316 (Line
[Line
.size() - 1] != '\n' && Line
[Line
.size() - 1] != '\r'));
318 while (!Line
.empty() &&
319 (Line
[Line
.size() - 1] == '\n' || Line
[Line
.size() - 1] == '\r'))
320 Line
.resize(Line
.size() - 1);
325 #endif // HAVE_LIBEDIT