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