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 //===----------------------------------------------------------------------===// 9 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 <stdio.h> 16 #ifdef HAVE_LIBEDIT 17 #include <histedit.h> 18 #endif 19 20 using namespace llvm; 21 22 std::string LineEditor::getDefaultHistoryPath(StringRef ProgName) { 23 SmallString<32> Path; 24 if (sys::path::home_directory(Path)) { 25 sys::path::append(Path, "." + ProgName + "-history"); 26 return Path.str(); 27 } 28 return std::string(); 29 } 30 31 LineEditor::CompleterConcept::~CompleterConcept() {} 32 LineEditor::ListCompleterConcept::~ListCompleterConcept() {} 33 34 std::string LineEditor::ListCompleterConcept::getCommonPrefix( 35 const std::vector<Completion> &Comps) { 36 assert(!Comps.empty()); 37 38 std::string CommonPrefix = Comps[0].TypedText; 39 for (std::vector<Completion>::const_iterator I = Comps.begin() + 1, 40 E = Comps.end(); 41 I != E; ++I) { 42 size_t Len = std::min(CommonPrefix.size(), I->TypedText.size()); 43 size_t CommonLen = 0; 44 for (; CommonLen != Len; ++CommonLen) { 45 if (CommonPrefix[CommonLen] != I->TypedText[CommonLen]) 46 break; 47 } 48 CommonPrefix.resize(CommonLen); 49 } 50 return CommonPrefix; 51 } 52 53 LineEditor::CompletionAction 54 LineEditor::ListCompleterConcept::complete(StringRef Buffer, size_t Pos) const { 55 CompletionAction Action; 56 std::vector<Completion> Comps = getCompletions(Buffer, Pos); 57 if (Comps.empty()) { 58 Action.Kind = CompletionAction::AK_ShowCompletions; 59 return Action; 60 } 61 62 std::string CommonPrefix = getCommonPrefix(Comps); 63 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 (std::vector<Completion>::iterator I = Comps.begin(), E = Comps.end(); 72 I != E; ++I) 73 Action.Completions.push_back(I->DisplayText); 74 } else { 75 Action.Kind = CompletionAction::AK_Insert; 76 Action.Text = CommonPrefix; 77 } 78 79 return Action; 80 } 81 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; 88 } 89 90 return Completer->complete(Buffer, Pos); 91 } 92 93 #ifdef HAVE_LIBEDIT 94 95 // libedit-based implementation. 96 97 struct LineEditor::InternalData { 98 LineEditor *LE; 99 100 History *Hist; 101 EditLine *EL; 102 103 unsigned PrevCount; 104 std::string ContinuationOutput; 105 }; 106 107 static const char *ElGetPromptFn(EditLine *EL) { 108 LineEditor::InternalData *Data; 109 if (el_get(EL, EL_CLIENTDATA, &Data) == 0) 110 return Data->LE->getPrompt().c_str(); 111 return "> "; 112 } 113 114 // Handles tab completion. 115 // 116 // This function is really horrible. But since the alternative is to get into 117 // the line editor business, here we are. 118 static unsigned char ElCompletionFn(EditLine *EL, int ch) { 119 LineEditor::InternalData *Data; 120 if (el_get(EL, EL_CLIENTDATA, &Data) == 0) { 121 if (!Data->ContinuationOutput.empty()) { 122 // This is the continuation of the AK_ShowCompletions branch below. 123 FILE *Out; 124 if (::el_get(EL, EL_GETFP, 1, &Out) != 0) 125 return CC_ERROR; 126 127 // Print the required output (see below). 128 ::fwrite(Data->ContinuationOutput.c_str(), 129 Data->ContinuationOutput.size(), 1, Out); 130 131 // Push a sequence of Ctrl-B characters to move the cursor back to its 132 // original position. 133 std::string Prevs(Data->PrevCount, '\02'); 134 ::el_push(EL, const_cast<char *>(Prevs.c_str())); 135 136 Data->ContinuationOutput.clear(); 137 138 return CC_REFRESH; 139 } 140 141 const LineInfo *LI = ::el_line(EL); 142 LineEditor::CompletionAction Action = Data->LE->getCompletionAction( 143 StringRef(LI->buffer, LI->lastchar - LI->buffer), 144 LI->cursor - LI->buffer); 145 switch (Action.Kind) { 146 case LineEditor::CompletionAction::AK_Insert: 147 ::el_insertstr(EL, Action.Text.c_str()); 148 return CC_REFRESH; 149 150 case LineEditor::CompletionAction::AK_ShowCompletions: 151 if (Action.Completions.empty()) { 152 return CC_REFRESH_BEEP; 153 } else { 154 // Push a Ctrl-E and a tab. The Ctrl-E causes libedit to move the cursor 155 // to the end of the line, so that when we emit a newline we will be on 156 // a new blank line. The tab causes libedit to call this function again 157 // after moving the cursor. There doesn't seem to be anything we can do 158 // from here to cause libedit to move the cursor immediately. This will 159 // break horribly if the user has rebound their keys, so for now we do 160 // not permit user rebinding. 161 ::el_push(EL, const_cast<char *>("\05\t")); 162 163 // This assembles the output for the continuation block above. 164 raw_string_ostream OS(Data->ContinuationOutput); 165 166 // Move cursor to a blank line. 167 OS << "\n"; 168 169 // Emit the completions. 170 for (std::vector<std::string>::iterator I = Action.Completions.begin(), 171 E = Action.Completions.end(); 172 I != E; ++I) { 173 OS << *I << "\n"; 174 } 175 176 // Fool libedit into thinking nothing has changed. Reprint its prompt 177 // and the user input. Note that the cursor will remain at the end of 178 // the line after this. 179 OS << Data->LE->getPrompt() 180 << StringRef(LI->buffer, LI->lastchar - LI->buffer); 181 182 // This is the number of characters we need to tell libedit to go back: 183 // the distance between end of line and the original cursor position. 184 Data->PrevCount = LI->lastchar - LI->cursor; 185 186 return CC_REFRESH; 187 } 188 } 189 } 190 return CC_ERROR; 191 } 192 193 LineEditor::LineEditor(StringRef ProgName, StringRef HistoryPath, FILE *In, 194 FILE *Out, FILE *Err) 195 : Prompt((ProgName + "> ").str()), HistoryPath(HistoryPath), 196 Data(new InternalData) { 197 if (HistoryPath.empty()) 198 this->HistoryPath = getDefaultHistoryPath(ProgName); 199 200 Data->LE = this; 201 202 Data->Hist = ::history_init(); 203 assert(Data->Hist); 204 205 Data->EL = ::el_init(ProgName.str().c_str(), In, Out, Err); 206 assert(Data->EL); 207 208 ::el_set(Data->EL, EL_PROMPT, ElGetPromptFn); 209 ::el_set(Data->EL, EL_EDITOR, "emacs"); 210 ::el_set(Data->EL, EL_HIST, history, Data->Hist); 211 ::el_set(Data->EL, EL_ADDFN, "tab_complete", "Tab completion function", 212 ElCompletionFn); 213 ::el_set(Data->EL, EL_BIND, "\t", "tab_complete", NULL); 214 ::el_set(Data->EL, EL_BIND, "^r", "em-inc-search-prev", 215 NULL); // Cycle through backwards search, entering string 216 ::el_set(Data->EL, EL_BIND, "^w", "ed-delete-prev-word", 217 NULL); // Delete previous word, behave like bash does. 218 ::el_set(Data->EL, EL_BIND, "\033[3~", "ed-delete-next-char", 219 NULL); // Fix the delete key. 220 ::el_set(Data->EL, EL_CLIENTDATA, Data.get()); 221 222 HistEvent HE; 223 ::history(Data->Hist, &HE, H_SETSIZE, 800); 224 ::history(Data->Hist, &HE, H_SETUNIQUE, 1); 225 loadHistory(); 226 } 227 228 LineEditor::~LineEditor() { 229 saveHistory(); 230 231 FILE *Out; 232 if (::el_get(Data->EL, EL_GETFP, 1, &Out) != 0) 233 Out = 0; 234 235 ::history_end(Data->Hist); 236 ::el_end(Data->EL); 237 238 if (Out) 239 ::fwrite("\n", 1, 1, Out); 240 } 241 242 void LineEditor::saveHistory() { 243 if (!HistoryPath.empty()) { 244 HistEvent HE; 245 ::history(Data->Hist, &HE, H_SAVE, HistoryPath.c_str()); 246 } 247 } 248 249 void LineEditor::loadHistory() { 250 if (!HistoryPath.empty()) { 251 HistEvent HE; 252 ::history(Data->Hist, &HE, H_LOAD, HistoryPath.c_str()); 253 } 254 } 255 256 Optional<std::string> LineEditor::readLine() const { 257 // Call el_gets to prompt the user and read the user's input. 258 int LineLen = 0; 259 const char *Line = ::el_gets(Data->EL, &LineLen); 260 261 // Either of these may mean end-of-file. 262 if (!Line || LineLen == 0) 263 return Optional<std::string>(); 264 265 // Strip any newlines off the end of the string. 266 while (LineLen > 0 && 267 (Line[LineLen - 1] == '\n' || Line[LineLen - 1] == '\r')) 268 --LineLen; 269 270 HistEvent HE; 271 if (LineLen > 0) 272 ::history(Data->Hist, &HE, H_ENTER, Line); 273 274 return std::string(Line, LineLen); 275 } 276 277 #else 278 279 // Simple fgets-based implementation. 280 281 struct LineEditor::InternalData { 282 FILE *In; 283 FILE *Out; 284 }; 285 286 LineEditor::LineEditor(StringRef ProgName, StringRef HistoryPath, FILE *In, 287 FILE *Out, FILE *Err) 288 : Prompt((ProgName + "> ").str()), Data(new InternalData) { 289 Data->In = In; 290 Data->Out = Out; 291 } 292 293 LineEditor::~LineEditor() { 294 ::fwrite("\n", 1, 1, Data->Out); 295 } 296 297 void LineEditor::saveHistory() {} 298 void LineEditor::loadHistory() {} 299 300 Optional<std::string> LineEditor::readLine() const { 301 ::fprintf(Data->Out, "%s", Prompt.c_str()); 302 303 std::string Line; 304 do { 305 char Buf[64]; 306 char *Res = ::fgets(Buf, sizeof(Buf), Data->In); 307 if (!Res) { 308 if (Line.empty()) 309 return Optional<std::string>(); 310 else 311 return Line; 312 } 313 Line.append(Buf); 314 } while (Line.empty() || 315 (Line[Line.size() - 1] != '\n' && Line[Line.size() - 1] != '\r')); 316 317 while (!Line.empty() && 318 (Line[Line.size() - 1] == '\n' || Line[Line.size() - 1] == '\r')) 319 Line.resize(Line.size() - 1); 320 321 return Line; 322 } 323 324 #endif 325