LineEditor.cpp 9.6 KB

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