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
17#include "lldb/Host/Host.h"
22#include "lldb/Utility/Status.h"
26
27#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/Locale.h"
29#include "llvm/Support/Threading.h"
30
31using namespace lldb_private;
32using namespace lldb_private::line_editor;
33
34// Workaround for what looks like an OS X-specific issue, but other platforms
35// may benefit from something similar if issues arise. The libedit library
36// doesn't explicitly initialize the curses termcap library, which it gets away
37// with until TERM is set to VT100 where it stumbles over an implementation
38// assumption that may not exist on other platforms. The setupterm() function
39// would normally require headers that don't work gracefully in this context,
40// so the function declaration has been hoisted here.
41#if defined(__APPLE__)
42extern "C" {
43int setupterm(char *term, int fildes, int *errret);
44}
45#define USE_SETUPTERM_WORKAROUND
46#endif
47
48// Editline uses careful cursor management to achieve the illusion of editing a
49// multi-line block of text with a single line editor. Preserving this
50// illusion requires fairly careful management of cursor state. Read and
51// understand the relationship between DisplayInput(), MoveCursor(),
52// SetCurrentLine(), and SaveEditedLine() before making changes.
53
54/// https://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf
55#define ESCAPE "\x1b"
56#define ANSI_CLEAR_BELOW ESCAPE "[J"
57#define ANSI_CLEAR_RIGHT ESCAPE "[K"
58#define ANSI_SET_COLUMN_N ESCAPE "[%dG"
59#define ANSI_UP_N_ROWS ESCAPE "[%dA"
60#define ANSI_DOWN_N_ROWS ESCAPE "[%dB"
61
62#if LLDB_EDITLINE_USE_WCHAR
63
64#define EditLineConstString(str) L##str
65#define EditLineStringFormatSpec "%ls"
66
67#else
68
69#define EditLineConstString(str) str
70#define EditLineStringFormatSpec "%s"
71
72// use #defines so wide version functions and structs will resolve to old
73// versions for case of libedit not built with wide char support
74#define history_w history
75#define history_winit history_init
76#define history_wend history_end
77#define HistoryW History
78#define HistEventW HistEvent
79#define LineInfoW LineInfo
80
81#define el_wgets el_gets
82#define el_wgetc el_getc
83#define el_wpush el_push
84#define el_wparse el_parse
85#define el_wset el_set
86#define el_wget el_get
87#define el_wline el_line
88#define el_winsertstr el_insertstr
89#define el_wdeletestr el_deletestr
90
91#endif // #if LLDB_EDITLINE_USE_WCHAR
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
101static size_t ColumnWidth(llvm::StringRef str) {
102 return llvm::sys::locale::columnWidth(str);
103}
104
106 // The naming used by editline for the history operations is counter
107 // intuitive to how it's used in LLDB's editline implementation.
108 //
109 // - The H_LAST returns the oldest entry in the history.
110 //
111 // - The H_PREV operation returns the previous element in the history, which
112 // is newer than the current one.
113 //
114 // - The H_CURR returns the current entry in the history.
115 //
116 // - The H_NEXT operation returns the next element in the history, which is
117 // older than the current one.
118 //
119 // - The H_FIRST returns the most recent entry in the history.
120 //
121 // The naming of the enum entries match the semantic meaning.
122 switch(op) {
123 case HistoryOperation::Oldest:
124 return H_LAST;
125 case HistoryOperation::Older:
126 return H_NEXT;
127 case HistoryOperation::Current:
128 return H_CURR;
129 case HistoryOperation::Newer:
130 return H_PREV;
131 case HistoryOperation::Newest:
132 return H_FIRST;
133 }
134 llvm_unreachable("Fully covered switch!");
135}
136
137
138EditLineStringType CombineLines(const std::vector<EditLineStringType> &lines) {
139 EditLineStringStreamType combined_stream;
140 for (EditLineStringType line : lines) {
141 combined_stream << line.c_str() << "\n";
142 }
143 return combined_stream.str();
144}
145
146std::vector<EditLineStringType> SplitLines(const EditLineStringType &input) {
147 std::vector<EditLineStringType> result;
148 size_t start = 0;
149 while (start < input.length()) {
150 size_t end = input.find('\n', start);
151 if (end == std::string::npos) {
152 result.push_back(input.substr(start));
153 break;
154 }
155 result.push_back(input.substr(start, end - start));
156 start = end + 1;
157 }
158 // Treat an empty history session as a single command of zero-length instead
159 // of returning an empty vector.
160 if (result.empty()) {
161 result.emplace_back();
162 }
163 return result;
164}
165
167 int indent_correction) {
168 if (indent_correction == 0)
169 return line;
170 if (indent_correction < 0)
171 return line.substr(-indent_correction);
172 return EditLineStringType(indent_correction, EditLineCharType(' ')) + line;
173}
174
176 int space_count = 0;
177 for (EditLineCharType ch : line) {
178 if (ch != EditLineCharType(' '))
179 break;
180 ++space_count;
181 }
182 return space_count;
183}
184
185bool IsInputPending(FILE *file) {
186 // FIXME: This will be broken on Windows if we ever re-enable Editline. You
187 // can't use select
188 // on something that isn't a socket. This will have to be re-written to not
189 // use a FILE*, but instead use some kind of yet-to-be-created abstraction
190 // that select-like functionality on non-socket objects.
191 const int fd = fileno(file);
192 SelectHelper select_helper;
193 select_helper.SetTimeout(std::chrono::microseconds(0));
194 select_helper.FDSetRead(fd);
195 return select_helper.Select().Success();
196}
197
198namespace lldb_private {
199namespace line_editor {
200typedef std::weak_ptr<EditlineHistory> EditlineHistoryWP;
201
202// EditlineHistory objects are sometimes shared between multiple Editline
203// instances with the same program name.
204
206private:
207 // Use static GetHistory() function to get a EditlineHistorySP to one of
208 // these objects
209 EditlineHistory(const std::string &prefix, uint32_t size, bool unique_entries)
210 : m_prefix(prefix) {
212 history_w(m_history, &m_event, H_SETSIZE, size);
213 if (unique_entries)
214 history_w(m_history, &m_event, H_SETUNIQUE, 1);
215 }
216
217 const char *GetHistoryFilePath() {
218 // Compute the history path lazily.
219 if (m_path.empty() && m_history && !m_prefix.empty()) {
220 llvm::SmallString<128> lldb_history_file;
221 FileSystem::Instance().GetHomeDirectory(lldb_history_file);
222 llvm::sys::path::append(lldb_history_file, ".lldb");
223
224 // LLDB stores its history in ~/.lldb/. If for some reason this directory
225 // isn't writable or cannot be created, history won't be available.
226 if (!llvm::sys::fs::create_directory(lldb_history_file)) {
227#if LLDB_EDITLINE_USE_WCHAR
228 std::string filename = m_prefix + "-widehistory";
229#else
230 std::string filename = m_prefix + "-history";
231#endif
232 llvm::sys::path::append(lldb_history_file, filename);
233 m_path = std::string(lldb_history_file.str());
234 }
235 }
236
237 if (m_path.empty())
238 return nullptr;
239
240 return m_path.c_str();
241 }
242
243public:
245 Save();
246
247 if (m_history) {
249 m_history = nullptr;
250 }
251 }
252
253 static EditlineHistorySP GetHistory(const std::string &prefix) {
254 typedef std::map<std::string, EditlineHistoryWP> WeakHistoryMap;
255 static std::recursive_mutex g_mutex;
256 static WeakHistoryMap g_weak_map;
257 std::lock_guard<std::recursive_mutex> guard(g_mutex);
258 WeakHistoryMap::const_iterator pos = g_weak_map.find(prefix);
259 EditlineHistorySP history_sp;
260 if (pos != g_weak_map.end()) {
261 history_sp = pos->second.lock();
262 if (history_sp)
263 return history_sp;
264 g_weak_map.erase(pos);
265 }
266 history_sp.reset(new EditlineHistory(prefix, 800, true));
267 g_weak_map[prefix] = history_sp;
268 return history_sp;
269 }
270
271 bool IsValid() const { return m_history != nullptr; }
272
274
275 void Enter(const EditLineCharType *line_cstr) {
276 if (m_history)
277 history_w(m_history, &m_event, H_ENTER, line_cstr);
278 }
279
280 bool Load() {
281 if (m_history) {
282 const char *path = GetHistoryFilePath();
283 if (path) {
284 history_w(m_history, &m_event, H_LOAD, path);
285 return true;
286 }
287 }
288 return false;
289 }
290
291 bool Save() {
292 if (m_history) {
293 const char *path = GetHistoryFilePath();
294 if (path) {
295 history_w(m_history, &m_event, H_SAVE, path);
296 return true;
297 }
298 }
299 return false;
300 }
301
302protected:
303 /// The history object.
304 HistoryW *m_history = nullptr;
305 /// The history event needed to contain all history events.
307 /// The prefix name (usually the editline program name) to use when
308 /// loading/saving history.
309 std::string m_prefix;
310 /// Path to the history file.
311 std::string m_path;
312};
313}
314}
315
316// Editline private methods
317
318void Editline::SetBaseLineNumber(int line_number) {
319 m_base_line_number = line_number;
321 std::max<int>(3, std::to_string(line_number).length() + 1);
322}
323
324std::string Editline::PromptForIndex(int line_index) {
325 bool use_line_numbers = m_multiline_enabled && m_base_line_number > 0;
326 std::string prompt = m_set_prompt;
327 if (use_line_numbers && prompt.length() == 0)
328 prompt = ": ";
329 std::string continuation_prompt = prompt;
330 if (m_set_continuation_prompt.length() > 0) {
331 continuation_prompt = m_set_continuation_prompt;
332 // Ensure that both prompts are the same length through space padding
333 const size_t prompt_width = ColumnWidth(prompt);
334 const size_t cont_prompt_width = ColumnWidth(continuation_prompt);
335 const size_t padded_prompt_width =
336 std::max(prompt_width, cont_prompt_width);
337 if (prompt_width < padded_prompt_width)
338 prompt += std::string(padded_prompt_width - prompt_width, ' ');
339 else if (cont_prompt_width < padded_prompt_width)
340 continuation_prompt +=
341 std::string(padded_prompt_width - cont_prompt_width, ' ');
342 }
343
344 if (use_line_numbers) {
345 StreamString prompt_stream;
346 prompt_stream.Printf(
347 "%*d%s", m_line_number_digits, m_base_line_number + line_index,
348 (line_index == 0) ? prompt.c_str() : continuation_prompt.c_str());
349 return std::string(std::move(prompt_stream.GetString()));
350 }
351 return (line_index == 0) ? prompt : continuation_prompt;
352}
353
354void Editline::SetCurrentLine(int line_index) {
355 m_current_line_index = line_index;
356 m_current_prompt = PromptForIndex(line_index);
357}
358
360
362 const char *editor;
363 el_get(m_editline, EL_EDITOR, &editor);
364 return editor[0] == 'e';
365}
366
368 const LineInfoW *info = el_wline(m_editline);
369 for (const EditLineCharType *character = info->buffer;
370 character < info->lastchar; character++) {
371 if (*character != ' ')
372 return false;
373 }
374 return true;
375}
376
378 int line = 0;
379 if (location == CursorLocation::EditingPrompt ||
380 location == CursorLocation::BlockEnd ||
381 location == CursorLocation::EditingCursor) {
382 for (unsigned index = 0; index < m_current_line_index; index++) {
383 line += CountRowsForLine(m_input_lines[index]);
384 }
385 if (location == CursorLocation::EditingCursor) {
386 line += cursor_row;
387 } else if (location == CursorLocation::BlockEnd) {
388 for (unsigned index = m_current_line_index; index < m_input_lines.size();
389 index++) {
390 line += CountRowsForLine(m_input_lines[index]);
391 }
392 --line;
393 }
394 }
395 return line;
396}
397
399 const LineInfoW *info = el_wline(m_editline);
400 int editline_cursor_position =
401 (int)((info->cursor - info->buffer) + GetPromptWidth());
402 int editline_cursor_row = editline_cursor_position / m_terminal_width;
403
404 // Determine relative starting and ending lines
405 int fromLine = GetLineIndexForLocation(from, editline_cursor_row);
406 int toLine = GetLineIndexForLocation(to, editline_cursor_row);
407 if (toLine != fromLine) {
408 fprintf(m_output_file,
409 (toLine > fromLine) ? ANSI_DOWN_N_ROWS : ANSI_UP_N_ROWS,
410 std::abs(toLine - fromLine));
411 }
412
413 // Determine target column
414 int toColumn = 1;
415 if (to == CursorLocation::EditingCursor) {
416 toColumn =
417 editline_cursor_position - (editline_cursor_row * m_terminal_width) + 1;
418 } else if (to == CursorLocation::BlockEnd && !m_input_lines.empty()) {
419 toColumn =
420 ((m_input_lines[m_input_lines.size() - 1].length() + GetPromptWidth()) %
421 80) +
422 1;
423 }
424 fprintf(m_output_file, ANSI_SET_COLUMN_N, toColumn);
425}
426
427void Editline::DisplayInput(int firstIndex) {
429 int line_count = (int)m_input_lines.size();
430 for (int index = firstIndex; index < line_count; index++) {
431 fprintf(m_output_file,
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(m_output_file, "\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() + 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 lines.AppendString(m_utf8conv.to_bytes(line));
462#else
463 lines.AppendString(line);
464#endif
465 --line_count;
466 }
467 return lines;
468}
469
471 assert(op == HistoryOperation::Older || op == HistoryOperation::Newer);
472 if (!m_history_sp || !m_history_sp->IsValid())
473 return CC_ERROR;
474
475 HistoryW *pHistory = m_history_sp->GetHistoryPtr();
476 HistEventW history_event;
477 std::vector<EditLineStringType> new_input_lines;
478
479 // Treat moving from the "live" entry differently
480 if (!m_in_history) {
481 switch (op) {
482 case HistoryOperation::Newer:
483 return CC_ERROR; // Can't go newer than the "live" entry
484 case HistoryOperation::Older: {
485 if (history_w(pHistory, &history_event,
486 GetOperation(HistoryOperation::Newest)) == -1)
487 return CC_ERROR;
488 // Save any edits to the "live" entry in case we return by moving forward
489 // in history (it would be more bash-like to save over any current entry,
490 // but libedit doesn't offer the ability to add entries anywhere except
491 // the end.)
494 m_in_history = true;
495 } break;
496 default:
497 llvm_unreachable("unsupported history direction");
498 }
499 } else {
500 if (history_w(pHistory, &history_event, GetOperation(op)) == -1) {
501 switch (op) {
502 case HistoryOperation::Older:
503 // Can't move earlier than the earliest entry.
504 return CC_ERROR;
505 case HistoryOperation::Newer:
506 // Moving to newer-than-the-newest entry yields the "live" entry.
507 new_input_lines = m_live_history_lines;
508 m_in_history = false;
509 break;
510 default:
511 llvm_unreachable("unsupported history direction");
512 }
513 }
514 }
515
516 // If we're pulling the lines from history, split them apart
517 if (m_in_history)
518 new_input_lines = SplitLines(history_event.str);
519
520 // Erase the current edit session and replace it with a new one
521 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
522 m_input_lines = new_input_lines;
523 DisplayInput();
524
525 // Prepare to edit the last line when moving to previous entry, or the first
526 // line when moving to next entry
527 switch (op) {
528 case HistoryOperation::Older:
529 m_current_line_index = (int)m_input_lines.size() - 1;
530 break;
531 case HistoryOperation::Newer:
533 break;
534 default:
535 llvm_unreachable("unsupported history direction");
536 }
538 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
539 return CC_NEWLINE;
540}
541
543 const LineInfoW *info = el_wline(m_editline);
544
545 // Paint a ANSI formatted version of the desired prompt over the version
546 // libedit draws. (will only be requested if colors are supported)
548 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
549 fprintf(m_output_file,
550 "%s"
551 "%s"
552 "%s",
553 m_prompt_ansi_prefix.c_str(), Prompt(),
554 m_prompt_ansi_suffix.c_str());
555 MoveCursor(CursorLocation::EditingPrompt, CursorLocation::EditingCursor);
557 }
558
560 // Detect when the number of rows used for this input line changes due to
561 // an edit
562 int lineLength = (int)((info->lastchar - info->buffer) + GetPromptWidth());
563 int new_line_rows = (lineLength / m_terminal_width) + 1;
564 if (m_current_line_rows != -1 && new_line_rows != m_current_line_rows) {
565 // Respond by repainting the current state from this line on
566 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
569 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
570 }
571 m_current_line_rows = new_line_rows;
572 }
573
574 // Read an actual character
575 while (true) {
577 char ch = 0;
578
581
582 // This mutex is locked by our caller (GetLine). Unlock it while we read a
583 // character (blocking operation), so we do not hold the mutex
584 // indefinitely. This gives a chance for someone to interrupt us. After
585 // Read returns, immediately lock the mutex again and check if we were
586 // interrupted.
587 m_output_mutex.unlock();
588 int read_count =
589 m_input_connection.Read(&ch, 1, std::nullopt, status, nullptr);
590 m_output_mutex.lock();
591 if (m_editor_status == EditorStatus::Interrupted) {
592 while (read_count > 0 && status == lldb::eConnectionStatusSuccess)
593 read_count =
594 m_input_connection.Read(&ch, 1, std::nullopt, status, nullptr);
596 return 0;
597 }
598
599 if (read_count) {
600 if (CompleteCharacter(ch, *c))
601 return 1;
602 } else {
603 switch (status) {
604 case lldb::eConnectionStatusSuccess: // Success
605 break;
606
608 llvm_unreachable("Interrupts should have been handled above.");
609
610 case lldb::eConnectionStatusError: // Check GetError() for details
611 case lldb::eConnectionStatusTimedOut: // Request timed out
612 case lldb::eConnectionStatusEndOfFile: // End-of-file encountered
613 case lldb::eConnectionStatusNoConnection: // No connection
614 case lldb::eConnectionStatusLostConnection: // Lost connection while
615 // connected to a valid
616 // connection
617 m_editor_status = EditorStatus::EndOfInput;
618 return 0;
619 }
620 }
621 }
622}
623
624const char *Editline::Prompt() {
625 if (!m_prompt_ansi_prefix.empty() || !m_prompt_ansi_suffix.empty())
627 return m_current_prompt.c_str();
628}
629
630unsigned char Editline::BreakLineCommand(int ch) {
631 // Preserve any content beyond the cursor, truncate and save the current line
632 const LineInfoW *info = el_wline(m_editline);
633 auto current_line =
634 EditLineStringType(info->buffer, info->cursor - info->buffer);
635 auto new_line_fragment =
636 EditLineStringType(info->cursor, info->lastchar - info->cursor);
637 m_input_lines[m_current_line_index] = current_line;
638
639 // Ignore whitespace-only extra fragments when breaking a line
640 if (::IsOnlySpaces(new_line_fragment))
641 new_line_fragment = EditLineConstString("");
642
643 // Establish the new cursor position at the start of a line when inserting a
644 // line break
646
647 // Don't perform automatic formatting when pasting
649 // Apply smart indentation
652#if LLDB_EDITLINE_USE_WCHAR
653 lines.AppendString(m_utf8conv.to_bytes(new_line_fragment));
654#else
655 lines.AppendString(new_line_fragment);
656#endif
657
658 int indent_correction = m_fix_indentation_callback(this, lines, 0);
659 new_line_fragment = FixIndentation(new_line_fragment, indent_correction);
660 m_revert_cursor_index = GetIndentation(new_line_fragment);
661 }
662 }
663
664 // Insert the new line and repaint everything from the split line on down
666 new_line_fragment);
667 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
669
670 // Reposition the cursor to the right line and prepare to edit the new line
672 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
673 return CC_NEWLINE;
674}
675
676unsigned char Editline::EndOrAddLineCommand(int ch) {
677 // Don't perform end of input detection when pasting, always treat this as a
678 // line break
680 return BreakLineCommand(ch);
681 }
682
683 // Save any edits to this line
685
686 // If this is the end of the last line, consider whether to add a line
687 // instead
688 const LineInfoW *info = el_wline(m_editline);
689 if (m_current_line_index == m_input_lines.size() - 1 &&
690 info->cursor == info->lastchar) {
692 auto lines = GetInputAsStringList();
693 if (!m_is_input_complete_callback(this, lines)) {
694 return BreakLineCommand(ch);
695 }
696
697 // The completion test is allowed to change the input lines when complete
698 m_input_lines.clear();
699 for (unsigned index = 0; index < lines.GetSize(); index++) {
700#if LLDB_EDITLINE_USE_WCHAR
701 m_input_lines.insert(m_input_lines.end(),
702 m_utf8conv.from_bytes(lines[index]));
703#else
704 m_input_lines.insert(m_input_lines.end(), lines[index]);
705#endif
706 }
707 }
708 }
709 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
710 fprintf(m_output_file, "\n");
711 m_editor_status = EditorStatus::Complete;
712 return CC_NEWLINE;
713}
714
715unsigned char Editline::DeleteNextCharCommand(int ch) {
716 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
717
718 // Just delete the next character normally if possible
719 if (info->cursor < info->lastchar) {
720 info->cursor++;
721 el_deletestr(m_editline, 1);
722 return CC_REFRESH;
723 }
724
725 // Fail when at the end of the last line, except when ^D is pressed on the
726 // line is empty, in which case it is treated as EOF
727 if (m_current_line_index == m_input_lines.size() - 1) {
728 if (ch == 4 && info->buffer == info->lastchar) {
729 fprintf(m_output_file, "^D\n");
730 m_editor_status = EditorStatus::EndOfInput;
731 return CC_EOF;
732 }
733 return CC_ERROR;
734 }
735
736 // Prepare to combine this line with the one below
737 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
738
739 // Insert the next line of text at the cursor and restore the cursor position
740 const EditLineCharType *cursor = info->cursor;
742 info->cursor = cursor;
744
745 // Delete the extra line
747
748 // Clear and repaint from this line on down
750 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
751 return CC_REFRESH;
752}
753
755 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
756
757 // Just delete the previous character normally when not at the start of a
758 // line
759 if (info->cursor > info->buffer) {
760 el_deletestr(m_editline, 1);
761 return CC_REFRESH;
762 }
763
764 // No prior line and no prior character? Let the user know
765 if (m_current_line_index == 0)
766 return CC_ERROR;
767
768 // No prior character, but prior line? Combine with the line above
771 auto priorLine = m_input_lines[m_current_line_index];
775
776 // Repaint from the new line down
778 CountRowsForLine(priorLine), 1);
780
781 // Put the cursor back where libedit expects it to be before returning to
782 // editing by telling libedit about the newly inserted text
783 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
784 el_winsertstr(m_editline, priorLine.c_str());
785 return CC_REDISPLAY;
786}
787
788unsigned char Editline::PreviousLineCommand(int ch) {
790
791 if (m_current_line_index == 0) {
792 return RecallHistory(HistoryOperation::Older);
793 }
794
795 // Start from a known location
796 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
797
798 // Treat moving up from a blank last line as a deletion of that line
799 if (m_current_line_index == m_input_lines.size() - 1 && IsOnlySpaces()) {
802 }
803
807 return CC_NEWLINE;
808}
809
810unsigned char Editline::NextLineCommand(int ch) {
812
813 // Handle attempts to move down from the last line
814 if (m_current_line_index == m_input_lines.size() - 1) {
815 // Don't add an extra line if the existing last line is blank, move through
816 // history instead
817 if (IsOnlySpaces()) {
818 return RecallHistory(HistoryOperation::Newer);
819 }
820
821 // Determine indentation for the new line
822 int indentation = 0;
825 lines.AppendString("");
826 indentation = m_fix_indentation_callback(this, lines, 0);
827 }
828 m_input_lines.insert(
829 m_input_lines.end(),
830 EditLineStringType(indentation, EditLineCharType(' ')));
831 }
832
833 // Move down past the current line using newlines to force scrolling if
834 // needed
836 const LineInfoW *info = el_wline(m_editline);
837 int cursor_position = (int)((info->cursor - info->buffer) + GetPromptWidth());
838 int cursor_row = cursor_position / m_terminal_width;
839 for (int line_count = 0; line_count < m_current_line_rows - cursor_row;
840 line_count++) {
841 fprintf(m_output_file, "\n");
842 }
843 return CC_NEWLINE;
844}
845
846unsigned char Editline::PreviousHistoryCommand(int ch) {
848
849 return RecallHistory(HistoryOperation::Older);
850}
851
852unsigned char Editline::NextHistoryCommand(int ch) {
854
855 return RecallHistory(HistoryOperation::Newer);
856}
857
858unsigned char Editline::FixIndentationCommand(int ch) {
860 return CC_NORM;
861
862 // Insert the character typed before proceeding
863 EditLineCharType inserted[] = {(EditLineCharType)ch, 0};
864 el_winsertstr(m_editline, inserted);
865 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
866 int cursor_position = info->cursor - info->buffer;
867
868 // Save the edits and determine the correct indentation level
871 int indent_correction =
872 m_fix_indentation_callback(this, lines, cursor_position);
873
874 // If it is already correct no special work is needed
875 if (indent_correction == 0)
876 return CC_REFRESH;
877
878 // Change the indentation level of the line
879 std::string currentLine = lines.GetStringAtIndex(m_current_line_index);
880 if (indent_correction > 0) {
881 currentLine = currentLine.insert(0, indent_correction, ' ');
882 } else {
883 currentLine = currentLine.erase(0, -indent_correction);
884 }
885#if LLDB_EDITLINE_USE_WCHAR
886 m_input_lines[m_current_line_index] = m_utf8conv.from_bytes(currentLine);
887#else
888 m_input_lines[m_current_line_index] = currentLine;
889#endif
890
891 // Update the display to reflect the change
892 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
894
895 // Reposition the cursor back on the original line and prepare to restart
896 // editing with a new cursor position
898 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
899 m_revert_cursor_index = cursor_position + indent_correction;
900 return CC_NEWLINE;
901}
902
903unsigned char Editline::RevertLineCommand(int ch) {
905 if (m_revert_cursor_index >= 0) {
906 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
907 info->cursor = info->buffer + m_revert_cursor_index;
908 if (info->cursor > info->lastchar) {
909 info->cursor = info->lastchar;
910 }
912 }
913 return CC_REFRESH;
914}
915
916unsigned char Editline::BufferStartCommand(int ch) {
918 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
921 return CC_NEWLINE;
922}
923
924unsigned char Editline::BufferEndCommand(int ch) {
926 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
927 SetCurrentLine((int)m_input_lines.size() - 1);
928 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
929 return CC_NEWLINE;
930}
931
932/// Prints completions and their descriptions to the given file. Only the
933/// completions in the interval [start, end) are printed.
934static void
935PrintCompletion(FILE *output_file,
936 llvm::ArrayRef<CompletionResult::Completion> results,
937 size_t max_len) {
938 for (const CompletionResult::Completion &c : results) {
939 fprintf(output_file, "\t%-*s", (int)max_len, c.GetCompletion().c_str());
940 if (!c.GetDescription().empty())
941 fprintf(output_file, " -- %s", c.GetDescription().c_str());
942 fprintf(output_file, "\n");
943 }
944}
945
947 Editline &editline, llvm::ArrayRef<CompletionResult::Completion> results) {
948 assert(!results.empty());
949
950 fprintf(editline.m_output_file,
951 "\n" ANSI_CLEAR_BELOW "Available completions:\n");
952 const size_t page_size = 40;
953 bool all = false;
954
955 auto longest =
956 std::max_element(results.begin(), results.end(), [](auto &c1, auto &c2) {
957 return c1.GetCompletion().size() < c2.GetCompletion().size();
958 });
959
960 const size_t max_len = longest->GetCompletion().size();
961
962 if (results.size() < page_size) {
963 PrintCompletion(editline.m_output_file, results, max_len);
964 return;
965 }
966
967 size_t cur_pos = 0;
968 while (cur_pos < results.size()) {
969 size_t remaining = results.size() - cur_pos;
970 size_t next_size = all ? remaining : std::min(page_size, remaining);
971
972 PrintCompletion(editline.m_output_file, results.slice(cur_pos, next_size),
973 max_len);
974
975 cur_pos += next_size;
976
977 if (cur_pos >= results.size())
978 break;
979
980 fprintf(editline.m_output_file, "More (Y/n/a): ");
981 char reply = 'n';
982 int got_char = el_getc(editline.m_editline, &reply);
983 // Check for a ^C or other interruption.
984 if (editline.m_editor_status == EditorStatus::Interrupted) {
985 editline.m_editor_status = EditorStatus::Editing;
986 fprintf(editline.m_output_file, "^C\n");
987 break;
988 }
989
990 fprintf(editline.m_output_file, "\n");
991 if (got_char == -1 || reply == 'n')
992 break;
993 if (reply == 'a')
994 all = true;
995 }
996}
997
998unsigned char Editline::TabCommand(int ch) {
1000 return CC_ERROR;
1001
1002 const LineInfo *line_info = el_line(m_editline);
1003
1004 llvm::StringRef line(line_info->buffer,
1005 line_info->lastchar - line_info->buffer);
1006 unsigned cursor_index = line_info->cursor - line_info->buffer;
1007 CompletionResult result;
1008 CompletionRequest request(line, cursor_index, result);
1009
1010 m_completion_callback(request);
1011
1012 llvm::ArrayRef<CompletionResult::Completion> results = result.GetResults();
1013
1014 StringList completions;
1015 result.GetMatches(completions);
1016
1017 if (results.size() == 0)
1018 return CC_ERROR;
1019
1020 if (results.size() == 1) {
1021 CompletionResult::Completion completion = results.front();
1022 switch (completion.GetMode()) {
1024 std::string to_add = completion.GetCompletion();
1025 // Terminate the current argument with a quote if it started with a quote.
1026 if (!request.GetParsedLine().empty() && request.GetParsedArg().IsQuoted())
1027 to_add.push_back(request.GetParsedArg().GetQuoteChar());
1028 to_add.push_back(' ');
1029 el_deletestr(m_editline, request.GetCursorArgumentPrefix().size());
1030 el_insertstr(m_editline, to_add.c_str());
1031 // Clear all the autosuggestion parts if the only single space can be completed.
1032 if (to_add == " ")
1033 return CC_REDISPLAY;
1034 return CC_REFRESH;
1035 }
1037 std::string to_add = completion.GetCompletion();
1038 to_add = to_add.substr(request.GetCursorArgumentPrefix().size());
1039 el_insertstr(m_editline, to_add.c_str());
1040 break;
1041 }
1043 el_deletestr(m_editline, line_info->cursor - line_info->buffer);
1044 el_insertstr(m_editline, completion.GetCompletion().c_str());
1045 break;
1046 }
1047 }
1048 return CC_REDISPLAY;
1049 }
1050
1051 // If we get a longer match display that first.
1052 std::string longest_prefix = completions.LongestCommonPrefix();
1053 if (!longest_prefix.empty())
1054 longest_prefix =
1055 longest_prefix.substr(request.GetCursorArgumentPrefix().size());
1056 if (!longest_prefix.empty()) {
1057 el_insertstr(m_editline, longest_prefix.c_str());
1058 return CC_REDISPLAY;
1059 }
1060
1061 DisplayCompletions(*this, results);
1062
1063 DisplayInput();
1064 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
1065 return CC_REDISPLAY;
1066}
1067
1069 if (!m_suggestion_callback) {
1070 return CC_REDISPLAY;
1071 }
1072
1073 const LineInfo *line_info = el_line(m_editline);
1074 llvm::StringRef line(line_info->buffer,
1075 line_info->lastchar - line_info->buffer);
1076
1077 if (std::optional<std::string> to_add = m_suggestion_callback(line))
1078 el_insertstr(m_editline, to_add->c_str());
1079
1080 return CC_REDISPLAY;
1081}
1082
1083unsigned char Editline::TypedCharacter(int ch) {
1084 std::string typed = std::string(1, ch);
1085 el_insertstr(m_editline, typed.c_str());
1086
1087 if (!m_suggestion_callback) {
1088 return CC_REDISPLAY;
1089 }
1090
1091 const LineInfo *line_info = el_line(m_editline);
1092 llvm::StringRef line(line_info->buffer,
1093 line_info->lastchar - line_info->buffer);
1094
1095 if (std::optional<std::string> to_add = m_suggestion_callback(line)) {
1096 std::string to_add_color =
1098 fputs(typed.c_str(), m_output_file);
1099 fputs(to_add_color.c_str(), m_output_file);
1100 size_t new_autosuggestion_size = line.size() + to_add->length();
1101 // Print spaces to hide any remains of a previous longer autosuggestion.
1102 if (new_autosuggestion_size < m_previous_autosuggestion_size) {
1103 size_t spaces_to_print =
1104 m_previous_autosuggestion_size - new_autosuggestion_size;
1105 std::string spaces = std::string(spaces_to_print, ' ');
1106 fputs(spaces.c_str(), m_output_file);
1107 }
1108 m_previous_autosuggestion_size = new_autosuggestion_size;
1109
1110 int editline_cursor_position =
1111 (int)((line_info->cursor - line_info->buffer) + GetPromptWidth());
1112 int editline_cursor_row = editline_cursor_position / m_terminal_width;
1113 int toColumn =
1114 editline_cursor_position - (editline_cursor_row * m_terminal_width);
1115 fprintf(m_output_file, ANSI_SET_COLUMN_N, toColumn);
1116 return CC_REFRESH;
1117 }
1118
1119 return CC_REDISPLAY;
1120}
1121
1123 const EditLineCharType *helptext,
1124 EditlineCommandCallbackType callbackFn) {
1125 el_wset(m_editline, EL_ADDFN, command, helptext, callbackFn);
1126}
1127
1129 EditlinePromptCallbackType callbackFn) {
1130 el_set(m_editline, EL_PROMPT, callbackFn);
1131}
1132
1134 el_wset(m_editline, EL_GETCFN, callbackFn);
1135}
1136
1137void Editline::ConfigureEditor(bool multiline) {
1138 if (m_editline && m_multiline_enabled == multiline)
1139 return;
1140 m_multiline_enabled = multiline;
1141
1142 if (m_editline) {
1143 // Disable edit mode to stop the terminal from flushing all input during
1144 // the call to el_end() since we expect to have multiple editline instances
1145 // in this program.
1146 el_set(m_editline, EL_EDITMODE, 0);
1147 el_end(m_editline);
1148 }
1149
1150 m_editline =
1153
1154 if (m_history_sp && m_history_sp->IsValid()) {
1155 if (!m_history_sp->Load()) {
1156 fputs("Could not load history file\n.", m_output_file);
1157 }
1158 el_wset(m_editline, EL_HIST, history, m_history_sp->GetHistoryPtr());
1159 }
1160 el_set(m_editline, EL_CLIENTDATA, this);
1161 el_set(m_editline, EL_SIGNAL, 0);
1162 el_set(m_editline, EL_EDITOR, "emacs");
1163
1164 SetGetCharacterFunction([](EditLine *editline, EditLineGetCharType *c) {
1165 return Editline::InstanceFor(editline)->GetCharacter(c);
1166 });
1167
1168 SetEditLinePromptCallback([](EditLine *editline) {
1169 return Editline::InstanceFor(editline)->Prompt();
1170 });
1171
1172 // Commands used for multiline support, registered whether or not they're
1173 // used
1175 EditLineConstString("lldb-break-line"),
1176 EditLineConstString("Insert a line break"),
1177 [](EditLine *editline, int ch) {
1178 return Editline::InstanceFor(editline)->BreakLineCommand(ch);
1179 });
1180
1182 EditLineConstString("lldb-end-or-add-line"),
1183 EditLineConstString("End editing or continue when incomplete"),
1184 [](EditLine *editline, int ch) {
1185 return Editline::InstanceFor(editline)->EndOrAddLineCommand(ch);
1186 });
1188 EditLineConstString("lldb-delete-next-char"),
1189 EditLineConstString("Delete next character"),
1190 [](EditLine *editline, int ch) {
1191 return Editline::InstanceFor(editline)->DeleteNextCharCommand(ch);
1192 });
1194 EditLineConstString("lldb-delete-previous-char"),
1195 EditLineConstString("Delete previous character"),
1196 [](EditLine *editline, int ch) {
1198 });
1200 EditLineConstString("lldb-previous-line"),
1201 EditLineConstString("Move to previous line"),
1202 [](EditLine *editline, int ch) {
1203 return Editline::InstanceFor(editline)->PreviousLineCommand(ch);
1204 });
1206 EditLineConstString("lldb-next-line"),
1207 EditLineConstString("Move to next line"), [](EditLine *editline, int ch) {
1208 return Editline::InstanceFor(editline)->NextLineCommand(ch);
1209 });
1211 EditLineConstString("lldb-previous-history"),
1212 EditLineConstString("Move to previous history"),
1213 [](EditLine *editline, int ch) {
1214 return Editline::InstanceFor(editline)->PreviousHistoryCommand(ch);
1215 });
1217 EditLineConstString("lldb-next-history"),
1218 EditLineConstString("Move to next history"),
1219 [](EditLine *editline, int ch) {
1220 return Editline::InstanceFor(editline)->NextHistoryCommand(ch);
1221 });
1223 EditLineConstString("lldb-buffer-start"),
1224 EditLineConstString("Move to start of buffer"),
1225 [](EditLine *editline, int ch) {
1226 return Editline::InstanceFor(editline)->BufferStartCommand(ch);
1227 });
1229 EditLineConstString("lldb-buffer-end"),
1230 EditLineConstString("Move to end of buffer"),
1231 [](EditLine *editline, int ch) {
1232 return Editline::InstanceFor(editline)->BufferEndCommand(ch);
1233 });
1235 EditLineConstString("lldb-fix-indentation"),
1236 EditLineConstString("Fix line indentation"),
1237 [](EditLine *editline, int ch) {
1238 return Editline::InstanceFor(editline)->FixIndentationCommand(ch);
1239 });
1240
1241 // Register the complete callback under two names for compatibility with
1242 // older clients using custom .editrc files (largely because libedit has a
1243 // bad bug where if you have a bind command that tries to bind to a function
1244 // name that doesn't exist, it can corrupt the heap and crash your process
1245 // later.)
1246 EditlineCommandCallbackType complete_callback = [](EditLine *editline,
1247 int ch) {
1248 return Editline::InstanceFor(editline)->TabCommand(ch);
1249 };
1251 EditLineConstString("Invoke completion"),
1252 complete_callback);
1254 EditLineConstString("Invoke completion"),
1255 complete_callback);
1256
1257 // General bindings we don't mind being overridden
1258 if (!multiline) {
1259 el_set(m_editline, EL_BIND, "^r", "em-inc-search-prev",
1260 NULL); // Cycle through backwards search, entering string
1261
1264 EditLineConstString("lldb-apply-complete"),
1265 EditLineConstString("Adopt autocompletion"),
1266 [](EditLine *editline, int ch) {
1267 return Editline::InstanceFor(editline)->ApplyAutosuggestCommand(ch);
1268 });
1269
1270 el_set(m_editline, EL_BIND, "^f", "lldb-apply-complete",
1271 NULL); // Apply a part that is suggested automatically
1272
1274 EditLineConstString("lldb-typed-character"),
1275 EditLineConstString("Typed character"),
1276 [](EditLine *editline, int ch) {
1277 return Editline::InstanceFor(editline)->TypedCharacter(ch);
1278 });
1279
1280 char bind_key[2] = {0, 0};
1281 llvm::StringRef ascii_chars =
1282 "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXZY1234567890!\"#$%"
1283 "&'()*+,./:;<=>?@[]_`{|}~ ";
1284 for (char c : ascii_chars) {
1285 bind_key[0] = c;
1286 el_set(m_editline, EL_BIND, bind_key, "lldb-typed-character", NULL);
1287 }
1288 el_set(m_editline, EL_BIND, "\\-", "lldb-typed-character", NULL);
1289 el_set(m_editline, EL_BIND, "\\^", "lldb-typed-character", NULL);
1290 el_set(m_editline, EL_BIND, "\\\\", "lldb-typed-character", NULL);
1291 }
1292 }
1293
1294 el_set(m_editline, EL_BIND, "^w", "ed-delete-prev-word",
1295 NULL); // Delete previous word, behave like bash in emacs mode
1296 el_set(m_editline, EL_BIND, "\t", "lldb-complete",
1297 NULL); // Bind TAB to auto complete
1298
1299 // Allow ctrl-left-arrow and ctrl-right-arrow for navigation, behave like
1300 // bash in emacs mode.
1301 el_set(m_editline, EL_BIND, ESCAPE "[1;5C", "em-next-word", NULL);
1302 el_set(m_editline, EL_BIND, ESCAPE "[1;5D", "ed-prev-word", NULL);
1303 el_set(m_editline, EL_BIND, ESCAPE "[5C", "em-next-word", NULL);
1304 el_set(m_editline, EL_BIND, ESCAPE "[5D", "ed-prev-word", NULL);
1305 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[C", "em-next-word", NULL);
1306 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[D", "ed-prev-word", NULL);
1307
1308 // Allow user-specific customization prior to registering bindings we
1309 // absolutely require
1310 el_source(m_editline, nullptr);
1311
1312 // Register an internal binding that external developers shouldn't use
1314 EditLineConstString("lldb-revert-line"),
1315 EditLineConstString("Revert line to saved state"),
1316 [](EditLine *editline, int ch) {
1317 return Editline::InstanceFor(editline)->RevertLineCommand(ch);
1318 });
1319
1320 // Register keys that perform auto-indent correction
1322 char bind_key[2] = {0, 0};
1323 const char *indent_chars = m_fix_indentation_callback_chars;
1324 while (*indent_chars) {
1325 bind_key[0] = *indent_chars;
1326 el_set(m_editline, EL_BIND, bind_key, "lldb-fix-indentation", NULL);
1327 ++indent_chars;
1328 }
1329 }
1330
1331 // Multi-line editor bindings
1332 if (multiline) {
1333 el_set(m_editline, EL_BIND, "\n", "lldb-end-or-add-line", NULL);
1334 el_set(m_editline, EL_BIND, "\r", "lldb-end-or-add-line", NULL);
1335 el_set(m_editline, EL_BIND, ESCAPE "\n", "lldb-break-line", NULL);
1336 el_set(m_editline, EL_BIND, ESCAPE "\r", "lldb-break-line", NULL);
1337 el_set(m_editline, EL_BIND, "^p", "lldb-previous-line", NULL);
1338 el_set(m_editline, EL_BIND, "^n", "lldb-next-line", NULL);
1339 el_set(m_editline, EL_BIND, "^?", "lldb-delete-previous-char", NULL);
1340 el_set(m_editline, EL_BIND, "^d", "lldb-delete-next-char", NULL);
1341 el_set(m_editline, EL_BIND, ESCAPE "[3~", "lldb-delete-next-char", NULL);
1342 el_set(m_editline, EL_BIND, ESCAPE "[\\^", "lldb-revert-line", NULL);
1343
1344 // Editor-specific bindings
1345 if (IsEmacs()) {
1346 el_set(m_editline, EL_BIND, ESCAPE "<", "lldb-buffer-start", NULL);
1347 el_set(m_editline, EL_BIND, ESCAPE ">", "lldb-buffer-end", NULL);
1348 el_set(m_editline, EL_BIND, ESCAPE "[A", "lldb-previous-line", NULL);
1349 el_set(m_editline, EL_BIND, ESCAPE "[B", "lldb-next-line", NULL);
1350 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[A", "lldb-previous-history",
1351 NULL);
1352 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[B", "lldb-next-history",
1353 NULL);
1354 el_set(m_editline, EL_BIND, ESCAPE "[1;3A", "lldb-previous-history",
1355 NULL);
1356 el_set(m_editline, EL_BIND, ESCAPE "[1;3B", "lldb-next-history", NULL);
1357 } else {
1358 el_set(m_editline, EL_BIND, "^H", "lldb-delete-previous-char", NULL);
1359
1360 el_set(m_editline, EL_BIND, "-a", ESCAPE "[A", "lldb-previous-line",
1361 NULL);
1362 el_set(m_editline, EL_BIND, "-a", ESCAPE "[B", "lldb-next-line", NULL);
1363 el_set(m_editline, EL_BIND, "-a", "x", "lldb-delete-next-char", NULL);
1364 el_set(m_editline, EL_BIND, "-a", "^H", "lldb-delete-previous-char",
1365 NULL);
1366 el_set(m_editline, EL_BIND, "-a", "^?", "lldb-delete-previous-char",
1367 NULL);
1368
1369 // Escape is absorbed exiting edit mode, so re-register important
1370 // sequences without the prefix
1371 el_set(m_editline, EL_BIND, "-a", "[A", "lldb-previous-line", NULL);
1372 el_set(m_editline, EL_BIND, "-a", "[B", "lldb-next-line", NULL);
1373 el_set(m_editline, EL_BIND, "-a", "[\\^", "lldb-revert-line", NULL);
1374 }
1375 }
1376}
1377
1378// Editline public methods
1379
1380Editline *Editline::InstanceFor(EditLine *editline) {
1381 Editline *editor;
1382 el_get(editline, EL_CLIENTDATA, &editor);
1383 return editor;
1384}
1385
1386Editline::Editline(const char *editline_name, FILE *input_file,
1387 FILE *output_file, FILE *error_file,
1388 std::recursive_mutex &output_mutex)
1389 : m_editor_status(EditorStatus::Complete), m_input_file(input_file),
1390 m_output_file(output_file), m_error_file(error_file),
1391 m_input_connection(fileno(input_file), false),
1392 m_output_mutex(output_mutex) {
1393 // Get a shared history instance
1394 m_editor_name = (editline_name == nullptr) ? "lldb-tmp" : editline_name;
1396
1397#ifdef USE_SETUPTERM_WORKAROUND
1398 if (m_output_file) {
1399 const int term_fd = fileno(m_output_file);
1400 if (term_fd != -1) {
1401 static std::recursive_mutex *g_init_terminal_fds_mutex_ptr = nullptr;
1402 static std::set<int> *g_init_terminal_fds_ptr = nullptr;
1403 static llvm::once_flag g_once_flag;
1404 llvm::call_once(g_once_flag, [&]() {
1405 g_init_terminal_fds_mutex_ptr =
1406 new std::recursive_mutex(); // NOTE: Leak to avoid C++ destructor
1407 // chain issues
1408 g_init_terminal_fds_ptr = new std::set<int>(); // NOTE: Leak to avoid
1409 // C++ destructor chain
1410 // issues
1411 });
1412
1413 // We must make sure to initialize the terminal a given file descriptor
1414 // only once. If we do this multiple times, we start leaking memory.
1415 std::lock_guard<std::recursive_mutex> guard(
1416 *g_init_terminal_fds_mutex_ptr);
1417 if (g_init_terminal_fds_ptr->find(term_fd) ==
1418 g_init_terminal_fds_ptr->end()) {
1419 g_init_terminal_fds_ptr->insert(term_fd);
1420 setupterm((char *)0, term_fd, (int *)0);
1421 }
1422 }
1423 }
1424#endif
1425}
1426
1428 if (m_editline) {
1429 // Disable edit mode to stop the terminal from flushing all input during
1430 // the call to el_end() since we expect to have multiple editline instances
1431 // in this program.
1432 el_set(m_editline, EL_EDITMODE, 0);
1433 el_end(m_editline);
1434 m_editline = nullptr;
1435 }
1436
1437 // EditlineHistory objects are sometimes shared between multiple Editline
1438 // instances with the same program name. So just release our shared pointer
1439 // and if we are the last owner, it will save the history to the history save
1440 // file automatically.
1441 m_history_sp.reset();
1442}
1443
1444void Editline::SetPrompt(const char *prompt) {
1445 m_set_prompt = prompt == nullptr ? "" : prompt;
1446}
1447
1448void Editline::SetContinuationPrompt(const char *continuation_prompt) {
1450 continuation_prompt == nullptr ? "" : continuation_prompt;
1451}
1452
1454
1456 if (!m_editline)
1457 return;
1458
1460 el_resize(m_editline);
1461 int columns;
1462 // This function is documenting as taking (const char *, void *) for the
1463 // vararg part, but in reality in was consuming arguments until the first
1464 // null pointer. This was fixed in libedit in April 2019
1465 // <http://mail-index.netbsd.org/source-changes/2019/04/26/msg105454.html>,
1466 // but we're keeping the workaround until a version with that fix is more
1467 // widely available.
1468 if (el_get(m_editline, EL_GETTC, "co", &columns, nullptr) == 0) {
1469 m_terminal_width = columns;
1470 if (m_current_line_rows != -1) {
1471 const LineInfoW *info = el_wline(m_editline);
1472 int lineLength =
1473 (int)((info->lastchar - info->buffer) + GetPromptWidth());
1474 m_current_line_rows = (lineLength / columns) + 1;
1475 }
1476 } else {
1477 m_terminal_width = INT_MAX;
1479 }
1480}
1481
1482const char *Editline::GetPrompt() { return m_set_prompt.c_str(); }
1483
1485
1487 bool result = true;
1488 std::lock_guard<std::recursive_mutex> guard(m_output_mutex);
1489 if (m_editor_status == EditorStatus::Editing) {
1490 fprintf(m_output_file, "^C\n");
1492 }
1493 m_editor_status = EditorStatus::Interrupted;
1494 return result;
1495}
1496
1498 bool result = true;
1499 std::lock_guard<std::recursive_mutex> guard(m_output_mutex);
1500 if (m_editor_status == EditorStatus::Editing) {
1501 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1504 }
1505 m_editor_status = EditorStatus::Interrupted;
1506 return result;
1507}
1508
1509bool Editline::GetLine(std::string &line, bool &interrupted) {
1510 ConfigureEditor(false);
1511 m_input_lines = std::vector<EditLineStringType>();
1512 m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1513
1514 std::lock_guard<std::recursive_mutex> guard(m_output_mutex);
1515
1516 lldbassert(m_editor_status != EditorStatus::Editing);
1517 if (m_editor_status == EditorStatus::Interrupted) {
1518 m_editor_status = EditorStatus::Complete;
1519 interrupted = true;
1520 return true;
1521 }
1522
1523 SetCurrentLine(0);
1524 m_in_history = false;
1525 m_editor_status = EditorStatus::Editing;
1527
1528 int count;
1529 auto input = el_wgets(m_editline, &count);
1530
1531 interrupted = m_editor_status == EditorStatus::Interrupted;
1532 if (!interrupted) {
1533 if (input == nullptr) {
1534 fprintf(m_output_file, "\n");
1535 m_editor_status = EditorStatus::EndOfInput;
1536 } else {
1537 m_history_sp->Enter(input);
1538#if LLDB_EDITLINE_USE_WCHAR
1539 line = m_utf8conv.to_bytes(SplitLines(input)[0]);
1540#else
1541 line = SplitLines(input)[0];
1542#endif
1543 m_editor_status = EditorStatus::Complete;
1544 }
1545 }
1546 return m_editor_status != EditorStatus::EndOfInput;
1547}
1548
1549bool Editline::GetLines(int first_line_number, StringList &lines,
1550 bool &interrupted) {
1551 ConfigureEditor(true);
1552
1553 // Print the initial input lines, then move the cursor back up to the start
1554 // of input
1555 SetBaseLineNumber(first_line_number);
1556 m_input_lines = std::vector<EditLineStringType>();
1557 m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1558
1559 std::lock_guard<std::recursive_mutex> guard(m_output_mutex);
1560 // Begin the line editing loop
1561 DisplayInput();
1562 SetCurrentLine(0);
1563 MoveCursor(CursorLocation::BlockEnd, CursorLocation::BlockStart);
1564 m_editor_status = EditorStatus::Editing;
1565 m_in_history = false;
1566
1568 while (m_editor_status == EditorStatus::Editing) {
1569 int count;
1572 "\x1b[^")); // Revert to the existing line content
1573 el_wgets(m_editline, &count);
1574 }
1575
1576 interrupted = m_editor_status == EditorStatus::Interrupted;
1577 if (!interrupted) {
1578 // Save the completed entry in history before returning. Don't save empty
1579 // input as that just clutters the command history.
1580 if (!m_input_lines.empty())
1581 m_history_sp->Enter(CombineLines(m_input_lines).c_str());
1582
1583 lines = GetInputAsStringList();
1584 }
1585 return m_editor_status != EditorStatus::EndOfInput;
1586}
1587
1588void Editline::PrintAsync(Stream *stream, const char *s, size_t len) {
1589 std::lock_guard<std::recursive_mutex> guard(m_output_mutex);
1590 if (m_editor_status == EditorStatus::Editing) {
1591 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1593 }
1594 stream->Write(s, len);
1595 stream->Flush();
1596 if (m_editor_status == EditorStatus::Editing) {
1597 DisplayInput();
1598 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
1599 }
1600}
1601
1603#if !LLDB_EDITLINE_USE_WCHAR
1604 if (ch == (char)EOF)
1605 return false;
1606
1607 out = (unsigned char)ch;
1608 return true;
1609#else
1610 std::codecvt_utf8<wchar_t> cvt;
1611 llvm::SmallString<4> input;
1612 for (;;) {
1613 const char *from_next;
1614 wchar_t *to_next;
1615 std::mbstate_t state = std::mbstate_t();
1616 input.push_back(ch);
1617 switch (cvt.in(state, input.begin(), input.end(), from_next, &out, &out + 1,
1618 to_next)) {
1619 case std::codecvt_base::ok:
1620 return out != (EditLineGetCharType)WEOF;
1621
1622 case std::codecvt_base::error:
1623 case std::codecvt_base::noconv:
1624 return false;
1625
1626 case std::codecvt_base::partial:
1628 size_t read_count = m_input_connection.Read(
1629 &ch, 1, std::chrono::seconds(0), status, nullptr);
1630 if (read_count == 0)
1631 return false;
1632 break;
1633 }
1634 }
1635#endif
1636}
#define el_wgets
Definition: Editline.cpp:81
EditLineStringType CombineLines(const std::vector< EditLineStringType > &lines)
Definition: Editline.cpp:138
#define EditLineConstString(str)
Definition: Editline.cpp:69
#define ANSI_UP_N_ROWS
Definition: Editline.cpp:59
#define el_wline
Definition: Editline.cpp:87
static void PrintCompletion(FILE *output_file, llvm::ArrayRef< CompletionResult::Completion > results, size_t max_len)
Prints completions and their descriptions to the given file.
Definition: Editline.cpp:935
#define EditLineStringFormatSpec
Definition: Editline.cpp:70
#define LineInfoW
Definition: Editline.cpp:79
EditLineStringType FixIndentation(const EditLineStringType &line, int indent_correction)
Definition: Editline.cpp:166
#define ANSI_DOWN_N_ROWS
Definition: Editline.cpp:60
#define history_wend
Definition: Editline.cpp:76
#define el_winsertstr
Definition: Editline.cpp:88
#define el_wpush
Definition: Editline.cpp:83
#define HistEventW
Definition: Editline.cpp:78
#define history_winit
Definition: Editline.cpp:75
bool IsInputPending(FILE *file)
Definition: Editline.cpp:185
static size_t ColumnWidth(llvm::StringRef str)
Definition: Editline.cpp:101
#define ANSI_CLEAR_BELOW
Definition: Editline.cpp:56
#define el_wset
Definition: Editline.cpp:85
#define ANSI_SET_COLUMN_N
Definition: Editline.cpp:58
std::vector< EditLineStringType > SplitLines(const EditLineStringType &input)
Definition: Editline.cpp:146
#define HistoryW
Definition: Editline.cpp:77
bool IsOnlySpaces(const EditLineStringType &content)
Definition: Editline.cpp:93
#define history_w
Definition: Editline.cpp:74
int GetIndentation(const EditLineStringType &line)
Definition: Editline.cpp:175
static int GetOperation(HistoryOperation op)
Definition: Editline.cpp:105
#define ESCAPE
https://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf
Definition: Editline.cpp:55
#define lldbassert(x)
Definition: LLDBAssert.h:15
lldb_private::Status Select()
void FDSetRead(lldb::socket_t fd)
void SetTimeout(const std::chrono::microseconds &timeout)
bool empty() const
Definition: Args.h:118
"lldb/Utility/ArgCompletionRequest.h"
const Args & GetParsedLine() const
llvm::StringRef GetCursorArgumentPrefix() const
const Args::ArgEntry & GetParsedArg()
A single completion and all associated data.
const std::string & GetCompletion() const
llvm::ArrayRef< Completion > GetResults() const
void GetMatches(StringList &matches) const
Adds all collected completion matches to the given list.
bool InterruptRead() override
Interrupts an ongoing Read() operation.
size_t Read(void *dst, size_t dst_len, const Timeout< std::micro > &timeout, lldb::ConnectionStatus &status, Status *error_ptr) override
The read function that attempts to read from the connection.
Instances of Editline provide an abstraction over libedit's EditLine facility.
Definition: Editline.h:153
IsInputCompleteCallbackType m_is_input_complete_callback
Definition: Editline.h:394
EditorStatus m_editor_status
Definition: Editline.h:376
unsigned char PreviousLineCommand(int ch)
Line navigation command used when ^P or up arrow are pressed in multi-line mode.
Definition: Editline.cpp:788
unsigned char RecallHistory(HistoryOperation op)
Replaces the current multi-line session with the next entry from history.
Definition: Editline.cpp:470
bool IsOnlySpaces()
Returns true if the current EditLine buffer contains nothing but spaces, or is empty.
Definition: Editline.cpp:367
::EditLine * m_editline
Definition: Editline.h:370
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:398
std::string m_suggestion_ansi_suffix
Definition: Editline.h:405
void SetGetCharacterFunction(EditlineGetCharCallbackType callbackFn)
Definition: Editline.cpp:1133
std::string m_current_prompt
Definition: Editline.h:385
static void DisplayCompletions(Editline &editline, llvm::ArrayRef< CompletionResult::Completion > results)
Definition: Editline.cpp:946
std::string m_set_continuation_prompt
Definition: Editline.h:384
std::size_t m_previous_autosuggestion_size
Definition: Editline.h:407
ConnectionFileDescriptor m_input_connection
Definition: Editline.h:392
unsigned char BufferStartCommand(int ch)
Buffer start command used when Esc < is typed in multi-line emacs mode.
Definition: Editline.cpp:916
const char * Prompt()
Prompt implementation for EditLine.
Definition: Editline.cpp:624
unsigned char EndOrAddLineCommand(int ch)
Command used when return is pressed in multi-line mode.
Definition: Editline.cpp:676
unsigned char DeletePreviousCharCommand(int ch)
Delete command used when backspace is pressed in multi-line mode.
Definition: Editline.cpp:754
int GetLineIndexForLocation(CursorLocation location, int cursor_row)
Helper method used by MoveCursor to determine relative line position.
Definition: Editline.cpp:377
std::string m_prompt_ansi_prefix
Definition: Editline.h:402
bool IsEmacs()
Returns true if the underlying EditLine session's keybindings are Emacs-based, or false if they are V...
Definition: Editline.cpp:361
CompleteCallbackType m_completion_callback
Definition: Editline.h:399
size_t GetPromptWidth()
Determines the width of the prompt in characters.
Definition: Editline.cpp:359
unsigned char PreviousHistoryCommand(int ch)
History navigation command used when Alt + up arrow is pressed in multi-line mode.
Definition: Editline.cpp:846
const char * m_fix_indentation_callback_chars
Definition: Editline.h:397
std::string m_editor_name
Definition: Editline.h:388
uint32_t GetCurrentLine()
Returns the index of the line currently being edited.
Definition: Editline.cpp:1484
void DisplayInput(int firstIndex=0)
Clear from cursor position to bottom of screen and print input lines including prompts,...
Definition: Editline.cpp:427
int GetCharacter(EditLineGetCharType *c)
Character reading implementation for EditLine that supports our multi-line editing trickery.
Definition: Editline.cpp:542
void TerminalSizeChanged()
Call when the terminal size changes.
Definition: Editline.cpp:1453
volatile std::sig_atomic_t m_terminal_size_has_changed
Definition: Editline.h:387
void SetEditLinePromptCallback(EditlinePromptCallbackType callbackFn)
Definition: Editline.cpp:1128
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:1380
bool GetLine(std::string &line, bool &interrupted)
Prompts for and reads a single line of user input.
Definition: Editline.cpp:1509
std::string m_set_prompt
Definition: Editline.h:383
void SetCurrentLine(int line_index)
Sets the current line index between line edits to allow free movement between lines.
Definition: Editline.cpp:354
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 ConfigureEditor(bool multiline)
Ensures that the current EditLine instance is properly configured for single or multi-line editing.
Definition: Editline.cpp:1137
unsigned char NextLineCommand(int ch)
Line navigation command used when ^N or down arrow are pressed in multi-line mode.
Definition: Editline.cpp:810
void PrintAsync(Stream *stream, const char *s, size_t len)
Definition: Editline.cpp:1588
std::vector< EditLineStringType > m_live_history_lines
Definition: Editline.h:373
void AddFunctionToEditLine(const EditLineCharType *command, const EditLineCharType *helptext, EditlineCommandCallbackType callbackFn)
Definition: Editline.cpp:1122
std::vector< EditLineStringType > m_input_lines
Definition: Editline.h:375
bool CompleteCharacter(char ch, EditLineGetCharType &out)
Definition: Editline.cpp:1602
bool Cancel()
Cancel this edit and obliterate all trace of it.
Definition: Editline.cpp:1497
unsigned char DeleteNextCharCommand(int ch)
Delete command used when delete is pressed in multi-line mode.
Definition: Editline.cpp:715
std::string m_suggestion_ansi_prefix
Definition: Editline.h:404
SuggestionCallbackType m_suggestion_callback
Definition: Editline.h:400
unsigned char FixIndentationCommand(int ch)
Respond to normal character insertion by fixing line indentation.
Definition: Editline.cpp:858
unsigned char NextHistoryCommand(int ch)
History navigation command used when Alt + down arrow is pressed in multi-line mode.
Definition: Editline.cpp:852
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:1444
unsigned char BufferEndCommand(int ch)
Buffer end command used when Esc > is typed in multi-line emacs mode.
Definition: Editline.cpp:924
unsigned char TypedCharacter(int ch)
Command used when a character is typed.
Definition: Editline.cpp:1083
unsigned char BreakLineCommand(int ch)
Line break command used when meta+return is pressed in multi-line mode.
Definition: Editline.cpp:630
FixIndentationCallbackType m_fix_indentation_callback
Definition: Editline.h:396
unsigned char ApplyAutosuggestCommand(int ch)
Apply autosuggestion part in gray as editline.
Definition: Editline.cpp:1068
unsigned char TabCommand(int ch)
Context-sensitive tab insertion or code completion command used when the tab key is typed.
Definition: Editline.cpp:998
Editline(const char *editor_name, FILE *input_file, FILE *output_file, FILE *error_file, std::recursive_mutex &output_mutex)
Definition: Editline.cpp:1386
std::recursive_mutex & m_output_mutex
Definition: Editline.h:408
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:1448
unsigned m_current_line_index
Definition: Editline.h:379
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:324
unsigned char RevertLineCommand(int ch)
Revert line command used when moving between lines.
Definition: Editline.cpp:903
bool Interrupt()
Interrupt the current edit as if ^C was pressed.
Definition: Editline.cpp:1486
const char * GetPrompt()
Returns the prompt established by SetPrompt.
Definition: Editline.cpp:1482
void SetBaseLineNumber(int line_number)
Sets the lowest line number for multi-line editing sessions.
Definition: Editline.cpp:318
bool GetLines(int first_line_number, StringList &lines, bool &interrupted)
Prompts for and reads a multi-line batch of user input.
Definition: Editline.cpp:1549
std::string m_prompt_ansi_suffix
Definition: Editline.h:403
bool GetHomeDirectory(llvm::SmallVectorImpl< char > &path) const
Get the user home directory.
static FileSystem & Instance()
bool Success() const
Test for success condition.
Definition: Status.cpp:279
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
Definition: Stream.h:101
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:107
virtual void Flush()=0
Flush the stream.
void AppendString(const std::string &s)
Definition: StringList.cpp:43
const char * GetStringAtIndex(size_t idx) const
Definition: StringList.cpp:86
std::string LongestCommonPrefix()
Definition: StringList.cpp:107
void Enter(const EditLineCharType *line_cstr)
Definition: Editline.cpp:275
std::string m_path
Path to the history file.
Definition: Editline.cpp:311
std::string m_prefix
The prefix name (usually the editline program name) to use when loading/saving history.
Definition: Editline.cpp:309
HistoryW * m_history
The history object.
Definition: Editline.cpp:304
EditlineHistory(const std::string &prefix, uint32_t size, bool unique_entries)
Definition: Editline.cpp:209
static EditlineHistorySP GetHistory(const std::string &prefix)
Definition: Editline.cpp:253
HistEventW m_event
The history event needed to contain all history events.
Definition: Editline.cpp:306
std::stringstream EditLineStringStreamType
Definition: Editline.h:70
std::weak_ptr< EditlineHistory > EditlineHistoryWP
Definition: Editline.cpp:200
unsigned char(*)(::EditLine *editline, int ch) EditlineCommandCallbackType
Definition: Editline.h:87
const char *(*)(::EditLine *editline) EditlinePromptCallbackType
Definition: Editline.h:88
int(*)(::EditLine *editline, EditLineGetCharType *c) EditlineGetCharCallbackType
Definition: Editline.h:85
std::string EditLineStringType
Definition: Editline.h:69
HistoryOperation
Operation for the history.
Definition: Editline.h:140
std::shared_ptr< EditlineHistory > EditlineHistorySP
Definition: Editline.h:92
EditorStatus
Status used to decide when and how to start editing another line in multi-line sessions.
Definition: Editline.h:107
@ Complete
Editing complete, returns the complete set of edited lines.
CursorLocation
Established locations that can be easily moved among with MoveCursor.
Definition: Editline.h:123
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
@ 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.
bool IsQuoted() const
Returns true if this argument was quoted in any way.
Definition: Args.h:52
char GetQuoteChar() const
Definition: Args.h:53