LineEditor.cpp 9.7 KB

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