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/STLExtras.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");
28 return std::string(Path
);
33 LineEditor::CompleterConcept::~CompleterConcept() = default;
34 LineEditor::ListCompleterConcept::~ListCompleterConcept() = default;
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 (const Completion
&C
: llvm::drop_begin(Comps
)) {
42 size_t Len
= std::min(CommonPrefix
.size(), C
.TypedText
.size());
44 for (; CommonLen
!= Len
; ++CommonLen
) {
45 if (CommonPrefix
[CommonLen
] != C
.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 (const Completion
&Comp
: Comps
)
72 Action
.Completions
.push_back(Comp
.DisplayText
);
74 Action
.Kind
= CompletionAction::AK_Insert
;
75 Action
.Text
= CommonPrefix
;
81 LineEditor::CompletionAction
LineEditor::getCompletionAction(StringRef Buffer
,
84 CompletionAction Action
;
85 Action
.Kind
= CompletionAction::AK_ShowCompletions
;
89 return Completer
->complete(Buffer
, Pos
);
94 // libedit-based implementation.
96 struct LineEditor::InternalData
{
103 std::string ContinuationOutput
;
110 const char *ElGetPromptFn(EditLine
*EL
) {
111 LineEditor::InternalData
*Data
;
112 if (el_get(EL
, EL_CLIENTDATA
, &Data
) == 0)
113 return Data
->LE
->getPrompt().c_str();
117 // Handles tab completion.
119 // This function is really horrible. But since the alternative is to get into
120 // the line editor business, here we are.
121 unsigned char ElCompletionFn(EditLine
*EL
, int ch
) {
122 LineEditor::InternalData
*Data
;
123 if (el_get(EL
, EL_CLIENTDATA
, &Data
) == 0) {
124 if (!Data
->ContinuationOutput
.empty()) {
125 // This is the continuation of the AK_ShowCompletions branch below.
126 FILE *Out
= Data
->Out
;
128 // Print the required output (see below).
129 ::fwrite(Data
->ContinuationOutput
.c_str(),
130 Data
->ContinuationOutput
.size(), 1, Out
);
132 // Push a sequence of Ctrl-B characters to move the cursor back to its
133 // original position.
134 std::string
Prevs(Data
->PrevCount
, '\02');
135 ::el_push(EL
, const_cast<char *>(Prevs
.c_str()));
137 Data
->ContinuationOutput
.clear();
142 const LineInfo
*LI
= ::el_line(EL
);
143 LineEditor::CompletionAction Action
= Data
->LE
->getCompletionAction(
144 StringRef(LI
->buffer
, LI
->lastchar
- LI
->buffer
),
145 LI
->cursor
- LI
->buffer
);
146 switch (Action
.Kind
) {
147 case LineEditor::CompletionAction::AK_Insert
:
148 ::el_insertstr(EL
, Action
.Text
.c_str());
151 case LineEditor::CompletionAction::AK_ShowCompletions
:
152 if (Action
.Completions
.empty()) {
153 return CC_REFRESH_BEEP
;
155 // Push a Ctrl-E and a tab. The Ctrl-E causes libedit to move the cursor
156 // to the end of the line, so that when we emit a newline we will be on
157 // a new blank line. The tab causes libedit to call this function again
158 // after moving the cursor. There doesn't seem to be anything we can do
159 // from here to cause libedit to move the cursor immediately. This will
160 // break horribly if the user has rebound their keys, so for now we do
161 // not permit user rebinding.
162 ::el_push(EL
, const_cast<char *>("\05\t"));
164 // This assembles the output for the continuation block above.
165 raw_string_ostream
OS(Data
->ContinuationOutput
);
167 // Move cursor to a blank line.
170 // Emit the completions.
171 for (const std::string
&Completion
: Action
.Completions
)
172 OS
<< Completion
<< "\n";
174 // Fool libedit into thinking nothing has changed. Reprint its prompt
175 // and the user input. Note that the cursor will remain at the end of
176 // the line after this.
177 OS
<< Data
->LE
->getPrompt()
178 << StringRef(LI
->buffer
, LI
->lastchar
- LI
->buffer
);
180 // This is the number of characters we need to tell libedit to go back:
181 // the distance between end of line and the original cursor position.
182 Data
->PrevCount
= LI
->lastchar
- LI
->cursor
;
191 } // end anonymous namespace
193 LineEditor::LineEditor(StringRef ProgName
, StringRef HistoryPath
, FILE *In
,
194 FILE *Out
, FILE *Err
)
195 : Prompt((ProgName
+ "> ").str()), HistoryPath(std::string(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 std::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)
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
);
272 #else // HAVE_LIBEDIT
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 std::optional
<std::string
> LineEditor::readLine() const {
296 ::fprintf(Data
->Out
, "%s", Prompt
.c_str());
301 char *Res
= ::fgets(Buf
, sizeof(Buf
), Data
->In
);
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);
319 #endif // HAVE_LIBEDIT