]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/include/lldb/Host/Editline.h
Merge ^/head r326936 through r327149.
[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.
27 // d) The incremental search uses escape to cancel 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 #include <locale>
37 #include <sstream>
38 #include <vector>
39
40 // components needed to handle wide characters ( <codecvt>, codecvt_utf8,
41 // libedit built with '--enable-widec' )
42 // are available on some platforms. The wchar_t versions of libedit functions
43 // will only be
44 // used in cases where this is true.  This is a compile time dependecy, for now
45 // selected per target Platform
46 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) ||       \
47     defined(__OpenBSD__)
48 #define LLDB_EDITLINE_USE_WCHAR 1
49 #include <codecvt>
50 #else
51 #define LLDB_EDITLINE_USE_WCHAR 0
52 #endif
53
54 #include "lldb/Host/ConnectionFileDescriptor.h"
55 #include "lldb/lldb-private.h"
56
57 #if defined(_WIN32)
58 #include "lldb/Host/windows/editlinewin.h"
59 #elif !defined(__ANDROID__)
60 #include <histedit.h>
61 #endif
62
63 #include <mutex>
64 #include <string>
65 #include <vector>
66
67 #include "lldb/Host/ConnectionFileDescriptor.h"
68 #include "lldb/Host/Predicate.h"
69 #include "lldb/Utility/FileSpec.h"
70
71 namespace lldb_private {
72 namespace line_editor {
73
74 // type alias's to help manage 8 bit and wide character versions of libedit
75 #if LLDB_EDITLINE_USE_WCHAR
76 using EditLineStringType = std::wstring;
77 using EditLineStringStreamType = std::wstringstream;
78 using EditLineCharType = wchar_t;
79 #else
80 using EditLineStringType = std::string;
81 using EditLineStringStreamType = std::stringstream;
82 using EditLineCharType = char;
83 #endif
84
85 #ifdef EL_CLIENTDATA    /* editline with wide support + wide char read function */
86 using EditLineGetCharType = wchar_t;
87 #else
88 using EditLineGetCharType = char;
89 #endif
90
91 typedef int (*EditlineGetCharCallbackType)(::EditLine *editline,
92                                            EditLineGetCharType *c);
93 typedef unsigned char (*EditlineCommandCallbackType)(::EditLine *editline,
94                                                      int ch);
95 typedef const char *(*EditlinePromptCallbackType)(::EditLine *editline);
96
97 class EditlineHistory;
98
99 typedef std::shared_ptr<EditlineHistory> EditlineHistorySP;
100
101 typedef bool (*IsInputCompleteCallbackType)(Editline *editline,
102                                             StringList &lines, void *baton);
103
104 typedef int (*FixIndentationCallbackType)(Editline *editline,
105                                           const StringList &lines,
106                                           int cursor_position, void *baton);
107
108 typedef int (*CompleteCallbackType)(const char *current_line,
109                                     const char *cursor, const char *last_char,
110                                     int skip_first_n_matches, int max_matches,
111                                     StringList &matches, void *baton);
112
113 /// Status used to decide when and how to start editing another line in
114 /// multi-line sessions
115 enum class EditorStatus {
116
117   /// The default state proceeds to edit the current line
118   Editing,
119
120   /// Editing complete, returns the complete set of edited lines
121   Complete,
122
123   /// End of input reported
124   EndOfInput,
125
126   /// Editing interrupted
127   Interrupted
128 };
129
130 /// Established locations that can be easily moved among with MoveCursor
131 enum class CursorLocation {
132   /// The start of the first line in a multi-line edit session
133   BlockStart,
134
135   /// The start of the current line in a multi-line edit session
136   EditingPrompt,
137
138   /// The location of the cursor on the current line in a multi-line edit
139   /// session
140   EditingCursor,
141
142   /// The location immediately after the last character in a multi-line edit
143   /// session
144   BlockEnd
145 };
146 }
147
148 using namespace line_editor;
149
150 /// Instances of Editline provide an abstraction over libedit's EditLine
151 /// facility.  Both
152 /// single- and multi-line editing are supported.
153 class Editline {
154 public:
155   Editline(const char *editor_name, FILE *input_file, FILE *output_file,
156            FILE *error_file, bool color_prompts);
157
158   ~Editline();
159
160   /// Uses the user data storage of EditLine to retrieve an associated instance
161   /// of Editline.
162   static Editline *InstanceFor(::EditLine *editline);
163
164   /// Sets a string to be used as a prompt, or combined with a line number to
165   /// form a prompt.
166   void SetPrompt(const char *prompt);
167
168   /// Sets an alternate string to be used as a prompt for the second line and
169   /// beyond in multi-line
170   /// editing scenarios.
171   void SetContinuationPrompt(const char *continuation_prompt);
172
173   /// Required to update the width of the terminal registered for I/O.  It is
174   /// critical that this
175   /// be correct at all times.
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 the tab key
191   void SetAutoCompleteCallback(CompleteCallbackType callback, void *baton);
192
193   /// Register a callback for testing whether multi-line input is complete
194   void SetIsInputCompleteCallback(IsInputCompleteCallbackType callback,
195                                   void *baton);
196
197   /// Register a callback for determining the appropriate indentation for a line
198   /// when creating a newline.  An optional set of insertable characters can
199   /// also
200   /// trigger the callback.
201   bool SetFixIndentationCallback(FixIndentationCallbackType callback,
202                                  void *baton, const char *indent_chars);
203
204   /// Prompts for and reads a single line of user input.
205   bool GetLine(std::string &line, bool &interrupted);
206
207   /// Prompts for and reads a multi-line batch of user input.
208   bool GetLines(int first_line_number, StringList &lines, bool &interrupted);
209
210   void PrintAsync(Stream *stream, const char *s, size_t len);
211
212 private:
213   /// Sets the lowest line number for multi-line editing sessions.  A value of
214   /// zero suppresses
215   /// line number printing in the prompt.
216   void SetBaseLineNumber(int line_number);
217
218   /// Returns the complete prompt by combining the prompt or continuation prompt
219   /// with line numbers
220   /// as appropriate.  The line index is a zero-based index into the current
221   /// multi-line session.
222   std::string PromptForIndex(int line_index);
223
224   /// Sets the current line index between line edits to allow free movement
225   /// between lines.  Updates
226   /// the prompt to match.
227   void SetCurrentLine(int line_index);
228
229   /// Determines the width of the prompt in characters.  The width is guaranteed
230   /// to be the same for
231   /// all lines of the current multi-line session.
232   int GetPromptWidth();
233
234   /// Returns true if the underlying EditLine session's keybindings are
235   /// Emacs-based, or false if
236   /// they are VI-based.
237   bool IsEmacs();
238
239   /// Returns true if the current EditLine buffer contains nothing but spaces,
240   /// or is empty.
241   bool IsOnlySpaces();
242
243   /// Helper method used by MoveCursor to determine relative line position.
244   int GetLineIndexForLocation(CursorLocation location, int cursor_row);
245
246   /// Move the cursor from one well-established location to another using
247   /// relative line positioning
248   /// and absolute column positioning.
249   void MoveCursor(CursorLocation from, CursorLocation to);
250
251   /// Clear from cursor position to bottom of screen and print input lines
252   /// including prompts, optionally
253   /// starting from a specific line.  Lines are drawn with an extra space at the
254   /// end to reserve room for
255   /// the rightmost cursor position.
256   void DisplayInput(int firstIndex = 0);
257
258   /// Counts the number of rows a given line of content will end up occupying,
259   /// taking into account both
260   /// the preceding prompt and a single trailing space occupied by a cursor when
261   /// at the end of the line.
262   int CountRowsForLine(const EditLineStringType &content);
263
264   /// Save the line currently being edited
265   void SaveEditedLine();
266
267   /// Convert the current input lines into a UTF8 StringList
268   StringList GetInputAsStringList(int line_count = UINT32_MAX);
269
270   /// Replaces the current multi-line session with the next entry from history.
271   /// When the parameter is
272   /// true it will take the next earlier entry from history, when it is false it
273   /// takes the next most
274   /// recent.
275   unsigned char RecallHistory(bool earlier);
276
277   /// Character reading implementation for EditLine that supports our multi-line
278   /// editing trickery.
279   int GetCharacter(EditLineGetCharType *c);
280
281   /// Prompt implementation for EditLine.
282   const char *Prompt();
283
284   /// Line break command used when meta+return is pressed in multi-line mode.
285   unsigned char BreakLineCommand(int ch);
286
287   /// Command used when return is pressed in multi-line mode.
288   unsigned char EndOrAddLineCommand(int ch);
289
290   /// Delete command used when delete is pressed in multi-line mode.
291   unsigned char DeleteNextCharCommand(int ch);
292
293   /// Delete command used when backspace is pressed in multi-line mode.
294   unsigned char DeletePreviousCharCommand(int ch);
295
296   /// Line navigation command used when ^P or up arrow are pressed in multi-line
297   /// mode.
298   unsigned char PreviousLineCommand(int ch);
299
300   /// Line navigation command used when ^N or down arrow are pressed in
301   /// multi-line mode.
302   unsigned char NextLineCommand(int ch);
303
304   /// History navigation command used when Alt + up arrow is pressed in
305   /// multi-line mode.
306   unsigned char PreviousHistoryCommand(int ch);
307
308   /// History navigation command used when Alt + down arrow is pressed in
309   /// multi-line mode.
310   unsigned char NextHistoryCommand(int ch);
311
312   /// Buffer start command used when Esc < is typed in multi-line emacs mode.
313   unsigned char BufferStartCommand(int ch);
314
315   /// Buffer end command used when Esc > is typed in multi-line emacs mode.
316   unsigned char BufferEndCommand(int ch);
317
318   /// Context-sensitive tab insertion or code completion command used when the
319   /// tab key is typed.
320   unsigned char TabCommand(int ch);
321
322   /// Respond to normal character insertion by fixing line indentation
323   unsigned char FixIndentationCommand(int ch);
324
325   /// Revert line command used when moving between lines.
326   unsigned char RevertLineCommand(int ch);
327
328   /// Ensures that the current EditLine instance is properly configured for
329   /// single or multi-line editing.
330   void ConfigureEditor(bool multiline);
331
332   bool CompleteCharacter(char ch, EditLineGetCharType &out);
333
334 private:
335 #if LLDB_EDITLINE_USE_WCHAR
336   std::wstring_convert<std::codecvt_utf8<wchar_t>> m_utf8conv;
337 #endif
338   ::EditLine *m_editline = nullptr;
339   EditlineHistorySP m_history_sp;
340   bool m_in_history = false;
341   std::vector<EditLineStringType> m_live_history_lines;
342   bool m_multiline_enabled = false;
343   std::vector<EditLineStringType> m_input_lines;
344   EditorStatus m_editor_status;
345   bool m_color_prompts = true;
346   int m_terminal_width = 0;
347   int m_base_line_number = 0;
348   unsigned m_current_line_index = 0;
349   int m_current_line_rows = -1;
350   int m_revert_cursor_index = 0;
351   int m_line_number_digits = 3;
352   std::string m_set_prompt;
353   std::string m_set_continuation_prompt;
354   std::string m_current_prompt;
355   bool m_needs_prompt_repaint = false;
356   std::string m_editor_name;
357   FILE *m_input_file;
358   FILE *m_output_file;
359   FILE *m_error_file;
360   ConnectionFileDescriptor m_input_connection;
361   IsInputCompleteCallbackType m_is_input_complete_callback = nullptr;
362   void *m_is_input_complete_callback_baton = nullptr;
363   FixIndentationCallbackType m_fix_indentation_callback = nullptr;
364   void *m_fix_indentation_callback_baton = nullptr;
365   const char *m_fix_indentation_callback_chars = nullptr;
366   CompleteCallbackType m_completion_callback = nullptr;
367   void *m_completion_callback_baton = nullptr;
368
369   std::mutex m_output_mutex;
370 };
371 }
372
373 #endif // #if defined(__cplusplus)
374 #endif // liblldb_Editline_h_