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/Host/ConnectionFileDescriptor.h"
15 #include "lldb/Host/Editline.h"
16 #include "lldb/Host/FileSystem.h"
17 #include "lldb/Host/Host.h"
18 #include "lldb/Utility/FileSpec.h"
19 #include "lldb/Utility/LLDBAssert.h"
20 #include "lldb/Utility/SelectHelper.h"
21 #include "lldb/Utility/Status.h"
22 #include "lldb/Utility/StreamString.h"
23 #include "lldb/Utility/StringList.h"
24 #include "lldb/Utility/Timeout.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/Threading.h"
29 using namespace lldb_private;
30 using namespace lldb_private::line_editor;
32 // Workaround for what looks like an OS X-specific issue, but other platforms
33 // may benefit from something similar if issues arise. The libedit library
34 // doesn't explicitly initialize the curses termcap library, which it gets away
35 // with until TERM is set to VT100 where it stumbles over an implementation
36 // assumption that may not exist on other platforms. The setupterm() function
37 // would normally require headers that don't work gracefully in this context,
38 // so the function declaraction has been hoisted here.
39 #if defined(__APPLE__)
41 int setupterm(char *term, int fildes, int *errret);
43 #define USE_SETUPTERM_WORKAROUND
46 // Editline uses careful cursor management to achieve the illusion of editing a
47 // multi-line block of text with a single line editor. Preserving this
48 // illusion requires fairly careful management of cursor state. Read and
49 // understand the relationship between DisplayInput(), MoveCursor(),
50 // SetCurrentLine(), and SaveEditedLine() before making changes.
53 #define ANSI_FAINT ESCAPE "[2m"
54 #define ANSI_UNFAINT ESCAPE "[22m"
55 #define ANSI_CLEAR_BELOW ESCAPE "[J"
56 #define ANSI_CLEAR_RIGHT ESCAPE "[K"
57 #define ANSI_SET_COLUMN_N ESCAPE "[%dG"
58 #define ANSI_UP_N_ROWS ESCAPE "[%dA"
59 #define ANSI_DOWN_N_ROWS ESCAPE "[%dB"
61 #if LLDB_EDITLINE_USE_WCHAR
63 #define EditLineConstString(str) L##str
64 #define EditLineStringFormatSpec "%ls"
68 #define EditLineConstString(str) str
69 #define EditLineStringFormatSpec "%s"
71 // use #defines so wide version functions and structs will resolve to old
72 // versions for case of libedit not built with wide char support
73 #define history_w history
74 #define history_winit history_init
75 #define history_wend history_end
76 #define HistoryW History
77 #define HistEventW HistEvent
78 #define LineInfoW LineInfo
80 #define el_wgets el_gets
81 #define el_wgetc el_getc
82 #define el_wpush el_push
83 #define el_wparse el_parse
84 #define el_wset el_set
85 #define el_wget el_get
86 #define el_wline el_line
87 #define el_winsertstr el_insertstr
88 #define el_wdeletestr el_deletestr
90 #endif // #if LLDB_EDITLINE_USE_WCHAR
92 bool IsOnlySpaces(const EditLineStringType &content) {
93 for (wchar_t ch : content) {
94 if (ch != EditLineCharType(' '))
100 EditLineStringType CombineLines(const std::vector<EditLineStringType> &lines) {
101 EditLineStringStreamType combined_stream;
102 for (EditLineStringType line : lines) {
103 combined_stream << line.c_str() << "\n";
105 return combined_stream.str();
108 std::vector<EditLineStringType> SplitLines(const EditLineStringType &input) {
109 std::vector<EditLineStringType> result;
111 while (start < input.length()) {
112 size_t end = input.find('\n', start);
113 if (end == std::string::npos) {
114 result.insert(result.end(), input.substr(start));
117 result.insert(result.end(), input.substr(start, end - start));
123 EditLineStringType FixIndentation(const EditLineStringType &line,
124 int indent_correction) {
125 if (indent_correction == 0)
127 if (indent_correction < 0)
128 return line.substr(-indent_correction);
129 return EditLineStringType(indent_correction, EditLineCharType(' ')) + line;
132 int GetIndentation(const EditLineStringType &line) {
134 for (EditLineCharType ch : line) {
135 if (ch != EditLineCharType(' '))
142 bool IsInputPending(FILE *file) {
143 // FIXME: This will be broken on Windows if we ever re-enable Editline. You
145 // on something that isn't a socket. This will have to be re-written to not
146 // use a FILE*, but instead use some kind of yet-to-be-created abstraction
147 // that select-like functionality on non-socket objects.
148 const int fd = fileno(file);
149 SelectHelper select_helper;
150 select_helper.SetTimeout(std::chrono::microseconds(0));
151 select_helper.FDSetRead(fd);
152 return select_helper.Select().Success();
155 namespace lldb_private {
156 namespace line_editor {
157 typedef std::weak_ptr<EditlineHistory> EditlineHistoryWP;
159 // EditlineHistory objects are sometimes shared between multiple Editline
160 // instances with the same program name.
162 class EditlineHistory {
164 // Use static GetHistory() function to get a EditlineHistorySP to one of
166 EditlineHistory(const std::string &prefix, uint32_t size, bool unique_entries)
167 : m_history(NULL), m_event(), m_prefix(prefix), m_path() {
168 m_history = history_winit();
169 history_w(m_history, &m_event, H_SETSIZE, size);
171 history_w(m_history, &m_event, H_SETUNIQUE, 1);
174 const char *GetHistoryFilePath() {
175 if (m_path.empty() && m_history && !m_prefix.empty()) {
176 FileSpec parent_path("~/.lldb");
177 FileSystem::Instance().Resolve(parent_path);
178 char history_path[PATH_MAX];
179 if (!llvm::sys::fs::create_directory(parent_path.GetPath())) {
180 snprintf(history_path, sizeof(history_path), "~/.lldb/%s-history",
183 snprintf(history_path, sizeof(history_path), "~/%s-widehistory",
186 auto file_spec = FileSpec(history_path);
187 FileSystem::Instance().Resolve(file_spec);
188 m_path = file_spec.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 && !m_input_lines.empty()) {
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
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
439 // in history (it would be more bash-like to save over any current entry,
440 // but libedit doesn't offer the ability to add entries anywhere except the
443 m_live_history_lines = m_input_lines;
446 if (history_w(pHistory, &history_event, earlier ? H_PREV : H_NEXT) == -1) {
447 // Can't move earlier than the earliest entry
451 // ... but moving to newer than the newest yields the "live" entry
452 new_input_lines = m_live_history_lines;
453 m_in_history = false;
457 // If we're pulling the lines from history, split them apart
459 new_input_lines = SplitLines(history_event.str);
461 // Erase the current edit session and replace it with a new one
462 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
463 m_input_lines = new_input_lines;
466 // Prepare to edit the last line when moving to previous entry, or the first
467 // line when moving to next entry
468 SetCurrentLine(m_current_line_index =
469 earlier ? (int)m_input_lines.size() - 1 : 0);
470 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
474 int Editline::GetCharacter(EditLineGetCharType *c) {
475 const LineInfoW *info = el_wline(m_editline);
477 // Paint a faint version of the desired prompt over the version libedit draws
478 // (will only be requested if colors are supported)
479 if (m_needs_prompt_repaint) {
480 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
481 fprintf(m_output_file, "%s"
484 ANSI_FAINT, Prompt(), ANSI_UNFAINT);
485 MoveCursor(CursorLocation::EditingPrompt, CursorLocation::EditingCursor);
486 m_needs_prompt_repaint = false;
489 if (m_multiline_enabled) {
490 // Detect when the number of rows used for this input line changes due to
492 int lineLength = (int)((info->lastchar - info->buffer) + GetPromptWidth());
493 int new_line_rows = (lineLength / m_terminal_width) + 1;
494 if (m_current_line_rows != -1 && new_line_rows != m_current_line_rows) {
495 // Respond by repainting the current state from this line on
496 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
498 DisplayInput(m_current_line_index);
499 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
501 m_current_line_rows = new_line_rows;
504 // Read an actual character
506 lldb::ConnectionStatus status = lldb::eConnectionStatusSuccess;
509 // This mutex is locked by our caller (GetLine). Unlock it while we read a
510 // character (blocking operation), so we do not hold the mutex
511 // indefinitely. This gives a chance for someone to interrupt us. After
512 // Read returns, immediately lock the mutex again and check if we were
514 m_output_mutex.unlock();
515 int read_count = m_input_connection.Read(&ch, 1, llvm::None, status, NULL);
516 m_output_mutex.lock();
517 if (m_editor_status == EditorStatus::Interrupted) {
518 while (read_count > 0 && status == lldb::eConnectionStatusSuccess)
519 read_count = m_input_connection.Read(&ch, 1, llvm::None, status, NULL);
520 lldbassert(status == lldb::eConnectionStatusInterrupted);
525 if (CompleteCharacter(ch, *c))
529 case lldb::eConnectionStatusSuccess: // Success
532 case lldb::eConnectionStatusInterrupted:
533 llvm_unreachable("Interrupts should have been handled above.");
535 case lldb::eConnectionStatusError: // Check GetError() for details
536 case lldb::eConnectionStatusTimedOut: // Request timed out
537 case lldb::eConnectionStatusEndOfFile: // End-of-file encountered
538 case lldb::eConnectionStatusNoConnection: // No connection
539 case lldb::eConnectionStatusLostConnection: // Lost connection while
540 // connected to a valid
542 m_editor_status = EditorStatus::EndOfInput;
549 const char *Editline::Prompt() {
551 m_needs_prompt_repaint = true;
552 return m_current_prompt.c_str();
555 unsigned char Editline::BreakLineCommand(int ch) {
556 // Preserve any content beyond the cursor, truncate and save the current line
557 const LineInfoW *info = el_wline(m_editline);
559 EditLineStringType(info->buffer, info->cursor - info->buffer);
560 auto new_line_fragment =
561 EditLineStringType(info->cursor, info->lastchar - info->cursor);
562 m_input_lines[m_current_line_index] = current_line;
564 // Ignore whitespace-only extra fragments when breaking a line
565 if (::IsOnlySpaces(new_line_fragment))
566 new_line_fragment = EditLineConstString("");
568 // Establish the new cursor position at the start of a line when inserting a
570 m_revert_cursor_index = 0;
572 // Don't perform automatic formatting when pasting
573 if (!IsInputPending(m_input_file)) {
574 // Apply smart indentation
575 if (m_fix_indentation_callback) {
576 StringList lines = GetInputAsStringList(m_current_line_index + 1);
577 #if LLDB_EDITLINE_USE_WCHAR
578 lines.AppendString(m_utf8conv.to_bytes(new_line_fragment));
580 lines.AppendString(new_line_fragment);
583 int indent_correction = m_fix_indentation_callback(
584 this, lines, 0, m_fix_indentation_callback_baton);
585 new_line_fragment = FixIndentation(new_line_fragment, indent_correction);
586 m_revert_cursor_index = GetIndentation(new_line_fragment);
590 // Insert the new line and repaint everything from the split line on down
591 m_input_lines.insert(m_input_lines.begin() + m_current_line_index + 1,
593 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
594 DisplayInput(m_current_line_index);
596 // Reposition the cursor to the right line and prepare to edit the new line
597 SetCurrentLine(m_current_line_index + 1);
598 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
602 unsigned char Editline::EndOrAddLineCommand(int ch) {
603 // Don't perform end of input detection when pasting, always treat this as a
605 if (IsInputPending(m_input_file)) {
606 return BreakLineCommand(ch);
609 // Save any edits to this line
612 // If this is the end of the last line, consider whether to add a line
614 const LineInfoW *info = el_wline(m_editline);
615 if (m_current_line_index == m_input_lines.size() - 1 &&
616 info->cursor == info->lastchar) {
617 if (m_is_input_complete_callback) {
618 auto lines = GetInputAsStringList();
619 if (!m_is_input_complete_callback(this, lines,
620 m_is_input_complete_callback_baton)) {
621 return BreakLineCommand(ch);
624 // The completion test is allowed to change the input lines when complete
625 m_input_lines.clear();
626 for (unsigned index = 0; index < lines.GetSize(); index++) {
627 #if LLDB_EDITLINE_USE_WCHAR
628 m_input_lines.insert(m_input_lines.end(),
629 m_utf8conv.from_bytes(lines[index]));
631 m_input_lines.insert(m_input_lines.end(), lines[index]);
636 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
637 fprintf(m_output_file, "\n");
638 m_editor_status = EditorStatus::Complete;
642 unsigned char Editline::DeleteNextCharCommand(int ch) {
643 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
645 // Just delete the next character normally if possible
646 if (info->cursor < info->lastchar) {
648 el_deletestr(m_editline, 1);
652 // Fail when at the end of the last line, except when ^D is pressed on the
653 // line is empty, in which case it is treated as EOF
654 if (m_current_line_index == m_input_lines.size() - 1) {
655 if (ch == 4 && info->buffer == info->lastchar) {
656 fprintf(m_output_file, "^D\n");
657 m_editor_status = EditorStatus::EndOfInput;
663 // Prepare to combine this line with the one below
664 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
666 // Insert the next line of text at the cursor and restore the cursor position
667 const EditLineCharType *cursor = info->cursor;
668 el_winsertstr(m_editline, m_input_lines[m_current_line_index + 1].c_str());
669 info->cursor = cursor;
672 // Delete the extra line
673 m_input_lines.erase(m_input_lines.begin() + m_current_line_index + 1);
675 // Clear and repaint from this line on down
676 DisplayInput(m_current_line_index);
677 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
681 unsigned char Editline::DeletePreviousCharCommand(int ch) {
682 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
684 // Just delete the previous character normally when not at the start of a
686 if (info->cursor > info->buffer) {
687 el_deletestr(m_editline, 1);
691 // No prior line and no prior character? Let the user know
692 if (m_current_line_index == 0)
695 // No prior character, but prior line? Combine with the line above
697 SetCurrentLine(m_current_line_index - 1);
698 auto priorLine = m_input_lines[m_current_line_index];
699 m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
700 m_input_lines[m_current_line_index] =
701 priorLine + m_input_lines[m_current_line_index];
703 // Repaint from the new line down
704 fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
705 CountRowsForLine(priorLine), 1);
706 DisplayInput(m_current_line_index);
708 // Put the cursor back where libedit expects it to be before returning to
709 // editing by telling libedit about the newly inserted text
710 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
711 el_winsertstr(m_editline, priorLine.c_str());
715 unsigned char Editline::PreviousLineCommand(int ch) {
718 if (m_current_line_index == 0) {
719 return RecallHistory(true);
722 // Start from a known location
723 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
725 // Treat moving up from a blank last line as a deletion of that line
726 if (m_current_line_index == m_input_lines.size() - 1 && IsOnlySpaces()) {
727 m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
728 fprintf(m_output_file, ANSI_CLEAR_BELOW);
731 SetCurrentLine(m_current_line_index - 1);
732 fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
733 CountRowsForLine(m_input_lines[m_current_line_index]), 1);
737 unsigned char Editline::NextLineCommand(int ch) {
740 // Handle attempts to move down from the last line
741 if (m_current_line_index == m_input_lines.size() - 1) {
742 // Don't add an extra line if the existing last line is blank, move through
744 if (IsOnlySpaces()) {
745 return RecallHistory(false);
748 // Determine indentation for the new line
750 if (m_fix_indentation_callback) {
751 StringList lines = GetInputAsStringList();
752 lines.AppendString("");
753 indentation = m_fix_indentation_callback(
754 this, lines, 0, m_fix_indentation_callback_baton);
756 m_input_lines.insert(
758 EditLineStringType(indentation, EditLineCharType(' ')));
761 // Move down past the current line using newlines to force scrolling if
763 SetCurrentLine(m_current_line_index + 1);
764 const LineInfoW *info = el_wline(m_editline);
765 int cursor_position = (int)((info->cursor - info->buffer) + GetPromptWidth());
766 int cursor_row = cursor_position / m_terminal_width;
767 for (int line_count = 0; line_count < m_current_line_rows - cursor_row;
769 fprintf(m_output_file, "\n");
774 unsigned char Editline::PreviousHistoryCommand(int ch) {
777 return RecallHistory(true);
780 unsigned char Editline::NextHistoryCommand(int ch) {
783 return RecallHistory(false);
786 unsigned char Editline::FixIndentationCommand(int ch) {
787 if (!m_fix_indentation_callback)
790 // Insert the character typed before proceeding
791 EditLineCharType inserted[] = {(EditLineCharType)ch, 0};
792 el_winsertstr(m_editline, inserted);
793 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
794 int cursor_position = info->cursor - info->buffer;
796 // Save the edits and determine the correct indentation level
798 StringList lines = GetInputAsStringList(m_current_line_index + 1);
799 int indent_correction = m_fix_indentation_callback(
800 this, lines, cursor_position, m_fix_indentation_callback_baton);
802 // If it is already correct no special work is needed
803 if (indent_correction == 0)
806 // Change the indentation level of the line
807 std::string currentLine = lines.GetStringAtIndex(m_current_line_index);
808 if (indent_correction > 0) {
809 currentLine = currentLine.insert(0, indent_correction, ' ');
811 currentLine = currentLine.erase(0, -indent_correction);
813 #if LLDB_EDITLINE_USE_WCHAR
814 m_input_lines[m_current_line_index] = m_utf8conv.from_bytes(currentLine);
816 m_input_lines[m_current_line_index] = currentLine;
819 // Update the display to reflect the change
820 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
821 DisplayInput(m_current_line_index);
823 // Reposition the cursor back on the original line and prepare to restart
824 // editing with a new cursor position
825 SetCurrentLine(m_current_line_index);
826 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
827 m_revert_cursor_index = cursor_position + indent_correction;
831 unsigned char Editline::RevertLineCommand(int ch) {
832 el_winsertstr(m_editline, m_input_lines[m_current_line_index].c_str());
833 if (m_revert_cursor_index >= 0) {
834 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
835 info->cursor = info->buffer + m_revert_cursor_index;
836 if (info->cursor > info->lastchar) {
837 info->cursor = info->lastchar;
839 m_revert_cursor_index = -1;
844 unsigned char Editline::BufferStartCommand(int ch) {
846 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
848 m_revert_cursor_index = 0;
852 unsigned char Editline::BufferEndCommand(int ch) {
854 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
855 SetCurrentLine((int)m_input_lines.size() - 1);
856 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
860 //------------------------------------------------------------------------------
861 /// Prints completions and their descriptions to the given file. Only the
862 /// completions in the interval [start, end) are printed.
863 //------------------------------------------------------------------------------
864 static void PrintCompletion(FILE *output_file, size_t start, size_t end,
865 StringList &completions, StringList &descriptions) {
866 // This is an 'int' because of printf.
869 for (size_t i = start; i < end; i++) {
870 const char *completion_str = completions.GetStringAtIndex(i);
871 max_len = std::max((int)strlen(completion_str), max_len);
874 for (size_t i = start; i < end; i++) {
875 const char *completion_str = completions.GetStringAtIndex(i);
876 const char *description_str = descriptions.GetStringAtIndex(i);
878 fprintf(output_file, "\n\t%-*s", max_len, completion_str);
880 // Print the description if we got one.
881 if (strlen(description_str))
882 fprintf(output_file, " -- %s", description_str);
886 unsigned char Editline::TabCommand(int ch) {
887 if (m_completion_callback == nullptr)
890 const LineInfo *line_info = el_line(m_editline);
891 StringList completions, descriptions;
894 const int num_completions = m_completion_callback(
895 line_info->buffer, line_info->cursor, line_info->lastchar,
896 0, // Don't skip any matches (start at match zero)
897 -1, // Get all the matches
898 completions, descriptions, m_completion_callback_baton);
900 if (num_completions == 0)
902 // if (num_completions == -1)
904 // el_insertstr (m_editline, m_completion_key);
905 // return CC_REDISPLAY;
908 if (num_completions == -2) {
909 // Replace the entire line with the first string...
910 el_deletestr(m_editline, line_info->cursor - line_info->buffer);
911 el_insertstr(m_editline, completions.GetStringAtIndex(0));
915 // If we get a longer match display that first.
916 const char *completion_str = completions.GetStringAtIndex(0);
917 if (completion_str != nullptr && *completion_str != '\0') {
918 el_insertstr(m_editline, completion_str);
922 if (num_completions > 1) {
923 int num_elements = num_completions + 1;
924 fprintf(m_output_file, "\n" ANSI_CLEAR_BELOW "Available completions:");
925 if (num_completions < page_size) {
926 PrintCompletion(m_output_file, 1, num_elements, completions,
928 fprintf(m_output_file, "\n");
933 while (cur_pos < num_elements) {
934 int endpoint = cur_pos + page_size;
935 if (endpoint > num_elements)
936 endpoint = num_elements;
938 PrintCompletion(m_output_file, cur_pos, endpoint, completions,
942 if (cur_pos >= num_elements) {
943 fprintf(m_output_file, "\n");
947 fprintf(m_output_file, "\nMore (Y/n/a): ");
949 got_char = el_getc(m_editline, &reply);
950 if (got_char == -1 || reply == 'n')
953 page_size = num_elements - cur_pos;
957 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
962 void Editline::ConfigureEditor(bool multiline) {
963 if (m_editline && m_multiline_enabled == multiline)
965 m_multiline_enabled = multiline;
968 // Disable edit mode to stop the terminal from flushing all input during
969 // the call to el_end() since we expect to have multiple editline instances
971 el_set(m_editline, EL_EDITMODE, 0);
976 el_init(m_editor_name.c_str(), m_input_file, m_output_file, m_error_file);
977 TerminalSizeChanged();
979 if (m_history_sp && m_history_sp->IsValid()) {
980 m_history_sp->Load();
981 el_wset(m_editline, EL_HIST, history, m_history_sp->GetHistoryPtr());
983 el_set(m_editline, EL_CLIENTDATA, this);
984 el_set(m_editline, EL_SIGNAL, 0);
985 el_set(m_editline, EL_EDITOR, "emacs");
986 el_set(m_editline, EL_PROMPT,
987 (EditlinePromptCallbackType)([](EditLine *editline) {
988 return Editline::InstanceFor(editline)->Prompt();
991 el_wset(m_editline, EL_GETCFN, (EditlineGetCharCallbackType)([](
992 EditLine *editline, EditLineGetCharType *c) {
993 return Editline::InstanceFor(editline)->GetCharacter(c);
996 // Commands used for multiline support, registered whether or not they're
998 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-break-line"),
999 EditLineConstString("Insert a line break"),
1000 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1001 return Editline::InstanceFor(editline)->BreakLineCommand(ch);
1003 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-end-or-add-line"),
1004 EditLineConstString("End editing or continue when incomplete"),
1005 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1006 return Editline::InstanceFor(editline)->EndOrAddLineCommand(ch);
1008 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-delete-next-char"),
1009 EditLineConstString("Delete next character"),
1010 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1011 return Editline::InstanceFor(editline)->DeleteNextCharCommand(ch);
1014 m_editline, EL_ADDFN, EditLineConstString("lldb-delete-previous-char"),
1015 EditLineConstString("Delete previous character"),
1016 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1017 return Editline::InstanceFor(editline)->DeletePreviousCharCommand(ch);
1019 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-line"),
1020 EditLineConstString("Move to previous line"),
1021 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1022 return Editline::InstanceFor(editline)->PreviousLineCommand(ch);
1024 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-line"),
1025 EditLineConstString("Move to next line"),
1026 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1027 return Editline::InstanceFor(editline)->NextLineCommand(ch);
1029 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-history"),
1030 EditLineConstString("Move to previous history"),
1031 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1032 return Editline::InstanceFor(editline)->PreviousHistoryCommand(ch);
1034 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-history"),
1035 EditLineConstString("Move to next history"),
1036 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1037 return Editline::InstanceFor(editline)->NextHistoryCommand(ch);
1039 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-start"),
1040 EditLineConstString("Move to start of buffer"),
1041 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1042 return Editline::InstanceFor(editline)->BufferStartCommand(ch);
1044 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-end"),
1045 EditLineConstString("Move to end of buffer"),
1046 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1047 return Editline::InstanceFor(editline)->BufferEndCommand(ch);
1049 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-fix-indentation"),
1050 EditLineConstString("Fix line indentation"),
1051 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1052 return Editline::InstanceFor(editline)->FixIndentationCommand(ch);
1055 // Register the complete callback under two names for compatibility with
1056 // older clients using custom .editrc files (largely because libedit has a
1057 // bad bug where if you have a bind command that tries to bind to a function
1058 // name that doesn't exist, it can corrupt the heap and crash your process
1060 EditlineCommandCallbackType complete_callback = [](EditLine *editline,
1062 return Editline::InstanceFor(editline)->TabCommand(ch);
1064 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-complete"),
1065 EditLineConstString("Invoke completion"), complete_callback);
1066 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb_complete"),
1067 EditLineConstString("Invoke completion"), complete_callback);
1069 // General bindings we don't mind being overridden
1071 el_set(m_editline, EL_BIND, "^r", "em-inc-search-prev",
1072 NULL); // Cycle through backwards search, entering string
1074 el_set(m_editline, EL_BIND, "^w", "ed-delete-prev-word",
1075 NULL); // Delete previous word, behave like bash in emacs mode
1076 el_set(m_editline, EL_BIND, "\t", "lldb-complete",
1077 NULL); // Bind TAB to auto complete
1079 // Allow user-specific customization prior to registering bindings we
1080 // absolutely require
1081 el_source(m_editline, NULL);
1083 // Register an internal binding that external developers shouldn't use
1084 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-revert-line"),
1085 EditLineConstString("Revert line to saved state"),
1086 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1087 return Editline::InstanceFor(editline)->RevertLineCommand(ch);
1090 // Register keys that perform auto-indent correction
1091 if (m_fix_indentation_callback && m_fix_indentation_callback_chars) {
1092 char bind_key[2] = {0, 0};
1093 const char *indent_chars = m_fix_indentation_callback_chars;
1094 while (*indent_chars) {
1095 bind_key[0] = *indent_chars;
1096 el_set(m_editline, EL_BIND, bind_key, "lldb-fix-indentation", NULL);
1101 // Multi-line editor bindings
1103 el_set(m_editline, EL_BIND, "\n", "lldb-end-or-add-line", NULL);
1104 el_set(m_editline, EL_BIND, "\r", "lldb-end-or-add-line", NULL);
1105 el_set(m_editline, EL_BIND, ESCAPE "\n", "lldb-break-line", NULL);
1106 el_set(m_editline, EL_BIND, ESCAPE "\r", "lldb-break-line", NULL);
1107 el_set(m_editline, EL_BIND, "^p", "lldb-previous-line", NULL);
1108 el_set(m_editline, EL_BIND, "^n", "lldb-next-line", NULL);
1109 el_set(m_editline, EL_BIND, "^?", "lldb-delete-previous-char", NULL);
1110 el_set(m_editline, EL_BIND, "^d", "lldb-delete-next-char", NULL);
1111 el_set(m_editline, EL_BIND, ESCAPE "[3~", "lldb-delete-next-char", NULL);
1112 el_set(m_editline, EL_BIND, ESCAPE "[\\^", "lldb-revert-line", NULL);
1114 // Editor-specific bindings
1116 el_set(m_editline, EL_BIND, ESCAPE "<", "lldb-buffer-start", NULL);
1117 el_set(m_editline, EL_BIND, ESCAPE ">", "lldb-buffer-end", NULL);
1118 el_set(m_editline, EL_BIND, ESCAPE "[A", "lldb-previous-line", NULL);
1119 el_set(m_editline, EL_BIND, ESCAPE "[B", "lldb-next-line", NULL);
1120 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[A", "lldb-previous-history",
1122 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[B", "lldb-next-history",
1124 el_set(m_editline, EL_BIND, ESCAPE "[1;3A", "lldb-previous-history",
1126 el_set(m_editline, EL_BIND, ESCAPE "[1;3B", "lldb-next-history", NULL);
1128 el_set(m_editline, EL_BIND, "^H", "lldb-delete-previous-char", NULL);
1130 el_set(m_editline, EL_BIND, "-a", ESCAPE "[A", "lldb-previous-line",
1132 el_set(m_editline, EL_BIND, "-a", ESCAPE "[B", "lldb-next-line", NULL);
1133 el_set(m_editline, EL_BIND, "-a", "x", "lldb-delete-next-char", NULL);
1134 el_set(m_editline, EL_BIND, "-a", "^H", "lldb-delete-previous-char",
1136 el_set(m_editline, EL_BIND, "-a", "^?", "lldb-delete-previous-char",
1139 // Escape is absorbed exiting edit mode, so re-register important
1140 // sequences without the prefix
1141 el_set(m_editline, EL_BIND, "-a", "[A", "lldb-previous-line", NULL);
1142 el_set(m_editline, EL_BIND, "-a", "[B", "lldb-next-line", NULL);
1143 el_set(m_editline, EL_BIND, "-a", "[\\^", "lldb-revert-line", NULL);
1148 //------------------------------------------------------------------
1149 // Editline public methods
1150 //------------------------------------------------------------------
1152 Editline *Editline::InstanceFor(EditLine *editline) {
1154 el_get(editline, EL_CLIENTDATA, &editor);
1158 Editline::Editline(const char *editline_name, FILE *input_file,
1159 FILE *output_file, FILE *error_file, bool color_prompts)
1160 : m_editor_status(EditorStatus::Complete), m_color_prompts(color_prompts),
1161 m_input_file(input_file), m_output_file(output_file),
1162 m_error_file(error_file), m_input_connection(fileno(input_file), false) {
1163 // Get a shared history instance
1164 m_editor_name = (editline_name == nullptr) ? "lldb-tmp" : editline_name;
1165 m_history_sp = EditlineHistory::GetHistory(m_editor_name);
1167 #ifdef USE_SETUPTERM_WORKAROUND
1168 if (m_output_file) {
1169 const int term_fd = fileno(m_output_file);
1170 if (term_fd != -1) {
1171 static std::mutex *g_init_terminal_fds_mutex_ptr = nullptr;
1172 static std::set<int> *g_init_terminal_fds_ptr = nullptr;
1173 static llvm::once_flag g_once_flag;
1174 llvm::call_once(g_once_flag, [&]() {
1175 g_init_terminal_fds_mutex_ptr =
1176 new std::mutex(); // NOTE: Leak to avoid C++ destructor chain issues
1177 g_init_terminal_fds_ptr = new std::set<int>(); // NOTE: Leak to avoid
1178 // C++ destructor chain
1182 // We must make sure to initialize the terminal a given file descriptor
1183 // only once. If we do this multiple times, we start leaking memory.
1184 std::lock_guard<std::mutex> guard(*g_init_terminal_fds_mutex_ptr);
1185 if (g_init_terminal_fds_ptr->find(term_fd) ==
1186 g_init_terminal_fds_ptr->end()) {
1187 g_init_terminal_fds_ptr->insert(term_fd);
1188 setupterm((char *)0, term_fd, (int *)0);
1195 Editline::~Editline() {
1197 // Disable edit mode to stop the terminal from flushing all input during
1198 // the call to el_end() since we expect to have multiple editline instances
1200 el_set(m_editline, EL_EDITMODE, 0);
1202 m_editline = nullptr;
1205 // EditlineHistory objects are sometimes shared between multiple Editline
1206 // instances with the same program name. So just release our shared pointer
1207 // and if we are the last owner, it will save the history to the history save
1208 // file automatically.
1209 m_history_sp.reset();
1212 void Editline::SetPrompt(const char *prompt) {
1213 m_set_prompt = prompt == nullptr ? "" : prompt;
1216 void Editline::SetContinuationPrompt(const char *continuation_prompt) {
1217 m_set_continuation_prompt =
1218 continuation_prompt == nullptr ? "" : continuation_prompt;
1221 void Editline::TerminalSizeChanged() {
1222 if (m_editline != nullptr) {
1223 el_resize(m_editline);
1225 // Despite the man page claiming non-zero indicates success, it's actually
1227 if (el_get(m_editline, EL_GETTC, "co", &columns) == 0) {
1228 m_terminal_width = columns;
1229 if (m_current_line_rows != -1) {
1230 const LineInfoW *info = el_wline(m_editline);
1232 (int)((info->lastchar - info->buffer) + GetPromptWidth());
1233 m_current_line_rows = (lineLength / columns) + 1;
1236 m_terminal_width = INT_MAX;
1237 m_current_line_rows = 1;
1242 const char *Editline::GetPrompt() { return m_set_prompt.c_str(); }
1244 uint32_t Editline::GetCurrentLine() { return m_current_line_index; }
1246 bool Editline::Interrupt() {
1248 std::lock_guard<std::mutex> guard(m_output_mutex);
1249 if (m_editor_status == EditorStatus::Editing) {
1250 fprintf(m_output_file, "^C\n");
1251 result = m_input_connection.InterruptRead();
1253 m_editor_status = EditorStatus::Interrupted;
1257 bool Editline::Cancel() {
1259 std::lock_guard<std::mutex> guard(m_output_mutex);
1260 if (m_editor_status == EditorStatus::Editing) {
1261 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1262 fprintf(m_output_file, ANSI_CLEAR_BELOW);
1263 result = m_input_connection.InterruptRead();
1265 m_editor_status = EditorStatus::Interrupted;
1269 void Editline::SetAutoCompleteCallback(CompleteCallbackType callback,
1271 m_completion_callback = callback;
1272 m_completion_callback_baton = baton;
1275 void Editline::SetIsInputCompleteCallback(IsInputCompleteCallbackType callback,
1277 m_is_input_complete_callback = callback;
1278 m_is_input_complete_callback_baton = baton;
1281 bool Editline::SetFixIndentationCallback(FixIndentationCallbackType callback,
1283 const char *indent_chars) {
1284 m_fix_indentation_callback = callback;
1285 m_fix_indentation_callback_baton = baton;
1286 m_fix_indentation_callback_chars = indent_chars;
1290 bool Editline::GetLine(std::string &line, bool &interrupted) {
1291 ConfigureEditor(false);
1292 m_input_lines = std::vector<EditLineStringType>();
1293 m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1295 std::lock_guard<std::mutex> guard(m_output_mutex);
1297 lldbassert(m_editor_status != EditorStatus::Editing);
1298 if (m_editor_status == EditorStatus::Interrupted) {
1299 m_editor_status = EditorStatus::Complete;
1305 m_in_history = false;
1306 m_editor_status = EditorStatus::Editing;
1307 m_revert_cursor_index = -1;
1310 auto input = el_wgets(m_editline, &count);
1312 interrupted = m_editor_status == EditorStatus::Interrupted;
1314 if (input == nullptr) {
1315 fprintf(m_output_file, "\n");
1316 m_editor_status = EditorStatus::EndOfInput;
1318 m_history_sp->Enter(input);
1319 #if LLDB_EDITLINE_USE_WCHAR
1320 line = m_utf8conv.to_bytes(SplitLines(input)[0]);
1322 line = SplitLines(input)[0];
1324 m_editor_status = EditorStatus::Complete;
1327 return m_editor_status != EditorStatus::EndOfInput;
1330 bool Editline::GetLines(int first_line_number, StringList &lines,
1331 bool &interrupted) {
1332 ConfigureEditor(true);
1334 // Print the initial input lines, then move the cursor back up to the start
1336 SetBaseLineNumber(first_line_number);
1337 m_input_lines = std::vector<EditLineStringType>();
1338 m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1340 std::lock_guard<std::mutex> guard(m_output_mutex);
1341 // Begin the line editing loop
1344 MoveCursor(CursorLocation::BlockEnd, CursorLocation::BlockStart);
1345 m_editor_status = EditorStatus::Editing;
1346 m_in_history = false;
1348 m_revert_cursor_index = -1;
1349 while (m_editor_status == EditorStatus::Editing) {
1351 m_current_line_rows = -1;
1352 el_wpush(m_editline, EditLineConstString(
1353 "\x1b[^")); // Revert to the existing line content
1354 el_wgets(m_editline, &count);
1357 interrupted = m_editor_status == EditorStatus::Interrupted;
1359 // Save the completed entry in history before returning
1360 m_history_sp->Enter(CombineLines(m_input_lines).c_str());
1362 lines = GetInputAsStringList();
1364 return m_editor_status != EditorStatus::EndOfInput;
1367 void Editline::PrintAsync(Stream *stream, const char *s, size_t len) {
1368 std::lock_guard<std::mutex> guard(m_output_mutex);
1369 if (m_editor_status == EditorStatus::Editing) {
1370 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1371 fprintf(m_output_file, ANSI_CLEAR_BELOW);
1373 stream->Write(s, len);
1375 if (m_editor_status == EditorStatus::Editing) {
1377 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
1381 bool Editline::CompleteCharacter(char ch, EditLineGetCharType &out) {
1382 #if !LLDB_EDITLINE_USE_WCHAR
1383 if (ch == (char)EOF)
1386 out = (unsigned char)ch;
1389 std::codecvt_utf8<wchar_t> cvt;
1390 llvm::SmallString<4> input;
1392 const char *from_next;
1394 std::mbstate_t state = std::mbstate_t();
1395 input.push_back(ch);
1396 switch (cvt.in(state, input.begin(), input.end(), from_next, &out, &out + 1,
1398 case std::codecvt_base::ok:
1401 case std::codecvt_base::error:
1402 case std::codecvt_base::noconv:
1405 case std::codecvt_base::partial:
1406 lldb::ConnectionStatus status;
1407 size_t read_count = m_input_connection.Read(
1408 &ch, 1, std::chrono::seconds(0), status, nullptr);
1409 if (read_count == 0)