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 LLDB_EDITLINE_USE_WCHAR
530 // After the initial interruptible read, this is guaranteed not to block
531 ungetc(ch, m_input_file);
532 *c = fgetwc(m_input_file);
542 case lldb::eConnectionStatusSuccess: // Success
545 case lldb::eConnectionStatusInterrupted:
546 lldbassert(0 && "Interrupts should have been handled above.");
548 case lldb::eConnectionStatusError: // Check GetError() for details
549 case lldb::eConnectionStatusTimedOut: // Request timed out
550 case lldb::eConnectionStatusEndOfFile: // End-of-file encountered
551 case lldb::eConnectionStatusNoConnection: // No connection
552 case lldb::eConnectionStatusLostConnection: // Lost connection while
553 // connected to a valid
555 m_editor_status = EditorStatus::EndOfInput;
562 const char *Editline::Prompt() {
564 m_needs_prompt_repaint = true;
565 return m_current_prompt.c_str();
568 unsigned char Editline::BreakLineCommand(int ch) {
569 // Preserve any content beyond the cursor, truncate and save the current line
570 const LineInfoW *info = el_wline(m_editline);
572 EditLineStringType(info->buffer, info->cursor - info->buffer);
573 auto new_line_fragment =
574 EditLineStringType(info->cursor, info->lastchar - info->cursor);
575 m_input_lines[m_current_line_index] = current_line;
577 // Ignore whitespace-only extra fragments when breaking a line
578 if (::IsOnlySpaces(new_line_fragment))
579 new_line_fragment = EditLineConstString("");
581 // Establish the new cursor position at the start of a line when inserting a
583 m_revert_cursor_index = 0;
585 // Don't perform automatic formatting when pasting
586 if (!IsInputPending(m_input_file)) {
587 // Apply smart indentation
588 if (m_fix_indentation_callback) {
589 StringList lines = GetInputAsStringList(m_current_line_index + 1);
590 #if LLDB_EDITLINE_USE_WCHAR
591 lines.AppendString(m_utf8conv.to_bytes(new_line_fragment));
593 lines.AppendString(new_line_fragment);
596 int indent_correction = m_fix_indentation_callback(
597 this, lines, 0, m_fix_indentation_callback_baton);
598 new_line_fragment = FixIndentation(new_line_fragment, indent_correction);
599 m_revert_cursor_index = GetIndentation(new_line_fragment);
603 // Insert the new line and repaint everything from the split line on down
604 m_input_lines.insert(m_input_lines.begin() + m_current_line_index + 1,
606 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
607 DisplayInput(m_current_line_index);
609 // Reposition the cursor to the right line and prepare to edit the new line
610 SetCurrentLine(m_current_line_index + 1);
611 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
615 unsigned char Editline::EndOrAddLineCommand(int ch) {
616 // Don't perform end of input detection when pasting, always treat this as a
618 if (IsInputPending(m_input_file)) {
619 return BreakLineCommand(ch);
622 // Save any edits to this line
625 // If this is the end of the last line, consider whether to add a line instead
626 const LineInfoW *info = el_wline(m_editline);
627 if (m_current_line_index == m_input_lines.size() - 1 &&
628 info->cursor == info->lastchar) {
629 if (m_is_input_complete_callback) {
630 auto lines = GetInputAsStringList();
631 if (!m_is_input_complete_callback(this, lines,
632 m_is_input_complete_callback_baton)) {
633 return BreakLineCommand(ch);
636 // The completion test is allowed to change the input lines when complete
637 m_input_lines.clear();
638 for (unsigned index = 0; index < lines.GetSize(); index++) {
639 #if LLDB_EDITLINE_USE_WCHAR
640 m_input_lines.insert(m_input_lines.end(),
641 m_utf8conv.from_bytes(lines[index]));
643 m_input_lines.insert(m_input_lines.end(), lines[index]);
648 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
649 fprintf(m_output_file, "\n");
650 m_editor_status = EditorStatus::Complete;
654 unsigned char Editline::DeleteNextCharCommand(int ch) {
655 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
657 // Just delete the next character normally if possible
658 if (info->cursor < info->lastchar) {
660 el_deletestr(m_editline, 1);
664 // Fail when at the end of the last line, except when ^D is pressed on
665 // the line is empty, in which case it is treated as EOF
666 if (m_current_line_index == m_input_lines.size() - 1) {
667 if (ch == 4 && info->buffer == info->lastchar) {
668 fprintf(m_output_file, "^D\n");
669 m_editor_status = EditorStatus::EndOfInput;
675 // Prepare to combine this line with the one below
676 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
678 // Insert the next line of text at the cursor and restore the cursor position
679 const EditLineCharType *cursor = info->cursor;
680 el_winsertstr(m_editline, m_input_lines[m_current_line_index + 1].c_str());
681 info->cursor = cursor;
684 // Delete the extra line
685 m_input_lines.erase(m_input_lines.begin() + m_current_line_index + 1);
687 // Clear and repaint from this line on down
688 DisplayInput(m_current_line_index);
689 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
693 unsigned char Editline::DeletePreviousCharCommand(int ch) {
694 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
696 // Just delete the previous character normally when not at the start of a line
697 if (info->cursor > info->buffer) {
698 el_deletestr(m_editline, 1);
702 // No prior line and no prior character? Let the user know
703 if (m_current_line_index == 0)
706 // No prior character, but prior line? Combine with the line above
708 SetCurrentLine(m_current_line_index - 1);
709 auto priorLine = m_input_lines[m_current_line_index];
710 m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
711 m_input_lines[m_current_line_index] =
712 priorLine + m_input_lines[m_current_line_index];
714 // Repaint from the new line down
715 fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
716 CountRowsForLine(priorLine), 1);
717 DisplayInput(m_current_line_index);
719 // Put the cursor back where libedit expects it to be before returning to
721 // by telling libedit about the newly inserted text
722 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
723 el_winsertstr(m_editline, priorLine.c_str());
727 unsigned char Editline::PreviousLineCommand(int ch) {
730 if (m_current_line_index == 0) {
731 return RecallHistory(true);
734 // Start from a known location
735 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
737 // Treat moving up from a blank last line as a deletion of that line
738 if (m_current_line_index == m_input_lines.size() - 1 && IsOnlySpaces()) {
739 m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
740 fprintf(m_output_file, ANSI_CLEAR_BELOW);
743 SetCurrentLine(m_current_line_index - 1);
744 fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
745 CountRowsForLine(m_input_lines[m_current_line_index]), 1);
749 unsigned char Editline::NextLineCommand(int ch) {
752 // Handle attempts to move down from the last line
753 if (m_current_line_index == m_input_lines.size() - 1) {
754 // Don't add an extra line if the existing last line is blank, move through
756 if (IsOnlySpaces()) {
757 return RecallHistory(false);
760 // Determine indentation for the new line
762 if (m_fix_indentation_callback) {
763 StringList lines = GetInputAsStringList();
764 lines.AppendString("");
765 indentation = m_fix_indentation_callback(
766 this, lines, 0, m_fix_indentation_callback_baton);
768 m_input_lines.insert(
770 EditLineStringType(indentation, EditLineCharType(' ')));
773 // Move down past the current line using newlines to force scrolling if needed
774 SetCurrentLine(m_current_line_index + 1);
775 const LineInfoW *info = el_wline(m_editline);
776 int cursor_position = (int)((info->cursor - info->buffer) + GetPromptWidth());
777 int cursor_row = cursor_position / m_terminal_width;
778 for (int line_count = 0; line_count < m_current_line_rows - cursor_row;
780 fprintf(m_output_file, "\n");
785 unsigned char Editline::PreviousHistoryCommand(int ch) {
788 return RecallHistory(true);
791 unsigned char Editline::NextHistoryCommand(int ch) {
794 return RecallHistory(false);
797 unsigned char Editline::FixIndentationCommand(int ch) {
798 if (!m_fix_indentation_callback)
801 // Insert the character typed before proceeding
802 EditLineCharType inserted[] = {(EditLineCharType)ch, 0};
803 el_winsertstr(m_editline, inserted);
804 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
805 int cursor_position = info->cursor - info->buffer;
807 // Save the edits and determine the correct indentation level
809 StringList lines = GetInputAsStringList(m_current_line_index + 1);
810 int indent_correction = m_fix_indentation_callback(
811 this, lines, cursor_position, m_fix_indentation_callback_baton);
813 // If it is already correct no special work is needed
814 if (indent_correction == 0)
817 // Change the indentation level of the line
818 std::string currentLine = lines.GetStringAtIndex(m_current_line_index);
819 if (indent_correction > 0) {
820 currentLine = currentLine.insert(0, indent_correction, ' ');
822 currentLine = currentLine.erase(0, -indent_correction);
824 #if LLDB_EDITLINE_USE_WCHAR
825 m_input_lines[m_current_line_index] = m_utf8conv.from_bytes(currentLine);
827 m_input_lines[m_current_line_index] = currentLine;
830 // Update the display to reflect the change
831 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
832 DisplayInput(m_current_line_index);
834 // Reposition the cursor back on the original line and prepare to restart
836 // with a new cursor position
837 SetCurrentLine(m_current_line_index);
838 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
839 m_revert_cursor_index = cursor_position + indent_correction;
843 unsigned char Editline::RevertLineCommand(int ch) {
844 el_winsertstr(m_editline, m_input_lines[m_current_line_index].c_str());
845 if (m_revert_cursor_index >= 0) {
846 LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
847 info->cursor = info->buffer + m_revert_cursor_index;
848 if (info->cursor > info->lastchar) {
849 info->cursor = info->lastchar;
851 m_revert_cursor_index = -1;
856 unsigned char Editline::BufferStartCommand(int ch) {
858 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
860 m_revert_cursor_index = 0;
864 unsigned char Editline::BufferEndCommand(int ch) {
866 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
867 SetCurrentLine((int)m_input_lines.size() - 1);
868 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
872 unsigned char Editline::TabCommand(int ch) {
873 if (m_completion_callback == nullptr)
876 const LineInfo *line_info = el_line(m_editline);
877 StringList completions;
880 const int num_completions = m_completion_callback(
881 line_info->buffer, line_info->cursor, line_info->lastchar,
882 0, // Don't skip any matches (start at match zero)
883 -1, // Get all the matches
884 completions, m_completion_callback_baton);
886 if (num_completions == 0)
888 // if (num_completions == -1)
890 // el_insertstr (m_editline, m_completion_key);
891 // return CC_REDISPLAY;
894 if (num_completions == -2) {
895 // Replace the entire line with the first string...
896 el_deletestr(m_editline, line_info->cursor - line_info->buffer);
897 el_insertstr(m_editline, completions.GetStringAtIndex(0));
901 // If we get a longer match display that first.
902 const char *completion_str = completions.GetStringAtIndex(0);
903 if (completion_str != nullptr && *completion_str != '\0') {
904 el_insertstr(m_editline, completion_str);
908 if (num_completions > 1) {
909 int num_elements = num_completions + 1;
910 fprintf(m_output_file, "\n" ANSI_CLEAR_BELOW "Available completions:");
911 if (num_completions < page_size) {
912 for (int i = 1; i < num_elements; i++) {
913 completion_str = completions.GetStringAtIndex(i);
914 fprintf(m_output_file, "\n\t%s", completion_str);
916 fprintf(m_output_file, "\n");
921 while (cur_pos < num_elements) {
922 int endpoint = cur_pos + page_size;
923 if (endpoint > num_elements)
924 endpoint = num_elements;
925 for (; cur_pos < endpoint; cur_pos++) {
926 completion_str = completions.GetStringAtIndex(cur_pos);
927 fprintf(m_output_file, "\n\t%s", completion_str);
930 if (cur_pos >= num_elements) {
931 fprintf(m_output_file, "\n");
935 fprintf(m_output_file, "\nMore (Y/n/a): ");
937 got_char = el_getc(m_editline, &reply);
938 if (got_char == -1 || reply == 'n')
941 page_size = num_elements - cur_pos;
945 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
950 void Editline::ConfigureEditor(bool multiline) {
951 if (m_editline && m_multiline_enabled == multiline)
953 m_multiline_enabled = multiline;
956 // Disable edit mode to stop the terminal from flushing all input
957 // during the call to el_end() since we expect to have multiple editline
958 // instances in this program.
959 el_set(m_editline, EL_EDITMODE, 0);
964 el_init(m_editor_name.c_str(), m_input_file, m_output_file, m_error_file);
965 TerminalSizeChanged();
967 if (m_history_sp && m_history_sp->IsValid()) {
968 m_history_sp->Load();
969 el_wset(m_editline, EL_HIST, history, m_history_sp->GetHistoryPtr());
971 el_set(m_editline, EL_CLIENTDATA, this);
972 el_set(m_editline, EL_SIGNAL, 0);
973 el_set(m_editline, EL_EDITOR, "emacs");
974 el_set(m_editline, EL_PROMPT,
975 (EditlinePromptCallbackType)([](EditLine *editline) {
976 return Editline::InstanceFor(editline)->Prompt();
979 el_wset(m_editline, EL_GETCFN, (EditlineGetCharCallbackType)([](
980 EditLine *editline, EditLineCharType *c) {
981 return Editline::InstanceFor(editline)->GetCharacter(c);
984 // Commands used for multiline support, registered whether or not they're used
985 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-break-line"),
986 EditLineConstString("Insert a line break"),
987 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
988 return Editline::InstanceFor(editline)->BreakLineCommand(ch);
990 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-end-or-add-line"),
991 EditLineConstString("End editing or continue when incomplete"),
992 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
993 return Editline::InstanceFor(editline)->EndOrAddLineCommand(ch);
995 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-delete-next-char"),
996 EditLineConstString("Delete next character"),
997 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
998 return Editline::InstanceFor(editline)->DeleteNextCharCommand(ch);
1001 m_editline, EL_ADDFN, EditLineConstString("lldb-delete-previous-char"),
1002 EditLineConstString("Delete previous character"),
1003 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1004 return Editline::InstanceFor(editline)->DeletePreviousCharCommand(ch);
1006 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-line"),
1007 EditLineConstString("Move to previous line"),
1008 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1009 return Editline::InstanceFor(editline)->PreviousLineCommand(ch);
1011 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-line"),
1012 EditLineConstString("Move to next line"),
1013 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1014 return Editline::InstanceFor(editline)->NextLineCommand(ch);
1016 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-history"),
1017 EditLineConstString("Move to previous history"),
1018 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1019 return Editline::InstanceFor(editline)->PreviousHistoryCommand(ch);
1021 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-history"),
1022 EditLineConstString("Move to next history"),
1023 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1024 return Editline::InstanceFor(editline)->NextHistoryCommand(ch);
1026 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-start"),
1027 EditLineConstString("Move to start of buffer"),
1028 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1029 return Editline::InstanceFor(editline)->BufferStartCommand(ch);
1031 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-end"),
1032 EditLineConstString("Move to end of buffer"),
1033 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1034 return Editline::InstanceFor(editline)->BufferEndCommand(ch);
1036 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-fix-indentation"),
1037 EditLineConstString("Fix line indentation"),
1038 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1039 return Editline::InstanceFor(editline)->FixIndentationCommand(ch);
1042 // Register the complete callback under two names for compatibility with older
1044 // custom .editrc files (largely because libedit has a bad bug where if you
1045 // have a bind command
1046 // that tries to bind to a function name that doesn't exist, it can corrupt
1048 // crash your process later.)
1049 EditlineCommandCallbackType complete_callback = [](EditLine *editline,
1051 return Editline::InstanceFor(editline)->TabCommand(ch);
1053 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-complete"),
1054 EditLineConstString("Invoke completion"), complete_callback);
1055 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb_complete"),
1056 EditLineConstString("Invoke completion"), complete_callback);
1058 // General bindings we don't mind being overridden
1060 el_set(m_editline, EL_BIND, "^r", "em-inc-search-prev",
1061 NULL); // Cycle through backwards search, entering string
1063 el_set(m_editline, EL_BIND, "^w", "ed-delete-prev-word",
1064 NULL); // Delete previous word, behave like bash in emacs mode
1065 el_set(m_editline, EL_BIND, "\t", "lldb-complete",
1066 NULL); // Bind TAB to auto complete
1068 // Allow user-specific customization prior to registering bindings we
1069 // absolutely require
1070 el_source(m_editline, NULL);
1072 // Register an internal binding that external developers shouldn't use
1073 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-revert-line"),
1074 EditLineConstString("Revert line to saved state"),
1075 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1076 return Editline::InstanceFor(editline)->RevertLineCommand(ch);
1079 // Register keys that perform auto-indent correction
1080 if (m_fix_indentation_callback && m_fix_indentation_callback_chars) {
1081 char bind_key[2] = {0, 0};
1082 const char *indent_chars = m_fix_indentation_callback_chars;
1083 while (*indent_chars) {
1084 bind_key[0] = *indent_chars;
1085 el_set(m_editline, EL_BIND, bind_key, "lldb-fix-indentation", NULL);
1090 // Multi-line editor bindings
1092 el_set(m_editline, EL_BIND, "\n", "lldb-end-or-add-line", NULL);
1093 el_set(m_editline, EL_BIND, "\r", "lldb-end-or-add-line", NULL);
1094 el_set(m_editline, EL_BIND, ESCAPE "\n", "lldb-break-line", NULL);
1095 el_set(m_editline, EL_BIND, ESCAPE "\r", "lldb-break-line", NULL);
1096 el_set(m_editline, EL_BIND, "^p", "lldb-previous-line", NULL);
1097 el_set(m_editline, EL_BIND, "^n", "lldb-next-line", NULL);
1098 el_set(m_editline, EL_BIND, "^?", "lldb-delete-previous-char", NULL);
1099 el_set(m_editline, EL_BIND, "^d", "lldb-delete-next-char", NULL);
1100 el_set(m_editline, EL_BIND, ESCAPE "[3~", "lldb-delete-next-char", NULL);
1101 el_set(m_editline, EL_BIND, ESCAPE "[\\^", "lldb-revert-line", NULL);
1103 // Editor-specific bindings
1105 el_set(m_editline, EL_BIND, ESCAPE "<", "lldb-buffer-start", NULL);
1106 el_set(m_editline, EL_BIND, ESCAPE ">", "lldb-buffer-end", NULL);
1107 el_set(m_editline, EL_BIND, ESCAPE "[A", "lldb-previous-line", NULL);
1108 el_set(m_editline, EL_BIND, ESCAPE "[B", "lldb-next-line", NULL);
1109 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[A", "lldb-previous-history",
1111 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[B", "lldb-next-history",
1113 el_set(m_editline, EL_BIND, ESCAPE "[1;3A", "lldb-previous-history",
1115 el_set(m_editline, EL_BIND, ESCAPE "[1;3B", "lldb-next-history", NULL);
1117 el_set(m_editline, EL_BIND, "^H", "lldb-delete-previous-char", NULL);
1119 el_set(m_editline, EL_BIND, "-a", ESCAPE "[A", "lldb-previous-line",
1121 el_set(m_editline, EL_BIND, "-a", ESCAPE "[B", "lldb-next-line", NULL);
1122 el_set(m_editline, EL_BIND, "-a", "x", "lldb-delete-next-char", NULL);
1123 el_set(m_editline, EL_BIND, "-a", "^H", "lldb-delete-previous-char",
1125 el_set(m_editline, EL_BIND, "-a", "^?", "lldb-delete-previous-char",
1128 // Escape is absorbed exiting edit mode, so re-register important
1130 // without the prefix
1131 el_set(m_editline, EL_BIND, "-a", "[A", "lldb-previous-line", NULL);
1132 el_set(m_editline, EL_BIND, "-a", "[B", "lldb-next-line", NULL);
1133 el_set(m_editline, EL_BIND, "-a", "[\\^", "lldb-revert-line", NULL);
1138 //------------------------------------------------------------------
1139 // Editline public methods
1140 //------------------------------------------------------------------
1142 Editline *Editline::InstanceFor(EditLine *editline) {
1144 el_get(editline, EL_CLIENTDATA, &editor);
1148 Editline::Editline(const char *editline_name, FILE *input_file,
1149 FILE *output_file, FILE *error_file, bool color_prompts)
1150 : m_editor_status(EditorStatus::Complete), m_color_prompts(color_prompts),
1151 m_input_file(input_file), m_output_file(output_file),
1152 m_error_file(error_file), m_input_connection(fileno(input_file), false) {
1153 // Get a shared history instance
1154 m_editor_name = (editline_name == nullptr) ? "lldb-tmp" : editline_name;
1155 m_history_sp = EditlineHistory::GetHistory(m_editor_name);
1157 #ifdef USE_SETUPTERM_WORKAROUND
1158 if (m_output_file) {
1159 const int term_fd = fileno(m_output_file);
1160 if (term_fd != -1) {
1161 static std::mutex *g_init_terminal_fds_mutex_ptr = nullptr;
1162 static std::set<int> *g_init_terminal_fds_ptr = nullptr;
1163 static std::once_flag g_once_flag;
1164 std::call_once(g_once_flag, [&]() {
1165 g_init_terminal_fds_mutex_ptr =
1166 new std::mutex(); // NOTE: Leak to avoid C++ destructor chain issues
1167 g_init_terminal_fds_ptr = new std::set<int>(); // NOTE: Leak to avoid
1168 // C++ destructor chain
1172 // We must make sure to initialize the terminal a given file descriptor
1173 // only once. If we do this multiple times, we start leaking memory.
1174 std::lock_guard<std::mutex> guard(*g_init_terminal_fds_mutex_ptr);
1175 if (g_init_terminal_fds_ptr->find(term_fd) ==
1176 g_init_terminal_fds_ptr->end()) {
1177 g_init_terminal_fds_ptr->insert(term_fd);
1178 setupterm((char *)0, term_fd, (int *)0);
1185 Editline::~Editline() {
1187 // Disable edit mode to stop the terminal from flushing all input
1188 // during the call to el_end() since we expect to have multiple editline
1189 // instances in this program.
1190 el_set(m_editline, EL_EDITMODE, 0);
1192 m_editline = nullptr;
1195 // EditlineHistory objects are sometimes shared between multiple
1196 // Editline instances with the same program name. So just release
1197 // our shared pointer and if we are the last owner, it will save the
1198 // history to the history save file automatically.
1199 m_history_sp.reset();
1202 void Editline::SetPrompt(const char *prompt) {
1203 m_set_prompt = prompt == nullptr ? "" : prompt;
1206 void Editline::SetContinuationPrompt(const char *continuation_prompt) {
1207 m_set_continuation_prompt =
1208 continuation_prompt == nullptr ? "" : continuation_prompt;
1211 void Editline::TerminalSizeChanged() {
1212 if (m_editline != nullptr) {
1213 el_resize(m_editline);
1215 // Despite the man page claiming non-zero indicates success, it's actually
1217 if (el_get(m_editline, EL_GETTC, "co", &columns) == 0) {
1218 m_terminal_width = columns;
1219 if (m_current_line_rows != -1) {
1220 const LineInfoW *info = el_wline(m_editline);
1222 (int)((info->lastchar - info->buffer) + GetPromptWidth());
1223 m_current_line_rows = (lineLength / columns) + 1;
1226 m_terminal_width = INT_MAX;
1227 m_current_line_rows = 1;
1232 const char *Editline::GetPrompt() { return m_set_prompt.c_str(); }
1234 uint32_t Editline::GetCurrentLine() { return m_current_line_index; }
1236 bool Editline::Interrupt() {
1238 std::lock_guard<std::mutex> guard(m_output_mutex);
1239 if (m_editor_status == EditorStatus::Editing) {
1240 fprintf(m_output_file, "^C\n");
1241 result = m_input_connection.InterruptRead();
1243 m_editor_status = EditorStatus::Interrupted;
1247 bool Editline::Cancel() {
1249 std::lock_guard<std::mutex> guard(m_output_mutex);
1250 if (m_editor_status == EditorStatus::Editing) {
1251 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1252 fprintf(m_output_file, ANSI_CLEAR_BELOW);
1253 result = m_input_connection.InterruptRead();
1255 m_editor_status = EditorStatus::Interrupted;
1259 void Editline::SetAutoCompleteCallback(CompleteCallbackType callback,
1261 m_completion_callback = callback;
1262 m_completion_callback_baton = baton;
1265 void Editline::SetIsInputCompleteCallback(IsInputCompleteCallbackType callback,
1267 m_is_input_complete_callback = callback;
1268 m_is_input_complete_callback_baton = baton;
1271 bool Editline::SetFixIndentationCallback(FixIndentationCallbackType callback,
1273 const char *indent_chars) {
1274 m_fix_indentation_callback = callback;
1275 m_fix_indentation_callback_baton = baton;
1276 m_fix_indentation_callback_chars = indent_chars;
1280 bool Editline::GetLine(std::string &line, bool &interrupted) {
1281 ConfigureEditor(false);
1282 m_input_lines = std::vector<EditLineStringType>();
1283 m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1285 std::lock_guard<std::mutex> guard(m_output_mutex);
1287 lldbassert(m_editor_status != EditorStatus::Editing);
1288 if (m_editor_status == EditorStatus::Interrupted) {
1289 m_editor_status = EditorStatus::Complete;
1295 m_in_history = false;
1296 m_editor_status = EditorStatus::Editing;
1297 m_revert_cursor_index = -1;
1300 auto input = el_wgets(m_editline, &count);
1302 interrupted = m_editor_status == EditorStatus::Interrupted;
1304 if (input == nullptr) {
1305 fprintf(m_output_file, "\n");
1306 m_editor_status = EditorStatus::EndOfInput;
1308 m_history_sp->Enter(input);
1309 #if LLDB_EDITLINE_USE_WCHAR
1310 line = m_utf8conv.to_bytes(SplitLines(input)[0]);
1312 line = SplitLines(input)[0];
1314 m_editor_status = EditorStatus::Complete;
1317 return m_editor_status != EditorStatus::EndOfInput;
1320 bool Editline::GetLines(int first_line_number, StringList &lines,
1321 bool &interrupted) {
1322 ConfigureEditor(true);
1324 // Print the initial input lines, then move the cursor back up to the start of
1326 SetBaseLineNumber(first_line_number);
1327 m_input_lines = std::vector<EditLineStringType>();
1328 m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1330 std::lock_guard<std::mutex> guard(m_output_mutex);
1331 // Begin the line editing loop
1334 MoveCursor(CursorLocation::BlockEnd, CursorLocation::BlockStart);
1335 m_editor_status = EditorStatus::Editing;
1336 m_in_history = false;
1338 m_revert_cursor_index = -1;
1339 while (m_editor_status == EditorStatus::Editing) {
1341 m_current_line_rows = -1;
1342 el_wpush(m_editline, EditLineConstString(
1343 "\x1b[^")); // Revert to the existing line content
1344 el_wgets(m_editline, &count);
1347 interrupted = m_editor_status == EditorStatus::Interrupted;
1349 // Save the completed entry in history before returning
1350 m_history_sp->Enter(CombineLines(m_input_lines).c_str());
1352 lines = GetInputAsStringList();
1354 return m_editor_status != EditorStatus::EndOfInput;
1357 void Editline::PrintAsync(Stream *stream, const char *s, size_t len) {
1358 std::lock_guard<std::mutex> guard(m_output_mutex);
1359 if (m_editor_status == EditorStatus::Editing) {
1360 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1361 fprintf(m_output_file, ANSI_CLEAR_BELOW);
1363 stream->Write(s, len);
1365 if (m_editor_status == EditorStatus::Editing) {
1367 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);