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/Host/ConnectionFileDescriptor.h"
42 #include "lldb/lldb-private.h"
43 
44 #if defined(_WIN32)
45 #include "lldb/Host/windows/editlinewin.h"
46 #elif !defined(__ANDROID__)
47 #include <histedit.h>
48 #endif
49 
50 #include <csignal>
51 #include <mutex>
52 #include <string>
53 #include <vector>
54 
55 #include "lldb/Host/ConnectionFileDescriptor.h"
56 #include "lldb/Utility/CompletionRequest.h"
57 #include "lldb/Utility/FileSpec.h"
58 #include "lldb/Utility/Predicate.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 typedef int (*EditlineGetCharCallbackType)(::EditLine *editline,
85                                            EditLineGetCharType *c);
86 typedef unsigned char (*EditlineCommandCallbackType)(::EditLine *editline,
87                                                      int ch);
88 typedef const char *(*EditlinePromptCallbackType)(::EditLine *editline);
89 
90 class EditlineHistory;
91 
92 typedef std::shared_ptr<EditlineHistory> EditlineHistorySP;
93 
94 typedef bool (*IsInputCompleteCallbackType)(Editline *editline,
95                                             StringList &lines, void *baton);
96 
97 typedef int (*FixIndentationCallbackType)(Editline *editline,
98                                           const StringList &lines,
99                                           int cursor_position, void *baton);
100 
101 typedef llvm::Optional<std::string> (*SuggestionCallbackType)(
102     llvm::StringRef line, void *baton);
103 
104 typedef void (*CompleteCallbackType)(CompletionRequest &request, void *baton);
105 
106 /// Status used to decide when and how to start editing another line in
107 /// multi-line sessions
108 enum class EditorStatus {
109 
110   /// The default state proceeds to edit the current line
111   Editing,
112 
113   /// Editing complete, returns the complete set of edited lines
114   Complete,
115 
116   /// End of input reported
117   EndOfInput,
118 
119   /// Editing interrupted
120   Interrupted
121 };
122 
123 /// Established locations that can be easily moved among with MoveCursor
124 enum class CursorLocation {
125   /// The start of the first line in a multi-line edit session
126   BlockStart,
127 
128   /// The start of the current line in a multi-line edit session
129   EditingPrompt,
130 
131   /// The location of the cursor on the current line in a multi-line edit
132   /// session
133   EditingCursor,
134 
135   /// The location immediately after the last character in a multi-line edit
136   /// session
137   BlockEnd
138 };
139 
140 /// Operation for the history.
141 enum class HistoryOperation {
142   Oldest,
143   Older,
144   Current,
145   Newer,
146   Newest
147 };
148 }
149 
150 using namespace line_editor;
151 
152 /// Instances of Editline provide an abstraction over libedit's EditLine
153 /// facility.  Both
154 /// single- and multi-line editing are supported.
155 class Editline {
156 public:
157   Editline(const char *editor_name, FILE *input_file, FILE *output_file,
158            FILE *error_file, 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, void *baton);
192 
193   /// Register a callback for the tab key
194   void SetAutoCompleteCallback(CompleteCallbackType callback, void *baton);
195 
196   /// Register a callback for testing whether multi-line input is complete
197   void SetIsInputCompleteCallback(IsInputCompleteCallbackType callback,
198                                   void *baton);
199 
200   /// Register a callback for determining the appropriate indentation for a line
201   /// when creating a newline.  An optional set of insertable characters can
202   /// also
203   /// trigger the callback.
204   bool SetFixIndentationCallback(FixIndentationCallbackType callback,
205                                  void *baton, const char *indent_chars);
206 
207   /// Prompts for and reads a single line of user input.
208   bool GetLine(std::string &line, bool &interrupted);
209 
210   /// Prompts for and reads a multi-line batch of user input.
211   bool GetLines(int first_line_number, StringList &lines, bool &interrupted);
212 
213   void PrintAsync(Stream *stream, const char *s, size_t len);
214 
215 private:
216   /// Sets the lowest line number for multi-line editing sessions.  A value of
217   /// zero suppresses
218   /// line number printing in the prompt.
219   void SetBaseLineNumber(int line_number);
220 
221   /// Returns the complete prompt by combining the prompt or continuation prompt
222   /// with line numbers
223   /// as appropriate.  The line index is a zero-based index into the current
224   /// multi-line session.
225   std::string PromptForIndex(int line_index);
226 
227   /// Sets the current line index between line edits to allow free movement
228   /// between lines.  Updates
229   /// the prompt to match.
230   void SetCurrentLine(int line_index);
231 
232   /// Determines the width of the prompt in characters.  The width is guaranteed
233   /// to be the same for
234   /// all lines of the current multi-line session.
235   int GetPromptWidth();
236 
237   /// Returns true if the underlying EditLine session's keybindings are
238   /// Emacs-based, or false if
239   /// they are VI-based.
240   bool IsEmacs();
241 
242   /// Returns true if the current EditLine buffer contains nothing but spaces,
243   /// or is empty.
244   bool IsOnlySpaces();
245 
246   /// Helper method used by MoveCursor to determine relative line position.
247   int GetLineIndexForLocation(CursorLocation location, int cursor_row);
248 
249   /// Move the cursor from one well-established location to another using
250   /// relative line positioning
251   /// and absolute column positioning.
252   void MoveCursor(CursorLocation from, CursorLocation to);
253 
254   /// Clear from cursor position to bottom of screen and print input lines
255   /// including prompts, optionally
256   /// starting from a specific line.  Lines are drawn with an extra space at the
257   /// end to reserve room for
258   /// the rightmost cursor position.
259   void DisplayInput(int firstIndex = 0);
260 
261   /// Counts the number of rows a given line of content will end up occupying,
262   /// taking into account both
263   /// the preceding prompt and a single trailing space occupied by a cursor when
264   /// at the end of the line.
265   int CountRowsForLine(const EditLineStringType &content);
266 
267   /// Save the line currently being edited
268   void SaveEditedLine();
269 
270   /// Convert the current input lines into a UTF8 StringList
271   StringList GetInputAsStringList(int line_count = UINT32_MAX);
272 
273   /// Replaces the current multi-line session with the next entry from history.
274   unsigned char RecallHistory(HistoryOperation op);
275 
276   /// Character reading implementation for EditLine that supports our multi-line
277   /// editing trickery.
278   int GetCharacter(EditLineGetCharType *c);
279 
280   /// Prompt implementation for EditLine.
281   const char *Prompt();
282 
283   /// Line break command used when meta+return is pressed in multi-line mode.
284   unsigned char BreakLineCommand(int ch);
285 
286   /// Command used when return is pressed in multi-line mode.
287   unsigned char EndOrAddLineCommand(int ch);
288 
289   /// Delete command used when delete is pressed in multi-line mode.
290   unsigned char DeleteNextCharCommand(int ch);
291 
292   /// Delete command used when backspace is pressed in multi-line mode.
293   unsigned char DeletePreviousCharCommand(int ch);
294 
295   /// Line navigation command used when ^P or up arrow are pressed in multi-line
296   /// mode.
297   unsigned char PreviousLineCommand(int ch);
298 
299   /// Line navigation command used when ^N or down arrow are pressed in
300   /// multi-line mode.
301   unsigned char NextLineCommand(int ch);
302 
303   /// History navigation command used when Alt + up arrow is pressed in
304   /// multi-line mode.
305   unsigned char PreviousHistoryCommand(int ch);
306 
307   /// History navigation command used when Alt + down arrow is pressed in
308   /// multi-line mode.
309   unsigned char NextHistoryCommand(int ch);
310 
311   /// Buffer start command used when Esc < is typed in multi-line emacs mode.
312   unsigned char BufferStartCommand(int ch);
313 
314   /// Buffer end command used when Esc > is typed in multi-line emacs mode.
315   unsigned char BufferEndCommand(int ch);
316 
317   /// Context-sensitive tab insertion or code completion command used when the
318   /// tab key is typed.
319   unsigned char TabCommand(int ch);
320 
321   /// Apply autosuggestion part in gray as editline.
322   unsigned char ApplyAutosuggestCommand(int ch);
323 
324   /// Command used when a character is typed.
325   unsigned char TypedCharacter(int ch);
326 
327   /// Respond to normal character insertion by fixing line indentation
328   unsigned char FixIndentationCommand(int ch);
329 
330   /// Revert line command used when moving between lines.
331   unsigned char RevertLineCommand(int ch);
332 
333   /// Ensures that the current EditLine instance is properly configured for
334   /// single or multi-line editing.
335   void ConfigureEditor(bool multiline);
336 
337   bool CompleteCharacter(char ch, EditLineGetCharType &out);
338 
339   void ApplyTerminalSizeChange();
340 
341 #if LLDB_EDITLINE_USE_WCHAR
342   std::wstring_convert<std::codecvt_utf8<wchar_t>> m_utf8conv;
343 #endif
344   ::EditLine *m_editline = nullptr;
345   EditlineHistorySP m_history_sp;
346   bool m_in_history = false;
347   std::vector<EditLineStringType> m_live_history_lines;
348   bool m_multiline_enabled = false;
349   std::vector<EditLineStringType> m_input_lines;
350   EditorStatus m_editor_status;
351   bool m_color_prompts = true;
352   int m_terminal_width = 0;
353   int m_base_line_number = 0;
354   unsigned m_current_line_index = 0;
355   int m_current_line_rows = -1;
356   int m_revert_cursor_index = 0;
357   int m_line_number_digits = 3;
358   std::string m_set_prompt;
359   std::string m_set_continuation_prompt;
360   std::string m_current_prompt;
361   bool m_needs_prompt_repaint = false;
362   volatile std::sig_atomic_t m_terminal_size_has_changed = 0;
363   std::string m_editor_name;
364   FILE *m_input_file;
365   FILE *m_output_file;
366   FILE *m_error_file;
367   ConnectionFileDescriptor m_input_connection;
368   IsInputCompleteCallbackType m_is_input_complete_callback = nullptr;
369   void *m_is_input_complete_callback_baton = nullptr;
370   FixIndentationCallbackType m_fix_indentation_callback = nullptr;
371   void *m_fix_indentation_callback_baton = nullptr;
372   const char *m_fix_indentation_callback_chars = nullptr;
373   CompleteCallbackType m_completion_callback = nullptr;
374   void *m_completion_callback_baton = nullptr;
375   SuggestionCallbackType m_suggestion_callback = nullptr;
376   void *m_suggestion_callback_baton = nullptr;
377   std::size_t m_previous_autosuggestion_size = 0;
378   std::mutex m_output_mutex;
379 };
380 }
381 
382 #endif // #if defined(__cplusplus)
383 #endif // LLDB_HOST_EDITLINE_H
384