]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/include/lldb/Host/Editline.h
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / include / lldb / Host / Editline.h
1 //===-- Editline.h ----------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 // TODO: wire up window size changes
11
12 // If we ever get a private copy of libedit, there are a number of defects that
13 // would be nice to fix;
14 // a) Sometimes text just disappears while editing.  In an 80-column editor
15 // paste the following text, without
16 //    the quotes:
17 //    "This is a test of the input system missing Hello, World!  Do you
18 //    disappear when it gets to a particular length?"
19 //    Now press ^A to move to the start and type 3 characters, and you'll see a
20 //    good amount of the text will
21 //    disappear.  It's still in the buffer, just invisible.
22 // b) The prompt printing logic for dealing with ANSI formatting characters is
23 // broken, which is why we're
24 //    working around it here.
25 // c) When resizing the terminal window, if the cursor moves between rows
26 // libedit will get confused. d) The incremental search uses escape to cancel
27 // input, so it's confused by
28 // ANSI sequences starting with escape.
29 // e) Emoji support is fairly terrible, presumably it doesn't understand
30 // composed characters?
31
32 #ifndef liblldb_Editline_h_
33 #define liblldb_Editline_h_
34 #if defined(__cplusplus)
35
36 #if LLDB_EDITLINE_USE_WCHAR
37 #include <codecvt>
38 #endif
39 #include <locale>
40 #include <sstream>
41 #include <vector>
42
43 #include "lldb/Host/ConnectionFileDescriptor.h"
44 #include "lldb/lldb-private.h"
45
46 #if defined(_WIN32)
47 #include "lldb/Host/windows/editlinewin.h"
48 #elif !defined(__ANDROID__)
49 #include <histedit.h>
50 #endif
51
52 #include <mutex>
53 #include <string>
54 #include <vector>
55
56 #include "lldb/Host/ConnectionFileDescriptor.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 int (*CompleteCallbackType)(const char *current_line,
102                                     const char *cursor, const char *last_char,
103                                     int skip_first_n_matches, int max_matches,
104                                     StringList &matches,
105                                     StringList &descriptions, void *baton);
106
107 /// Status used to decide when and how to start editing another line in
108 /// multi-line sessions
109 enum class EditorStatus {
110
111   /// The default state proceeds to edit the current line
112   Editing,
113
114   /// Editing complete, returns the complete set of edited lines
115   Complete,
116
117   /// End of input reported
118   EndOfInput,
119
120   /// Editing interrupted
121   Interrupted
122 };
123
124 /// Established locations that can be easily moved among with MoveCursor
125 enum class CursorLocation {
126   /// The start of the first line in a multi-line edit session
127   BlockStart,
128
129   /// The start of the current line in a multi-line edit session
130   EditingPrompt,
131
132   /// The location of the cursor on the current line in a multi-line edit
133   /// session
134   EditingCursor,
135
136   /// The location immediately after the last character in a multi-line edit
137   /// session
138   BlockEnd
139 };
140 }
141
142 using namespace line_editor;
143
144 /// Instances of Editline provide an abstraction over libedit's EditLine
145 /// facility.  Both
146 /// single- and multi-line editing are supported.
147 class Editline {
148 public:
149   Editline(const char *editor_name, FILE *input_file, FILE *output_file,
150            FILE *error_file, bool color_prompts);
151
152   ~Editline();
153
154   /// Uses the user data storage of EditLine to retrieve an associated instance
155   /// of Editline.
156   static Editline *InstanceFor(::EditLine *editline);
157
158   /// Sets a string to be used as a prompt, or combined with a line number to
159   /// form a prompt.
160   void SetPrompt(const char *prompt);
161
162   /// Sets an alternate string to be used as a prompt for the second line and
163   /// beyond in multi-line
164   /// editing scenarios.
165   void SetContinuationPrompt(const char *continuation_prompt);
166
167   /// Required to update the width of the terminal registered for I/O.  It is
168   /// critical that this
169   /// be correct at all times.
170   void TerminalSizeChanged();
171
172   /// Returns the prompt established by SetPrompt()
173   const char *GetPrompt();
174
175   /// Returns the index of the line currently being edited
176   uint32_t GetCurrentLine();
177
178   /// Interrupt the current edit as if ^C was pressed
179   bool Interrupt();
180
181   /// Cancel this edit and oblitarate all trace of it
182   bool Cancel();
183
184   /// Register a callback for the tab key
185   void SetAutoCompleteCallback(CompleteCallbackType callback, void *baton);
186
187   /// Register a callback for testing whether multi-line input is complete
188   void SetIsInputCompleteCallback(IsInputCompleteCallbackType callback,
189                                   void *baton);
190
191   /// Register a callback for determining the appropriate indentation for a line
192   /// when creating a newline.  An optional set of insertable characters can
193   /// also
194   /// trigger the callback.
195   bool SetFixIndentationCallback(FixIndentationCallbackType callback,
196                                  void *baton, const char *indent_chars);
197
198   /// Prompts for and reads a single line of user input.
199   bool GetLine(std::string &line, bool &interrupted);
200
201   /// Prompts for and reads a multi-line batch of user input.
202   bool GetLines(int first_line_number, StringList &lines, bool &interrupted);
203
204   void PrintAsync(Stream *stream, const char *s, size_t len);
205
206 private:
207   /// Sets the lowest line number for multi-line editing sessions.  A value of
208   /// zero suppresses
209   /// line number printing in the prompt.
210   void SetBaseLineNumber(int line_number);
211
212   /// Returns the complete prompt by combining the prompt or continuation prompt
213   /// with line numbers
214   /// as appropriate.  The line index is a zero-based index into the current
215   /// multi-line session.
216   std::string PromptForIndex(int line_index);
217
218   /// Sets the current line index between line edits to allow free movement
219   /// between lines.  Updates
220   /// the prompt to match.
221   void SetCurrentLine(int line_index);
222
223   /// Determines the width of the prompt in characters.  The width is guaranteed
224   /// to be the same for
225   /// all lines of the current multi-line session.
226   int GetPromptWidth();
227
228   /// Returns true if the underlying EditLine session's keybindings are
229   /// Emacs-based, or false if
230   /// they are VI-based.
231   bool IsEmacs();
232
233   /// Returns true if the current EditLine buffer contains nothing but spaces,
234   /// or is empty.
235   bool IsOnlySpaces();
236
237   /// Helper method used by MoveCursor to determine relative line position.
238   int GetLineIndexForLocation(CursorLocation location, int cursor_row);
239
240   /// Move the cursor from one well-established location to another using
241   /// relative line positioning
242   /// and absolute column positioning.
243   void MoveCursor(CursorLocation from, CursorLocation to);
244
245   /// Clear from cursor position to bottom of screen and print input lines
246   /// including prompts, optionally
247   /// starting from a specific line.  Lines are drawn with an extra space at the
248   /// end to reserve room for
249   /// the rightmost cursor position.
250   void DisplayInput(int firstIndex = 0);
251
252   /// Counts the number of rows a given line of content will end up occupying,
253   /// taking into account both
254   /// the preceding prompt and a single trailing space occupied by a cursor when
255   /// at the end of the line.
256   int CountRowsForLine(const EditLineStringType &content);
257
258   /// Save the line currently being edited
259   void SaveEditedLine();
260
261   /// Convert the current input lines into a UTF8 StringList
262   StringList GetInputAsStringList(int line_count = UINT32_MAX);
263
264   /// Replaces the current multi-line session with the next entry from history.
265   /// When the parameter is
266   /// true it will take the next earlier entry from history, when it is false it
267   /// takes the next most
268   /// recent.
269   unsigned char RecallHistory(bool earlier);
270
271   /// Character reading implementation for EditLine that supports our multi-line
272   /// editing trickery.
273   int GetCharacter(EditLineGetCharType *c);
274
275   /// Prompt implementation for EditLine.
276   const char *Prompt();
277
278   /// Line break command used when meta+return is pressed in multi-line mode.
279   unsigned char BreakLineCommand(int ch);
280
281   /// Command used when return is pressed in multi-line mode.
282   unsigned char EndOrAddLineCommand(int ch);
283
284   /// Delete command used when delete is pressed in multi-line mode.
285   unsigned char DeleteNextCharCommand(int ch);
286
287   /// Delete command used when backspace is pressed in multi-line mode.
288   unsigned char DeletePreviousCharCommand(int ch);
289
290   /// Line navigation command used when ^P or up arrow are pressed in multi-line
291   /// mode.
292   unsigned char PreviousLineCommand(int ch);
293
294   /// Line navigation command used when ^N or down arrow are pressed in
295   /// multi-line mode.
296   unsigned char NextLineCommand(int ch);
297
298   /// History navigation command used when Alt + up arrow is pressed in
299   /// multi-line mode.
300   unsigned char PreviousHistoryCommand(int ch);
301
302   /// History navigation command used when Alt + down arrow is pressed in
303   /// multi-line mode.
304   unsigned char NextHistoryCommand(int ch);
305
306   /// Buffer start command used when Esc < is typed in multi-line emacs mode.
307   unsigned char BufferStartCommand(int ch);
308
309   /// Buffer end command used when Esc > is typed in multi-line emacs mode.
310   unsigned char BufferEndCommand(int ch);
311
312   /// Context-sensitive tab insertion or code completion command used when the
313   /// tab key is typed.
314   unsigned char TabCommand(int ch);
315
316   /// Respond to normal character insertion by fixing line indentation
317   unsigned char FixIndentationCommand(int ch);
318
319   /// Revert line command used when moving between lines.
320   unsigned char RevertLineCommand(int ch);
321
322   /// Ensures that the current EditLine instance is properly configured for
323   /// single or multi-line editing.
324   void ConfigureEditor(bool multiline);
325
326   bool CompleteCharacter(char ch, EditLineGetCharType &out);
327
328 private:
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   std::string m_editor_name;
351   FILE *m_input_file;
352   FILE *m_output_file;
353   FILE *m_error_file;
354   ConnectionFileDescriptor m_input_connection;
355   IsInputCompleteCallbackType m_is_input_complete_callback = nullptr;
356   void *m_is_input_complete_callback_baton = nullptr;
357   FixIndentationCallbackType m_fix_indentation_callback = nullptr;
358   void *m_fix_indentation_callback_baton = nullptr;
359   const char *m_fix_indentation_callback_chars = nullptr;
360   CompleteCallbackType m_completion_callback = nullptr;
361   void *m_completion_callback_baton = nullptr;
362
363   std::mutex m_output_mutex;
364 };
365 }
366
367 #endif // #if defined(__cplusplus)
368 #endif // liblldb_Editline_h_