LLDB mainline
Editline.h
Go to the documentation of this file.
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
31#include "lldb/Host/Config.h"
32
33#include <locale>
34#include <sstream>
35#include <vector>
36
37#include "lldb/lldb-private.h"
38
39#if !defined(_WIN32) && !defined(__ANDROID__)
40#include <histedit.h>
41#endif
42
43#include <csignal>
44#include <mutex>
45#include <optional>
46#include <string>
47#include <vector>
48
54
55#include "llvm/ADT/FunctionExtras.h"
56
57namespace lldb_private {
58namespace line_editor {
59
60// type alias's to help manage 8 bit and wide character versions of libedit
61#if LLDB_EDITLINE_USE_WCHAR
62using EditLineStringType = std::wstring;
63using EditLineStringStreamType = std::wstringstream;
64using EditLineCharType = wchar_t;
65#else
66using EditLineStringType = std::string;
67using EditLineStringStreamType = std::stringstream;
68using EditLineCharType = char;
69#endif
70
71// At one point the callback type of el_set getchar callback changed from char
72// to wchar_t. It is not possible to detect differentiate between the two
73// versions exactly, but this is a pretty good approximation and allows us to
74// build against almost any editline version out there.
75// It does, however, require extra care when invoking el_getc, as the type
76// of the input is a single char buffer, but the callback will write a wchar_t.
77#if LLDB_EDITLINE_USE_WCHAR || defined(EL_CLIENTDATA) || LLDB_HAVE_EL_RFUNC_T
78using EditLineGetCharType = wchar_t;
79#else
81#endif
82
83using EditlineGetCharCallbackType = int (*)(::EditLine *editline,
85using EditlineCommandCallbackType = unsigned char (*)(::EditLine *editline,
86 int ch);
87using EditlinePromptCallbackType = const char *(*)(::EditLine *editline);
88
89class EditlineHistory;
90
91using EditlineHistorySP = std::shared_ptr<EditlineHistory>;
92
94 llvm::unique_function<bool(Editline *, StringList &)>;
95
97 llvm::unique_function<int(Editline *, StringList &, int)>;
98
100 llvm::unique_function<std::optional<std::string>(llvm::StringRef)>;
101
102using CompleteCallbackType = llvm::unique_function<void(CompletionRequest &)>;
103
104/// Status used to decide when and how to start editing another line in
105/// multi-line sessions.
106enum class EditorStatus {
107
108 /// The default state proceeds to edit the current line.
109 Editing,
110
111 /// Editing complete, returns the complete set of edited lines.
112 Complete,
113
114 /// End of input reported.
116
117 /// Editing interrupted.
119};
120
121/// Established locations that can be easily moved among with MoveCursor.
122enum class CursorLocation {
123 /// The start of the first line in a multi-line edit session.
125
126 /// The start of the current line in a multi-line edit session.
128
129 /// The location of the cursor on the current line in a multi-line edit
130 /// session.
132
133 /// The location immediately after the last character in a multi-line edit
134 /// session.
136};
137
138/// Operation for the history.
140 Oldest,
141 Older,
142 Current,
143 Newer,
144 Newest
145};
146}
147
148using namespace line_editor;
149
150/// Instances of Editline provide an abstraction over libedit's EditLine
151/// facility. Both single- and multi-line editing are supported.
152class Editline {
153public:
154 Editline(const char *editor_name, FILE *input_file, FILE *output_file,
155 FILE *error_file, std::recursive_mutex &output_mutex);
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 static void
165 llvm::ArrayRef<CompletionResult::Completion> results);
166
167 /// Sets a string to be used as a prompt, or combined with a line number to
168 /// form a prompt.
169 void SetPrompt(const char *prompt);
170
171 /// Sets an alternate string to be used as a prompt for the second line and
172 /// beyond in multi-line 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 obliterate all trace of it.
188 bool Cancel();
189
190 /// Register a callback for autosuggestion.
192 m_suggestion_callback = std::move(callback);
193 }
194
195 /// Register a callback for the tab key
197 m_completion_callback = std::move(callback);
198 }
199
200 /// Register a callback for testing whether multi-line input is complete
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.
209 const char *indent_chars) {
210 m_fix_indentation_callback = std::move(callback);
212 }
213
214 void SetPromptAnsiPrefix(std::string prefix) {
215 m_prompt_ansi_prefix = std::move(prefix);
216 }
217
218 void SetPromptAnsiSuffix(std::string suffix) {
219 m_prompt_ansi_suffix = std::move(suffix);
220 }
221
222 void SetSuggestionAnsiPrefix(std::string prefix) {
223 m_suggestion_ansi_prefix = std::move(prefix);
224 }
225
226 void SetSuggestionAnsiSuffix(std::string suffix) {
227 m_suggestion_ansi_suffix = std::move(suffix);
228 }
229
230 /// Prompts for and reads a single line of user input.
231 bool GetLine(std::string &line, bool &interrupted);
232
233 /// Prompts for and reads a multi-line batch of user input.
234 bool GetLines(int first_line_number, StringList &lines, bool &interrupted);
235
236 void PrintAsync(Stream *stream, const char *s, size_t len);
237
238 /// Convert the current input lines into a UTF8 StringList
240
242
244
245private:
246 /// Sets the lowest line number for multi-line editing sessions. A value of
247 /// zero suppresses line number printing in the prompt.
248 void SetBaseLineNumber(int line_number);
249
250 /// Returns the complete prompt by combining the prompt or continuation prompt
251 /// with line numbers as appropriate. The line index is a zero-based index
252 /// into the current multi-line session.
253 std::string PromptForIndex(int line_index);
254
255 /// Sets the current line index between line edits to allow free movement
256 /// between lines. Updates the prompt to match.
257 void SetCurrentLine(int line_index);
258
259 /// Determines the width of the prompt in characters. The width is guaranteed
260 /// to be the same for all lines of the current multi-line session.
261 size_t GetPromptWidth();
262
263 /// Returns true if the underlying EditLine session's keybindings are
264 /// Emacs-based, or false if they are VI-based.
265 bool IsEmacs();
266
267 /// Returns true if the current EditLine buffer contains nothing but spaces,
268 /// or is empty.
269 bool IsOnlySpaces();
270
271 /// Helper method used by MoveCursor to determine relative line position.
272 int GetLineIndexForLocation(CursorLocation location, int cursor_row);
273
274 /// Move the cursor from one well-established location to another using
275 /// relative line positioning and absolute column positioning.
277
278 /// Clear from cursor position to bottom of screen and print input lines
279 /// including prompts, optionally starting from a specific line. Lines are
280 /// drawn with an extra space at the end to reserve room for the rightmost
281 /// cursor position.
282 void DisplayInput(int firstIndex = 0);
283
284 /// Counts the number of rows a given line of content will end up occupying,
285 /// taking into account both the preceding prompt and a single trailing space
286 /// occupied by a cursor when at the end of the line.
287 int CountRowsForLine(const EditLineStringType &content);
288
289 /// Save the line currently being edited.
290 void SaveEditedLine();
291
292 /// Replaces the current multi-line session with the next entry from history.
293 unsigned char RecallHistory(HistoryOperation op);
294
295 /// Character reading implementation for EditLine that supports our multi-line
296 /// editing trickery.
298
299 /// Prompt implementation for EditLine.
300 const char *Prompt();
301
302 /// Line break command used when meta+return is pressed in multi-line mode.
303 unsigned char BreakLineCommand(int ch);
304
305 /// Command used when return is pressed in multi-line mode.
306 unsigned char EndOrAddLineCommand(int ch);
307
308 /// Delete command used when delete is pressed in multi-line mode.
309 unsigned char DeleteNextCharCommand(int ch);
310
311 /// Delete command used when backspace is pressed in multi-line mode.
312 unsigned char DeletePreviousCharCommand(int ch);
313
314 /// Line navigation command used when ^P or up arrow are pressed in multi-line
315 /// mode.
316 unsigned char PreviousLineCommand(int ch);
317
318 /// Line navigation command used when ^N or down arrow are pressed in
319 /// multi-line mode.
320 unsigned char NextLineCommand(int ch);
321
322 /// History navigation command used when Alt + up arrow is pressed in
323 /// multi-line mode.
324 unsigned char PreviousHistoryCommand(int ch);
325
326 /// History navigation command used when Alt + down arrow is pressed in
327 /// multi-line mode.
328 unsigned char NextHistoryCommand(int ch);
329
330 /// Buffer start command used when Esc < is typed in multi-line emacs mode.
331 unsigned char BufferStartCommand(int ch);
332
333 /// Buffer end command used when Esc > is typed in multi-line emacs mode.
334 unsigned char BufferEndCommand(int ch);
335
336 /// Context-sensitive tab insertion or code completion command used when the
337 /// tab key is typed.
338 unsigned char TabCommand(int ch);
339
340 /// Apply autosuggestion part in gray as editline.
341 unsigned char ApplyAutosuggestCommand(int ch);
342
343 /// Command used when a character is typed.
344 unsigned char TypedCharacter(int ch);
345
346 /// Respond to normal character insertion by fixing line indentation
347 unsigned char FixIndentationCommand(int ch);
348
349 /// Revert line command used when moving between lines.
350 unsigned char RevertLineCommand(int ch);
351
352 /// Ensures that the current EditLine instance is properly configured for
353 /// single or multi-line editing.
354 void ConfigureEditor(bool multiline);
355
356 bool CompleteCharacter(char ch, EditLineGetCharType &out);
357
359
360 // The following set various editline parameters. It's not any less
361 // verbose to put the editline calls into a function, but it
362 // provides type safety, since the editline functions take varargs
363 // parameters.
364 void AddFunctionToEditLine(const EditLineCharType *command,
365 const EditLineCharType *helptext,
366 EditlineCommandCallbackType callbackFn);
369
370 ::EditLine *m_editline = nullptr;
372 bool m_in_history = false;
373 std::vector<EditLineStringType> m_live_history_lines;
375 std::vector<EditLineStringType> m_input_lines;
384 std::string m_set_prompt;
386 std::string m_current_prompt;
388 volatile std::sig_atomic_t m_terminal_size_has_changed = 0;
389 std::string m_editor_name;
394
396
398 const char *m_fix_indentation_callback_chars = nullptr;
399
402
407
409 std::recursive_mutex &m_output_mutex;
410};
411}
412
413#endif // LLDB_HOST_EDITLINE_H
"lldb/Utility/ArgCompletionRequest.h"
Instances of Editline provide an abstraction over libedit's EditLine facility.
Definition: Editline.h:152
IsInputCompleteCallbackType m_is_input_complete_callback
Definition: Editline.h:395
EditorStatus m_editor_status
Definition: Editline.h:376
void SetSuggestionCallback(SuggestionCallbackType callback)
Register a callback for autosuggestion.
Definition: Editline.h:191
unsigned char PreviousLineCommand(int ch)
Line navigation command used when ^P or up arrow are pressed in multi-line mode.
Definition: Editline.cpp:779
unsigned char RecallHistory(HistoryOperation op)
Replaces the current multi-line session with the next entry from history.
Definition: Editline.cpp:458
size_t GetTerminalWidth()
Definition: Editline.h:241
bool IsOnlySpaces()
Returns true if the current EditLine buffer contains nothing but spaces, or is empty.
Definition: Editline.cpp:353
::EditLine * m_editline
Definition: Editline.h:370
void SaveEditedLine()
Save the line currently being edited.
Definition: Editline.cpp:435
void SetSuggestionAnsiSuffix(std::string suffix)
Definition: Editline.h:226
void MoveCursor(CursorLocation from, CursorLocation to)
Move the cursor from one well-established location to another using relative line positioning and abs...
Definition: Editline.cpp:384
std::string m_suggestion_ansi_suffix
Definition: Editline.h:406
void SetGetCharacterFunction(EditlineGetCharCallbackType callbackFn)
Definition: Editline.cpp:1220
void SetIsInputCompleteCallback(IsInputCompleteCallbackType callback)
Register a callback for testing whether multi-line input is complete.
Definition: Editline.h:201
std::string m_current_prompt
Definition: Editline.h:386
static void DisplayCompletions(Editline &editline, llvm::ArrayRef< CompletionResult::Completion > results)
Definition: Editline.cpp:1028
void SetAutoCompleteCallback(CompleteCallbackType callback)
Register a callback for the tab key.
Definition: Editline.h:196
std::string m_set_continuation_prompt
Definition: Editline.h:385
std::size_t m_previous_autosuggestion_size
Definition: Editline.h:408
ConnectionFileDescriptor m_input_connection
Definition: Editline.h:393
unsigned char BufferStartCommand(int ch)
Buffer start command used when Esc < is typed in multi-line emacs mode.
Definition: Editline.cpp:909
const char * Prompt()
Prompt implementation for EditLine.
Definition: Editline.cpp:612
unsigned char EndOrAddLineCommand(int ch)
Command used when return is pressed in multi-line mode.
Definition: Editline.cpp:666
unsigned char DeletePreviousCharCommand(int ch)
Delete command used when backspace is pressed in multi-line mode.
Definition: Editline.cpp:745
void SetPromptAnsiSuffix(std::string suffix)
Definition: Editline.h:218
int GetLineIndexForLocation(CursorLocation location, int cursor_row)
Helper method used by MoveCursor to determine relative line position.
Definition: Editline.cpp:363
std::string m_prompt_ansi_prefix
Definition: Editline.h:403
bool IsEmacs()
Returns true if the underlying EditLine session's keybindings are Emacs-based, or false if they are V...
Definition: Editline.cpp:347
CompleteCallbackType m_completion_callback
Definition: Editline.h:400
size_t GetPromptWidth()
Determines the width of the prompt in characters.
Definition: Editline.cpp:345
unsigned char PreviousHistoryCommand(int ch)
History navigation command used when Alt + up arrow is pressed in multi-line mode.
Definition: Editline.cpp:837
const char * m_fix_indentation_callback_chars
Definition: Editline.h:398
std::string m_editor_name
Definition: Editline.h:389
uint32_t GetCurrentLine()
Returns the index of the line currently being edited.
Definition: Editline.cpp:1549
void DisplayInput(int firstIndex=0)
Clear from cursor position to bottom of screen and print input lines including prompts,...
Definition: Editline.cpp:413
int GetCharacter(EditLineGetCharType *c)
Character reading implementation for EditLine that supports our multi-line editing trickery.
Definition: Editline.cpp:530
void TerminalSizeChanged()
Call when the terminal size changes.
Definition: Editline.cpp:1511
volatile std::sig_atomic_t m_terminal_size_has_changed
Definition: Editline.h:388
void SetEditLinePromptCallback(EditlinePromptCallbackType callbackFn)
Definition: Editline.cpp:1215
EditlineHistorySP m_history_sp
Definition: Editline.h:371
static Editline * InstanceFor(::EditLine *editline)
Uses the user data storage of EditLine to retrieve an associated instance of Editline.
Definition: Editline.cpp:1467
bool GetLine(std::string &line, bool &interrupted)
Prompts for and reads a single line of user input.
Definition: Editline.cpp:1574
std::string m_set_prompt
Definition: Editline.h:384
void SetCurrentLine(int line_index)
Sets the current line index between line edits to allow free movement between lines.
Definition: Editline.cpp:340
int CountRowsForLine(const EditLineStringType &content)
Counts the number of rows a given line of content will end up occupying, taking into account both the...
Definition: Editline.cpp:428
void ConfigureEditor(bool multiline)
Ensures that the current EditLine instance is properly configured for single or multi-line editing.
Definition: Editline.cpp:1224
unsigned char NextLineCommand(int ch)
Line navigation command used when ^N or down arrow are pressed in multi-line mode.
Definition: Editline.cpp:801
void PrintAsync(Stream *stream, const char *s, size_t len)
Definition: Editline.cpp:1653
void SetPromptAnsiPrefix(std::string prefix)
Definition: Editline.h:214
std::vector< EditLineStringType > m_live_history_lines
Definition: Editline.h:373
void SetFixIndentationCallback(FixIndentationCallbackType callback, const char *indent_chars)
Register a callback for determining the appropriate indentation for a line when creating a newline.
Definition: Editline.h:208
void AddFunctionToEditLine(const EditLineCharType *command, const EditLineCharType *helptext, EditlineCommandCallbackType callbackFn)
Definition: Editline.cpp:1209
std::vector< EditLineStringType > m_input_lines
Definition: Editline.h:375
bool CompleteCharacter(char ch, EditLineGetCharType &out)
Definition: Editline.cpp:1668
bool Cancel()
Cancel this edit and obliterate all trace of it.
Definition: Editline.cpp:1562
unsigned char DeleteNextCharCommand(int ch)
Delete command used when delete is pressed in multi-line mode.
Definition: Editline.cpp:706
std::string m_suggestion_ansi_prefix
Definition: Editline.h:405
SuggestionCallbackType m_suggestion_callback
Definition: Editline.h:401
unsigned char FixIndentationCommand(int ch)
Respond to normal character insertion by fixing line indentation.
Definition: Editline.cpp:849
unsigned char NextHistoryCommand(int ch)
History navigation command used when Alt + down arrow is pressed in multi-line mode.
Definition: Editline.cpp:843
void SetPrompt(const char *prompt)
Sets a string to be used as a prompt, or combined with a line number to form a prompt.
Definition: Editline.cpp:1502
size_t GetTerminalHeight()
Definition: Editline.h:243
unsigned char BufferEndCommand(int ch)
Buffer end command used when Esc > is typed in multi-line emacs mode.
Definition: Editline.cpp:917
unsigned char TypedCharacter(int ch)
Command used when a character is typed.
Definition: Editline.cpp:1170
unsigned char BreakLineCommand(int ch)
Line break command used when meta+return is pressed in multi-line mode.
Definition: Editline.cpp:618
void SetSuggestionAnsiPrefix(std::string prefix)
Definition: Editline.h:222
FixIndentationCallbackType m_fix_indentation_callback
Definition: Editline.h:397
unsigned char ApplyAutosuggestCommand(int ch)
Apply autosuggestion part in gray as editline.
Definition: Editline.cpp:1155
unsigned char TabCommand(int ch)
Context-sensitive tab insertion or code completion command used when the tab key is typed.
Definition: Editline.cpp:1082
std::recursive_mutex & m_output_mutex
Definition: Editline.h:409
void SetContinuationPrompt(const char *continuation_prompt)
Sets an alternate string to be used as a prompt for the second line and beyond in multi-line editing ...
Definition: Editline.cpp:1506
unsigned m_current_line_index
Definition: Editline.h:380
StringList GetInputAsStringList(int line_count=UINT32_MAX)
Convert the current input lines into a UTF8 StringList.
Definition: Editline.cpp:441
std::string PromptForIndex(int line_index)
Returns the complete prompt by combining the prompt or continuation prompt with line numbers as appro...
Definition: Editline.cpp:310
unsigned char RevertLineCommand(int ch)
Revert line command used when moving between lines.
Definition: Editline.cpp:896
bool Interrupt()
Interrupt the current edit as if ^C was pressed.
Definition: Editline.cpp:1551
const char * GetPrompt()
Returns the prompt established by SetPrompt.
Definition: Editline.cpp:1547
void SetBaseLineNumber(int line_number)
Sets the lowest line number for multi-line editing sessions.
Definition: Editline.cpp:304
bool GetLines(int first_line_number, StringList &lines, bool &interrupted)
Prompts for and reads a multi-line batch of user input.
Definition: Editline.cpp:1614
std::string m_prompt_ansi_suffix
Definition: Editline.h:404
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
#define UINT32_MAX
Definition: lldb-defines.h:19
std::stringstream EditLineStringStreamType
Definition: Editline.h:67
llvm::unique_function< void(CompletionRequest &)> CompleteCallbackType
Definition: Editline.h:102
unsigned char(*)(::EditLine *editline, int ch) EditlineCommandCallbackType
Definition: Editline.h:86
const char *(*)(::EditLine *editline) EditlinePromptCallbackType
Definition: Editline.h:87
llvm::unique_function< int(Editline *, StringList &, int)> FixIndentationCallbackType
Definition: Editline.h:97
llvm::unique_function< bool(Editline *, StringList &)> IsInputCompleteCallbackType
Definition: Editline.h:94
int(*)(::EditLine *editline, EditLineGetCharType *c) EditlineGetCharCallbackType
Definition: Editline.h:84
std::string EditLineStringType
Definition: Editline.h:66
HistoryOperation
Operation for the history.
Definition: Editline.h:139
std::shared_ptr< EditlineHistory > EditlineHistorySP
Definition: Editline.h:91
EditorStatus
Status used to decide when and how to start editing another line in multi-line sessions.
Definition: Editline.h:106
@ EndOfInput
End of input reported.
@ Complete
Editing complete, returns the complete set of edited lines.
@ Editing
The default state proceeds to edit the current line.
CursorLocation
Established locations that can be easily moved among with MoveCursor.
Definition: Editline.h:122
@ BlockEnd
The location immediately after the last character in a multi-line edit session.
@ BlockStart
The start of the first line in a multi-line edit session.
@ EditingCursor
The location of the cursor on the current line in a multi-line edit session.
@ EditingPrompt
The start of the current line in a multi-line edit session.
llvm::unique_function< std::optional< std::string >(llvm::StringRef)> SuggestionCallbackType
Definition: Editline.h:100
A class that represents a running process on the host machine.