1 //===-- LineEditor.cpp - line editor --------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/LineEditor/LineEditor.h"
10 #include "llvm/ADT/SmallString.h"
11 #include "llvm/Config/config.h"
12 #include "llvm/Support/Path.h"
13 #include "llvm/Support/raw_ostream.h"
23 std::string
LineEditor::getDefaultHistoryPath(StringRef ProgName
) {
25 if (sys::path::home_directory(Path
)) {
26 sys::path::append(Path
, "." + ProgName
+ "-history");
32 LineEditor::CompleterConcept::~CompleterConcept() {}
33 LineEditor::ListCompleterConcept::~ListCompleterConcept() {}
35 std::string
LineEditor::ListCompleterConcept::getCommonPrefix(
36 const std::vector
<Completion
> &Comps
) {
37 assert(!Comps
.empty());
39 std::string CommonPrefix
= Comps
[0].TypedText
;
40 for (std::vector
<Completion
>::const_iterator I
= Comps
.begin() + 1,
43 size_t Len
= std::min(CommonPrefix
.size(), I
->TypedText
.size());
45 for (; CommonLen
!= Len
; ++CommonLen
) {
46 if (CommonPrefix
[CommonLen
] != I
->TypedText
[CommonLen
])
49 CommonPrefix
.resize(CommonLen
);
54 LineEditor::CompletionAction
55 LineEditor::ListCompleterConcept::complete(StringRef Buffer
, size_t Pos
) const {
56 CompletionAction Action
;
57 std::vector
<Completion
> Comps
= getCompletions(Buffer
, Pos
);
59 Action
.Kind
= CompletionAction::AK_ShowCompletions
;
63 std::string CommonPrefix
= getCommonPrefix(Comps
);
65 // If the common prefix is non-empty we can simply insert it. If there is a
66 // single completion, this will insert the full completion. If there is more
67 // than one, this might be enough information to jog the user's memory but if
68 // not the user can also hit tab again to see the completions because the
69 // common prefix will then be empty.
70 if (CommonPrefix
.empty()) {
71 Action
.Kind
= CompletionAction::AK_ShowCompletions
;
72 for (std::vector
<Completion
>::iterator I
= Comps
.begin(), E
= Comps
.end();
74 Action
.Completions
.push_back(I
->DisplayText
);
76 Action
.Kind
= CompletionAction::AK_Insert
;
77 Action
.Text
= CommonPrefix
;
83 LineEditor::CompletionAction
LineEditor::getCompletionAction(StringRef Buffer
,
86 CompletionAction Action
;
87 Action
.Kind
= CompletionAction::AK_ShowCompletions
;
91 return Completer
->complete(Buffer
, Pos
);
96 // libedit-based implementation.
98 struct LineEditor::InternalData
{
105 std::string ContinuationOutput
;
112 const char *ElGetPromptFn(EditLine
*EL
) {
113 LineEditor::InternalData
*Data
;
114 if (el_get(EL
, EL_CLIENTDATA
, &Data
) == 0)
115 return Data
->LE
->getPrompt().c_str();
119 // Handles tab completion.
121 // This function is really horrible. But since the alternative is to get into
122 // the line editor business, here we are.
123 unsigned char ElCompletionFn(EditLine
*EL
, int ch
) {
124 LineEditor::InternalData
*Data
;
125 if (el_get(EL
, EL_CLIENTDATA
, &Data
) == 0) {
126 if (!Data
->ContinuationOutput
.empty()) {
127 // This is the continuation of the AK_ShowCompletions branch below.
128 FILE *Out
= Data
->Out
;
130 // Print the required output (see below).
131 ::fwrite(Data
->ContinuationOutput
.c_str(),
132 Data
->ContinuationOutput
.size(), 1, Out
);
134 // Push a sequence of Ctrl-B characters to move the cursor back to its
135 // original position.
136 std::string
Prevs(Data
->PrevCount
, '\02');
137 ::el_push(EL
, const_cast<char *>(Prevs
.c_str()));
139 Data
->ContinuationOutput
.clear();
144 const LineInfo
*LI
= ::el_line(EL
);
145 LineEditor::CompletionAction Action
= Data
->LE
->getCompletionAction(
146 StringRef(LI
->buffer
, LI
->lastchar
- LI
->buffer
),
147 LI
->cursor
- LI
->buffer
);
148 switch (Action
.Kind
) {
149 case LineEditor::CompletionAction::AK_Insert
:
150 ::el_insertstr(EL
, Action
.Text
.c_str());
153 case LineEditor::CompletionAction::AK_ShowCompletions
:
154 if (Action
.Completions
.empty()) {
155 return CC_REFRESH_BEEP
;
157 // Push a Ctrl-E and a tab. The Ctrl-E causes libedit to move the cursor
158 // to the end of the line, so that when we emit a newline we will be on
159 // a new blank line. The tab causes libedit to call this function again
160 // after moving the cursor. There doesn't seem to be anything we can do
161 // from here to cause libedit to move the cursor immediately. This will
162 // break horribly if the user has rebound their keys, so for now we do
163 // not permit user rebinding.
164 ::el_push(EL
, const_cast<char *>("\05\t"));
166 // This assembles the output for the continuation block above.
167 raw_string_ostream
OS(Data
->ContinuationOutput
);
169 // Move cursor to a blank line.
172 // Emit the completions.
173 for (std::vector
<std::string
>::iterator I
= Action
.Completions
.begin(),
174 E
= Action
.Completions
.end();
179 // Fool libedit into thinking nothing has changed. Reprint its prompt
180 // and the user input. Note that the cursor will remain at the end of
181 // the line after this.
182 OS
<< Data
->LE
->getPrompt()
183 << StringRef(LI
->buffer
, LI
->lastchar
- LI
->buffer
);
185 // This is the number of characters we need to tell libedit to go back:
186 // the distance between end of line and the original cursor position.
187 Data
->PrevCount
= LI
->lastchar
- LI
->cursor
;
196 } // end anonymous namespace
198 LineEditor::LineEditor(StringRef ProgName
, StringRef HistoryPath
, FILE *In
,
199 FILE *Out
, FILE *Err
)
200 : Prompt((ProgName
+ "> ").str()), HistoryPath(HistoryPath
),
201 Data(new InternalData
) {
202 if (HistoryPath
.empty())
203 this->HistoryPath
= getDefaultHistoryPath(ProgName
);
208 Data
->Hist
= ::history_init();
211 Data
->EL
= ::el_init(ProgName
.str().c_str(), In
, Out
, Err
);
214 ::el_set(Data
->EL
, EL_PROMPT
, ElGetPromptFn
);
215 ::el_set(Data
->EL
, EL_EDITOR
, "emacs");
216 ::el_set(Data
->EL
, EL_HIST
, history
, Data
->Hist
);
217 ::el_set(Data
->EL
, EL_ADDFN
, "tab_complete", "Tab completion function",
219 ::el_set(Data
->EL
, EL_BIND
, "\t", "tab_complete", NULL
);
220 ::el_set(Data
->EL
, EL_BIND
, "^r", "em-inc-search-prev",
221 NULL
); // Cycle through backwards search, entering string
222 ::el_set(Data
->EL
, EL_BIND
, "^w", "ed-delete-prev-word",
223 NULL
); // Delete previous word, behave like bash does.
224 ::el_set(Data
->EL
, EL_BIND
, "\033[3~", "ed-delete-next-char",
225 NULL
); // Fix the delete key.
226 ::el_set(Data
->EL
, EL_CLIENTDATA
, Data
.get());
229 ::history(Data
->Hist
, &HE
, H_SETSIZE
, 800);
230 ::history(Data
->Hist
, &HE
, H_SETUNIQUE
, 1);
234 LineEditor::~LineEditor() {
237 ::history_end(Data
->Hist
);
239 ::fwrite("\n", 1, 1, Data
->Out
);
242 void LineEditor::saveHistory() {
243 if (!HistoryPath
.empty()) {
245 ::history(Data
->Hist
, &HE
, H_SAVE
, HistoryPath
.c_str());
249 void LineEditor::loadHistory() {
250 if (!HistoryPath
.empty()) {
252 ::history(Data
->Hist
, &HE
, H_LOAD
, HistoryPath
.c_str());
256 Optional
<std::string
> LineEditor::readLine() const {
257 // Call el_gets to prompt the user and read the user's input.
259 const char *Line
= ::el_gets(Data
->EL
, &LineLen
);
261 // Either of these may mean end-of-file.
262 if (!Line
|| LineLen
== 0)
263 return Optional
<std::string
>();
265 // Strip any newlines off the end of the string.
266 while (LineLen
> 0 &&
267 (Line
[LineLen
- 1] == '\n' || Line
[LineLen
- 1] == '\r'))
272 ::history(Data
->Hist
, &HE
, H_ENTER
, Line
);
274 return std::string(Line
, LineLen
);
277 #else // HAVE_LIBEDIT
279 // Simple fgets-based implementation.
281 struct LineEditor::InternalData
{
286 LineEditor::LineEditor(StringRef ProgName
, StringRef HistoryPath
, FILE *In
,
287 FILE *Out
, FILE *Err
)
288 : Prompt((ProgName
+ "> ").str()), Data(new InternalData
) {
293 LineEditor::~LineEditor() {
294 ::fwrite("\n", 1, 1, Data
->Out
);
297 void LineEditor::saveHistory() {}
298 void LineEditor::loadHistory() {}
300 Optional
<std::string
> LineEditor::readLine() const {
301 ::fprintf(Data
->Out
, "%s", Prompt
.c_str());
306 char *Res
= ::fgets(Buf
, sizeof(Buf
), Data
->In
);
309 return Optional
<std::string
>();
314 } while (Line
.empty() ||
315 (Line
[Line
.size() - 1] != '\n' && Line
[Line
.size() - 1] != '\r'));
317 while (!Line
.empty() &&
318 (Line
[Line
.size() - 1] == '\n' || Line
[Line
.size() - 1] == '\r'))
319 Line
.resize(Line
.size() - 1);
324 #endif // HAVE_LIBEDIT