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
38#include "lldb/lldb-private.h"
39
40#if !defined(_WIN32) && !defined(__ANDROID__)
41#include <histedit.h>
42#endif
43
44#include <csignal>
45#include <mutex>
46#include <optional>
47#include <string>
48#include <vector>
49
55
56#include "llvm/ADT/FunctionExtras.h"
57
58namespace lldb_private {
59namespace line_editor {
60
61// type alias's to help manage 8 bit and wide character versions of libedit
62#if LLDB_EDITLINE_USE_WCHAR
63using EditLineStringType = std::wstring;
64using EditLineStringStreamType = std::wstringstream;
65using EditLineCharType = wchar_t;
66#else
67using EditLineStringType = std::string;
68using EditLineStringStreamType = std::stringstream;
69using EditLineCharType = char;
70#endif
71
72// At one point the callback type of el_set getchar callback changed from char
73// to wchar_t. It is not possible to detect differentiate between the two
74// versions exactly, but this is a pretty good approximation and allows us to
75// build against almost any editline version out there.
76// It does, however, require extra care when invoking el_getc, as the type
77// of the input is a single char buffer, but the callback will write a wchar_t.
78#if LLDB_EDITLINE_USE_WCHAR || defined(EL_CLIENTDATA) || LLDB_HAVE_EL_RFUNC_T
79using EditLineGetCharType = wchar_t;
80#else
82#endif
83
84using EditlineGetCharCallbackType = int (*)(::EditLine *editline,
86using EditlineCommandCallbackType = unsigned char (*)(::EditLine *editline,
87 int ch);
88using EditlinePromptCallbackType = const char *(*)(::EditLine *editline);
89
90class EditlineHistory;
91
92using EditlineHistorySP = std::shared_ptr<EditlineHistory>;
93
95 llvm::unique_function<bool(Editline *, StringList &)>;
96
98 llvm::unique_function<int(Editline *, StringList &, int)>;
99
101 llvm::unique_function<std::optional<std::string>(llvm::StringRef)>;
102
103using CompleteCallbackType = llvm::unique_function<void(CompletionRequest &)>;
104
105using RedrawCallbackType = llvm::unique_function<void()>;
106
107/// Status used to decide when and how to start editing another line in
108/// multi-line sessions.
109enum class EditorStatus {
110
111 /// The default state proceeds to edit the current line.
113
114 /// Editing complete, returns the complete set of edited lines.
116
117 /// End of input reported.
119
120 /// Editing interrupted.
122};
123
124/// Established locations that can be easily moved among with MoveCursor.
125enum class CursorLocation {
126 /// The start of the first line in a multi-line edit session.
128
129 /// The start of the current line in a multi-line edit session.
131
132 /// The location of the cursor on the current line in a multi-line edit
133 /// session.
135
136 /// The location immediately after the last character in a multi-line edit
137 /// session.
139};
140
141/// Operation for the history.
149}
150
151using namespace line_editor;
152
153/// Instances of Editline provide an abstraction over libedit's EditLine
154/// facility. Both single- and multi-line editing are supported.
155class Editline {
156public:
157 Editline(const char *editor_name, FILE *input_file,
158 lldb::LockableStreamFileSP output_stream_sp,
159 lldb::LockableStreamFileSP error_stream_sp, bool color);
160
161 ~Editline();
162
163 /// Uses the user data storage of EditLine to retrieve an associated instance
164 /// of Editline.
165 static Editline *InstanceFor(::EditLine *editline);
166
167 static void
169 llvm::ArrayRef<CompletionResult::Completion> results);
170
171 /// Sets if editline should use color.
172 void UseColor(bool use_color);
173
174 /// Sets a string to be used as a prompt, or combined with a line number to
175 /// form a prompt.
176 void SetPrompt(const char *prompt);
177
178 /// Sets an alternate string to be used as a prompt for the second line and
179 /// beyond in multi-line editing scenarios.
180 void SetContinuationPrompt(const char *continuation_prompt);
181
182 /// Call when the terminal size changes.
183 void TerminalSizeChanged();
184
185 /// Returns the prompt established by SetPrompt.
186 const char *GetPrompt();
187
188 /// Returns the index of the line currently being edited.
189 uint32_t GetCurrentLine();
190
191 /// Interrupt the current edit as if ^C was pressed.
192 bool Interrupt();
193
194 /// Cancel this edit and obliterate all trace of it.
195 bool Cancel();
196
197 /// Register a callback for autosuggestion.
199 m_suggestion_callback = std::move(callback);
200 }
201
202 /// Register a callback for redrawing the statusline.
204 m_redraw_callback = std::move(callback);
205 }
206
207 /// Register a callback for the tab key
209 m_completion_callback = std::move(callback);
210 }
211
212 /// Register a callback for testing whether multi-line input is complete
216
217 /// Register a callback for determining the appropriate indentation for a line
218 /// when creating a newline. An optional set of insertable characters can
219 /// also trigger the callback.
221 const char *indent_chars) {
222 m_fix_indentation_callback = std::move(callback);
224 }
225
226 void SetPromptAnsiPrefix(std::string prefix) {
227 if (m_color)
228 m_prompt_ansi_prefix = std::move(prefix);
229 else
230 m_prompt_ansi_prefix.clear();
231 }
232
233 void SetPromptAnsiSuffix(std::string suffix) {
234 if (m_color)
235 m_prompt_ansi_suffix = std::move(suffix);
236 else
237 m_prompt_ansi_suffix.clear();
238 }
239
240 void SetSuggestionAnsiPrefix(std::string prefix) {
241 if (m_color)
242 m_suggestion_ansi_prefix = std::move(prefix);
243 else
245 }
246
247 void SetSuggestionAnsiSuffix(std::string suffix) {
248 if (m_color)
249 m_suggestion_ansi_suffix = std::move(suffix);
250 else
252 }
253
254 /// Prompts for and reads a single line of user input.
255 bool GetLine(std::string &line, bool &interrupted);
256
257 /// Prompts for and reads a multi-line batch of user input.
258 bool GetLines(int first_line_number, StringList &lines, bool &interrupted);
259
260 void PrintAsync(lldb::LockableStreamFileSP stream_sp, const char *s,
261 size_t len);
262
263 /// Convert the current input lines into a UTF8 StringList
265
267
269
270 void Refresh();
271
272private:
273 /// Sets the lowest line number for multi-line editing sessions. A value of
274 /// zero suppresses line number printing in the prompt.
275 void SetBaseLineNumber(int line_number);
276
277 /// Returns the complete prompt by combining the prompt or continuation prompt
278 /// with line numbers as appropriate. The line index is a zero-based index
279 /// into the current multi-line session.
280 std::string PromptForIndex(int line_index);
281
282 /// Sets the current line index between line edits to allow free movement
283 /// between lines. Updates the prompt to match.
284 void SetCurrentLine(int line_index);
285
286 /// Determines the width of the prompt in characters. The width is guaranteed
287 /// to be the same for all lines of the current multi-line session.
288 size_t GetPromptWidth();
289
290 /// Returns true if the underlying EditLine session's keybindings are
291 /// Emacs-based, or false if they are VI-based.
292 bool IsEmacs();
293
294 /// Returns true if the current EditLine buffer contains nothing but spaces,
295 /// or is empty.
296 bool IsOnlySpaces();
297
298 /// Helper method used by MoveCursor to determine relative line position.
299 int GetLineIndexForLocation(CursorLocation location, int cursor_row);
300
301 /// Move the cursor from one well-established location to another using
302 /// relative line positioning and absolute column positioning.
304
305 /// Clear from cursor position to bottom of screen and print input lines
306 /// including prompts, optionally starting from a specific line. Lines are
307 /// drawn with an extra space at the end to reserve room for the rightmost
308 /// cursor position.
309 void DisplayInput(int firstIndex = 0);
310
311 /// Counts the number of rows a given line of content will end up occupying,
312 /// taking into account both the preceding prompt and a single trailing space
313 /// occupied by a cursor when at the end of the line.
314 int CountRowsForLine(const EditLineStringType &content);
315
316 /// Save the line currently being edited.
317 void SaveEditedLine();
318
319 /// Replaces the current multi-line session with the next entry from history.
320 unsigned char RecallHistory(HistoryOperation op);
321
322 /// Character reading implementation for EditLine that supports our multi-line
323 /// editing trickery.
325
326 /// Prompt implementation for EditLine.
327 const char *Prompt();
328
329 /// Line break command used when meta+return is pressed in multi-line mode.
330 unsigned char BreakLineCommand(int ch);
331
332 /// Command used when return is pressed in multi-line mode.
333 unsigned char EndOrAddLineCommand(int ch);
334
335 /// Delete command used when delete is pressed in multi-line mode.
336 unsigned char DeleteNextCharCommand(int ch);
337
338 /// Delete command used when backspace is pressed in multi-line mode.
339 unsigned char DeletePreviousCharCommand(int ch);
340
341 /// Line navigation command used when ^P or up arrow are pressed in multi-line
342 /// mode.
343 unsigned char PreviousLineCommand(int ch);
344
345 /// Line navigation command used when ^N or down arrow are pressed in
346 /// multi-line mode.
347 unsigned char NextLineCommand(int ch);
348
349 /// History navigation command used when Alt + up arrow is pressed in
350 /// multi-line mode.
351 unsigned char PreviousHistoryCommand(int ch);
352
353 /// History navigation command used when Alt + down arrow is pressed in
354 /// multi-line mode.
355 unsigned char NextHistoryCommand(int ch);
356
357 /// Buffer start command used when Esc < is typed in multi-line emacs mode.
358 unsigned char BufferStartCommand(int ch);
359
360 /// Buffer end command used when Esc > is typed in multi-line emacs mode.
361 unsigned char BufferEndCommand(int ch);
362
363 /// Context-sensitive tab insertion or code completion command used when the
364 /// tab key is typed.
365 unsigned char TabCommand(int ch);
366
367 /// Apply autosuggestion part in gray as editline.
368 unsigned char ApplyAutosuggestCommand(int ch);
369
370 /// Command used when a character is typed.
371 unsigned char TypedCharacter(int ch);
372
373 /// Respond to normal character insertion by fixing line indentation
374 unsigned char FixIndentationCommand(int ch);
375
376 /// Revert line command used when moving between lines.
377 unsigned char RevertLineCommand(int ch);
378
379 /// Ensures that the current EditLine instance is properly configured for
380 /// single or multi-line editing.
381 void ConfigureEditor(bool multiline);
382
383 bool CompleteCharacter(char ch, EditLineGetCharType &out);
384
386
387 // The following set various editline parameters. It's not any less
388 // verbose to put the editline calls into a function, but it
389 // provides type safety, since the editline functions take varargs
390 // parameters.
391 void AddFunctionToEditLine(const EditLineCharType *command,
392 const EditLineCharType *helptext,
393 EditlineCommandCallbackType callbackFn);
396
397 ::EditLine *m_editline = nullptr;
399 bool m_in_history = false;
400 std::vector<EditLineStringType> m_live_history_lines;
402 std::vector<EditLineStringType> m_input_lines;
411 std::string m_set_prompt;
413 std::string m_current_prompt;
415 volatile std::sig_atomic_t m_terminal_size_has_changed = 0;
416 std::string m_editor_name;
420
421 std::optional<LockedStreamFile> m_locked_output;
422
424
426
428 const char *m_fix_indentation_callback_chars = nullptr;
429
433
439
441};
442}
443
444#endif // LLDB_HOST_EDITLINE_H
"lldb/Utility/ArgCompletionRequest.h"
Instances of Editline provide an abstraction over libedit's EditLine facility.
Definition Editline.h:155
IsInputCompleteCallbackType m_is_input_complete_callback
Definition Editline.h:425
EditorStatus m_editor_status
Definition Editline.h:403
std::optional< LockedStreamFile > m_locked_output
Definition Editline.h:421
void SetSuggestionCallback(SuggestionCallbackType callback)
Register a callback for autosuggestion.
Definition Editline.h:198
lldb::LockableStreamFileSP m_output_stream_sp
Definition Editline.h:418
unsigned char PreviousLineCommand(int ch)
Line navigation command used when ^P or up arrow are pressed in multi-line mode.
Definition Editline.cpp:800
unsigned char RecallHistory(HistoryOperation op)
Replaces the current multi-line session with the next entry from history.
Definition Editline.cpp:472
size_t GetTerminalWidth()
Definition Editline.h:266
bool IsOnlySpaces()
Returns true if the current EditLine buffer contains nothing but spaces, or is empty.
Definition Editline.cpp:363
::EditLine * m_editline
Definition Editline.h:397
void SaveEditedLine()
Save the line currently being edited.
Definition Editline.cpp:449
void SetSuggestionAnsiSuffix(std::string suffix)
Definition Editline.h:247
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:394
std::string m_suggestion_ansi_suffix
Definition Editline.h:438
void SetGetCharacterFunction(EditlineGetCharCallbackType callbackFn)
void SetIsInputCompleteCallback(IsInputCompleteCallbackType callback)
Register a callback for testing whether multi-line input is complete.
Definition Editline.h:213
std::string m_current_prompt
Definition Editline.h:413
static void DisplayCompletions(Editline &editline, llvm::ArrayRef< CompletionResult::Completion > results)
void SetAutoCompleteCallback(CompleteCallbackType callback)
Register a callback for the tab key.
Definition Editline.h:208
std::string m_set_continuation_prompt
Definition Editline.h:412
std::size_t m_previous_autosuggestion_size
Definition Editline.h:440
ConnectionFileDescriptor m_input_connection
Definition Editline.h:423
unsigned char BufferStartCommand(int ch)
Buffer start command used when Esc < is typed in multi-line emacs mode.
Definition Editline.cpp:934
const char * Prompt()
Prompt implementation for EditLine.
Definition Editline.cpp:630
unsigned char EndOrAddLineCommand(int ch)
Command used when return is pressed in multi-line mode.
Definition Editline.cpp:684
unsigned char DeletePreviousCharCommand(int ch)
Delete command used when backspace is pressed in multi-line mode.
Definition Editline.cpp:765
void SetPromptAnsiSuffix(std::string suffix)
Definition Editline.h:233
int GetLineIndexForLocation(CursorLocation location, int cursor_row)
Helper method used by MoveCursor to determine relative line position.
Definition Editline.cpp:373
void SetRedrawCallback(RedrawCallbackType callback)
Register a callback for redrawing the statusline.
Definition Editline.h:203
std::string m_prompt_ansi_prefix
Definition Editline.h:435
bool IsEmacs()
Returns true if the underlying EditLine session's keybindings are Emacs-based, or false if they are V...
Definition Editline.cpp:357
CompleteCallbackType m_completion_callback
Definition Editline.h:430
size_t GetPromptWidth()
Determines the width of the prompt in characters.
Definition Editline.cpp:353
unsigned char PreviousHistoryCommand(int ch)
History navigation command used when Alt + up arrow is pressed in multi-line mode.
Definition Editline.cpp:862
const char * m_fix_indentation_callback_chars
Definition Editline.h:428
std::string m_editor_name
Definition Editline.h:416
uint32_t GetCurrentLine()
Returns the index of the line currently being edited.
void DisplayInput(int firstIndex=0)
Clear from cursor position to bottom of screen and print input lines including prompts,...
Definition Editline.cpp:425
int GetCharacter(EditLineGetCharType *c)
Character reading implementation for EditLine that supports our multi-line editing trickery.
Definition Editline.cpp:544
Editline(const char *editor_name, FILE *input_file, lldb::LockableStreamFileSP output_stream_sp, lldb::LockableStreamFileSP error_stream_sp, bool color)
void TerminalSizeChanged()
Call when the terminal size changes.
volatile std::sig_atomic_t m_terminal_size_has_changed
Definition Editline.h:415
void SetEditLinePromptCallback(EditlinePromptCallbackType callbackFn)
EditlineHistorySP m_history_sp
Definition Editline.h:398
static Editline * InstanceFor(::EditLine *editline)
Uses the user data storage of EditLine to retrieve an associated instance of Editline.
bool GetLine(std::string &line, bool &interrupted)
Prompts for and reads a single line of user input.
std::string m_set_prompt
Definition Editline.h:411
void SetCurrentLine(int line_index)
Sets the current line index between line edits to allow free movement between lines.
Definition Editline.cpp:348
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:442
void PrintAsync(lldb::LockableStreamFileSP stream_sp, const char *s, size_t len)
void ConfigureEditor(bool multiline)
Ensures that the current EditLine instance is properly configured for single or multi-line editing.
unsigned char NextLineCommand(int ch)
Line navigation command used when ^N or down arrow are pressed in multi-line mode.
Definition Editline.cpp:824
void SetPromptAnsiPrefix(std::string prefix)
Definition Editline.h:226
std::vector< EditLineStringType > m_live_history_lines
Definition Editline.h:400
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:220
lldb::LockableStreamFileSP m_error_stream_sp
Definition Editline.h:419
void AddFunctionToEditLine(const EditLineCharType *command, const EditLineCharType *helptext, EditlineCommandCallbackType callbackFn)
std::vector< EditLineStringType > m_input_lines
Definition Editline.h:402
bool CompleteCharacter(char ch, EditLineGetCharType &out)
bool Cancel()
Cancel this edit and obliterate all trace of it.
unsigned char DeleteNextCharCommand(int ch)
Delete command used when delete is pressed in multi-line mode.
Definition Editline.cpp:725
std::string m_suggestion_ansi_prefix
Definition Editline.h:437
SuggestionCallbackType m_suggestion_callback
Definition Editline.h:431
unsigned char FixIndentationCommand(int ch)
Respond to normal character insertion by fixing line indentation.
Definition Editline.cpp:874
unsigned char NextHistoryCommand(int ch)
History navigation command used when Alt + down arrow is pressed in multi-line mode.
Definition Editline.cpp:868
void SetPrompt(const char *prompt)
Sets a string to be used as a prompt, or combined with a line number to form a prompt.
size_t GetTerminalHeight()
Definition Editline.h:268
unsigned char BufferEndCommand(int ch)
Buffer end command used when Esc > is typed in multi-line emacs mode.
Definition Editline.cpp:942
unsigned char TypedCharacter(int ch)
Command used when a character is typed.
unsigned char BreakLineCommand(int ch)
Line break command used when meta+return is pressed in multi-line mode.
Definition Editline.cpp:636
void UseColor(bool use_color)
Sets if editline should use color.
void SetSuggestionAnsiPrefix(std::string prefix)
Definition Editline.h:240
RedrawCallbackType m_redraw_callback
Definition Editline.h:432
FixIndentationCallbackType m_fix_indentation_callback
Definition Editline.h:427
unsigned char ApplyAutosuggestCommand(int ch)
Apply autosuggestion part in gray as editline.
unsigned char TabCommand(int ch)
Context-sensitive tab insertion or code completion command used when the tab key is typed.
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 ...
unsigned m_current_line_index
Definition Editline.h:407
StringList GetInputAsStringList(int line_count=UINT32_MAX)
Convert the current input lines into a UTF8 StringList.
Definition Editline.cpp:455
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:318
unsigned char RevertLineCommand(int ch)
Revert line command used when moving between lines.
Definition Editline.cpp:921
bool Interrupt()
Interrupt the current edit as if ^C was pressed.
const char * GetPrompt()
Returns the prompt established by SetPrompt.
void SetBaseLineNumber(int line_number)
Sets the lowest line number for multi-line editing sessions.
Definition Editline.cpp:312
bool GetLines(int first_line_number, StringList &lines, bool &interrupted)
Prompts for and reads a multi-line batch of user input.
std::string m_prompt_ansi_suffix
Definition Editline.h:436
#define UINT32_MAX
std::shared_ptr< EditlineHistory > EditlineHistorySP
Definition Editline.h:92
std::stringstream EditLineStringStreamType
Definition Editline.h:68
llvm::unique_function< bool(Editline *, StringList &)> IsInputCompleteCallbackType
Definition Editline.h:94
llvm::unique_function< void(CompletionRequest &)> CompleteCallbackType
Definition Editline.h:103
llvm::unique_function< void()> RedrawCallbackType
Definition Editline.h:105
llvm::unique_function< std::optional< std::string >(llvm::StringRef)> SuggestionCallbackType
Definition Editline.h:100
unsigned char(*)(::EditLine *editline, int ch) EditlineCommandCallbackType
Definition Editline.h:86
HistoryOperation
Operation for the history.
Definition Editline.h:142
EditorStatus
Status used to decide when and how to start editing another line in multi-line sessions.
Definition Editline.h:109
@ Interrupted
Editing interrupted.
Definition Editline.h:121
@ EndOfInput
End of input reported.
Definition Editline.h:118
@ Complete
Editing complete, returns the complete set of edited lines.
Definition Editline.h:115
@ Editing
The default state proceeds to edit the current line.
Definition Editline.h:112
std::string EditLineStringType
Definition Editline.h:67
const char *(*)(::EditLine *editline) EditlinePromptCallbackType
Definition Editline.h:88
CursorLocation
Established locations that can be easily moved among with MoveCursor.
Definition Editline.h:125
@ BlockEnd
The location immediately after the last character in a multi-line edit session.
Definition Editline.h:138
@ BlockStart
The start of the first line in a multi-line edit session.
Definition Editline.h:127
@ EditingCursor
The location of the cursor on the current line in a multi-line edit session.
Definition Editline.h:134
@ EditingPrompt
The start of the current line in a multi-line edit session.
Definition Editline.h:130
int(*)(::EditLine *editline, EditLineGetCharType *c) EditlineGetCharCallbackType
Definition Editline.h:84
llvm::unique_function< int(Editline *, StringList &, int)> FixIndentationCallbackType
Definition Editline.h:97
A class that represents a running process on the host machine.
std::shared_ptr< lldb_private::LockableStreamFile > LockableStreamFileSP