LineEditor.cpp 9.4 KB

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