[PowerPC] Do not emit record-form rotates when record-form andi/andis suffices
[llvm-core.git] / lib / LineEditor / LineEditor.cpp
blob533a928b2dfdcfb732de6976f2ca7fa332952c15
1 //===-- LineEditor.cpp - line editor --------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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"
15 #include <algorithm>
16 #include <cassert>
17 #include <cstdio>
18 #ifdef HAVE_LIBEDIT
19 #include <histedit.h>
20 #endif
22 using namespace llvm;
24 std::string LineEditor::getDefaultHistoryPath(StringRef ProgName) {
25 SmallString<32> Path;
26 if (sys::path::home_directory(Path)) {
27 sys::path::append(Path, "." + ProgName + "-history");
28 return Path.str();
30 return std::string();
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,
42 E = Comps.end();
43 I != E; ++I) {
44 size_t Len = std::min(CommonPrefix.size(), I->TypedText.size());
45 size_t CommonLen = 0;
46 for (; CommonLen != Len; ++CommonLen) {
47 if (CommonPrefix[CommonLen] != I->TypedText[CommonLen])
48 break;
50 CommonPrefix.resize(CommonLen);
52 return CommonPrefix;
55 LineEditor::CompletionAction
56 LineEditor::ListCompleterConcept::complete(StringRef Buffer, size_t Pos) const {
57 CompletionAction Action;
58 std::vector<Completion> Comps = getCompletions(Buffer, Pos);
59 if (Comps.empty()) {
60 Action.Kind = CompletionAction::AK_ShowCompletions;
61 return Action;
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();
74 I != E; ++I)
75 Action.Completions.push_back(I->DisplayText);
76 } else {
77 Action.Kind = CompletionAction::AK_Insert;
78 Action.Text = CommonPrefix;
81 return Action;
84 LineEditor::CompletionAction LineEditor::getCompletionAction(StringRef Buffer,
85 size_t Pos) const {
86 if (!Completer) {
87 CompletionAction Action;
88 Action.Kind = CompletionAction::AK_ShowCompletions;
89 return Action;
92 return Completer->complete(Buffer, Pos);
95 #ifdef HAVE_LIBEDIT
97 // libedit-based implementation.
99 struct LineEditor::InternalData {
100 LineEditor *LE;
102 History *Hist;
103 EditLine *EL;
105 unsigned PrevCount;
106 std::string ContinuationOutput;
108 FILE *Out;
111 namespace {
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();
117 return "> ";
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();
142 return CC_REFRESH;
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());
152 return CC_REFRESH;
154 case LineEditor::CompletionAction::AK_ShowCompletions:
155 if (Action.Completions.empty()) {
156 return CC_REFRESH_BEEP;
157 } else {
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.
171 OS << "\n";
173 // Emit the completions.
174 for (std::vector<std::string>::iterator I = Action.Completions.begin(),
175 E = Action.Completions.end();
176 I != E; ++I) {
177 OS << *I << "\n";
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;
190 return CC_REFRESH;
194 return CC_ERROR;
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);
206 Data->LE = this;
207 Data->Out = Out;
209 Data->Hist = ::history_init();
210 assert(Data->Hist);
212 Data->EL = ::el_init(ProgName.str().c_str(), In, Out, Err);
213 assert(Data->EL);
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",
219 ElCompletionFn);
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());
229 HistEvent HE;
230 ::history(Data->Hist, &HE, H_SETSIZE, 800);
231 ::history(Data->Hist, &HE, H_SETUNIQUE, 1);
232 loadHistory();
235 LineEditor::~LineEditor() {
236 saveHistory();
238 ::history_end(Data->Hist);
239 ::el_end(Data->EL);
240 ::fwrite("\n", 1, 1, Data->Out);
243 void LineEditor::saveHistory() {
244 if (!HistoryPath.empty()) {
245 HistEvent HE;
246 ::history(Data->Hist, &HE, H_SAVE, HistoryPath.c_str());
250 void LineEditor::loadHistory() {
251 if (!HistoryPath.empty()) {
252 HistEvent HE;
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.
259 int LineLen = 0;
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'))
269 --LineLen;
271 HistEvent HE;
272 if (LineLen > 0)
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 {
283 FILE *In;
284 FILE *Out;
287 LineEditor::LineEditor(StringRef ProgName, StringRef HistoryPath, FILE *In,
288 FILE *Out, FILE *Err)
289 : Prompt((ProgName + "> ").str()), Data(new InternalData) {
290 Data->In = In;
291 Data->Out = Out;
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());
304 std::string Line;
305 do {
306 char Buf[64];
307 char *Res = ::fgets(Buf, sizeof(Buf), Data->In);
308 if (!Res) {
309 if (Line.empty())
310 return Optional<std::string>();
311 else
312 return Line;
314 Line.append(Buf);
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);
322 return Line;
325 #endif // HAVE_LIBEDIT