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 #if defined(__cplusplus)
31 
32 #include "lldb/Host/Config.h"
33 
34 #if LLDB_EDITLINE_USE_WCHAR
35 #include <codecvt>
36 #endif
37 #include <locale>
38 #include <sstream>
39 #include <vector>
40 
41 #include "lldb/lldb-private.h"
42 
43 #if !defined(_WIN32) && !defined(__ANDROID__)
44 #include <histedit.h>
45 #endif
46 
47 #include <csignal>
48 #include <mutex>
49 #include <string>
50 #include <vector>
51 
52 #include "lldb/Host/ConnectionFileDescriptor.h"
53 #include "lldb/Utility/CompletionRequest.h"
54 #include "lldb/Utility/FileSpec.h"
55 #include "lldb/Utility/Predicate.h"
56 #include "lldb/Utility/StringList.h"
57 
58 #include "llvm/ADT/FunctionExtras.h"
59 
60 namespace lldb_private {
61 namespace line_editor {
62 
63 // type alias's to help manage 8 bit and wide character versions of libedit
64 #if LLDB_EDITLINE_USE_WCHAR
65 using EditLineStringType = std::wstring;
66 using EditLineStringStreamType = std::wstringstream;
67 using EditLineCharType = wchar_t;
68 #else
69 using EditLineStringType = std::string;
70 using EditLineStringStreamType = std::stringstream;
71 using EditLineCharType = char;
72 #endif
73 
74 // At one point the callback type of el_set getchar callback changed from char
75 // to wchar_t. It is not possible to detect differentiate between the two
76 // versions exactly, but this is a pretty good approximation and allows us to
77 // build against almost any editline version out there.
78 #if LLDB_EDITLINE_USE_WCHAR || defined(EL_CLIENTDATA) || LLDB_HAVE_EL_RFUNC_T
79 using EditLineGetCharType = wchar_t;
80 #else
81 using EditLineGetCharType = char;
82 #endif
83 
84 using EditlineGetCharCallbackType = int (*)(::EditLine *editline,
85                                             EditLineGetCharType *c);
86 using EditlineCommandCallbackType = unsigned char (*)(::EditLine *editline,
87                                                       int ch);
88 using EditlinePromptCallbackType = const char *(*)(::EditLine *editline);
89 
90 class EditlineHistory;
91 
92 using EditlineHistorySP = std::shared_ptr<EditlineHistory>;
93 
94 using IsInputCompleteCallbackType =
95     llvm::unique_function<bool(Editline *, StringList &)>;
96 
97 using FixIndentationCallbackType =
98     llvm::unique_function<int(Editline *, StringList &, int)>;
99 
100 using SuggestionCallbackType =
101     llvm::unique_function<llvm::Optional<std::string>(llvm::StringRef)>;
102 
103 using CompleteCallbackType = llvm::unique_function<void(CompletionRequest &)>;
104 
105 /// Status used to decide when and how to start editing another line in
106 /// multi-line sessions
107 enum class EditorStatus {
108 
109   /// The default state proceeds to edit the current line
110   Editing,
111 
112   /// Editing complete, returns the complete set of edited lines
113   Complete,
114 
115   /// End of input reported
116   EndOfInput,
117 
118   /// Editing interrupted
119   Interrupted
120 };
121 
122 /// Established locations that can be easily moved among with MoveCursor
123 enum class CursorLocation {
124   /// The start of the first line in a multi-line edit session
125   BlockStart,
126 
127   /// The start of the current line in a multi-line edit session
128   EditingPrompt,
129 
130   /// The location of the cursor on the current line in a multi-line edit
131   /// session
132   EditingCursor,
133 
134   /// The location immediately after the last character in a multi-line edit
135   /// session
136   BlockEnd
137 };
138 
139 /// Operation for the history.
140 enum class HistoryOperation {
141   Oldest,
142   Older,
143   Current,
144   Newer,
145   Newest
146 };
147 }
148 
149 using namespace line_editor;
150 
151 /// Instances of Editline provide an abstraction over libedit's EditLine
152 /// facility.  Both
153 /// single- and multi-line editing are supported.
154 class Editline {
155 public:
156   Editline(const char *editor_name, FILE *input_file, FILE *output_file,
157            FILE *error_file, std::recursive_mutex &output_mutex,
158            bool color_prompts);
159 
160   ~Editline();
161 
162   /// Uses the user data storage of EditLine to retrieve an associated instance
163   /// of Editline.
164   static Editline *InstanceFor(::EditLine *editline);
165 
166   /// Sets a string to be used as a prompt, or combined with a line number to
167   /// form a prompt.
168   void SetPrompt(const char *prompt);
169 
170   /// Sets an alternate string to be used as a prompt for the second line and
171   /// beyond in multi-line
172   /// 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 oblitarate 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 SetSuggestionAnsiPrefix(std::string prefix) {
215     m_suggestion_ansi_prefix = std::move(prefix);
216   }
217 
218   void SetSuggestionAnsiSuffix(std::string suffix) {
219     m_suggestion_ansi_suffix = std::move(suffix);
220   }
221 
222   /// Prompts for and reads a single line of user input.
223   bool GetLine(std::string &line, bool &interrupted);
224 
225   /// Prompts for and reads a multi-line batch of user input.
226   bool GetLines(int first_line_number, StringList &lines, bool &interrupted);
227 
228   void PrintAsync(Stream *stream, const char *s, size_t len);
229 
230 private:
231   /// Sets the lowest line number for multi-line editing sessions.  A value of
232   /// zero suppresses
233   /// line number printing in the prompt.
234   void SetBaseLineNumber(int line_number);
235 
236   /// Returns the complete prompt by combining the prompt or continuation prompt
237   /// with line numbers
238   /// as appropriate.  The line index is a zero-based index into the current
239   /// multi-line session.
240   std::string PromptForIndex(int line_index);
241 
242   /// Sets the current line index between line edits to allow free movement
243   /// between lines.  Updates
244   /// the prompt to match.
245   void SetCurrentLine(int line_index);
246 
247   /// Determines the width of the prompt in characters.  The width is guaranteed
248   /// to be the same for
249   /// all lines of the current multi-line session.
250   int GetPromptWidth();
251 
252   /// Returns true if the underlying EditLine session's keybindings are
253   /// Emacs-based, or false if
254   /// they are VI-based.
255   bool IsEmacs();
256 
257   /// Returns true if the current EditLine buffer contains nothing but spaces,
258   /// or is empty.
259   bool IsOnlySpaces();
260 
261   /// Helper method used by MoveCursor to determine relative line position.
262   int GetLineIndexForLocation(CursorLocation location, int cursor_row);
263 
264   /// Move the cursor from one well-established location to another using
265   /// relative line positioning
266   /// and absolute column positioning.
267   void MoveCursor(CursorLocation from, CursorLocation to);
268 
269   /// Clear from cursor position to bottom of screen and print input lines
270   /// including prompts, optionally
271   /// starting from a specific line.  Lines are drawn with an extra space at the
272   /// end to reserve room for
273   /// the rightmost cursor position.
274   void DisplayInput(int firstIndex = 0);
275 
276   /// Counts the number of rows a given line of content will end up occupying,
277   /// taking into account both
278   /// the preceding prompt and a single trailing space occupied by a cursor when
279   /// at the end of the line.
280   int CountRowsForLine(const EditLineStringType &content);
281 
282   /// Save the line currently being edited
283   void SaveEditedLine();
284 
285   /// Convert the current input lines into a UTF8 StringList
286   StringList GetInputAsStringList(int line_count = UINT32_MAX);
287 
288   /// Replaces the current multi-line session with the next entry from history.
289   unsigned char RecallHistory(HistoryOperation op);
290 
291   /// Character reading implementation for EditLine that supports our multi-line
292   /// editing trickery.
293   int GetCharacter(EditLineGetCharType *c);
294 
295   /// Prompt implementation for EditLine.
296   const char *Prompt();
297 
298   /// Line break command used when meta+return is pressed in multi-line mode.
299   unsigned char BreakLineCommand(int ch);
300 
301   /// Command used when return is pressed in multi-line mode.
302   unsigned char EndOrAddLineCommand(int ch);
303 
304   /// Delete command used when delete is pressed in multi-line mode.
305   unsigned char DeleteNextCharCommand(int ch);
306 
307   /// Delete command used when backspace is pressed in multi-line mode.
308   unsigned char DeletePreviousCharCommand(int ch);
309 
310   /// Line navigation command used when ^P or up arrow are pressed in multi-line
311   /// mode.
312   unsigned char PreviousLineCommand(int ch);
313 
314   /// Line navigation command used when ^N or down arrow are pressed in
315   /// multi-line mode.
316   unsigned char NextLineCommand(int ch);
317 
318   /// History navigation command used when Alt + up arrow is pressed in
319   /// multi-line mode.
320   unsigned char PreviousHistoryCommand(int ch);
321 
322   /// History navigation command used when Alt + down arrow is pressed in
323   /// multi-line mode.
324   unsigned char NextHistoryCommand(int ch);
325 
326   /// Buffer start command used when Esc < is typed in multi-line emacs mode.
327   unsigned char BufferStartCommand(int ch);
328 
329   /// Buffer end command used when Esc > is typed in multi-line emacs mode.
330   unsigned char BufferEndCommand(int ch);
331 
332   /// Context-sensitive tab insertion or code completion command used when the
333   /// tab key is typed.
334   unsigned char TabCommand(int ch);
335 
336   /// Apply autosuggestion part in gray as editline.
337   unsigned char ApplyAutosuggestCommand(int ch);
338 
339   /// Command used when a character is typed.
340   unsigned char TypedCharacter(int ch);
341 
342   /// Respond to normal character insertion by fixing line indentation
343   unsigned char FixIndentationCommand(int ch);
344 
345   /// Revert line command used when moving between lines.
346   unsigned char RevertLineCommand(int ch);
347 
348   /// Ensures that the current EditLine instance is properly configured for
349   /// single or multi-line editing.
350   void ConfigureEditor(bool multiline);
351 
352   bool CompleteCharacter(char ch, EditLineGetCharType &out);
353 
354   void ApplyTerminalSizeChange();
355 
356   // The following set various editline parameters.  It's not any less
357   // verbose to put the editline calls into a function, but it
358   // provides type safety, since the editline functions take varargs
359   // parameters.
360   void AddFunctionToEditLine(const EditLineCharType *command,
361                              const EditLineCharType *helptext,
362                              EditlineCommandCallbackType callbackFn);
363   void SetEditLinePromptCallback(EditlinePromptCallbackType callbackFn);
364   void SetGetCharacterFunction(EditlineGetCharCallbackType callbackFn);
365 
366 #if LLDB_EDITLINE_USE_WCHAR
367   std::wstring_convert<std::codecvt_utf8<wchar_t>> m_utf8conv;
368 #endif
369   ::EditLine *m_editline = nullptr;
370   EditlineHistorySP m_history_sp;
371   bool m_in_history = false;
372   std::vector<EditLineStringType> m_live_history_lines;
373   bool m_multiline_enabled = false;
374   std::vector<EditLineStringType> m_input_lines;
375   EditorStatus m_editor_status;
376   bool m_color_prompts = true;
377   int m_terminal_width = 0;
378   int m_base_line_number = 0;
379   unsigned m_current_line_index = 0;
380   int m_current_line_rows = -1;
381   int m_revert_cursor_index = 0;
382   int m_line_number_digits = 3;
383   std::string m_set_prompt;
384   std::string m_set_continuation_prompt;
385   std::string m_current_prompt;
386   bool m_needs_prompt_repaint = false;
387   volatile std::sig_atomic_t m_terminal_size_has_changed = 0;
388   std::string m_editor_name;
389   FILE *m_input_file;
390   FILE *m_output_file;
391   FILE *m_error_file;
392   ConnectionFileDescriptor m_input_connection;
393 
394   IsInputCompleteCallbackType m_is_input_complete_callback;
395 
396   FixIndentationCallbackType m_fix_indentation_callback;
397   const char *m_fix_indentation_callback_chars = nullptr;
398 
399   CompleteCallbackType m_completion_callback;
400   SuggestionCallbackType m_suggestion_callback;
401 
402   std::string m_suggestion_ansi_prefix;
403   std::string m_suggestion_ansi_suffix;
404 
405   std::size_t m_previous_autosuggestion_size = 0;
406   std::recursive_mutex &m_output_mutex;
407 };
408 }
409 
410 #endif // #if defined(__cplusplus)
411 #endif // LLDB_HOST_EDITLINE_H
412