[clang][extract-api] Emit "navigator" property of "name" in SymbolGraph
[llvm-project.git] / llvm / lib / LineEditor / LineEditor.cpp
blob09ec65a1d9c902542a54e5a2480701e0377c246d
1 //===-- LineEditor.cpp - line editor --------------------------------------===//
2 //
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
6 //
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"
14 #include <algorithm>
15 #include <cassert>
16 #include <cstdio>
17 #ifdef HAVE_LIBEDIT
18 #include <histedit.h>
19 #endif
21 using namespace llvm;
23 std::string LineEditor::getDefaultHistoryPath(StringRef ProgName) {
24 SmallString<32> Path;
25 if (sys::path::home_directory(Path)) {
26 sys::path::append(Path, "." + ProgName + "-history");
27 return std::string(Path.str());
29 return std::string();
32 LineEditor::CompleterConcept::~CompleterConcept() = default;
33 LineEditor::ListCompleterConcept::~ListCompleterConcept() = default;
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,
41 E = Comps.end();
42 I != E; ++I) {
43 size_t Len = std::min(CommonPrefix.size(), I->TypedText.size());
44 size_t CommonLen = 0;
45 for (; CommonLen != Len; ++CommonLen) {
46 if (CommonPrefix[CommonLen] != I->TypedText[CommonLen])
47 break;
49 CommonPrefix.resize(CommonLen);
51 return CommonPrefix;
54 LineEditor::CompletionAction
55 LineEditor::ListCompleterConcept::complete(StringRef Buffer, size_t Pos) const {
56 CompletionAction Action;
57 std::vector<Completion> Comps = getCompletions(Buffer, Pos);
58 if (Comps.empty()) {
59 Action.Kind = CompletionAction::AK_ShowCompletions;
60 return Action;
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 (const Completion &Comp : Comps)
73 Action.Completions.push_back(Comp.DisplayText);
74 } else {
75 Action.Kind = CompletionAction::AK_Insert;
76 Action.Text = CommonPrefix;
79 return Action;
82 LineEditor::CompletionAction LineEditor::getCompletionAction(StringRef Buffer,
83 size_t Pos) const {
84 if (!Completer) {
85 CompletionAction Action;
86 Action.Kind = CompletionAction::AK_ShowCompletions;
87 return Action;
90 return Completer->complete(Buffer, Pos);
93 #ifdef HAVE_LIBEDIT
95 // libedit-based implementation.
97 struct LineEditor::InternalData {
98 LineEditor *LE;
100 History *Hist;
101 EditLine *EL;
103 unsigned PrevCount;
104 std::string ContinuationOutput;
106 FILE *Out;
109 namespace {
111 const char *ElGetPromptFn(EditLine *EL) {
112 LineEditor::InternalData *Data;
113 if (el_get(EL, EL_CLIENTDATA, &Data) == 0)
114 return Data->LE->getPrompt().c_str();
115 return "> ";
118 // Handles tab completion.
120 // This function is really horrible. But since the alternative is to get into
121 // the line editor business, here we are.
122 unsigned char ElCompletionFn(EditLine *EL, int ch) {
123 LineEditor::InternalData *Data;
124 if (el_get(EL, EL_CLIENTDATA, &Data) == 0) {
125 if (!Data->ContinuationOutput.empty()) {
126 // This is the continuation of the AK_ShowCompletions branch below.
127 FILE *Out = Data->Out;
129 // Print the required output (see below).
130 ::fwrite(Data->ContinuationOutput.c_str(),
131 Data->ContinuationOutput.size(), 1, Out);
133 // Push a sequence of Ctrl-B characters to move the cursor back to its
134 // original position.
135 std::string Prevs(Data->PrevCount, '\02');
136 ::el_push(EL, const_cast<char *>(Prevs.c_str()));
138 Data->ContinuationOutput.clear();
140 return CC_REFRESH;
143 const LineInfo *LI = ::el_line(EL);
144 LineEditor::CompletionAction Action = Data->LE->getCompletionAction(
145 StringRef(LI->buffer, LI->lastchar - LI->buffer),
146 LI->cursor - LI->buffer);
147 switch (Action.Kind) {
148 case LineEditor::CompletionAction::AK_Insert:
149 ::el_insertstr(EL, Action.Text.c_str());
150 return CC_REFRESH;
152 case LineEditor::CompletionAction::AK_ShowCompletions:
153 if (Action.Completions.empty()) {
154 return CC_REFRESH_BEEP;
155 } else {
156 // Push a Ctrl-E and a tab. The Ctrl-E causes libedit to move the cursor
157 // to the end of the line, so that when we emit a newline we will be on
158 // a new blank line. The tab causes libedit to call this function again
159 // after moving the cursor. There doesn't seem to be anything we can do
160 // from here to cause libedit to move the cursor immediately. This will
161 // break horribly if the user has rebound their keys, so for now we do
162 // not permit user rebinding.
163 ::el_push(EL, const_cast<char *>("\05\t"));
165 // This assembles the output for the continuation block above.
166 raw_string_ostream OS(Data->ContinuationOutput);
168 // Move cursor to a blank line.
169 OS << "\n";
171 // Emit the completions.
172 for (std::vector<std::string>::iterator I = Action.Completions.begin(),
173 E = Action.Completions.end();
174 I != E; ++I) {
175 OS << *I << "\n";
178 // Fool libedit into thinking nothing has changed. Reprint its prompt
179 // and the user input. Note that the cursor will remain at the end of
180 // the line after this.
181 OS << Data->LE->getPrompt()
182 << StringRef(LI->buffer, LI->lastchar - LI->buffer);
184 // This is the number of characters we need to tell libedit to go back:
185 // the distance between end of line and the original cursor position.
186 Data->PrevCount = LI->lastchar - LI->cursor;
188 return CC_REFRESH;
192 return CC_ERROR;
195 } // end anonymous namespace
197 LineEditor::LineEditor(StringRef ProgName, StringRef HistoryPath, FILE *In,
198 FILE *Out, FILE *Err)
199 : Prompt((ProgName + "> ").str()), HistoryPath(std::string(HistoryPath)),
200 Data(new InternalData) {
201 if (HistoryPath.empty())
202 this->HistoryPath = getDefaultHistoryPath(ProgName);
204 Data->LE = this;
205 Data->Out = Out;
207 Data->Hist = ::history_init();
208 assert(Data->Hist);
210 Data->EL = ::el_init(ProgName.str().c_str(), In, Out, Err);
211 assert(Data->EL);
213 ::el_set(Data->EL, EL_PROMPT, ElGetPromptFn);
214 ::el_set(Data->EL, EL_EDITOR, "emacs");
215 ::el_set(Data->EL, EL_HIST, history, Data->Hist);
216 ::el_set(Data->EL, EL_ADDFN, "tab_complete", "Tab completion function",
217 ElCompletionFn);
218 ::el_set(Data->EL, EL_BIND, "\t", "tab_complete", NULL);
219 ::el_set(Data->EL, EL_BIND, "^r", "em-inc-search-prev",
220 NULL); // Cycle through backwards search, entering string
221 ::el_set(Data->EL, EL_BIND, "^w", "ed-delete-prev-word",
222 NULL); // Delete previous word, behave like bash does.
223 ::el_set(Data->EL, EL_BIND, "\033[3~", "ed-delete-next-char",
224 NULL); // Fix the delete key.
225 ::el_set(Data->EL, EL_CLIENTDATA, Data.get());
227 HistEvent HE;
228 ::history(Data->Hist, &HE, H_SETSIZE, 800);
229 ::history(Data->Hist, &HE, H_SETUNIQUE, 1);
230 loadHistory();
233 LineEditor::~LineEditor() {
234 saveHistory();
236 ::history_end(Data->Hist);
237 ::el_end(Data->EL);
238 ::fwrite("\n", 1, 1, Data->Out);
241 void LineEditor::saveHistory() {
242 if (!HistoryPath.empty()) {
243 HistEvent HE;
244 ::history(Data->Hist, &HE, H_SAVE, HistoryPath.c_str());
248 void LineEditor::loadHistory() {
249 if (!HistoryPath.empty()) {
250 HistEvent HE;
251 ::history(Data->Hist, &HE, H_LOAD, HistoryPath.c_str());
255 Optional<std::string> LineEditor::readLine() const {
256 // Call el_gets to prompt the user and read the user's input.
257 int LineLen = 0;
258 const char *Line = ::el_gets(Data->EL, &LineLen);
260 // Either of these may mean end-of-file.
261 if (!Line || LineLen == 0)
262 return Optional<std::string>();
264 // Strip any newlines off the end of the string.
265 while (LineLen > 0 &&
266 (Line[LineLen - 1] == '\n' || Line[LineLen - 1] == '\r'))
267 --LineLen;
269 HistEvent HE;
270 if (LineLen > 0)
271 ::history(Data->Hist, &HE, H_ENTER, Line);
273 return std::string(Line, LineLen);
276 #else // HAVE_LIBEDIT
278 // Simple fgets-based implementation.
280 struct LineEditor::InternalData {
281 FILE *In;
282 FILE *Out;
285 LineEditor::LineEditor(StringRef ProgName, StringRef HistoryPath, FILE *In,
286 FILE *Out, FILE *Err)
287 : Prompt((ProgName + "> ").str()), Data(new InternalData) {
288 Data->In = In;
289 Data->Out = Out;
292 LineEditor::~LineEditor() {
293 ::fwrite("\n", 1, 1, Data->Out);
296 void LineEditor::saveHistory() {}
297 void LineEditor::loadHistory() {}
299 Optional<std::string> LineEditor::readLine() const {
300 ::fprintf(Data->Out, "%s", Prompt.c_str());
302 std::string Line;
303 do {
304 char Buf[64];
305 char *Res = ::fgets(Buf, sizeof(Buf), Data->In);
306 if (!Res) {
307 if (Line.empty())
308 return Optional<std::string>();
309 else
310 return Line;
312 Line.append(Buf);
313 } while (Line.empty() ||
314 (Line[Line.size() - 1] != '\n' && Line[Line.size() - 1] != '\r'));
316 while (!Line.empty() &&
317 (Line[Line.size() - 1] == '\n' || Line[Line.size() - 1] == '\r'))
318 Line.resize(Line.size() - 1);
320 return Line;
323 #endif // HAVE_LIBEDIT