LLDB mainline
Editline.cpp
Go to the documentation of this file.
1//===-- Editline.cpp ------------------------------------------------------===//
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#include <climits>
10#include <iomanip>
11#include <optional>
12
13#include "lldb/Host/Editline.h"
14#include "lldb/Host/HostInfo.h"
21#include "lldb/Utility/Status.h"
25#include "lldb/lldb-forward.h"
26#include "llvm/Support/ConvertUTF.h"
27
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/Locale.h"
30#include "llvm/Support/Threading.h"
31
32using namespace lldb_private;
33using namespace lldb_private::line_editor;
34
35// Editline uses careful cursor management to achieve the illusion of editing a
36// multi-line block of text with a single line editor. Preserving this
37// illusion requires fairly careful management of cursor state. Read and
38// understand the relationship between DisplayInput(), MoveCursor(),
39// SetCurrentLine(), and SaveEditedLine() before making changes.
40
41/// https://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf
42#define ESCAPE "\x1b"
43#define ANSI_CLEAR_BELOW ESCAPE "[J"
44#define ANSI_CLEAR_RIGHT ESCAPE "[K"
45#define ANSI_SET_COLUMN_N ESCAPE "[%dG"
46#define ANSI_UP_N_ROWS ESCAPE "[%dA"
47#define ANSI_DOWN_N_ROWS ESCAPE "[%dB"
48
49#if LLDB_EDITLINE_USE_WCHAR
50
51#define EditLineConstString(str) L##str
52#define EditLineStringFormatSpec "%ls"
53
54#else
55
56#define EditLineConstString(str) str
57#define EditLineStringFormatSpec "%s"
58
59// use #defines so wide version functions and structs will resolve to old
60// versions for case of libedit not built with wide char support
61#define history_w history
62#define history_winit history_init
63#define history_wend history_end
64#define HistoryW History
65#define HistEventW HistEvent
66#define LineInfoW LineInfo
67
68#define el_wgets el_gets
69#define el_wgetc el_getc
70#define el_wpush el_push
71#define el_wparse el_parse
72#define el_wset el_set
73#define el_wget el_get
74#define el_wline el_line
75#define el_winsertstr el_insertstr
76#define el_wdeletestr el_deletestr
77
78#endif // #if LLDB_EDITLINE_USE_WCHAR
79
80template <typename T> class ScopedOptional {
81public:
82 template <typename... Args>
83 ScopedOptional(std::optional<T> &optional, Args &&...args)
84 : m_optional(optional) {
85 m_optional.emplace(std::forward<Args>(args)...);
86 }
88
89private:
90 std::optional<T> &m_optional;
91};
92
93bool IsOnlySpaces(const EditLineStringType &content) {
94 for (wchar_t ch : content) {
95 if (ch != EditLineCharType(' '))
96 return false;
97 }
98 return true;
99}
100
102 // The naming used by editline for the history operations is counter
103 // intuitive to how it's used in LLDB's editline implementation.
104 //
105 // - The H_LAST returns the oldest entry in the history.
106 //
107 // - The H_PREV operation returns the previous element in the history, which
108 // is newer than the current one.
109 //
110 // - The H_CURR returns the current entry in the history.
111 //
112 // - The H_NEXT operation returns the next element in the history, which is
113 // older than the current one.
114 //
115 // - The H_FIRST returns the most recent entry in the history.
116 //
117 // The naming of the enum entries match the semantic meaning.
118 switch (op) {
120 return H_LAST;
122 return H_NEXT;
124 return H_CURR;
126 return H_PREV;
128 return H_FIRST;
129 }
130 llvm_unreachable("Fully covered switch!");
131}
132
133EditLineStringType CombineLines(const std::vector<EditLineStringType> &lines) {
134 EditLineStringStreamType combined_stream;
135 for (EditLineStringType line : lines) {
136 combined_stream << line.c_str() << "\n";
137 }
138 return combined_stream.str();
139}
140
141std::vector<EditLineStringType> SplitLines(const EditLineStringType &input) {
142 std::vector<EditLineStringType> result;
143 size_t start = 0;
144 while (start < input.length()) {
145 size_t end = input.find('\n', start);
146 if (end == std::string::npos) {
147 result.push_back(input.substr(start));
148 break;
149 }
150 result.push_back(input.substr(start, end - start));
151 start = end + 1;
152 }
153 // Treat an empty history session as a single command of zero-length instead
154 // of returning an empty vector.
155 if (result.empty()) {
156 result.emplace_back();
157 }
158 return result;
159}
160
162 int indent_correction) {
163 if (indent_correction == 0)
164 return line;
165 if (indent_correction < 0)
166 return line.substr(-indent_correction);
167 return EditLineStringType(indent_correction, EditLineCharType(' ')) + line;
168}
169
171 int space_count = 0;
172 for (EditLineCharType ch : line) {
173 if (ch != EditLineCharType(' '))
174 break;
175 ++space_count;
176 }
177 return space_count;
178}
179
180bool IsInputPending(FILE *file) {
181 // FIXME: This will be broken on Windows if we ever re-enable Editline. You
182 // can't use select
183 // on something that isn't a socket. This will have to be re-written to not
184 // use a FILE*, but instead use some kind of yet-to-be-created abstraction
185 // that select-like functionality on non-socket objects.
186 const int fd = fileno(file);
187 SelectHelper select_helper;
188 select_helper.SetTimeout(std::chrono::microseconds(0));
189 select_helper.FDSetRead(fd);
190 return select_helper.Select().Success();
191}
192
193namespace lldb_private {
194namespace line_editor {
195typedef std::weak_ptr<EditlineHistory> EditlineHistoryWP;
196
197// EditlineHistory objects are sometimes shared between multiple Editline
198// instances with the same program name.
199
201private:
202 // Use static GetHistory() function to get a EditlineHistorySP to one of
203 // these objects
204 EditlineHistory(const std::string &prefix, uint32_t size, bool unique_entries)
205 : m_prefix(prefix) {
207 history_w(m_history, &m_event, H_SETSIZE, size);
208 if (unique_entries)
209 history_w(m_history, &m_event, H_SETUNIQUE, 1);
210 }
211
212 const char *GetHistoryFilePath() {
213 // Compute the history path lazily.
214 if (m_path.empty() && m_history && !m_prefix.empty()) {
215 FileSpec lldb_dir = HostInfo::GetUserLLDBDir();
216
217 // LLDB stores its history in ~/.lldb/. If for some reason this directory
218 // isn't writable or cannot be created, history won't be available.
219 if (!llvm::sys::fs::create_directory(lldb_dir.GetPath())) {
220#if LLDB_EDITLINE_USE_WCHAR
221 std::string filename = m_prefix + "-widehistory";
222#else
223 std::string filename = m_prefix + "-history";
224#endif
225 FileSpec lldb_history_file =
226 lldb_dir.CopyByAppendingPathComponent(filename);
227 m_path = lldb_history_file.GetPath();
228 }
229 }
230
231 if (m_path.empty())
232 return nullptr;
233
234 return m_path.c_str();
235 }
236
237public:
239 Save();
240
241 if (m_history) {
243 m_history = nullptr;
244 }
245 }
246
247 static EditlineHistorySP GetHistory(const std::string &prefix) {
248 typedef std::map<std::string, EditlineHistoryWP> WeakHistoryMap;
249 static std::recursive_mutex g_mutex;
250 static WeakHistoryMap g_weak_map;
251 std::lock_guard<std::recursive_mutex> guard(g_mutex);
252 WeakHistoryMap::const_iterator pos = g_weak_map.find(prefix);
253 EditlineHistorySP history_sp;
254 if (pos != g_weak_map.end()) {
255 history_sp = pos->second.lock();
256 if (history_sp)
257 return history_sp;
258 g_weak_map.erase(pos);
259 }
260 history_sp.reset(new EditlineHistory(prefix, 800, true));
261 g_weak_map[prefix] = history_sp;
262 return history_sp;
263 }
264
265 bool IsValid() const { return m_history != nullptr; }
266
268
269 void Enter(const EditLineCharType *line_cstr) {
270 if (m_history)
271 history_w(m_history, &m_event, H_ENTER, line_cstr);
272 }
273
274 bool Load() {
275 if (m_history) {
276 const char *path = GetHistoryFilePath();
277 if (path) {
278 history_w(m_history, &m_event, H_LOAD, path);
279 return true;
280 }
281 }
282 return false;
283 }
284
285 bool Save() {
286 if (m_history) {
287 const char *path = GetHistoryFilePath();
288 if (path) {
289 history_w(m_history, &m_event, H_SAVE, path);
290 return true;
291 }
292 }
293 return false;
294 }
295
296protected:
297 /// The history object.
298 HistoryW *m_history = nullptr;
299 /// The history event needed to contain all history events.
300 HistEventW m_event;
301 /// The prefix name (usually the editline program name) to use when
302 /// loading/saving history.
303 std::string m_prefix;
304 /// Path to the history file.
305 std::string m_path;
306};
307} // namespace line_editor
308} // namespace lldb_private
309
310// Editline private methods
311
312void Editline::SetBaseLineNumber(int line_number) {
313 m_base_line_number = line_number;
315 std::max<int>(3, std::to_string(line_number).length() + 1);
316}
317
318std::string Editline::PromptForIndex(int line_index) {
319 bool use_line_numbers = m_multiline_enabled && m_base_line_number > 0;
320 std::string prompt = m_set_prompt;
321 if (use_line_numbers && prompt.length() == 0)
322 prompt = ": ";
323 std::string continuation_prompt = prompt;
324 if (m_set_continuation_prompt.length() > 0) {
325 continuation_prompt = m_set_continuation_prompt;
326 // Ensure that both prompts are the same length through space padding
327 const size_t prompt_width = ansi::ColumnWidth(prompt);
328 const size_t cont_prompt_width = ansi::ColumnWidth(continuation_prompt);
329 const size_t padded_prompt_width =
330 std::max(prompt_width, cont_prompt_width);
331 if (prompt_width < padded_prompt_width)
332 prompt += std::string(padded_prompt_width - prompt_width, ' ');
333 else if (cont_prompt_width < padded_prompt_width)
334 continuation_prompt +=
335 std::string(padded_prompt_width - cont_prompt_width, ' ');
336 }
337
338 if (use_line_numbers) {
339 StreamString prompt_stream;
340 prompt_stream.Printf(
341 "%*d%s", m_line_number_digits, m_base_line_number + line_index,
342 (line_index == 0) ? prompt.c_str() : continuation_prompt.c_str());
343 return std::string(std::move(prompt_stream.GetString()));
344 }
345 return (line_index == 0) ? prompt : continuation_prompt;
346}
347
348void Editline::SetCurrentLine(int line_index) {
349 m_current_line_index = line_index;
350 m_current_prompt = PromptForIndex(line_index);
351}
352
356
358 const char *editor;
359 el_get(m_editline, EL_EDITOR, &editor);
360 return editor[0] == 'e';
361}
362
364 const LineInfoW *info = el_wline(m_editline);
365 for (const EditLineCharType *character = info->buffer;
366 character < info->lastchar; character++) {
367 if (*character != ' ')
368 return false;
369 }
370 return true;
371}
372
374 int line = 0;
375 if (location == CursorLocation::EditingPrompt ||
376 location == CursorLocation::BlockEnd ||
377 location == CursorLocation::EditingCursor) {
378 for (unsigned index = 0; index < m_current_line_index; index++) {
379 line += CountRowsForLine(m_input_lines[index]);
380 }
381 if (location == CursorLocation::EditingCursor) {
382 line += cursor_row;
383 } else if (location == CursorLocation::BlockEnd) {
384 for (unsigned index = m_current_line_index; index < m_input_lines.size();
385 index++) {
386 line += CountRowsForLine(m_input_lines[index]);
387 }
388 --line;
389 }
390 }
391 return line;
392}
393
395 const LineInfoW *info = el_wline(m_editline);
396 int editline_cursor_position =
397 (int)((info->cursor - info->buffer) + GetPromptWidth());
398 int editline_cursor_row = editline_cursor_position / m_terminal_width;
399
400 LockedStreamFile locked_stream = m_output_stream_sp->Lock();
401
402 // Determine relative starting and ending lines
403 int fromLine = GetLineIndexForLocation(from, editline_cursor_row);
404 int toLine = GetLineIndexForLocation(to, editline_cursor_row);
405 if (toLine != fromLine) {
406 fprintf(locked_stream.GetFile().GetStream(),
407 (toLine > fromLine) ? ANSI_DOWN_N_ROWS : ANSI_UP_N_ROWS,
408 std::abs(toLine - fromLine));
409 }
410
411 // Determine target column
412 int toColumn = 1;
414 toColumn =
415 editline_cursor_position - (editline_cursor_row * m_terminal_width) + 1;
416 } else if (to == CursorLocation::BlockEnd && !m_input_lines.empty()) {
417 toColumn =
418 ((m_input_lines[m_input_lines.size() - 1].length() + GetPromptWidth()) %
419 80) +
420 1;
421 }
422 fprintf(locked_stream.GetFile().GetStream(), ANSI_SET_COLUMN_N, toColumn);
423}
424
425void Editline::DisplayInput(int firstIndex) {
426 LockedStreamFile locked_stream = m_output_stream_sp->Lock();
427 fprintf(locked_stream.GetFile().GetStream(),
429 int line_count = (int)m_input_lines.size();
430 for (int index = firstIndex; index < line_count; index++) {
431 fprintf(locked_stream.GetFile().GetStream(),
432 "%s"
433 "%s"
435 m_prompt_ansi_prefix.c_str(), PromptForIndex(index).c_str(),
436 m_prompt_ansi_suffix.c_str(), m_input_lines[index].c_str());
437 if (index < line_count - 1)
438 fprintf(locked_stream.GetFile().GetStream(), "\n");
439 }
440}
441
443 std::string prompt =
444 PromptForIndex(0); // Prompt width is constant during an edit session
445 int line_length = (int)(content.length() + ansi::ColumnWidth(prompt));
446 return (line_length / m_terminal_width) + 1;
447}
448
450 const LineInfoW *info = el_wline(m_editline);
452 EditLineStringType(info->buffer, info->lastchar - info->buffer);
453}
454
456 StringList lines;
457 for (EditLineStringType line : m_input_lines) {
458 if (line_count == 0)
459 break;
460#if LLDB_EDITLINE_USE_WCHAR
461 std::string buffer;
462 llvm::convertWideToUTF8(line, buffer);
463 lines.AppendString(buffer);
464#else
465 lines.AppendString(line);
466#endif
467 --line_count;
468 }
469 return lines;
470}
471
474 if (!m_history_sp || !m_history_sp->IsValid())
475 return CC_ERROR;
476
477 HistoryW *pHistory = m_history_sp->GetHistoryPtr();
478 HistEventW history_event;
479 std::vector<EditLineStringType> new_input_lines;
480
481 // Treat moving from the "live" entry differently
482 if (!m_in_history) {
483 switch (op) {
485 return CC_ERROR; // Can't go newer than the "live" entry
487 if (history_w(pHistory, &history_event,
489 return CC_ERROR;
490 // Save any edits to the "live" entry in case we return by moving forward
491 // in history (it would be more bash-like to save over any current entry,
492 // but libedit doesn't offer the ability to add entries anywhere except
493 // the end.)
496 m_in_history = true;
497 } break;
498 default:
499 llvm_unreachable("unsupported history direction");
500 }
501 } else {
502 if (history_w(pHistory, &history_event, GetOperation(op)) == -1) {
503 switch (op) {
505 // Can't move earlier than the earliest entry.
506 return CC_ERROR;
508 // Moving to newer-than-the-newest entry yields the "live" entry.
509 new_input_lines = m_live_history_lines;
510 m_in_history = false;
511 break;
512 default:
513 llvm_unreachable("unsupported history direction");
514 }
515 }
516 }
517
518 // If we're pulling the lines from history, split them apart
519 if (m_in_history)
520 new_input_lines = SplitLines(history_event.str);
521
522 // Erase the current edit session and replace it with a new one
524 m_input_lines = new_input_lines;
525 DisplayInput();
526
527 // Prepare to edit the last line when moving to previous entry, or the first
528 // line when moving to next entry
529 switch (op) {
531 m_current_line_index = (int)m_input_lines.size() - 1;
532 break;
535 break;
536 default:
537 llvm_unreachable("unsupported history direction");
538 }
541 return CC_NEWLINE;
542}
543
545 const LineInfoW *info = el_wline(m_editline);
546
547 // Paint a ANSI formatted version of the desired prompt over the version
548 // libedit draws. (will only be requested if colors are supported)
551 m_output_stream_sp->Lock());
553 fprintf(m_locked_output->GetFile().GetStream(),
554 "%s"
555 "%s"
556 "%s",
557 m_prompt_ansi_prefix.c_str(), Prompt(),
558 m_prompt_ansi_suffix.c_str());
561 }
562
564 // Detect when the number of rows used for this input line changes due to
565 // an edit
566 int lineLength = (int)((info->lastchar - info->buffer) + GetPromptWidth());
567 int new_line_rows = (lineLength / m_terminal_width) + 1;
568 if (m_current_line_rows != -1 && new_line_rows != m_current_line_rows) {
569 // Respond by repainting the current state from this line on
574 }
575 m_current_line_rows = new_line_rows;
576 }
577
579
580 // This mutex is locked by our caller (GetLine). Unlock it while we read a
581 // character (blocking operation), so we do not hold the mutex
582 // indefinitely. This gives a chance for someone to interrupt us. After
583 // Read returns, immediately lock the mutex again and check if we were
584 // interrupted.
585 m_locked_output.reset();
586
589
590 // Read an actual character
592 char ch = 0;
593 int read_count =
594 m_input_connection.Read(&ch, 1, std::nullopt, status, nullptr);
595
596 // Re-lock the output mutex to protected m_editor_status here and in the
597 // switch below.
598 m_locked_output.emplace(m_output_stream_sp->Lock());
600 while (read_count > 0 && status == lldb::eConnectionStatusSuccess)
601 read_count =
602 m_input_connection.Read(&ch, 1, std::nullopt, status, nullptr);
604 return 0;
605 }
606
607 if (read_count) {
608 if (CompleteCharacter(ch, *c))
609 return 1;
610 return 0;
611 }
612
613 switch (status) {
615 llvm_unreachable("Success should have resulted in positive read_count.");
617 llvm_unreachable("Interrupts should have been handled above.");
624 }
625
626 return 0;
627}
628
629const char *Editline::Prompt() {
630 if (m_color)
632 return m_current_prompt.c_str();
633}
634
635unsigned char Editline::BreakLineCommand(int ch) {
636 // Preserve any content beyond the cursor, truncate and save the current line
637 const LineInfoW *info = el_wline(m_editline);
638 auto current_line =
639 EditLineStringType(info->buffer, info->cursor - info->buffer);
640 auto new_line_fragment =
641 EditLineStringType(info->cursor, info->lastchar - info->cursor);
642 m_input_lines[m_current_line_index] = current_line;
643
644 // Ignore whitespace-only extra fragments when breaking a line
645 if (::IsOnlySpaces(new_line_fragment))
646 new_line_fragment = EditLineConstString("");
647
648 // Establish the new cursor position at the start of a line when inserting a
649 // line break
651
652 // Don't perform automatic formatting when pasting
654 // Apply smart indentation
657#if LLDB_EDITLINE_USE_WCHAR
658 std::string buffer;
659 llvm::convertWideToUTF8(new_line_fragment, buffer);
660 lines.AppendString(buffer);
661#else
662 lines.AppendString(new_line_fragment);
663#endif
664
665 int indent_correction = m_fix_indentation_callback(this, lines, 0);
666 new_line_fragment = FixIndentation(new_line_fragment, indent_correction);
667 m_revert_cursor_index = GetIndentation(new_line_fragment);
668 }
669 }
670
671 // Insert the new line and repaint everything from the split line on down
673 new_line_fragment);
676
677 // Reposition the cursor to the right line and prepare to edit the new line
680 return CC_NEWLINE;
681}
682
683unsigned char Editline::EndOrAddLineCommand(int ch) {
684 // Don't perform end of input detection when pasting, always treat this as a
685 // line break
687 return BreakLineCommand(ch);
688 }
689
690 // Save any edits to this line
692
693 // If this is the end of the last line, consider whether to add a line
694 // instead
695 const LineInfoW *info = el_wline(m_editline);
696 if (m_current_line_index == m_input_lines.size() - 1 &&
697 info->cursor == info->lastchar) {
699 auto lines = GetInputAsStringList();
700 if (!m_is_input_complete_callback(this, lines)) {
701 return BreakLineCommand(ch);
702 }
703
704 // The completion test is allowed to change the input lines when complete
705 m_input_lines.clear();
706 for (unsigned index = 0; index < lines.GetSize(); index++) {
707#if LLDB_EDITLINE_USE_WCHAR
708 std::wstring wbuffer;
709 llvm::ConvertUTF8toWide(lines[index], wbuffer);
710 m_input_lines.insert(m_input_lines.end(), wbuffer);
711#else
712 m_input_lines.insert(m_input_lines.end(), lines[index]);
713#endif
714 }
715 }
716 }
718 LockedStreamFile locked_stream = m_output_stream_sp->Lock();
719 fprintf(locked_stream.GetFile().GetStream(), "\n");
721 return CC_NEWLINE;
722}
723
724unsigned char Editline::DeleteNextCharCommand(int ch) {
725 LockedStreamFile locked_stream = m_output_stream_sp->Lock();
726 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
727
728 // Just delete the next character normally if possible
729 if (info->cursor < info->lastchar) {
730 info->cursor++;
731 el_deletestr(m_editline, 1);
732 return CC_REFRESH;
733 }
734
735 // Fail when at the end of the last line, except when ^D is pressed on the
736 // line is empty, in which case it is treated as EOF
737 if (m_current_line_index == m_input_lines.size() - 1) {
738 if (ch == 4 && info->buffer == info->lastchar) {
739 fprintf(locked_stream.GetFile().GetStream(), "^D\n");
741 return CC_EOF;
742 }
743 return CC_ERROR;
744 }
745
746 // Prepare to combine this line with the one below
748
749 // Insert the next line of text at the cursor and restore the cursor position
750 const EditLineCharType *cursor = info->cursor;
752 info->cursor = cursor;
754
755 // Delete the extra line
757
758 // Clear and repaint from this line on down
761 return CC_REFRESH;
762}
763
765 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
766
767 // Just delete the previous character normally when not at the start of a
768 // line
769 if (info->cursor > info->buffer) {
770 el_deletestr(m_editline, 1);
771 return CC_REFRESH;
772 }
773
774 // No prior line and no prior character? Let the user know
775 if (m_current_line_index == 0)
776 return CC_ERROR;
777
778 // No prior character, but prior line? Combine with the line above
781 auto priorLine = m_input_lines[m_current_line_index];
785
786 // Repaint from the new line down
787 LockedStreamFile locked_stream = m_output_stream_sp->Lock();
788 fprintf(locked_stream.GetFile().GetStream(), ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
789 CountRowsForLine(priorLine), 1);
791
792 // Put the cursor back where libedit expects it to be before returning to
793 // editing by telling libedit about the newly inserted text
795 el_winsertstr(m_editline, priorLine.c_str());
796 return CC_REDISPLAY;
797}
798
799unsigned char Editline::PreviousLineCommand(int ch) {
801
802 if (m_current_line_index == 0) {
804 }
805
806 LockedStreamFile locked_stream = m_output_stream_sp->Lock();
807
808 // Start from a known location
810
811 // Treat moving up from a blank last line as a deletion of that line
812 if (m_current_line_index == m_input_lines.size() - 1 && IsOnlySpaces()) {
814 fprintf(locked_stream.GetFile().GetStream(), ANSI_CLEAR_BELOW);
815 }
816
818 fprintf(locked_stream.GetFile().GetStream(), ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
820 return CC_NEWLINE;
821}
822
823unsigned char Editline::NextLineCommand(int ch) {
825
826 // Handle attempts to move down from the last line
827 if (m_current_line_index == m_input_lines.size() - 1) {
828 // Don't add an extra line if the existing last line is blank, move through
829 // history instead
830 if (IsOnlySpaces()) {
832 }
833
834 // Determine indentation for the new line
835 int indentation = 0;
838 lines.AppendString("");
839 indentation = m_fix_indentation_callback(this, lines, 0);
840 }
841 m_input_lines.insert(
842 m_input_lines.end(),
843 EditLineStringType(indentation, EditLineCharType(' ')));
844 }
845
846 // Move down past the current line using newlines to force scrolling if
847 // needed
849 const LineInfoW *info = el_wline(m_editline);
850 int cursor_position = (int)((info->cursor - info->buffer) + GetPromptWidth());
851 int cursor_row = cursor_position / m_terminal_width;
852
853 LockedStreamFile locked_stream = m_output_stream_sp->Lock();
854 for (int line_count = 0; line_count < m_current_line_rows - cursor_row;
855 line_count++) {
856 fprintf(locked_stream.GetFile().GetStream(), "\n");
857 }
858 return CC_NEWLINE;
859}
860
866
867unsigned char Editline::NextHistoryCommand(int ch) {
869
871}
872
873unsigned char Editline::FixIndentationCommand(int ch) {
875 return CC_NORM;
876
877 // Insert the character typed before proceeding
878 EditLineCharType inserted[] = {(EditLineCharType)ch, 0};
879 el_winsertstr(m_editline, inserted);
880 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
881 int cursor_position = info->cursor - info->buffer;
882
883 // Save the edits and determine the correct indentation level
886 int indent_correction =
887 m_fix_indentation_callback(this, lines, cursor_position);
888
889 // If it is already correct no special work is needed
890 if (indent_correction == 0)
891 return CC_REFRESH;
892
893 // Change the indentation level of the line
894 std::string currentLine = lines.GetStringAtIndex(m_current_line_index);
895 if (indent_correction > 0) {
896 currentLine = currentLine.insert(0, indent_correction, ' ');
897 } else {
898 currentLine = currentLine.erase(0, -indent_correction);
899 }
900#if LLDB_EDITLINE_USE_WCHAR
901 std::wstring wbuffer;
902 llvm::ConvertUTF8toWide(currentLine, wbuffer);
904#else
905 m_input_lines[m_current_line_index] = currentLine;
906#endif
907
908 // Update the display to reflect the change
911
912 // Reposition the cursor back on the original line and prepare to restart
913 // editing with a new cursor position
916 m_revert_cursor_index = cursor_position + indent_correction;
917 return CC_NEWLINE;
918}
919
920unsigned char Editline::RevertLineCommand(int ch) {
922 if (m_revert_cursor_index >= 0) {
923 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
924 info->cursor = info->buffer + m_revert_cursor_index;
925 if (info->cursor > info->lastchar) {
926 info->cursor = info->lastchar;
927 }
929 }
930 return CC_REFRESH;
931}
932
940
948
949/// Prints completions and their descriptions to the given file. Only the
950/// completions in the interval [start, end) are printed.
951static size_t
952PrintCompletion(FILE *output_file,
953 llvm::ArrayRef<CompletionResult::Completion> results,
954 size_t max_completion_length, size_t max_length,
955 std::optional<size_t> max_height = std::nullopt) {
956 constexpr size_t ellipsis_length = 3;
957 constexpr size_t padding_length = 8;
958 constexpr size_t separator_length = 4;
959
960 const size_t description_col =
961 std::min(max_completion_length + padding_length, max_length);
962
963 size_t lines_printed = 0;
964 size_t results_printed = 0;
965 for (const CompletionResult::Completion &c : results) {
966 if (max_height && lines_printed >= *max_height)
967 break;
968
969 results_printed++;
970
971 if (c.GetCompletion().empty())
972 continue;
973
974 // Print the leading padding.
975 fprintf(output_file, " ");
976
977 // Print the completion with trailing padding to the description column if
978 // that fits on the screen. Otherwise print whatever fits on the screen
979 // followed by ellipsis.
980 const size_t completion_length = c.GetCompletion().size();
981 if (padding_length + completion_length < max_length) {
982 fprintf(output_file, "%-*s",
983 static_cast<int>(description_col - padding_length),
984 c.GetCompletion().c_str());
985 } else {
986 // If the completion doesn't fit on the screen, print ellipsis and don't
987 // bother with the description.
988 fprintf(output_file, "%.*s...\n",
989 static_cast<int>(max_length - padding_length - ellipsis_length),
990 c.GetCompletion().c_str());
991 lines_printed++;
992 continue;
993 }
994
995 // If we don't have a description, or we don't have enough space left to
996 // print the separator followed by the ellipsis, we're done.
997 if (c.GetDescription().empty() ||
998 description_col + separator_length + ellipsis_length >= max_length) {
999 fprintf(output_file, "\n");
1000 lines_printed++;
1001 continue;
1002 }
1003
1004 // Print the separator.
1005 fprintf(output_file, " -- ");
1006
1007 // Descriptions can contain newlines. We want to print them below each
1008 // other, aligned after the separator. For example, foo has a
1009 // two-line description:
1010 //
1011 // foo -- Something that fits on the line.
1012 // More information below.
1013 //
1014 // However, as soon as a line exceed the available screen width and
1015 // print ellipsis, we don't print the next line. For example, foo has a
1016 // three-line description:
1017 //
1018 // foo -- Something that fits on the line.
1019 // Something much longer that doesn't fit...
1020 //
1021 // Because we had to print ellipsis on line two, we don't print the
1022 // third line.
1023 bool first = true;
1024 for (llvm::StringRef line : llvm::split(c.GetDescription(), '\n')) {
1025 if (line.empty())
1026 break;
1027 if (max_height && lines_printed >= *max_height)
1028 break;
1029 if (!first)
1030 fprintf(output_file, "%*s",
1031 static_cast<int>(description_col + separator_length), "");
1032
1033 first = false;
1034 const size_t position = description_col + separator_length;
1035 const size_t description_length = line.size();
1036 if (position + description_length < max_length) {
1037 fprintf(output_file, "%.*s\n", static_cast<int>(description_length),
1038 line.data());
1039 lines_printed++;
1040 } else {
1041 fprintf(output_file, "%.*s...\n",
1042 static_cast<int>(max_length - position - ellipsis_length),
1043 line.data());
1044 lines_printed++;
1045 continue;
1046 }
1047 }
1048 }
1049 return results_printed;
1050}
1051
1053 Editline &editline, llvm::ArrayRef<CompletionResult::Completion> results) {
1054 assert(!results.empty());
1055
1056 std::optional<LockedStreamFile> locked_stream =
1057 editline.m_output_stream_sp->Lock();
1058
1059 fprintf(locked_stream->GetFile().GetStream(),
1060 "\n" ANSI_CLEAR_BELOW "Available completions:\n");
1061
1062 /// Account for the current line, the line showing "Available completions"
1063 /// before and the line saying "More" after.
1064 const size_t page_size = editline.GetTerminalHeight() - 3;
1065
1066 bool all = false;
1067
1068 auto longest =
1069 std::max_element(results.begin(), results.end(), [](auto &c1, auto &c2) {
1070 return c1.GetCompletion().size() < c2.GetCompletion().size();
1071 });
1072
1073 const size_t max_len = longest->GetCompletion().size();
1074
1075 size_t cur_pos = 0;
1076 while (cur_pos < results.size()) {
1077 cur_pos += PrintCompletion(
1078 locked_stream->GetFile().GetStream(), results.slice(cur_pos), max_len,
1079 editline.GetTerminalWidth(),
1080 all ? std::nullopt : std::optional<size_t>(page_size));
1081
1082 if (cur_pos >= results.size())
1083 break;
1084
1085 fprintf(locked_stream->GetFile().GetStream(), "More (Y/n/a): ");
1086
1087 // Release the output lock across the blocking el_wgetc() so that
1088 // Interrupt(), which may run on another thread, can acquire it to wake
1089 // up the read.
1090 locked_stream.reset();
1091
1092 // The type for the output and the type for the parameter are different,
1093 // to allow interoperability with older versions of libedit. The container
1094 // for the reply must be as wide as what our implementation is using,
1095 // but libedit may use a narrower type depending on the build
1096 // configuration.
1097 EditLineGetCharType reply = L'n';
1098 int got_char = el_wgetc(editline.m_editline,
1099 reinterpret_cast<EditLineCharType *>(&reply));
1100
1101 locked_stream.emplace(editline.m_output_stream_sp->Lock());
1102
1103 // Check for a ^C or other interruption.
1106 fprintf(locked_stream->GetFile().GetStream(), "^C\n");
1107 break;
1108 }
1109
1110 fprintf(locked_stream->GetFile().GetStream(), "\n");
1111 if (got_char == -1 || reply == 'n')
1112 break;
1113 if (reply == 'a')
1114 all = true;
1115 }
1116}
1117
1118void Editline::UseColor(bool use_color) { m_color = use_color; }
1119
1120unsigned char Editline::TabCommand(int ch) {
1122 return CC_ERROR;
1123
1124 const LineInfo *line_info = el_line(m_editline);
1125
1126 llvm::StringRef line(line_info->buffer,
1127 line_info->lastchar - line_info->buffer);
1128 unsigned cursor_index = line_info->cursor - line_info->buffer;
1129 CompletionResult result;
1130 CompletionRequest request(line, cursor_index, result);
1131
1132 m_completion_callback(request);
1133
1134 llvm::ArrayRef<CompletionResult::Completion> results = result.GetResults();
1135
1136 StringList completions;
1137 result.GetMatches(completions);
1138
1139 if (results.size() == 0)
1140 return CC_ERROR;
1141
1142 if (results.size() == 1) {
1143 CompletionResult::Completion completion = results.front();
1144 switch (completion.GetMode()) {
1146 std::string to_add = completion.GetCompletion();
1147 // Terminate the current argument with a quote if it started with a quote.
1148 Args &parsedLine = request.GetParsedLine();
1149 if (!parsedLine.empty() && request.GetCursorIndex() < parsedLine.size() &&
1150 request.GetParsedArg().IsQuoted()) {
1151 to_add.push_back(request.GetParsedArg().GetQuoteChar());
1152 }
1153 to_add.push_back(' ');
1154 el_deletestr(m_editline, request.GetCursorArgumentPrefix().size());
1155 el_insertstr(m_editline, to_add.c_str());
1156 // Clear all the autosuggestion parts if the only single space can be
1157 // completed.
1158 if (to_add == " ")
1159 return CC_REDISPLAY;
1160 return CC_REFRESH;
1161 }
1163 std::string to_add = completion.GetCompletion();
1164 to_add = to_add.substr(request.GetCursorArgumentPrefix().size());
1165 el_insertstr(m_editline, to_add.c_str());
1166 break;
1167 }
1169 el_deletestr(m_editline, line_info->cursor - line_info->buffer);
1170 el_insertstr(m_editline, completion.GetCompletion().c_str());
1171 break;
1172 }
1173 }
1174 return CC_REDISPLAY;
1175 }
1176
1177 // If we get a longer match display that first.
1178 std::string longest_prefix = completions.LongestCommonPrefix();
1179 if (!longest_prefix.empty())
1180 longest_prefix =
1181 longest_prefix.substr(request.GetCursorArgumentPrefix().size());
1182 if (!longest_prefix.empty()) {
1183 el_insertstr(m_editline, longest_prefix.c_str());
1184 return CC_REDISPLAY;
1185 }
1186
1187 DisplayCompletions(*this, results);
1188
1189 DisplayInput();
1191 return CC_REDISPLAY;
1192}
1193
1195 if (!m_suggestion_callback) {
1196 return CC_REDISPLAY;
1197 }
1198
1199 const LineInfo *line_info = el_line(m_editline);
1200 llvm::StringRef line(line_info->buffer,
1201 line_info->lastchar - line_info->buffer);
1202
1203 if (std::optional<std::string> to_add = m_suggestion_callback(line))
1204 el_insertstr(m_editline, to_add->c_str());
1205
1206 return CC_REDISPLAY;
1207}
1208
1209unsigned char Editline::TypedCharacter(int ch) {
1210 std::string typed = std::string(1, ch);
1211 el_insertstr(m_editline, typed.c_str());
1212
1213 if (!m_suggestion_callback) {
1214 return CC_REDISPLAY;
1215 }
1216
1217 const LineInfo *line_info = el_line(m_editline);
1218 llvm::StringRef line(line_info->buffer,
1219 line_info->lastchar - line_info->buffer);
1220
1221 if (std::optional<std::string> to_add = m_suggestion_callback(line)) {
1222 LockedStreamFile locked_stream = m_output_stream_sp->Lock();
1223 std::string to_add_color =
1225 fputs(typed.c_str(), locked_stream.GetFile().GetStream());
1226 fputs(to_add_color.c_str(), locked_stream.GetFile().GetStream());
1227 size_t new_autosuggestion_size = line.size() + to_add->length();
1228 // Print spaces to hide any remains of a previous longer autosuggestion.
1229 if (new_autosuggestion_size < m_previous_autosuggestion_size) {
1230 size_t spaces_to_print =
1231 m_previous_autosuggestion_size - new_autosuggestion_size;
1232 std::string spaces = std::string(spaces_to_print, ' ');
1233 fputs(spaces.c_str(), locked_stream.GetFile().GetStream());
1234 }
1235 m_previous_autosuggestion_size = new_autosuggestion_size;
1236
1237 int editline_cursor_position =
1238 (int)((line_info->cursor - line_info->buffer) + GetPromptWidth());
1239 int editline_cursor_row = editline_cursor_position / m_terminal_width;
1240 int toColumn =
1241 editline_cursor_position - (editline_cursor_row * m_terminal_width);
1242 fprintf(locked_stream.GetFile().GetStream(), ANSI_SET_COLUMN_N, toColumn);
1243 return CC_REFRESH;
1244 }
1245
1246 return CC_REDISPLAY;
1247}
1248
1250 const EditLineCharType *helptext,
1251 EditlineCommandCallbackType callbackFn) {
1252 el_wset(m_editline, EL_ADDFN, command, helptext, callbackFn);
1253}
1254
1256 EditlinePromptCallbackType callbackFn) {
1257 el_set(m_editline, EL_PROMPT, callbackFn);
1258}
1259
1261 el_wset(m_editline, EL_GETCFN, callbackFn);
1262}
1263
1264void Editline::ConfigureEditor(bool multiline) {
1265 if (m_editline && m_multiline_enabled == multiline)
1266 return;
1267 m_multiline_enabled = multiline;
1268
1269 if (m_editline) {
1270 // Disable edit mode to stop the terminal from flushing all input during
1271 // the call to el_end() since we expect to have multiple editline instances
1272 // in this program.
1273 el_set(m_editline, EL_EDITMODE, 0);
1274 el_end(m_editline);
1275 }
1276
1277 LockedStreamFile locked_output_stream = m_output_stream_sp->Lock();
1278 LockedStreamFile locked_error_stream = m_output_stream_sp->Lock();
1279 m_editline = el_init(m_editor_name.c_str(), m_input_file,
1280 locked_output_stream.GetFile().GetStream(),
1281 locked_error_stream.GetFile().GetStream());
1283
1284 if (m_history_sp && m_history_sp->IsValid()) {
1285 if (!m_history_sp->Load()) {
1286 fputs("Could not load history file\n.",
1287 locked_output_stream.GetFile().GetStream());
1288 }
1289 el_wset(m_editline, EL_HIST, history, m_history_sp->GetHistoryPtr());
1290 }
1291 el_set(m_editline, EL_CLIENTDATA, this);
1292 el_set(m_editline, EL_SIGNAL, 0);
1293 el_set(m_editline, EL_EDITOR, "emacs");
1294
1295 SetGetCharacterFunction([](EditLine *editline, EditLineGetCharType *c) {
1296 return Editline::InstanceFor(editline)->GetCharacter(c);
1297 });
1298
1299 SetEditLinePromptCallback([](EditLine *editline) {
1300 return Editline::InstanceFor(editline)->Prompt();
1301 });
1302
1303 // Commands used for multiline support, registered whether or not they're
1304 // used
1306 EditLineConstString("lldb-break-line"),
1307 EditLineConstString("Insert a line break"),
1308 [](EditLine *editline, int ch) {
1309 return Editline::InstanceFor(editline)->BreakLineCommand(ch);
1310 });
1311
1313 EditLineConstString("lldb-end-or-add-line"),
1314 EditLineConstString("End editing or continue when incomplete"),
1315 [](EditLine *editline, int ch) {
1316 return Editline::InstanceFor(editline)->EndOrAddLineCommand(ch);
1317 });
1319 EditLineConstString("lldb-delete-next-char"),
1320 EditLineConstString("Delete next character"),
1321 [](EditLine *editline, int ch) {
1322 return Editline::InstanceFor(editline)->DeleteNextCharCommand(ch);
1323 });
1325 EditLineConstString("lldb-delete-previous-char"),
1326 EditLineConstString("Delete previous character"),
1327 [](EditLine *editline, int ch) {
1329 });
1331 EditLineConstString("lldb-previous-line"),
1332 EditLineConstString("Move to previous line"),
1333 [](EditLine *editline, int ch) {
1334 return Editline::InstanceFor(editline)->PreviousLineCommand(ch);
1335 });
1337 EditLineConstString("lldb-next-line"),
1338 EditLineConstString("Move to next line"), [](EditLine *editline, int ch) {
1339 return Editline::InstanceFor(editline)->NextLineCommand(ch);
1340 });
1342 EditLineConstString("lldb-previous-history"),
1343 EditLineConstString("Move to previous history"),
1344 [](EditLine *editline, int ch) {
1345 return Editline::InstanceFor(editline)->PreviousHistoryCommand(ch);
1346 });
1348 EditLineConstString("lldb-next-history"),
1349 EditLineConstString("Move to next history"),
1350 [](EditLine *editline, int ch) {
1351 return Editline::InstanceFor(editline)->NextHistoryCommand(ch);
1352 });
1354 EditLineConstString("lldb-buffer-start"),
1355 EditLineConstString("Move to start of buffer"),
1356 [](EditLine *editline, int ch) {
1357 return Editline::InstanceFor(editline)->BufferStartCommand(ch);
1358 });
1360 EditLineConstString("lldb-buffer-end"),
1361 EditLineConstString("Move to end of buffer"),
1362 [](EditLine *editline, int ch) {
1363 return Editline::InstanceFor(editline)->BufferEndCommand(ch);
1364 });
1366 EditLineConstString("lldb-fix-indentation"),
1367 EditLineConstString("Fix line indentation"),
1368 [](EditLine *editline, int ch) {
1369 return Editline::InstanceFor(editline)->FixIndentationCommand(ch);
1370 });
1371
1372 // Register the complete callback under two names for compatibility with
1373 // older clients using custom .editrc files (largely because libedit has a
1374 // bad bug where if you have a bind command that tries to bind to a function
1375 // name that doesn't exist, it can corrupt the heap and crash your process
1376 // later.)
1377 EditlineCommandCallbackType complete_callback = [](EditLine *editline,
1378 int ch) {
1379 return Editline::InstanceFor(editline)->TabCommand(ch);
1380 };
1382 EditLineConstString("Invoke completion"),
1383 complete_callback);
1385 EditLineConstString("Invoke completion"),
1386 complete_callback);
1387
1388 // General bindings we don't mind being overridden
1389 if (!multiline) {
1390 el_set(m_editline, EL_BIND, "^r", "em-inc-search-prev",
1391 NULL); // Cycle through backwards search, entering string
1392
1395 EditLineConstString("lldb-apply-complete"),
1396 EditLineConstString("Adopt autocompletion"),
1397 [](EditLine *editline, int ch) {
1398 return Editline::InstanceFor(editline)->ApplyAutosuggestCommand(ch);
1399 });
1400
1401 el_set(m_editline, EL_BIND, "^f", "lldb-apply-complete",
1402 NULL); // Apply a part that is suggested automatically
1403
1405 EditLineConstString("lldb-typed-character"),
1406 EditLineConstString("Typed character"),
1407 [](EditLine *editline, int ch) {
1408 return Editline::InstanceFor(editline)->TypedCharacter(ch);
1409 });
1410
1411 char bind_key[2] = {0, 0};
1412 llvm::StringRef ascii_chars =
1413 "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXZY1234567890!\"#$%"
1414 "&'()*+,./:;<=>?@[]_`{|}~ ";
1415 for (char c : ascii_chars) {
1416 bind_key[0] = c;
1417 el_set(m_editline, EL_BIND, bind_key, "lldb-typed-character", NULL);
1418 }
1419 el_set(m_editline, EL_BIND, "\\-", "lldb-typed-character", NULL);
1420 el_set(m_editline, EL_BIND, "\\^", "lldb-typed-character", NULL);
1421 el_set(m_editline, EL_BIND, "\\\\", "lldb-typed-character", NULL);
1422 }
1423 }
1424
1425 el_set(m_editline, EL_BIND, "^w", "ed-delete-prev-word",
1426 NULL); // Delete previous word, behave like bash in emacs mode
1427 el_set(m_editline, EL_BIND, "\t", "lldb-complete",
1428 NULL); // Bind TAB to auto complete
1429
1430 // Allow ctrl-left-arrow and ctrl-right-arrow for navigation, behave like
1431 // bash in emacs mode.
1432 el_set(m_editline, EL_BIND, ESCAPE "[1;5C", "em-next-word", NULL);
1433 el_set(m_editline, EL_BIND, ESCAPE "[1;5D", "ed-prev-word", NULL);
1434 el_set(m_editline, EL_BIND, ESCAPE "[5C", "em-next-word", NULL);
1435 el_set(m_editline, EL_BIND, ESCAPE "[5D", "ed-prev-word", NULL);
1436 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[C", "em-next-word", NULL);
1437 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[D", "ed-prev-word", NULL);
1438
1439 // Allow user-specific customization prior to registering bindings we
1440 // absolutely require
1441 el_source(m_editline, nullptr);
1442
1443 // Register an internal binding that external developers shouldn't use
1445 EditLineConstString("lldb-revert-line"),
1446 EditLineConstString("Revert line to saved state"),
1447 [](EditLine *editline, int ch) {
1448 return Editline::InstanceFor(editline)->RevertLineCommand(ch);
1449 });
1450
1451 // Register keys that perform auto-indent correction
1453 char bind_key[2] = {0, 0};
1454 const char *indent_chars = m_fix_indentation_callback_chars;
1455 while (*indent_chars) {
1456 bind_key[0] = *indent_chars;
1457 el_set(m_editline, EL_BIND, bind_key, "lldb-fix-indentation", NULL);
1458 ++indent_chars;
1459 }
1460 }
1461
1462 // Multi-line editor bindings
1463 if (multiline) {
1464 el_set(m_editline, EL_BIND, "\n", "lldb-end-or-add-line", NULL);
1465 el_set(m_editline, EL_BIND, "\r", "lldb-end-or-add-line", NULL);
1466 el_set(m_editline, EL_BIND, ESCAPE "\n", "lldb-break-line", NULL);
1467 el_set(m_editline, EL_BIND, ESCAPE "\r", "lldb-break-line", NULL);
1468 el_set(m_editline, EL_BIND, "^p", "lldb-previous-line", NULL);
1469 el_set(m_editline, EL_BIND, "^n", "lldb-next-line", NULL);
1470 el_set(m_editline, EL_BIND, "^?", "lldb-delete-previous-char", NULL);
1471 el_set(m_editline, EL_BIND, "^d", "lldb-delete-next-char", NULL);
1472 el_set(m_editline, EL_BIND, ESCAPE "[3~", "lldb-delete-next-char", NULL);
1473 el_set(m_editline, EL_BIND, ESCAPE "[\\^", "lldb-revert-line", NULL);
1474
1475 // Editor-specific bindings
1476 if (IsEmacs()) {
1477 el_set(m_editline, EL_BIND, ESCAPE "<", "lldb-buffer-start", NULL);
1478 el_set(m_editline, EL_BIND, ESCAPE ">", "lldb-buffer-end", NULL);
1479 el_set(m_editline, EL_BIND, ESCAPE "[A", "lldb-previous-line", NULL);
1480 el_set(m_editline, EL_BIND, ESCAPE "[B", "lldb-next-line", NULL);
1481 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[A", "lldb-previous-history",
1482 NULL);
1483 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[B", "lldb-next-history",
1484 NULL);
1485 el_set(m_editline, EL_BIND, ESCAPE "[1;3A", "lldb-previous-history",
1486 NULL);
1487 el_set(m_editline, EL_BIND, ESCAPE "[1;3B", "lldb-next-history", NULL);
1488 } else {
1489 el_set(m_editline, EL_BIND, "^H", "lldb-delete-previous-char", NULL);
1490
1491 el_set(m_editline, EL_BIND, "-a", ESCAPE "[A", "lldb-previous-line",
1492 NULL);
1493 el_set(m_editline, EL_BIND, "-a", ESCAPE "[B", "lldb-next-line", NULL);
1494 el_set(m_editline, EL_BIND, "-a", "x", "lldb-delete-next-char", NULL);
1495 el_set(m_editline, EL_BIND, "-a", "^H", "lldb-delete-previous-char",
1496 NULL);
1497 el_set(m_editline, EL_BIND, "-a", "^?", "lldb-delete-previous-char",
1498 NULL);
1499
1500 // Escape is absorbed exiting edit mode, so re-register important
1501 // sequences without the prefix
1502 el_set(m_editline, EL_BIND, "-a", "[A", "lldb-previous-line", NULL);
1503 el_set(m_editline, EL_BIND, "-a", "[B", "lldb-next-line", NULL);
1504 el_set(m_editline, EL_BIND, "-a", "[\\^", "lldb-revert-line", NULL);
1505 }
1506 }
1507}
1508
1509// Editline public methods
1510
1511Editline *Editline::InstanceFor(EditLine *editline) {
1512 Editline *editor;
1513 el_get(editline, EL_CLIENTDATA, &editor);
1514 return editor;
1515}
1516
1517Editline::Editline(const char *editline_name, FILE *input_file,
1518 lldb::LockableStreamFileSP output_stream_sp,
1519 lldb::LockableStreamFileSP error_stream_sp, bool color)
1521 m_output_stream_sp(output_stream_sp), m_error_stream_sp(error_stream_sp),
1522 m_input_connection(fileno(input_file), false), m_color(color) {
1523 assert(output_stream_sp && output_stream_sp->GetUnlockedFile().GetStream());
1524 assert(error_stream_sp && output_stream_sp->GetUnlockedFile().GetStream());
1525 // Get a shared history instance
1526 m_editor_name = (editline_name == nullptr) ? "lldb-tmp" : editline_name;
1528}
1529
1531 if (m_editline) {
1532 // Disable edit mode to stop the terminal from flushing all input during
1533 // the call to el_end() since we expect to have multiple editline instances
1534 // in this program.
1535 el_set(m_editline, EL_EDITMODE, 0);
1536 el_end(m_editline);
1537 m_editline = nullptr;
1538 }
1539
1540 // EditlineHistory objects are sometimes shared between multiple Editline
1541 // instances with the same program name. So just release our shared pointer
1542 // and if we are the last owner, it will save the history to the history save
1543 // file automatically.
1544 m_history_sp.reset();
1545}
1546
1547void Editline::SetPrompt(const char *prompt) {
1548 m_set_prompt = prompt == nullptr ? "" : prompt;
1549}
1550
1551void Editline::SetContinuationPrompt(const char *continuation_prompt) {
1553 continuation_prompt == nullptr ? "" : continuation_prompt;
1554}
1555
1557
1559 if (!m_editline)
1560 return;
1561
1563 el_resize(m_editline);
1564 int columns;
1565 // This function is documenting as taking (const char *, void *) for the
1566 // vararg part, but in reality in was consuming arguments until the first
1567 // null pointer. This was fixed in libedit in April 2019
1568 // <http://mail-index.netbsd.org/source-changes/2019/04/26/msg105454.html>,
1569 // but we're keeping the workaround until a version with that fix is more
1570 // widely available.
1571 if (el_get(m_editline, EL_GETTC, "co", &columns, nullptr) == 0) {
1572 m_terminal_width = columns;
1573 if (m_current_line_rows != -1) {
1574 const LineInfoW *info = el_wline(m_editline);
1575 int lineLength =
1576 (int)((info->lastchar - info->buffer) + GetPromptWidth());
1577 m_current_line_rows = (lineLength / columns) + 1;
1578 }
1579 } else {
1580 m_terminal_width = INT_MAX;
1582 }
1583
1584 int rows;
1585 if (el_get(m_editline, EL_GETTC, "li", &rows, nullptr) == 0) {
1586 m_terminal_height = rows;
1587 } else {
1588 m_terminal_height = INT_MAX;
1589 }
1590}
1591
1596
1597const char *Editline::GetPrompt() { return m_set_prompt.c_str(); }
1598
1600
1602 bool result = true;
1603 LockedStreamFile locked_stream = m_output_stream_sp->Lock();
1605 fprintf(locked_stream.GetFile().GetStream(), "^C\n");
1606 result = m_input_connection.InterruptRead();
1607 }
1609 return result;
1610}
1611
1613 bool result = true;
1614 LockedStreamFile locked_stream = m_output_stream_sp->Lock();
1617 fprintf(locked_stream.GetFile().GetStream(), ANSI_CLEAR_BELOW);
1618 result = m_input_connection.InterruptRead();
1619 }
1621 return result;
1622}
1623
1624bool Editline::GetLine(std::string &line, bool &interrupted) {
1625 ConfigureEditor(false);
1626 m_input_lines = std::vector<EditLineStringType>();
1627 m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1628
1630 m_output_stream_sp->Lock());
1631
1635 interrupted = true;
1636 return true;
1637 }
1638
1639 SetCurrentLine(0);
1640 m_in_history = false;
1643
1645 fprintf(m_locked_output->GetFile().GetStream(), "\r" ANSI_CLEAR_RIGHT);
1646
1647 int count;
1648 auto input = el_wgets(m_editline, &count);
1649
1651 if (!interrupted) {
1652 if (input == nullptr) {
1653 fprintf(m_locked_output->GetFile().GetStream(), "\n");
1655 } else {
1656 m_history_sp->Enter(input);
1657#if LLDB_EDITLINE_USE_WCHAR
1658 llvm::convertWideToUTF8(SplitLines(input)[0], line);
1659#else
1660 line = SplitLines(input)[0];
1661#endif
1663 }
1664 }
1666}
1667
1668bool Editline::GetLines(int first_line_number, StringList &lines,
1669 bool &interrupted) {
1670 ConfigureEditor(true);
1671
1672 // Print the initial input lines, then move the cursor back up to the start
1673 // of input
1674 SetBaseLineNumber(first_line_number);
1675 m_input_lines = std::vector<EditLineStringType>();
1676 m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1677
1679 m_output_stream_sp->Lock());
1680
1681 // Begin the line editing loop
1682 DisplayInput();
1683 SetCurrentLine(0);
1686 m_in_history = false;
1687
1690 int count;
1693 "\x1b[^")); // Revert to the existing line content
1694 el_wgets(m_editline, &count);
1695 }
1696
1698 if (!interrupted) {
1699 // Save the completed entry in history before returning. Don't save empty
1700 // input as that just clutters the command history.
1701 if (!m_input_lines.empty())
1702 m_history_sp->Enter(CombineLines(m_input_lines).c_str());
1703
1704 lines = GetInputAsStringList();
1705 }
1707}
1708
1710 size_t len) {
1711 LockedStreamFile locked_stream = m_output_stream_sp->Lock();
1716 fprintf(locked_stream.GetFile().GetStream(), ANSI_CLEAR_BELOW);
1717 }
1718 locked_stream.Write(s, len);
1720 DisplayInput();
1722 }
1723}
1724
1727 return;
1728 LockedStreamFile locked_stream = m_output_stream_sp->Lock();
1731 // EL_REFRESH redraws from libedit's cursor model, which is stale once the
1732 // statusline has moved the cursor, so it reprints the prompt at the wrong
1733 // column. Repaint from our own tracked position instead.
1736 DisplayInput();
1738 } else {
1739 el_set(m_editline, EL_REFRESH);
1740 }
1741}
1742
1744#if !LLDB_EDITLINE_USE_WCHAR
1745 if (ch == (char)EOF)
1746 return false;
1747
1748 out = (unsigned char)ch;
1749 return true;
1750#else
1751 llvm::SmallString<4> input;
1752 for (;;) {
1753 input.push_back(ch);
1754 auto *cur_ptr = reinterpret_cast<const llvm::UTF8 *>(input.begin());
1755 auto *end_ptr = reinterpret_cast<const llvm::UTF8 *>(input.end());
1756 llvm::UTF32 code_point = 0;
1757 llvm::ConversionResult cr = llvm::convertUTF8Sequence(
1758 &cur_ptr, end_ptr, &code_point, llvm::lenientConversion);
1759 switch (cr) {
1760 case llvm::conversionOK:
1761 out = code_point;
1762 return out != (EditLineGetCharType)WEOF;
1763 case llvm::targetExhausted:
1764 case llvm::sourceIllegal:
1765 return false;
1766 case llvm::sourceExhausted:
1768 size_t read_count = m_input_connection.Read(
1769 &ch, 1, std::chrono::seconds(0), status, nullptr);
1770 if (read_count == 0)
1771 return false;
1772 break;
1773 }
1774 }
1775#endif
1776}
#define el_wgets
Definition Editline.cpp:68
EditLineStringType CombineLines(const std::vector< EditLineStringType > &lines)
Definition Editline.cpp:133
#define EditLineConstString(str)
Definition Editline.cpp:56
#define ANSI_UP_N_ROWS
Definition Editline.cpp:46
#define el_wline
Definition Editline.cpp:74
#define EditLineStringFormatSpec
Definition Editline.cpp:57
static size_t PrintCompletion(FILE *output_file, llvm::ArrayRef< CompletionResult::Completion > results, size_t max_completion_length, size_t max_length, std::optional< size_t > max_height=std::nullopt)
Prints completions and their descriptions to the given file.
Definition Editline.cpp:952
#define LineInfoW
Definition Editline.cpp:66
EditLineStringType FixIndentation(const EditLineStringType &line, int indent_correction)
Definition Editline.cpp:161
#define ANSI_DOWN_N_ROWS
Definition Editline.cpp:47
#define history_wend
Definition Editline.cpp:63
#define el_winsertstr
Definition Editline.cpp:75
#define el_wpush
Definition Editline.cpp:70
#define history_winit
Definition Editline.cpp:62
bool IsInputPending(FILE *file)
Definition Editline.cpp:180
#define el_wgetc
Definition Editline.cpp:69
#define el_wset
Definition Editline.cpp:72
#define ANSI_CLEAR_RIGHT
Definition Editline.cpp:44
#define ANSI_SET_COLUMN_N
Definition Editline.cpp:45
std::vector< EditLineStringType > SplitLines(const EditLineStringType &input)
Definition Editline.cpp:141
#define HistoryW
Definition Editline.cpp:64
bool IsOnlySpaces(const EditLineStringType &content)
Definition Editline.cpp:93
#define history_w
Definition Editline.cpp:61
int GetIndentation(const EditLineStringType &line)
Definition Editline.cpp:170
static int GetOperation(HistoryOperation op)
Definition Editline.cpp:101
#define lldbassert(x)
Definition LLDBAssert.h:16
#define ANSI_CLEAR_BELOW
#define ESCAPE
std::optional< T > & m_optional
Definition Editline.cpp:90
ScopedOptional(std::optional< T > &optional, Args &&...args)
Definition Editline.cpp:83
lldb_private::Status Select()
void FDSetRead(lldb::socket_t fd)
void SetTimeout(const std::chrono::microseconds &timeout)
A command line argument class.
Definition Args.h:33
size_t size() const
Definition Args.h:139
bool empty() const
Definition Args.h:122
"lldb/Utility/ArgCompletionRequest.h"
llvm::StringRef GetCursorArgumentPrefix() const
const Args::ArgEntry & GetParsedArg()
A single completion and all associated data.
llvm::ArrayRef< Completion > GetResults() const
void GetMatches(StringList &matches) const
Adds all collected completion matches to the given list.
IsInputCompleteCallbackType m_is_input_complete_callback
Definition Editline.h:431
EditorStatus m_editor_status
Definition Editline.h:409
std::optional< LockedStreamFile > m_locked_output
Definition Editline.h:427
lldb::LockableStreamFileSP m_output_stream_sp
Definition Editline.h:424
unsigned char PreviousLineCommand(int ch)
Line navigation command used when ^P or up arrow are pressed in multi-line mode.
Definition Editline.cpp:799
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:403
void SaveEditedLine()
Save the line currently being edited.
Definition Editline.cpp:449
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:444
void SetGetCharacterFunction(EditlineGetCharCallbackType callbackFn)
std::string m_current_prompt
Definition Editline.h:419
static void DisplayCompletions(Editline &editline, llvm::ArrayRef< CompletionResult::Completion > results)
std::string m_set_continuation_prompt
Definition Editline.h:418
std::size_t m_previous_autosuggestion_size
Definition Editline.h:446
ConnectionFileDescriptor m_input_connection
Definition Editline.h:429
unsigned char BufferStartCommand(int ch)
Buffer start command used when Esc < is typed in multi-line emacs mode.
Definition Editline.cpp:933
const char * Prompt()
Prompt implementation for EditLine.
Definition Editline.cpp:629
unsigned char EndOrAddLineCommand(int ch)
Command used when return is pressed in multi-line mode.
Definition Editline.cpp:683
unsigned char DeletePreviousCharCommand(int ch)
Delete command used when backspace is pressed in multi-line mode.
Definition Editline.cpp:764
int GetLineIndexForLocation(CursorLocation location, int cursor_row)
Helper method used by MoveCursor to determine relative line position.
Definition Editline.cpp:373
std::string m_prompt_ansi_prefix
Definition Editline.h:441
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:436
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:861
const char * m_fix_indentation_callback_chars
Definition Editline.h:434
std::string m_editor_name
Definition Editline.h:422
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:421
void SetEditLinePromptCallback(EditlinePromptCallbackType callbackFn)
EditlineHistorySP m_history_sp
Definition Editline.h:404
void ApplyPendingTerminalSizeChange()
Apply a resize signaled by TerminalSizeChanged() if one is pending.
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:417
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:823
std::vector< EditLineStringType > m_live_history_lines
Definition Editline.h:406
lldb::LockableStreamFileSP m_error_stream_sp
Definition Editline.h:425
void AddFunctionToEditLine(const EditLineCharType *command, const EditLineCharType *helptext, EditlineCommandCallbackType callbackFn)
std::vector< EditLineStringType > m_input_lines
Definition Editline.h:408
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:724
std::string m_suggestion_ansi_prefix
Definition Editline.h:443
SuggestionCallbackType m_suggestion_callback
Definition Editline.h:437
unsigned char FixIndentationCommand(int ch)
Respond to normal character insertion by fixing line indentation.
Definition Editline.cpp:873
unsigned char NextHistoryCommand(int ch)
History navigation command used when Alt + down arrow is pressed in multi-line mode.
Definition Editline.cpp:867
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:941
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:635
void UseColor(bool use_color)
Sets if editline should use color.
RedrawCallbackType m_redraw_callback
Definition Editline.h:438
FixIndentationCallbackType m_fix_indentation_callback
Definition Editline.h:433
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:413
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:920
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:442
A file utility class.
Definition FileSpec.h:57
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
Definition FileSpec.cpp:421
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
virtual FILE * GetStream()
Get the underlying libc stream for this file, or NULL.
Definition File.cpp:121
bool Success() const
Test for success condition.
Definition Status.cpp:303
llvm::StringRef GetString() const
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
Definition Stream.h:111
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
void AppendString(const std::string &s)
const char * GetStringAtIndex(size_t idx) const
std::string LongestCommonPrefix()
void Enter(const EditLineCharType *line_cstr)
Definition Editline.cpp:269
std::string m_path
Path to the history file.
Definition Editline.cpp:305
std::string m_prefix
The prefix name (usually the editline program name) to use when loading/saving history.
Definition Editline.cpp:303
HistoryW * m_history
The history object.
Definition Editline.cpp:298
EditlineHistory(const std::string &prefix, uint32_t size, bool unique_entries)
Definition Editline.cpp:204
static EditlineHistorySP GetHistory(const std::string &prefix)
Definition Editline.cpp:247
HistEventW m_event
The history event needed to contain all history events.
Definition Editline.cpp:300
size_t ColumnWidth(llvm::StringRef str)
std::weak_ptr< EditlineHistory > EditlineHistoryWP
Definition Editline.cpp:195
std::shared_ptr< EditlineHistory > EditlineHistorySP
Definition Editline.h:92
std::stringstream EditLineStringStreamType
Definition Editline.h:68
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
A class that represents a running process on the host machine.
@ Partial
The current token has been partially completed.
@ Normal
The current token has been completed.
@ RewriteLine
The full line has been rewritten by the completion.
ConnectionStatus
Connection Status Types.
@ eConnectionStatusError
Check GetError() for details.
@ eConnectionStatusInterrupted
Interrupted read.
@ eConnectionStatusTimedOut
Request timed out.
@ eConnectionStatusEndOfFile
End-of-file encountered.
@ eConnectionStatusSuccess
Success.
@ eConnectionStatusLostConnection
Lost connection while connected to a valid connection.
@ eConnectionStatusNoConnection
No connection.
std::shared_ptr< lldb_private::LockableStreamFile > LockableStreamFileSP
bool IsQuoted() const
Returns true if this argument was quoted in any way.
Definition Args.h:54
char GetQuoteChar() const
Definition Args.h:55