1 //===-- Editline.cpp --------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
14 #include "lldb/Core/Error.h"
15 #include "lldb/Core/StreamString.h"
16 #include "lldb/Core/StringList.h"
17 #include "lldb/Host/ConnectionFileDescriptor.h"
18 #include "lldb/Host/Editline.h"
19 #include "lldb/Host/FileSpec.h"
20 #include "lldb/Host/FileSystem.h"
21 #include "lldb/Host/Host.h"
22 #include "lldb/Utility/LLDBAssert.h"
23 #include "lldb/Utility/SelectHelper.h"
25 using namespace lldb_private;
26 using namespace lldb_private::line_editor;
28 // Workaround for what looks like an OS X-specific issue, but other platforms
29 // may benefit from something similar if issues arise. The libedit library
30 // doesn't explicitly initialize the curses termcap library, which it gets away
31 // with until TERM is set to VT100 where it stumbles over an implementation
32 // assumption that may not exist on other platforms. The setupterm() function
33 // would normally require headers that don't work gracefully in this context, so
34 // the function declaraction has been hoisted here.
35 #if defined(__APPLE__)
37 int setupterm(char *term, int fildes, int *errret);
39 #define USE_SETUPTERM_WORKAROUND
42 // Editline uses careful cursor management to achieve the illusion of editing a
43 // multi-line block of text
44 // with a single line editor. Preserving this illusion requires fairly careful
45 // management of cursor
46 // state. Read and understand the relationship between DisplayInput(),
47 // MoveCursor(), SetCurrentLine(),
48 // and SaveEditedLine() before making changes.
51 #define ANSI_FAINT ESCAPE "[2m"
52 #define ANSI_UNFAINT ESCAPE "[22m"
53 #define ANSI_CLEAR_BELOW ESCAPE "[J"
54 #define ANSI_CLEAR_RIGHT ESCAPE "[K"
55 #define ANSI_SET_COLUMN_N ESCAPE "[%dG"
56 #define ANSI_UP_N_ROWS ESCAPE "[%dA"
57 #define ANSI_DOWN_N_ROWS ESCAPE "[%dB"
59 #if LLDB_EDITLINE_USE_WCHAR
61 #define EditLineConstString(str) L##str
62 #define EditLineStringFormatSpec "%ls"
66 #define EditLineConstString(str) str
67 #define EditLineStringFormatSpec "%s"
69 // use #defines so wide version functions and structs will resolve to old
71 // for case of libedit not built with wide char support
72 #define history_w history
73 #define history_winit history_init
74 #define history_wend history_end
75 #define HistoryW History
76 #define HistEventW HistEvent
77 #define LineInfoW LineInfo
79 #define el_wgets el_gets
80 #define el_wgetc el_getc
81 #define el_wpush el_push
82 #define el_wparse el_parse
83 #define el_wset el_set
84 #define el_wget el_get
85 #define el_wline el_line
86 #define el_winsertstr el_insertstr
87 #define el_wdeletestr el_deletestr
89 #endif // #if LLDB_EDITLINE_USE_WCHAR
91 bool IsOnlySpaces(const EditLineStringType &content) {
92 for (wchar_t ch : content) {
93 if (ch != EditLineCharType(' '))
99 EditLineStringType CombineLines(const std::vector<EditLineStringType> &lines) {
100 EditLineStringStreamType combined_stream;
101 for (EditLineStringType line : lines) {
102 combined_stream << line.c_str() << "\n";
104 return combined_stream.str();
107 std::vector<EditLineStringType> SplitLines(const EditLineStringType &input) {
108 std::vector<EditLineStringType> result;
110 while (start < input.length()) {
111 size_t end = input.find('\n', start);
112 if (end == std::string::npos) {
113 result.insert(result.end(), input.substr(start));
116 result.insert(result.end(), input.substr(start, end - start));
122 EditLineStringType FixIndentation(const EditLineStringType &line,
123 int indent_correction) {
124 if (indent_correction == 0)
126 if (indent_correction < 0)
127 return line.substr(-indent_correction);
128 return EditLineStringType(indent_correction, EditLineCharType(' ')) + line;
131 int GetIndentation(const EditLineStringType &line) {
133 for (EditLineCharType ch : line) {
134 if (ch != EditLineCharType(' '))
141 bool IsInputPending(FILE *file) {
142 // FIXME: This will be broken on Windows if we ever re-enable Editline. You
144 // on something that isn't a socket. This will have to be re-written to not
146 // instead use some kind of yet-to-be-created abstraction that select-like
148 // non-socket objects.
149 const int fd = fileno(file);
150 SelectHelper select_helper;
151 select_helper.SetTimeout(std::chrono::microseconds(0));
152 select_helper.FDSetRead(fd);
153 return select_helper.Select().Success();
156 namespace lldb_private {
157 namespace line_editor {
158 typedef std::weak_ptr<EditlineHistory> EditlineHistoryWP;
160 // EditlineHistory objects are sometimes shared between multiple
161 // Editline instances with the same program name.
163 class EditlineHistory {
165 // Use static GetHistory() function to get a EditlineHistorySP to one of these
167 EditlineHistory(const std::string &prefix, uint32_t size, bool unique_entries)
168 : m_history(NULL), m_event(), m_prefix(prefix), m_path() {
169 m_history = history_winit();
170 history_w(m_history, &m_event, H_SETSIZE, size);
172 history_w(m_history, &m_event, H_SETUNIQUE, 1);
175 const char *GetHistoryFilePath() {
176 if (m_path.empty() && m_history && !m_prefix.empty()) {
177 FileSpec parent_path{"~/.lldb", true};
178 char history_path[PATH_MAX];
179 if (FileSystem::MakeDirectory(parent_path,
180 lldb::eFilePermissionsDirectoryDefault)
182 snprintf(history_path, sizeof(history_path), "~/.lldb/%s-history",
185 snprintf(history_path, sizeof(history_path), "~/%s-widehistory",
188 m_path = FileSpec(history_path, true).GetPath();
192 return m_path.c_str();
200 history_wend(m_history);
205 static EditlineHistorySP GetHistory(const std::string &prefix) {
206 typedef std::map<std::string, EditlineHistoryWP> WeakHistoryMap;
207 static std::recursive_mutex g_mutex;
208 static WeakHistoryMap g_weak_map;
209 std::lock_guard<std::recursive_mutex> guard(g_mutex);
210 WeakHistoryMap::const_iterator pos = g_weak_map.find(prefix);
211 EditlineHistorySP history_sp;
212 if (pos != g_weak_map.end()) {
213 history_sp = pos->second.lock();
216 g_weak_map.erase(pos);
218 history_sp.reset(new EditlineHistory(prefix, 800, true));
219 g_weak_map[prefix] = history_sp;
223 bool IsValid() const { return m_history != NULL; }
225 HistoryW *GetHistoryPtr() { return m_history; }
227 void Enter(const EditLineCharType *line_cstr) {
229 history_w(m_history, &m_event, H_ENTER, line_cstr);
234 const char *path = GetHistoryFilePath();
236 history_w(m_history, &m_event, H_LOAD, path);
245 const char *path = GetHistoryFilePath();
247 history_w(m_history, &m_event, H_SAVE, path);
255 HistoryW *m_history; // The history object
256 HistEventW m_event; // The history event needed to contain all history events
257 std::string m_prefix; // The prefix name (usually the editline program name)
258 // to use when loading/saving history
259 std::string m_path; // Path to the history file
264 //------------------------------------------------------------------
265 // Editline private methods
266 //------------------------------------------------------------------
268 void Editline::SetBaseLineNumber(int line_number) {
269 std::stringstream line_number_stream;
270 line_number_stream << line_number;
271 m_base_line_number = line_number;
272 m_line_number_digits =
273 std::max(3, (int)line_number_stream.str().length() + 1);
276 std::string Editline::PromptForIndex(int line_index) {
277 bool use_line_numbers = m_multiline_enabled && m_base_line_number > 0;
278 std::string prompt = m_set_prompt;
279 if (use_line_numbers && prompt.length() == 0) {
282 std::string continuation_prompt = prompt;
283 if (m_set_continuation_prompt.length() > 0) {
284 continuation_prompt = m_set_continuation_prompt;
286 // Ensure that both prompts are the same length through space padding
287 while (continuation_prompt.length() < prompt.length()) {
288 continuation_prompt += ' ';
290 while (prompt.length() < continuation_prompt.length()) {
295 if (use_line_numbers) {
296 StreamString prompt_stream;
297 prompt_stream.Printf(
298 "%*d%s", m_line_number_digits, m_base_line_number + line_index,
299 (line_index == 0) ? prompt.c_str() : continuation_prompt.c_str());
300 return std::move(prompt_stream.GetString());
302 return (line_index == 0) ? prompt : continuation_prompt;
305 void Editline::SetCurrentLine(int line_index) {
306 m_current_line_index = line_index;
307 m_current_prompt = PromptForIndex(line_index);
310 int Editline::GetPromptWidth() { return (int)PromptForIndex(0).length(); }
312 bool Editline::IsEmacs() {
314 el_get(m_editline, EL_EDITOR, &editor);
315 return editor[0] == 'e';
318 bool Editline::IsOnlySpaces() {
319 const LineInfoW *info = el_wline(m_editline);
320 for (const EditLineCharType *character = info->buffer;
321 character < info->lastchar; character++) {
322 if (*character != ' ')
328 int Editline::GetLineIndexForLocation(CursorLocation location, int cursor_row) {
330 if (location == CursorLocation::EditingPrompt ||
331 location == CursorLocation::BlockEnd ||
332 location == CursorLocation::EditingCursor) {
333 for (unsigned index = 0; index < m_current_line_index; index++) {
334 line += CountRowsForLine(m_input_lines[index]);
336 if (location == CursorLocation::EditingCursor) {
338 } else if (location == CursorLocation::BlockEnd) {
339 for (unsigned index = m_current_line_index; index < m_input_lines.size();
341 line += CountRowsForLine(m_input_lines[index]);
349 void Editline::MoveCursor(CursorLocation from, CursorLocation to) {
350 const LineInfoW *info = el_wline(m_editline);
351 int editline_cursor_position =
352 (int)((info->cursor - info->buffer) + GetPromptWidth());
353 int editline_cursor_row = editline_cursor_position / m_terminal_width;
355 // Determine relative starting and ending lines
356 int fromLine = GetLineIndexForLocation(from, editline_cursor_row);
357 int toLine = GetLineIndexForLocation(to, editline_cursor_row);
358 if (toLine != fromLine) {
359 fprintf(m_output_file,
360 (toLine > fromLine) ? ANSI_DOWN_N_ROWS : ANSI_UP_N_ROWS,
361 std::abs(toLine - fromLine));
364 // Determine target column
366 if (to == CursorLocation::EditingCursor) {
368 editline_cursor_position - (editline_cursor_row * m_terminal_width) + 1;
369 } else if (to == CursorLocation::BlockEnd) {
371 ((m_input_lines[m_input_lines.size() - 1].length() + GetPromptWidth()) %
375 fprintf(m_output_file, ANSI_SET_COLUMN_N, toColumn);
378 void Editline::DisplayInput(int firstIndex) {
379 fprintf(m_output_file, ANSI_SET_COLUMN_N ANSI_CLEAR_BELOW, 1);
380 int line_count = (int)m_input_lines.size();
381 const char *faint = m_color_prompts ? ANSI_FAINT : "";
382 const char *unfaint = m_color_prompts ? ANSI_UNFAINT : "";
384 for (int index = firstIndex; index < line_count; index++) {
385 fprintf(m_output_file, "%s"
387 "%s" EditLineStringFormatSpec " ",
388 faint, PromptForIndex(index).c_str(), unfaint,
389 m_input_lines[index].c_str());
390 if (index < line_count - 1)
391 fprintf(m_output_file, "\n");
395 int Editline::CountRowsForLine(const EditLineStringType &content) {
397 PromptForIndex(0); // Prompt width is constant during an edit session
398 int line_length = (int)(content.length() + prompt.length());
399 return (line_length / m_terminal_width) + 1;
402 void Editline::SaveEditedLine() {
403 const LineInfoW *info = el_wline(m_editline);
404 m_input_lines[m_current_line_index] =
405 EditLineStringType(info->buffer, info->lastchar - info->buffer);
408 StringList Editline::GetInputAsStringList(int line_count) {
410 for (EditLineStringType line : m_input_lines) {
413 #if LLDB_EDITLINE_USE_WCHAR
414 lines.AppendString(m_utf8conv.to_bytes(line));
416 lines.AppendString(line);
423 unsigned char Editline::RecallHistory(bool earlier) {
424 if (!m_history_sp || !m_history_sp->IsValid())
427 HistoryW *pHistory = m_history_sp->GetHistoryPtr();
428 HistEventW history_event;
429 std::vector<EditLineStringType> new_input_lines;
431 // Treat moving from the "live" entry differently
433 if (earlier == false)
434 return CC_ERROR; // Can't go newer than the "live" entry
435 if (history_w(pHistory, &history_event, H_FIRST) == -1)
438 // Save any edits to the "live" entry in case we return by moving forward in
440 // (it would be more bash-like to save over any current entry, but libedit
442 // offer the ability to add entries anywhere except the end.)
444 m_live_history_lines = m_input_lines;
447 if (history_w(pHistory, &history_event, earlier ? H_NEXT : H_PREV) == -1) {
448 // Can't move earlier than the earliest entry
452 // ... but moving to newer than the newest yields the "live" entry
453 new_input_lines = m_live_history_lines;
454 m_in_history = false;
458 // If we're pulling the lines from history, split them apart
460 new_input_lines = SplitLines(history_event.str);
462 // Erase the current edit session and replace it with a new one
463 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
464 m_input_lines = new_input_lines;
467 // Prepare to edit the last line when moving to previous entry, or the first
469 // when moving to next entry
470 SetCurrentLine(m_current_line_index =
471 earlier ? (int)m_input_lines.size() - 1 : 0);
472 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
476 int Editline::GetCharacter(EditLineCharType *c) {
477 const LineInfoW *info = el_wline(m_editline);
479 // Paint a faint version of the desired prompt over the version libedit draws
480 // (will only be requested if colors are supported)
481 if (m_needs_prompt_repaint) {
482 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
483 fprintf(m_output_file, "%s"
486 ANSI_FAINT, Prompt(), ANSI_UNFAINT);
487 MoveCursor(CursorLocation::EditingPrompt, CursorLocation::EditingCursor);
488 m_needs_prompt_repaint = false;
491 if (m_multiline_enabled) {
492 // Detect when the number of rows used for this input line changes due to an
494 int lineLength = (int)((info->lastchar - info->buffer) + GetPromptWidth());
495 int new_line_rows = (lineLength / m_terminal_width) + 1;
496 if (m_current_line_rows != -1 && new_line_rows != m_current_line_rows) {
497 // Respond by repainting the current state from this line on
498 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
500 DisplayInput(m_current_line_index);
501 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
503 m_current_line_rows = new_line_rows;
506 // Read an actual character
508 lldb::ConnectionStatus status = lldb::eConnectionStatusSuccess;
511 // This mutex is locked by our caller (GetLine). Unlock it while we read a
513 // (blocking operation), so we do not hold the mutex indefinitely. This
515 // for someone to interrupt us. After Read returns, immediately lock the
517 // check if we were interrupted.
518 m_output_mutex.unlock();
519 int read_count = m_input_connection.Read(&ch, 1, llvm::None, status, NULL);
520 m_output_mutex.lock();
521 if (m_editor_status == EditorStatus::Interrupted) {
522 while (read_count > 0 && status == lldb::eConnectionStatusSuccess)
523 read_count = m_input_connection.Read(&ch, 1, llvm::None, status, NULL);
524 lldbassert(status == lldb::eConnectionStatusInterrupted);
529 if (CompleteCharacter(ch, *c))
533 case lldb::eConnectionStatusSuccess: // Success
536 case lldb::eConnectionStatusInterrupted:
537 lldbassert(0 && "Interrupts should have been handled above.");
539 case lldb::eConnectionStatusError: // Check GetError() for details
540 case lldb::eConnectionStatusTimedOut: // Request timed out
541 case lldb::eConnectionStatusEndOfFile: // End-of-file encountered
542 case lldb::eConnectionStatusNoConnection: // No connection
543 case lldb::eConnectionStatusLostConnection: // Lost connection while
544 // connected to a valid
546 m_editor_status = EditorStatus::EndOfInput;
553 const char *Editline::Prompt() {
555 m_needs_prompt_repaint = true;
556 return m_current_prompt.c_str();
559 unsigned char Editline::BreakLineCommand(int ch) {
560 // Preserve any content beyond the cursor, truncate and save the current line
561 const LineInfoW *info = el_wline(m_editline);
563 EditLineStringType(info->buffer, info->cursor - info->buffer);
564 auto new_line_fragment =
565 EditLineStringType(info->cursor, info->lastchar - info->cursor);
566 m_input_lines[m_current_line_index] = current_line;
568 // Ignore whitespace-only extra fragments when breaking a line
569 if (::IsOnlySpaces(new_line_fragment))
570 new_line_fragment = EditLineConstString("");
572 // Establish the new cursor position at the start of a line when inserting a
574 m_revert_cursor_index = 0;
576 // Don't perform automatic formatting when pasting
577 if (!IsInputPending(m_input_file)) {
578 // Apply smart indentation
579 if (m_fix_indentation_callback) {
580 StringList lines = GetInputAsStringList(m_current_line_index + 1);
581 #if LLDB_EDITLINE_USE_WCHAR
582 lines.AppendString(m_utf8conv.to_bytes(new_line_fragment));
584 lines.AppendString(new_line_fragment);
587 int indent_correction = m_fix_indentation_callback(
588 this, lines, 0, m_fix_indentation_callback_baton);
589 new_line_fragment = FixIndentation(new_line_fragment, indent_correction);
590 m_revert_cursor_index = GetIndentation(new_line_fragment);
594 // Insert the new line and repaint everything from the split line on down
595 m_input_lines.insert(m_input_lines.begin() + m_current_line_index + 1,
597 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
598 DisplayInput(m_current_line_index);
600 // Reposition the cursor to the right line and prepare to edit the new line
601 SetCurrentLine(m_current_line_index + 1);
602 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
606 unsigned char Editline::EndOrAddLineCommand(int ch) {
607 // Don't perform end of input detection when pasting, always treat this as a
609 if (IsInputPending(m_input_file)) {
610 return BreakLineCommand(ch);
613 // Save any edits to this line
616 // If this is the end of the last line, consider whether to add a line instead
617 const LineInfoW *info = el_wline(m_editline);
618 if (m_current_line_index == m_input_lines.size() - 1 &&
619 info->cursor == info->lastchar) {
620 if (m_is_input_complete_callback) {
621 auto lines = GetInputAsStringList();
622 if (!m_is_input_complete_callback(this, lines,
623 m_is_input_complete_callback_baton)) {
624 return BreakLineCommand(ch);
627 // The completion test is allowed to change the input lines when complete
628 m_input_lines.clear();
629 for (unsigned index = 0; index < lines.GetSize(); index++) {
630 #if LLDB_EDITLINE_USE_WCHAR
631 m_input_lines.insert(m_input_lines.end(),
632 m_utf8conv.from_bytes(lines[index]));
634 m_input_lines.insert(m_input_lines.end(), lines[index]);
639 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
640 fprintf(m_output_file, "\n");
641 m_editor_status = EditorStatus::Complete;
645 unsigned char Editline::DeleteNextCharCommand(int ch) {
646 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
648 // Just delete the next character normally if possible
649 if (info->cursor < info->lastchar) {
651 el_deletestr(m_editline, 1);
655 // Fail when at the end of the last line, except when ^D is pressed on
656 // the line is empty, in which case it is treated as EOF
657 if (m_current_line_index == m_input_lines.size() - 1) {
658 if (ch == 4 && info->buffer == info->lastchar) {
659 fprintf(m_output_file, "^D\n");
660 m_editor_status = EditorStatus::EndOfInput;
666 // Prepare to combine this line with the one below
667 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
669 // Insert the next line of text at the cursor and restore the cursor position
670 const EditLineCharType *cursor = info->cursor;
671 el_winsertstr(m_editline, m_input_lines[m_current_line_index + 1].c_str());
672 info->cursor = cursor;
675 // Delete the extra line
676 m_input_lines.erase(m_input_lines.begin() + m_current_line_index + 1);
678 // Clear and repaint from this line on down
679 DisplayInput(m_current_line_index);
680 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
684 unsigned char Editline::DeletePreviousCharCommand(int ch) {
685 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
687 // Just delete the previous character normally when not at the start of a line
688 if (info->cursor > info->buffer) {
689 el_deletestr(m_editline, 1);
693 // No prior line and no prior character? Let the user know
694 if (m_current_line_index == 0)
697 // No prior character, but prior line? Combine with the line above
699 SetCurrentLine(m_current_line_index - 1);
700 auto priorLine = m_input_lines[m_current_line_index];
701 m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
702 m_input_lines[m_current_line_index] =
703 priorLine + m_input_lines[m_current_line_index];
705 // Repaint from the new line down
706 fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
707 CountRowsForLine(priorLine), 1);
708 DisplayInput(m_current_line_index);
710 // Put the cursor back where libedit expects it to be before returning to
712 // by telling libedit about the newly inserted text
713 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
714 el_winsertstr(m_editline, priorLine.c_str());
718 unsigned char Editline::PreviousLineCommand(int ch) {
721 if (m_current_line_index == 0) {
722 return RecallHistory(true);
725 // Start from a known location
726 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
728 // Treat moving up from a blank last line as a deletion of that line
729 if (m_current_line_index == m_input_lines.size() - 1 && IsOnlySpaces()) {
730 m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
731 fprintf(m_output_file, ANSI_CLEAR_BELOW);
734 SetCurrentLine(m_current_line_index - 1);
735 fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
736 CountRowsForLine(m_input_lines[m_current_line_index]), 1);
740 unsigned char Editline::NextLineCommand(int ch) {
743 // Handle attempts to move down from the last line
744 if (m_current_line_index == m_input_lines.size() - 1) {
745 // Don't add an extra line if the existing last line is blank, move through
747 if (IsOnlySpaces()) {
748 return RecallHistory(false);
751 // Determine indentation for the new line
753 if (m_fix_indentation_callback) {
754 StringList lines = GetInputAsStringList();
755 lines.AppendString("");
756 indentation = m_fix_indentation_callback(
757 this, lines, 0, m_fix_indentation_callback_baton);
759 m_input_lines.insert(
761 EditLineStringType(indentation, EditLineCharType(' ')));
764 // Move down past the current line using newlines to force scrolling if needed
765 SetCurrentLine(m_current_line_index + 1);
766 const LineInfoW *info = el_wline(m_editline);
767 int cursor_position = (int)((info->cursor - info->buffer) + GetPromptWidth());
768 int cursor_row = cursor_position / m_terminal_width;
769 for (int line_count = 0; line_count < m_current_line_rows - cursor_row;
771 fprintf(m_output_file, "\n");
776 unsigned char Editline::PreviousHistoryCommand(int ch) {
779 return RecallHistory(true);
782 unsigned char Editline::NextHistoryCommand(int ch) {
785 return RecallHistory(false);
788 unsigned char Editline::FixIndentationCommand(int ch) {
789 if (!m_fix_indentation_callback)
792 // Insert the character typed before proceeding
793 EditLineCharType inserted[] = {(EditLineCharType)ch, 0};
794 el_winsertstr(m_editline, inserted);
795 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
796 int cursor_position = info->cursor - info->buffer;
798 // Save the edits and determine the correct indentation level
800 StringList lines = GetInputAsStringList(m_current_line_index + 1);
801 int indent_correction = m_fix_indentation_callback(
802 this, lines, cursor_position, m_fix_indentation_callback_baton);
804 // If it is already correct no special work is needed
805 if (indent_correction == 0)
808 // Change the indentation level of the line
809 std::string currentLine = lines.GetStringAtIndex(m_current_line_index);
810 if (indent_correction > 0) {
811 currentLine = currentLine.insert(0, indent_correction, ' ');
813 currentLine = currentLine.erase(0, -indent_correction);
815 #if LLDB_EDITLINE_USE_WCHAR
816 m_input_lines[m_current_line_index] = m_utf8conv.from_bytes(currentLine);
818 m_input_lines[m_current_line_index] = currentLine;
821 // Update the display to reflect the change
822 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
823 DisplayInput(m_current_line_index);
825 // Reposition the cursor back on the original line and prepare to restart
827 // with a new cursor position
828 SetCurrentLine(m_current_line_index);
829 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
830 m_revert_cursor_index = cursor_position + indent_correction;
834 unsigned char Editline::RevertLineCommand(int ch) {
835 el_winsertstr(m_editline, m_input_lines[m_current_line_index].c_str());
836 if (m_revert_cursor_index >= 0) {
837 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
838 info->cursor = info->buffer + m_revert_cursor_index;
839 if (info->cursor > info->lastchar) {
840 info->cursor = info->lastchar;
842 m_revert_cursor_index = -1;
847 unsigned char Editline::BufferStartCommand(int ch) {
849 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
851 m_revert_cursor_index = 0;
855 unsigned char Editline::BufferEndCommand(int ch) {
857 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
858 SetCurrentLine((int)m_input_lines.size() - 1);
859 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
863 unsigned char Editline::TabCommand(int ch) {
864 if (m_completion_callback == nullptr)
867 const LineInfo *line_info = el_line(m_editline);
868 StringList completions;
871 const int num_completions = m_completion_callback(
872 line_info->buffer, line_info->cursor, line_info->lastchar,
873 0, // Don't skip any matches (start at match zero)
874 -1, // Get all the matches
875 completions, m_completion_callback_baton);
877 if (num_completions == 0)
879 // if (num_completions == -1)
881 // el_insertstr (m_editline, m_completion_key);
882 // return CC_REDISPLAY;
885 if (num_completions == -2) {
886 // Replace the entire line with the first string...
887 el_deletestr(m_editline, line_info->cursor - line_info->buffer);
888 el_insertstr(m_editline, completions.GetStringAtIndex(0));
892 // If we get a longer match display that first.
893 const char *completion_str = completions.GetStringAtIndex(0);
894 if (completion_str != nullptr && *completion_str != '\0') {
895 el_insertstr(m_editline, completion_str);
899 if (num_completions > 1) {
900 int num_elements = num_completions + 1;
901 fprintf(m_output_file, "\n" ANSI_CLEAR_BELOW "Available completions:");
902 if (num_completions < page_size) {
903 for (int i = 1; i < num_elements; i++) {
904 completion_str = completions.GetStringAtIndex(i);
905 fprintf(m_output_file, "\n\t%s", completion_str);
907 fprintf(m_output_file, "\n");
912 while (cur_pos < num_elements) {
913 int endpoint = cur_pos + page_size;
914 if (endpoint > num_elements)
915 endpoint = num_elements;
916 for (; cur_pos < endpoint; cur_pos++) {
917 completion_str = completions.GetStringAtIndex(cur_pos);
918 fprintf(m_output_file, "\n\t%s", completion_str);
921 if (cur_pos >= num_elements) {
922 fprintf(m_output_file, "\n");
926 fprintf(m_output_file, "\nMore (Y/n/a): ");
928 got_char = el_getc(m_editline, &reply);
929 if (got_char == -1 || reply == 'n')
932 page_size = num_elements - cur_pos;
936 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
941 void Editline::ConfigureEditor(bool multiline) {
942 if (m_editline && m_multiline_enabled == multiline)
944 m_multiline_enabled = multiline;
947 // Disable edit mode to stop the terminal from flushing all input
948 // during the call to el_end() since we expect to have multiple editline
949 // instances in this program.
950 el_set(m_editline, EL_EDITMODE, 0);
955 el_init(m_editor_name.c_str(), m_input_file, m_output_file, m_error_file);
956 TerminalSizeChanged();
958 if (m_history_sp && m_history_sp->IsValid()) {
959 m_history_sp->Load();
960 el_wset(m_editline, EL_HIST, history, m_history_sp->GetHistoryPtr());
962 el_set(m_editline, EL_CLIENTDATA, this);
963 el_set(m_editline, EL_SIGNAL, 0);
964 el_set(m_editline, EL_EDITOR, "emacs");
965 el_set(m_editline, EL_PROMPT,
966 (EditlinePromptCallbackType)([](EditLine *editline) {
967 return Editline::InstanceFor(editline)->Prompt();
970 el_wset(m_editline, EL_GETCFN, (EditlineGetCharCallbackType)([](
971 EditLine *editline, EditLineCharType *c) {
972 return Editline::InstanceFor(editline)->GetCharacter(c);
975 // Commands used for multiline support, registered whether or not they're used
976 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-break-line"),
977 EditLineConstString("Insert a line break"),
978 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
979 return Editline::InstanceFor(editline)->BreakLineCommand(ch);
981 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-end-or-add-line"),
982 EditLineConstString("End editing or continue when incomplete"),
983 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
984 return Editline::InstanceFor(editline)->EndOrAddLineCommand(ch);
986 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-delete-next-char"),
987 EditLineConstString("Delete next character"),
988 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
989 return Editline::InstanceFor(editline)->DeleteNextCharCommand(ch);
992 m_editline, EL_ADDFN, EditLineConstString("lldb-delete-previous-char"),
993 EditLineConstString("Delete previous character"),
994 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
995 return Editline::InstanceFor(editline)->DeletePreviousCharCommand(ch);
997 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-line"),
998 EditLineConstString("Move to previous line"),
999 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1000 return Editline::InstanceFor(editline)->PreviousLineCommand(ch);
1002 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-line"),
1003 EditLineConstString("Move to next line"),
1004 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1005 return Editline::InstanceFor(editline)->NextLineCommand(ch);
1007 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-history"),
1008 EditLineConstString("Move to previous history"),
1009 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1010 return Editline::InstanceFor(editline)->PreviousHistoryCommand(ch);
1012 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-history"),
1013 EditLineConstString("Move to next history"),
1014 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1015 return Editline::InstanceFor(editline)->NextHistoryCommand(ch);
1017 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-start"),
1018 EditLineConstString("Move to start of buffer"),
1019 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1020 return Editline::InstanceFor(editline)->BufferStartCommand(ch);
1022 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-end"),
1023 EditLineConstString("Move to end of buffer"),
1024 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1025 return Editline::InstanceFor(editline)->BufferEndCommand(ch);
1027 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-fix-indentation"),
1028 EditLineConstString("Fix line indentation"),
1029 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1030 return Editline::InstanceFor(editline)->FixIndentationCommand(ch);
1033 // Register the complete callback under two names for compatibility with older
1035 // custom .editrc files (largely because libedit has a bad bug where if you
1036 // have a bind command
1037 // that tries to bind to a function name that doesn't exist, it can corrupt
1039 // crash your process later.)
1040 EditlineCommandCallbackType complete_callback = [](EditLine *editline,
1042 return Editline::InstanceFor(editline)->TabCommand(ch);
1044 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-complete"),
1045 EditLineConstString("Invoke completion"), complete_callback);
1046 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb_complete"),
1047 EditLineConstString("Invoke completion"), complete_callback);
1049 // General bindings we don't mind being overridden
1051 el_set(m_editline, EL_BIND, "^r", "em-inc-search-prev",
1052 NULL); // Cycle through backwards search, entering string
1054 el_set(m_editline, EL_BIND, "^w", "ed-delete-prev-word",
1055 NULL); // Delete previous word, behave like bash in emacs mode
1056 el_set(m_editline, EL_BIND, "\t", "lldb-complete",
1057 NULL); // Bind TAB to auto complete
1059 // Allow user-specific customization prior to registering bindings we
1060 // absolutely require
1061 el_source(m_editline, NULL);
1063 // Register an internal binding that external developers shouldn't use
1064 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-revert-line"),
1065 EditLineConstString("Revert line to saved state"),
1066 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1067 return Editline::InstanceFor(editline)->RevertLineCommand(ch);
1070 // Register keys that perform auto-indent correction
1071 if (m_fix_indentation_callback && m_fix_indentation_callback_chars) {
1072 char bind_key[2] = {0, 0};
1073 const char *indent_chars = m_fix_indentation_callback_chars;
1074 while (*indent_chars) {
1075 bind_key[0] = *indent_chars;
1076 el_set(m_editline, EL_BIND, bind_key, "lldb-fix-indentation", NULL);
1081 // Multi-line editor bindings
1083 el_set(m_editline, EL_BIND, "\n", "lldb-end-or-add-line", NULL);
1084 el_set(m_editline, EL_BIND, "\r", "lldb-end-or-add-line", NULL);
1085 el_set(m_editline, EL_BIND, ESCAPE "\n", "lldb-break-line", NULL);
1086 el_set(m_editline, EL_BIND, ESCAPE "\r", "lldb-break-line", NULL);
1087 el_set(m_editline, EL_BIND, "^p", "lldb-previous-line", NULL);
1088 el_set(m_editline, EL_BIND, "^n", "lldb-next-line", NULL);
1089 el_set(m_editline, EL_BIND, "^?", "lldb-delete-previous-char", NULL);
1090 el_set(m_editline, EL_BIND, "^d", "lldb-delete-next-char", NULL);
1091 el_set(m_editline, EL_BIND, ESCAPE "[3~", "lldb-delete-next-char", NULL);
1092 el_set(m_editline, EL_BIND, ESCAPE "[\\^", "lldb-revert-line", NULL);
1094 // Editor-specific bindings
1096 el_set(m_editline, EL_BIND, ESCAPE "<", "lldb-buffer-start", NULL);
1097 el_set(m_editline, EL_BIND, ESCAPE ">", "lldb-buffer-end", NULL);
1098 el_set(m_editline, EL_BIND, ESCAPE "[A", "lldb-previous-line", NULL);
1099 el_set(m_editline, EL_BIND, ESCAPE "[B", "lldb-next-line", NULL);
1100 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[A", "lldb-previous-history",
1102 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[B", "lldb-next-history",
1104 el_set(m_editline, EL_BIND, ESCAPE "[1;3A", "lldb-previous-history",
1106 el_set(m_editline, EL_BIND, ESCAPE "[1;3B", "lldb-next-history", NULL);
1108 el_set(m_editline, EL_BIND, "^H", "lldb-delete-previous-char", NULL);
1110 el_set(m_editline, EL_BIND, "-a", ESCAPE "[A", "lldb-previous-line",
1112 el_set(m_editline, EL_BIND, "-a", ESCAPE "[B", "lldb-next-line", NULL);
1113 el_set(m_editline, EL_BIND, "-a", "x", "lldb-delete-next-char", NULL);
1114 el_set(m_editline, EL_BIND, "-a", "^H", "lldb-delete-previous-char",
1116 el_set(m_editline, EL_BIND, "-a", "^?", "lldb-delete-previous-char",
1119 // Escape is absorbed exiting edit mode, so re-register important
1121 // without the prefix
1122 el_set(m_editline, EL_BIND, "-a", "[A", "lldb-previous-line", NULL);
1123 el_set(m_editline, EL_BIND, "-a", "[B", "lldb-next-line", NULL);
1124 el_set(m_editline, EL_BIND, "-a", "[\\^", "lldb-revert-line", NULL);
1129 //------------------------------------------------------------------
1130 // Editline public methods
1131 //------------------------------------------------------------------
1133 Editline *Editline::InstanceFor(EditLine *editline) {
1135 el_get(editline, EL_CLIENTDATA, &editor);
1139 Editline::Editline(const char *editline_name, FILE *input_file,
1140 FILE *output_file, FILE *error_file, bool color_prompts)
1141 : m_editor_status(EditorStatus::Complete), m_color_prompts(color_prompts),
1142 m_input_file(input_file), m_output_file(output_file),
1143 m_error_file(error_file), m_input_connection(fileno(input_file), false) {
1144 // Get a shared history instance
1145 m_editor_name = (editline_name == nullptr) ? "lldb-tmp" : editline_name;
1146 m_history_sp = EditlineHistory::GetHistory(m_editor_name);
1148 #ifdef USE_SETUPTERM_WORKAROUND
1149 if (m_output_file) {
1150 const int term_fd = fileno(m_output_file);
1151 if (term_fd != -1) {
1152 static std::mutex *g_init_terminal_fds_mutex_ptr = nullptr;
1153 static std::set<int> *g_init_terminal_fds_ptr = nullptr;
1154 static std::once_flag g_once_flag;
1155 std::call_once(g_once_flag, [&]() {
1156 g_init_terminal_fds_mutex_ptr =
1157 new std::mutex(); // NOTE: Leak to avoid C++ destructor chain issues
1158 g_init_terminal_fds_ptr = new std::set<int>(); // NOTE: Leak to avoid
1159 // C++ destructor chain
1163 // We must make sure to initialize the terminal a given file descriptor
1164 // only once. If we do this multiple times, we start leaking memory.
1165 std::lock_guard<std::mutex> guard(*g_init_terminal_fds_mutex_ptr);
1166 if (g_init_terminal_fds_ptr->find(term_fd) ==
1167 g_init_terminal_fds_ptr->end()) {
1168 g_init_terminal_fds_ptr->insert(term_fd);
1169 setupterm((char *)0, term_fd, (int *)0);
1176 Editline::~Editline() {
1178 // Disable edit mode to stop the terminal from flushing all input
1179 // during the call to el_end() since we expect to have multiple editline
1180 // instances in this program.
1181 el_set(m_editline, EL_EDITMODE, 0);
1183 m_editline = nullptr;
1186 // EditlineHistory objects are sometimes shared between multiple
1187 // Editline instances with the same program name. So just release
1188 // our shared pointer and if we are the last owner, it will save the
1189 // history to the history save file automatically.
1190 m_history_sp.reset();
1193 void Editline::SetPrompt(const char *prompt) {
1194 m_set_prompt = prompt == nullptr ? "" : prompt;
1197 void Editline::SetContinuationPrompt(const char *continuation_prompt) {
1198 m_set_continuation_prompt =
1199 continuation_prompt == nullptr ? "" : continuation_prompt;
1202 void Editline::TerminalSizeChanged() {
1203 if (m_editline != nullptr) {
1204 el_resize(m_editline);
1206 // Despite the man page claiming non-zero indicates success, it's actually
1208 if (el_get(m_editline, EL_GETTC, "co", &columns) == 0) {
1209 m_terminal_width = columns;
1210 if (m_current_line_rows != -1) {
1211 const LineInfoW *info = el_wline(m_editline);
1213 (int)((info->lastchar - info->buffer) + GetPromptWidth());
1214 m_current_line_rows = (lineLength / columns) + 1;
1217 m_terminal_width = INT_MAX;
1218 m_current_line_rows = 1;
1223 const char *Editline::GetPrompt() { return m_set_prompt.c_str(); }
1225 uint32_t Editline::GetCurrentLine() { return m_current_line_index; }
1227 bool Editline::Interrupt() {
1229 std::lock_guard<std::mutex> guard(m_output_mutex);
1230 if (m_editor_status == EditorStatus::Editing) {
1231 fprintf(m_output_file, "^C\n");
1232 result = m_input_connection.InterruptRead();
1234 m_editor_status = EditorStatus::Interrupted;
1238 bool Editline::Cancel() {
1240 std::lock_guard<std::mutex> guard(m_output_mutex);
1241 if (m_editor_status == EditorStatus::Editing) {
1242 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1243 fprintf(m_output_file, ANSI_CLEAR_BELOW);
1244 result = m_input_connection.InterruptRead();
1246 m_editor_status = EditorStatus::Interrupted;
1250 void Editline::SetAutoCompleteCallback(CompleteCallbackType callback,
1252 m_completion_callback = callback;
1253 m_completion_callback_baton = baton;
1256 void Editline::SetIsInputCompleteCallback(IsInputCompleteCallbackType callback,
1258 m_is_input_complete_callback = callback;
1259 m_is_input_complete_callback_baton = baton;
1262 bool Editline::SetFixIndentationCallback(FixIndentationCallbackType callback,
1264 const char *indent_chars) {
1265 m_fix_indentation_callback = callback;
1266 m_fix_indentation_callback_baton = baton;
1267 m_fix_indentation_callback_chars = indent_chars;
1271 bool Editline::GetLine(std::string &line, bool &interrupted) {
1272 ConfigureEditor(false);
1273 m_input_lines = std::vector<EditLineStringType>();
1274 m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1276 std::lock_guard<std::mutex> guard(m_output_mutex);
1278 lldbassert(m_editor_status != EditorStatus::Editing);
1279 if (m_editor_status == EditorStatus::Interrupted) {
1280 m_editor_status = EditorStatus::Complete;
1286 m_in_history = false;
1287 m_editor_status = EditorStatus::Editing;
1288 m_revert_cursor_index = -1;
1291 auto input = el_wgets(m_editline, &count);
1293 interrupted = m_editor_status == EditorStatus::Interrupted;
1295 if (input == nullptr) {
1296 fprintf(m_output_file, "\n");
1297 m_editor_status = EditorStatus::EndOfInput;
1299 m_history_sp->Enter(input);
1300 #if LLDB_EDITLINE_USE_WCHAR
1301 line = m_utf8conv.to_bytes(SplitLines(input)[0]);
1303 line = SplitLines(input)[0];
1305 m_editor_status = EditorStatus::Complete;
1308 return m_editor_status != EditorStatus::EndOfInput;
1311 bool Editline::GetLines(int first_line_number, StringList &lines,
1312 bool &interrupted) {
1313 ConfigureEditor(true);
1315 // Print the initial input lines, then move the cursor back up to the start of
1317 SetBaseLineNumber(first_line_number);
1318 m_input_lines = std::vector<EditLineStringType>();
1319 m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1321 std::lock_guard<std::mutex> guard(m_output_mutex);
1322 // Begin the line editing loop
1325 MoveCursor(CursorLocation::BlockEnd, CursorLocation::BlockStart);
1326 m_editor_status = EditorStatus::Editing;
1327 m_in_history = false;
1329 m_revert_cursor_index = -1;
1330 while (m_editor_status == EditorStatus::Editing) {
1332 m_current_line_rows = -1;
1333 el_wpush(m_editline, EditLineConstString(
1334 "\x1b[^")); // Revert to the existing line content
1335 el_wgets(m_editline, &count);
1338 interrupted = m_editor_status == EditorStatus::Interrupted;
1340 // Save the completed entry in history before returning
1341 m_history_sp->Enter(CombineLines(m_input_lines).c_str());
1343 lines = GetInputAsStringList();
1345 return m_editor_status != EditorStatus::EndOfInput;
1348 void Editline::PrintAsync(Stream *stream, const char *s, size_t len) {
1349 std::lock_guard<std::mutex> guard(m_output_mutex);
1350 if (m_editor_status == EditorStatus::Editing) {
1351 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1352 fprintf(m_output_file, ANSI_CLEAR_BELOW);
1354 stream->Write(s, len);
1356 if (m_editor_status == EditorStatus::Editing) {
1358 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
1362 bool Editline::CompleteCharacter(char ch, EditLineCharType &out) {
1363 #if !LLDB_EDITLINE_USE_WCHAR
1364 if (ch == (char)EOF)
1370 std::codecvt_utf8<wchar_t> cvt;
1371 llvm::SmallString<4> input;
1373 const char *from_next;
1375 std::mbstate_t state = std::mbstate_t();
1376 input.push_back(ch);
1377 switch (cvt.in(state, input.begin(), input.end(), from_next, &out, &out + 1,
1379 case std::codecvt_base::ok:
1382 case std::codecvt_base::error:
1383 case std::codecvt_base::noconv:
1386 case std::codecvt_base::partial:
1387 lldb::ConnectionStatus status;
1388 size_t read_count = m_input_connection.Read(
1389 &ch, 1, std::chrono::seconds(0), status, nullptr);
1390 if (read_count == 0)