xref: /llvm-project/lldb/include/lldb/Host/Editline.h (revision 2841cdbfda92b3fb5fbec726f3376b198106d496)
1 //===-- Editline.h ----------------------------------------------*- C++ -*-===//
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 
9 // TODO: wire up window size changes
10 
11 // If we ever get a private copy of libedit, there are a number of defects that
12 // would be nice to fix;
13 // a) Sometimes text just disappears while editing.  In an 80-column editor
14 // paste the following text, without
15 //    the quotes:
16 //    "This is a test of the input system missing Hello, World!  Do you
17 //    disappear when it gets to a particular length?"
18 //    Now press ^A to move to the start and type 3 characters, and you'll see a
19 //    good amount of the text will
20 //    disappear.  It's still in the buffer, just invisible.
21 // b) The prompt printing logic for dealing with ANSI formatting characters is
22 // broken, which is why we're working around it here.
23 // c) The incremental search uses escape to cancel input, so it's confused by
24 // ANSI sequences starting with escape.
25 // d) Emoji support is fairly terrible, presumably it doesn't understand
26 // composed characters?
27 
28 #ifndef LLDB_HOST_EDITLINE_H
29 #define LLDB_HOST_EDITLINE_H
30 
31 #include "lldb/Host/Config.h"
32 
33 #include <locale>
34 #include <sstream>
35 #include <vector>
36 
37 #include "lldb/lldb-private.h"
38 
39 #if !defined(_WIN32) && !defined(__ANDROID__)
40 #include <histedit.h>
41 #endif
42 
43 #include <csignal>
44 #include <mutex>
45 #include <optional>
46 #include <string>
47 #include <vector>
48 
49 #include "lldb/Host/ConnectionFileDescriptor.h"
50 #include "lldb/Utility/CompletionRequest.h"
51 #include "lldb/Utility/FileSpec.h"
52 #include "lldb/Utility/Predicate.h"
53 #include "lldb/Utility/StringList.h"
54 
55 #include "llvm/ADT/FunctionExtras.h"
56 
57 namespace lldb_private {
58 namespace line_editor {
59 
60 // type alias's to help manage 8 bit and wide character versions of libedit
61 #if LLDB_EDITLINE_USE_WCHAR
62 using EditLineStringType = std::wstring;
63 using EditLineStringStreamType = std::wstringstream;
64 using EditLineCharType = wchar_t;
65 #else
66 using EditLineStringType = std::string;
67 using EditLineStringStreamType = std::stringstream;
68 using EditLineCharType = char;
69 #endif
70 
71 // At one point the callback type of el_set getchar callback changed from char
72 // to wchar_t. It is not possible to detect differentiate between the two
73 // versions exactly, but this is a pretty good approximation and allows us to
74 // build against almost any editline version out there.
75 // It does, however, require extra care when invoking el_getc, as the type
76 // of the input is a single char buffer, but the callback will write a wchar_t.
77 #if LLDB_EDITLINE_USE_WCHAR || defined(EL_CLIENTDATA) || LLDB_HAVE_EL_RFUNC_T
78 using EditLineGetCharType = wchar_t;
79 #else
80 using EditLineGetCharType = char;
81 #endif
82 
83 using EditlineGetCharCallbackType = int (*)(::EditLine *editline,
84                                             EditLineGetCharType *c);
85 using EditlineCommandCallbackType = unsigned char (*)(::EditLine *editline,
86                                                       int ch);
87 using EditlinePromptCallbackType = const char *(*)(::EditLine *editline);
88 
89 class EditlineHistory;
90 
91 using EditlineHistorySP = std::shared_ptr<EditlineHistory>;
92 
93 using IsInputCompleteCallbackType =
94     llvm::unique_function<bool(Editline *, StringList &)>;
95 
96 using FixIndentationCallbackType =
97     llvm::unique_function<int(Editline *, StringList &, int)>;
98 
99 using SuggestionCallbackType =
100     llvm::unique_function<std::optional<std::string>(llvm::StringRef)>;
101 
102 using CompleteCallbackType = llvm::unique_function<void(CompletionRequest &)>;
103 
104 /// Status used to decide when and how to start editing another line in
105 /// multi-line sessions.
106 enum class EditorStatus {
107 
108   /// The default state proceeds to edit the current line.
109   Editing,
110 
111   /// Editing complete, returns the complete set of edited lines.
112   Complete,
113 
114   /// End of input reported.
115   EndOfInput,
116 
117   /// Editing interrupted.
118   Interrupted
119 };
120 
121 /// Established locations that can be easily moved among with MoveCursor.
122 enum class CursorLocation {
123   /// The start of the first line in a multi-line edit session.
124   BlockStart,
125 
126   /// The start of the current line in a multi-line edit session.
127   EditingPrompt,
128 
129   /// The location of the cursor on the current line in a multi-line edit
130   /// session.
131   EditingCursor,
132 
133   /// The location immediately after the last character in a multi-line edit
134   /// session.
135   BlockEnd
136 };
137 
138 /// Operation for the history.
139 enum class HistoryOperation {
140   Oldest,
141   Older,
142   Current,
143   Newer,
144   Newest
145 };
146 }
147 
148 using namespace line_editor;
149 
150 /// Instances of Editline provide an abstraction over libedit's EditLine
151 /// facility.  Both single- and multi-line editing are supported.
152 class Editline {
153 public:
154   Editline(const char *editor_name, FILE *input_file, FILE *output_file,
155            FILE *error_file, bool color, std::recursive_mutex &output_mutex);
156 
157   ~Editline();
158 
159   /// Uses the user data storage of EditLine to retrieve an associated instance
160   /// of Editline.
161   static Editline *InstanceFor(::EditLine *editline);
162 
163   static void
164   DisplayCompletions(Editline &editline,
165                      llvm::ArrayRef<CompletionResult::Completion> results);
166 
167   /// Sets a string to be used as a prompt, or combined with a line number to
168   /// form a prompt.
169   void SetPrompt(const char *prompt);
170 
171   /// Sets an alternate string to be used as a prompt for the second line and
172   /// beyond in multi-line editing scenarios.
173   void SetContinuationPrompt(const char *continuation_prompt);
174 
175   /// Call when the terminal size changes.
176   void TerminalSizeChanged();
177 
178   /// Returns the prompt established by SetPrompt.
179   const char *GetPrompt();
180 
181   /// Returns the index of the line currently being edited.
182   uint32_t GetCurrentLine();
183 
184   /// Interrupt the current edit as if ^C was pressed.
185   bool Interrupt();
186 
187   /// Cancel this edit and obliterate all trace of it.
188   bool Cancel();
189 
190   /// Register a callback for autosuggestion.
191   void SetSuggestionCallback(SuggestionCallbackType callback) {
192     m_suggestion_callback = std::move(callback);
193   }
194 
195   /// Register a callback for the tab key
196   void SetAutoCompleteCallback(CompleteCallbackType callback) {
197     m_completion_callback = std::move(callback);
198   }
199 
200   /// Register a callback for testing whether multi-line input is complete
201   void SetIsInputCompleteCallback(IsInputCompleteCallbackType callback) {
202     m_is_input_complete_callback = std::move(callback);
203   }
204 
205   /// Register a callback for determining the appropriate indentation for a line
206   /// when creating a newline.  An optional set of insertable characters can
207   /// also trigger the callback.
208   void SetFixIndentationCallback(FixIndentationCallbackType callback,
209                                  const char *indent_chars) {
210     m_fix_indentation_callback = std::move(callback);
211     m_fix_indentation_callback_chars = indent_chars;
212   }
213 
214   void SetPromptAnsiPrefix(std::string prefix) {
215     if (m_color)
216       m_prompt_ansi_prefix = std::move(prefix);
217   }
218 
219   void SetPromptAnsiSuffix(std::string suffix) {
220     if (m_color)
221       m_prompt_ansi_suffix = std::move(suffix);
222   }
223 
224   void SetSuggestionAnsiPrefix(std::string prefix) {
225     if (m_color)
226       m_suggestion_ansi_prefix = std::move(prefix);
227   }
228 
229   void SetSuggestionAnsiSuffix(std::string suffix) {
230     if (m_color)
231       m_suggestion_ansi_suffix = std::move(suffix);
232   }
233 
234   /// Prompts for and reads a single line of user input.
235   bool GetLine(std::string &line, bool &interrupted);
236 
237   /// Prompts for and reads a multi-line batch of user input.
238   bool GetLines(int first_line_number, StringList &lines, bool &interrupted);
239 
240   void PrintAsync(Stream *stream, const char *s, size_t len);
241 
242   /// Convert the current input lines into a UTF8 StringList
243   StringList GetInputAsStringList(int line_count = UINT32_MAX);
244 
245   size_t GetTerminalWidth() { return m_terminal_width; }
246 
247   size_t GetTerminalHeight() { return m_terminal_height; }
248 
249 private:
250   /// Sets the lowest line number for multi-line editing sessions.  A value of
251   /// zero suppresses line number printing in the prompt.
252   void SetBaseLineNumber(int line_number);
253 
254   /// Returns the complete prompt by combining the prompt or continuation prompt
255   /// with line numbers as appropriate.  The line index is a zero-based index
256   /// into the current multi-line session.
257   std::string PromptForIndex(int line_index);
258 
259   /// Sets the current line index between line edits to allow free movement
260   /// between lines.  Updates the prompt to match.
261   void SetCurrentLine(int line_index);
262 
263   /// Determines the width of the prompt in characters.  The width is guaranteed
264   /// to be the same for all lines of the current multi-line session.
265   size_t GetPromptWidth();
266 
267   /// Returns true if the underlying EditLine session's keybindings are
268   /// Emacs-based, or false if they are VI-based.
269   bool IsEmacs();
270 
271   /// Returns true if the current EditLine buffer contains nothing but spaces,
272   /// or is empty.
273   bool IsOnlySpaces();
274 
275   /// Helper method used by MoveCursor to determine relative line position.
276   int GetLineIndexForLocation(CursorLocation location, int cursor_row);
277 
278   /// Move the cursor from one well-established location to another using
279   /// relative line positioning and absolute column positioning.
280   void MoveCursor(CursorLocation from, CursorLocation to);
281 
282   /// Clear from cursor position to bottom of screen and print input lines
283   /// including prompts, optionally starting from a specific line.  Lines are
284   /// drawn with an extra space at the end to reserve room for the rightmost
285   /// cursor position.
286   void DisplayInput(int firstIndex = 0);
287 
288   /// Counts the number of rows a given line of content will end up occupying,
289   /// taking into account both the preceding prompt and a single trailing space
290   /// occupied by a cursor when at the end of the line.
291   int CountRowsForLine(const EditLineStringType &content);
292 
293   /// Save the line currently being edited.
294   void SaveEditedLine();
295 
296   /// Replaces the current multi-line session with the next entry from history.
297   unsigned char RecallHistory(HistoryOperation op);
298 
299   /// Character reading implementation for EditLine that supports our multi-line
300   /// editing trickery.
301   int GetCharacter(EditLineGetCharType *c);
302 
303   /// Prompt implementation for EditLine.
304   const char *Prompt();
305 
306   /// Line break command used when meta+return is pressed in multi-line mode.
307   unsigned char BreakLineCommand(int ch);
308 
309   /// Command used when return is pressed in multi-line mode.
310   unsigned char EndOrAddLineCommand(int ch);
311 
312   /// Delete command used when delete is pressed in multi-line mode.
313   unsigned char DeleteNextCharCommand(int ch);
314 
315   /// Delete command used when backspace is pressed in multi-line mode.
316   unsigned char DeletePreviousCharCommand(int ch);
317 
318   /// Line navigation command used when ^P or up arrow are pressed in multi-line
319   /// mode.
320   unsigned char PreviousLineCommand(int ch);
321 
322   /// Line navigation command used when ^N or down arrow are pressed in
323   /// multi-line mode.
324   unsigned char NextLineCommand(int ch);
325 
326   /// History navigation command used when Alt + up arrow is pressed in
327   /// multi-line mode.
328   unsigned char PreviousHistoryCommand(int ch);
329 
330   /// History navigation command used when Alt + down arrow is pressed in
331   /// multi-line mode.
332   unsigned char NextHistoryCommand(int ch);
333 
334   /// Buffer start command used when Esc < is typed in multi-line emacs mode.
335   unsigned char BufferStartCommand(int ch);
336 
337   /// Buffer end command used when Esc > is typed in multi-line emacs mode.
338   unsigned char BufferEndCommand(int ch);
339 
340   /// Context-sensitive tab insertion or code completion command used when the
341   /// tab key is typed.
342   unsigned char TabCommand(int ch);
343 
344   /// Apply autosuggestion part in gray as editline.
345   unsigned char ApplyAutosuggestCommand(int ch);
346 
347   /// Command used when a character is typed.
348   unsigned char TypedCharacter(int ch);
349 
350   /// Respond to normal character insertion by fixing line indentation
351   unsigned char FixIndentationCommand(int ch);
352 
353   /// Revert line command used when moving between lines.
354   unsigned char RevertLineCommand(int ch);
355 
356   /// Ensures that the current EditLine instance is properly configured for
357   /// single or multi-line editing.
358   void ConfigureEditor(bool multiline);
359 
360   bool CompleteCharacter(char ch, EditLineGetCharType &out);
361 
362   void ApplyTerminalSizeChange();
363 
364   // The following set various editline parameters.  It's not any less
365   // verbose to put the editline calls into a function, but it
366   // provides type safety, since the editline functions take varargs
367   // parameters.
368   void AddFunctionToEditLine(const EditLineCharType *command,
369                              const EditLineCharType *helptext,
370                              EditlineCommandCallbackType callbackFn);
371   void SetEditLinePromptCallback(EditlinePromptCallbackType callbackFn);
372   void SetGetCharacterFunction(EditlineGetCharCallbackType callbackFn);
373 
374   ::EditLine *m_editline = nullptr;
375   EditlineHistorySP m_history_sp;
376   bool m_in_history = false;
377   std::vector<EditLineStringType> m_live_history_lines;
378   bool m_multiline_enabled = false;
379   std::vector<EditLineStringType> m_input_lines;
380   EditorStatus m_editor_status;
381   int m_terminal_width = 0;
382   int m_terminal_height = 0;
383   int m_base_line_number = 0;
384   unsigned m_current_line_index = 0;
385   int m_current_line_rows = -1;
386   int m_revert_cursor_index = 0;
387   int m_line_number_digits = 3;
388   std::string m_set_prompt;
389   std::string m_set_continuation_prompt;
390   std::string m_current_prompt;
391   bool m_needs_prompt_repaint = false;
392   volatile std::sig_atomic_t m_terminal_size_has_changed = 0;
393   std::string m_editor_name;
394   FILE *m_input_file;
395   FILE *m_output_file;
396   FILE *m_error_file;
397   ConnectionFileDescriptor m_input_connection;
398 
399   IsInputCompleteCallbackType m_is_input_complete_callback;
400 
401   FixIndentationCallbackType m_fix_indentation_callback;
402   const char *m_fix_indentation_callback_chars = nullptr;
403 
404   CompleteCallbackType m_completion_callback;
405   SuggestionCallbackType m_suggestion_callback;
406 
407   bool m_color;
408   std::string m_prompt_ansi_prefix;
409   std::string m_prompt_ansi_suffix;
410   std::string m_suggestion_ansi_prefix;
411   std::string m_suggestion_ansi_suffix;
412 
413   std::size_t m_previous_autosuggestion_size = 0;
414   std::recursive_mutex &m_output_mutex;
415 };
416 }
417 
418 #endif // LLDB_HOST_EDITLINE_H
419