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/Editline.h"
15 #include "lldb/Host/ConnectionFileDescriptor.h"
16 #include "lldb/Core/Error.h"
17 #include "lldb/Core/StringList.h"
18 #include "lldb/Core/StreamString.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"
24 using namespace lldb_private;
25 using namespace lldb_private::line_editor;
27 // Workaround for what looks like an OS X-specific issue, but other platforms
28 // may benefit from something similar if issues arise. The libedit library
29 // doesn't explicitly initialize the curses termcap library, which it gets away
30 // with until TERM is set to VT100 where it stumbles over an implementation
31 // assumption that may not exist on other platforms. The setupterm() function
32 // would normally require headers that don't work gracefully in this context, so
33 // the function declaraction has been hoisted here.
34 #if defined(__APPLE__)
36 int setupterm(char *term, int fildes, int *errret);
38 #define USE_SETUPTERM_WORKAROUND
41 // Editline uses careful cursor management to achieve the illusion of editing a multi-line block of text
42 // with a single line editor. Preserving this illusion requires fairly careful management of cursor
43 // state. Read and understand the relationship between DisplayInput(), MoveCursor(), SetCurrentLine(),
44 // and SaveEditedLine() before making changes.
47 #define ANSI_FAINT ESCAPE "[2m"
48 #define ANSI_UNFAINT ESCAPE "[22m"
49 #define ANSI_CLEAR_BELOW ESCAPE "[J"
50 #define ANSI_CLEAR_RIGHT ESCAPE "[K"
51 #define ANSI_SET_COLUMN_N ESCAPE "[%dG"
52 #define ANSI_UP_N_ROWS ESCAPE "[%dA"
53 #define ANSI_DOWN_N_ROWS ESCAPE "[%dB"
55 #if LLDB_EDITLINE_USE_WCHAR
57 #define EditLineConstString(str) L##str
58 #define EditLineStringFormatSpec "%ls"
62 #define EditLineConstString(str) str
63 #define EditLineStringFormatSpec "%s"
65 // use #defines so wide version functions and structs will resolve to old versions
66 // for case of libedit not built with wide char support
67 #define history_w history
68 #define history_winit history_init
69 #define history_wend history_end
70 #define HistoryW History
71 #define HistEventW HistEvent
72 #define LineInfoW LineInfo
74 #define el_wgets el_gets
75 #define el_wgetc el_getc
76 #define el_wpush el_push
77 #define el_wparse el_parse
78 #define el_wset el_set
79 #define el_wget el_get
80 #define el_wline el_line
81 #define el_winsertstr el_insertstr
82 #define el_wdeletestr el_deletestr
84 #endif // #if LLDB_EDITLINE_USE_WCHAR
87 IsOnlySpaces (const EditLineStringType & content)
89 for (wchar_t ch : content)
91 if (ch != EditLineCharType(' '))
98 CombineLines (const std::vector<EditLineStringType> & lines)
100 EditLineStringStreamType combined_stream;
101 for (EditLineStringType line : lines)
103 combined_stream << line.c_str() << "\n";
105 return combined_stream.str();
108 std::vector<EditLineStringType>
109 SplitLines (const EditLineStringType & input)
111 std::vector<EditLineStringType> result;
113 while (start < input.length())
115 size_t end = input.find ('\n', start);
116 if (end == std::string::npos)
118 result.insert (result.end(), input.substr (start));
121 result.insert (result.end(), input.substr (start, end - start));
128 FixIndentation (const EditLineStringType & line, int indent_correction)
130 if (indent_correction == 0)
132 if (indent_correction < 0)
133 return line.substr (-indent_correction);
134 return EditLineStringType (indent_correction, EditLineCharType(' ')) + line;
138 GetIndentation (const EditLineStringType & line)
141 for (EditLineCharType ch : line)
143 if (ch != EditLineCharType(' '))
151 IsInputPending (FILE * file)
153 // FIXME: This will be broken on Windows if we ever re-enable Editline. You can't use select
154 // on something that isn't a socket. This will have to be re-written to not use a FILE*, but
155 // instead use some kind of yet-to-be-created abstraction that select-like functionality on
156 // non-socket objects.
157 const int fd = fileno (file);
161 timeval timeout = { 0, 0 };
162 return select (fd + 1, &fds, NULL, NULL, &timeout);
165 namespace lldb_private
167 namespace line_editor
169 typedef std::weak_ptr<EditlineHistory> EditlineHistoryWP;
171 // EditlineHistory objects are sometimes shared between multiple
172 // Editline instances with the same program name.
174 class EditlineHistory
177 // Use static GetHistory() function to get a EditlineHistorySP to one of these objects
178 EditlineHistory (const std::string &prefix, uint32_t size, bool unique_entries) :
184 m_history = history_winit();
185 history_w (m_history, &m_event, H_SETSIZE, size);
187 history_w (m_history, &m_event, H_SETUNIQUE, 1);
193 if (m_path.empty() && m_history && !m_prefix.empty())
195 FileSpec parent_path{"~/.lldb", true};
196 char history_path[PATH_MAX];
197 if (FileSystem::MakeDirectory(parent_path, lldb::eFilePermissionsDirectoryDefault).Success())
199 snprintf (history_path, sizeof (history_path), "~/.lldb/%s-history", m_prefix.c_str());
203 snprintf (history_path, sizeof (history_path), "~/%s-widehistory", m_prefix.c_str());
205 m_path = FileSpec (history_path, true).GetPath();
209 return m_path.c_str();
220 history_wend (m_history);
225 static EditlineHistorySP
226 GetHistory (const std::string &prefix)
228 typedef std::map<std::string, EditlineHistoryWP> WeakHistoryMap;
229 static std::recursive_mutex g_mutex;
230 static WeakHistoryMap g_weak_map;
231 std::lock_guard<std::recursive_mutex> guard(g_mutex);
232 WeakHistoryMap::const_iterator pos = g_weak_map.find (prefix);
233 EditlineHistorySP history_sp;
234 if (pos != g_weak_map.end())
236 history_sp = pos->second.lock();
239 g_weak_map.erase (pos);
241 history_sp.reset (new EditlineHistory (prefix, 800, true));
242 g_weak_map[prefix] = history_sp;
248 return m_history != NULL;
258 Enter (const EditLineCharType *line_cstr)
261 history_w (m_history, &m_event, H_ENTER, line_cstr);
269 const char *path = GetHistoryFilePath();
272 history_w (m_history, &m_event, H_LOAD, path);
284 const char *path = GetHistoryFilePath();
287 history_w (m_history, &m_event, H_SAVE, path);
295 HistoryW * m_history; // The history object
296 HistEventW m_event; // The history event needed to contain all history events
297 std::string m_prefix; // The prefix name (usually the editline program name) to use when loading/saving history
298 std::string m_path; // Path to the history file
303 //------------------------------------------------------------------
304 // Editline private methods
305 //------------------------------------------------------------------
308 Editline::SetBaseLineNumber (int line_number)
310 std::stringstream line_number_stream;
311 line_number_stream << line_number;
312 m_base_line_number = line_number;
313 m_line_number_digits = std::max (3, (int)line_number_stream.str().length() + 1);
317 Editline::PromptForIndex (int line_index)
319 bool use_line_numbers = m_multiline_enabled && m_base_line_number > 0;
320 std::string prompt = m_set_prompt;
321 if (use_line_numbers && prompt.length() == 0)
325 std::string continuation_prompt = prompt;
326 if (m_set_continuation_prompt.length() > 0)
328 continuation_prompt = m_set_continuation_prompt;
330 // Ensure that both prompts are the same length through space padding
331 while (continuation_prompt.length() < prompt.length())
333 continuation_prompt += ' ';
335 while (prompt.length() < continuation_prompt.length())
341 if (use_line_numbers)
343 StreamString prompt_stream;
344 prompt_stream.Printf("%*d%s", m_line_number_digits, m_base_line_number + line_index,
345 (line_index == 0) ? prompt.c_str() : continuation_prompt.c_str());
346 return std::move (prompt_stream.GetString());
348 return (line_index == 0) ? prompt : continuation_prompt;
352 Editline::SetCurrentLine (int line_index)
354 m_current_line_index = line_index;
355 m_current_prompt = PromptForIndex (line_index);
359 Editline::GetPromptWidth()
361 return (int)PromptForIndex (0).length();
368 el_get (m_editline, EL_EDITOR, &editor);
369 return editor[0] == 'e';
373 Editline::IsOnlySpaces()
375 const LineInfoW * info = el_wline (m_editline);
376 for (const EditLineCharType * character = info->buffer; character < info->lastchar; character++)
378 if (*character != ' ')
385 Editline::GetLineIndexForLocation (CursorLocation location, int cursor_row)
388 if (location == CursorLocation::EditingPrompt || location == CursorLocation::BlockEnd ||
389 location == CursorLocation::EditingCursor)
391 for (unsigned index = 0; index < m_current_line_index; index++)
393 line += CountRowsForLine (m_input_lines[index]);
395 if (location == CursorLocation::EditingCursor)
399 else if (location == CursorLocation::BlockEnd)
401 for (unsigned index = m_current_line_index; index < m_input_lines.size(); index++)
403 line += CountRowsForLine (m_input_lines[index]);
412 Editline::MoveCursor (CursorLocation from, CursorLocation to)
414 const LineInfoW * info = el_wline (m_editline);
415 int editline_cursor_position = (int)((info->cursor - info->buffer) + GetPromptWidth());
416 int editline_cursor_row = editline_cursor_position / m_terminal_width;
418 // Determine relative starting and ending lines
419 int fromLine = GetLineIndexForLocation (from, editline_cursor_row);
420 int toLine = GetLineIndexForLocation (to, editline_cursor_row);
421 if (toLine != fromLine)
423 fprintf (m_output_file, (toLine > fromLine) ? ANSI_DOWN_N_ROWS : ANSI_UP_N_ROWS, std::abs (toLine - fromLine));
426 // Determine target column
428 if (to == CursorLocation::EditingCursor)
430 toColumn = editline_cursor_position - (editline_cursor_row * m_terminal_width) + 1;
432 else if (to == CursorLocation::BlockEnd)
434 toColumn = ((m_input_lines[m_input_lines.size() - 1].length() + GetPromptWidth()) % 80) + 1;
436 fprintf (m_output_file, ANSI_SET_COLUMN_N, toColumn);
440 Editline::DisplayInput (int firstIndex)
442 fprintf (m_output_file, ANSI_SET_COLUMN_N ANSI_CLEAR_BELOW, 1);
443 int line_count = (int)m_input_lines.size();
444 const char *faint = m_color_prompts ? ANSI_FAINT : "";
445 const char *unfaint = m_color_prompts ? ANSI_UNFAINT : "";
447 for (int index = firstIndex; index < line_count; index++)
449 fprintf (m_output_file, "%s" "%s" "%s" EditLineStringFormatSpec " ",
451 PromptForIndex (index).c_str(),
453 m_input_lines[index].c_str());
454 if (index < line_count - 1)
455 fprintf (m_output_file, "\n");
461 Editline::CountRowsForLine (const EditLineStringType & content)
463 auto prompt = PromptForIndex (0); // Prompt width is constant during an edit session
464 int line_length = (int)(content.length() + prompt.length());
465 return (line_length / m_terminal_width) + 1;
469 Editline::SaveEditedLine()
471 const LineInfoW * info = el_wline (m_editline);
472 m_input_lines[m_current_line_index] = EditLineStringType (info->buffer, info->lastchar - info->buffer);
476 Editline::GetInputAsStringList(int line_count)
479 for (EditLineStringType line : m_input_lines)
483 #if LLDB_EDITLINE_USE_WCHAR
484 lines.AppendString (m_utf8conv.to_bytes (line));
486 lines.AppendString(line);
494 Editline::RecallHistory (bool earlier)
496 if (!m_history_sp || !m_history_sp->IsValid())
499 HistoryW * pHistory = m_history_sp->GetHistoryPtr();
500 HistEventW history_event;
501 std::vector<EditLineStringType> new_input_lines;
503 // Treat moving from the "live" entry differently
506 if (earlier == false)
507 return CC_ERROR; // Can't go newer than the "live" entry
508 if (history_w (pHistory, &history_event, H_FIRST) == -1)
511 // Save any edits to the "live" entry in case we return by moving forward in history
512 // (it would be more bash-like to save over any current entry, but libedit doesn't
513 // offer the ability to add entries anywhere except the end.)
515 m_live_history_lines = m_input_lines;
520 if (history_w (pHistory, &history_event, earlier ? H_NEXT : H_PREV) == -1)
522 // Can't move earlier than the earliest entry
526 // ... but moving to newer than the newest yields the "live" entry
527 new_input_lines = m_live_history_lines;
528 m_in_history = false;
532 // If we're pulling the lines from history, split them apart
534 new_input_lines = SplitLines (history_event.str);
536 // Erase the current edit session and replace it with a new one
537 MoveCursor (CursorLocation::EditingCursor, CursorLocation::BlockStart);
538 m_input_lines = new_input_lines;
541 // Prepare to edit the last line when moving to previous entry, or the first line
542 // when moving to next entry
543 SetCurrentLine (m_current_line_index = earlier ? (int)m_input_lines.size() - 1 : 0);
544 MoveCursor (CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
549 Editline::GetCharacter (EditLineCharType * c)
551 const LineInfoW * info = el_wline (m_editline);
553 // Paint a faint version of the desired prompt over the version libedit draws
554 // (will only be requested if colors are supported)
555 if (m_needs_prompt_repaint)
557 MoveCursor (CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
558 fprintf (m_output_file, "%s" "%s" "%s", ANSI_FAINT, Prompt(), ANSI_UNFAINT);
559 MoveCursor (CursorLocation::EditingPrompt, CursorLocation::EditingCursor);
560 m_needs_prompt_repaint = false;
563 if (m_multiline_enabled)
565 // Detect when the number of rows used for this input line changes due to an edit
566 int lineLength = (int)((info->lastchar - info->buffer) + GetPromptWidth());
567 int new_line_rows = (lineLength / m_terminal_width) + 1;
568 if (m_current_line_rows != -1 && new_line_rows != m_current_line_rows)
570 // Respond by repainting the current state from this line on
571 MoveCursor (CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
573 DisplayInput (m_current_line_index);
574 MoveCursor (CursorLocation::BlockEnd, CursorLocation::EditingCursor);
576 m_current_line_rows = new_line_rows;
579 // Read an actual character
582 lldb::ConnectionStatus status = lldb::eConnectionStatusSuccess;
585 // This mutex is locked by our caller (GetLine). Unlock it while we read a character
586 // (blocking operation), so we do not hold the mutex indefinitely. This gives a chance
587 // for someone to interrupt us. After Read returns, immediately lock the mutex again and
588 // check if we were interrupted.
589 m_output_mutex.unlock();
590 int read_count = m_input_connection.Read(&ch, 1, UINT32_MAX, status, NULL);
591 m_output_mutex.lock();
592 if (m_editor_status == EditorStatus::Interrupted)
594 while (read_count > 0 && status == lldb::eConnectionStatusSuccess)
595 read_count = m_input_connection.Read(&ch, 1, UINT32_MAX, status, NULL);
596 lldbassert(status == lldb::eConnectionStatusInterrupted);
602 #if LLDB_EDITLINE_USE_WCHAR
603 // After the initial interruptible read, this is guaranteed not to block
604 ungetc (ch, m_input_file);
605 *c = fgetwc (m_input_file);
618 case lldb::eConnectionStatusSuccess: // Success
621 case lldb::eConnectionStatusInterrupted:
622 lldbassert(0 && "Interrupts should have been handled above.");
624 case lldb::eConnectionStatusError: // Check GetError() for details
625 case lldb::eConnectionStatusTimedOut: // Request timed out
626 case lldb::eConnectionStatusEndOfFile: // End-of-file encountered
627 case lldb::eConnectionStatusNoConnection: // No connection
628 case lldb::eConnectionStatusLostConnection: // Lost connection while connected to a valid connection
629 m_editor_status = EditorStatus::EndOfInput;
640 m_needs_prompt_repaint = true;
641 return m_current_prompt.c_str();
645 Editline::BreakLineCommand (int ch)
647 // Preserve any content beyond the cursor, truncate and save the current line
648 const LineInfoW * info = el_wline (m_editline);
649 auto current_line = EditLineStringType (info->buffer, info->cursor - info->buffer);
650 auto new_line_fragment = EditLineStringType (info->cursor, info->lastchar - info->cursor);
651 m_input_lines[m_current_line_index] = current_line;
653 // Ignore whitespace-only extra fragments when breaking a line
654 if (::IsOnlySpaces (new_line_fragment))
655 new_line_fragment = EditLineConstString("");
657 // Establish the new cursor position at the start of a line when inserting a line break
658 m_revert_cursor_index = 0;
660 // Don't perform automatic formatting when pasting
661 if (!IsInputPending (m_input_file))
663 // Apply smart indentation
664 if (m_fix_indentation_callback)
666 StringList lines = GetInputAsStringList (m_current_line_index + 1);
667 #if LLDB_EDITLINE_USE_WCHAR
668 lines.AppendString (m_utf8conv.to_bytes (new_line_fragment));
670 lines.AppendString (new_line_fragment);
673 int indent_correction = m_fix_indentation_callback (this, lines, 0, m_fix_indentation_callback_baton);
674 new_line_fragment = FixIndentation(new_line_fragment, indent_correction);
675 m_revert_cursor_index = GetIndentation(new_line_fragment);
679 // Insert the new line and repaint everything from the split line on down
680 m_input_lines.insert (m_input_lines.begin() + m_current_line_index + 1, new_line_fragment);
681 MoveCursor (CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
682 DisplayInput (m_current_line_index);
684 // Reposition the cursor to the right line and prepare to edit the new line
685 SetCurrentLine (m_current_line_index + 1);
686 MoveCursor (CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
691 Editline::EndOrAddLineCommand(int ch)
693 // Don't perform end of input detection when pasting, always treat this as a line break
694 if (IsInputPending(m_input_file))
696 return BreakLineCommand(ch);
699 // Save any edits to this line
702 // If this is the end of the last line, consider whether to add a line instead
703 const LineInfoW *info = el_wline(m_editline);
704 if (m_current_line_index == m_input_lines.size() - 1 && info->cursor == info->lastchar)
706 if (m_is_input_complete_callback)
708 auto lines = GetInputAsStringList();
709 if (!m_is_input_complete_callback(this, lines, m_is_input_complete_callback_baton))
711 return BreakLineCommand(ch);
714 // The completion test is allowed to change the input lines when complete
715 m_input_lines.clear();
716 for (unsigned index = 0; index < lines.GetSize(); index++)
718 #if LLDB_EDITLINE_USE_WCHAR
719 m_input_lines.insert(m_input_lines.end(), m_utf8conv.from_bytes(lines[index]));
721 m_input_lines.insert(m_input_lines.end(), lines[index]);
726 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
727 fprintf(m_output_file, "\n");
728 m_editor_status = EditorStatus::Complete;
733 Editline::DeleteNextCharCommand(int ch)
735 LineInfoW * info = const_cast<LineInfoW *>(el_wline (m_editline));
737 // Just delete the next character normally if possible
738 if (info->cursor < info->lastchar)
741 el_deletestr (m_editline, 1);
745 // Fail when at the end of the last line, except when ^D is pressed on
746 // the line is empty, in which case it is treated as EOF
747 if (m_current_line_index == m_input_lines.size() - 1)
749 if (ch == 4 && info->buffer == info->lastchar)
751 fprintf (m_output_file, "^D\n");
752 m_editor_status = EditorStatus::EndOfInput;
758 // Prepare to combine this line with the one below
759 MoveCursor (CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
761 // Insert the next line of text at the cursor and restore the cursor position
762 const EditLineCharType * cursor = info->cursor;
763 el_winsertstr (m_editline, m_input_lines[m_current_line_index + 1].c_str());
764 info->cursor = cursor;
767 // Delete the extra line
768 m_input_lines.erase (m_input_lines.begin() + m_current_line_index + 1);
770 // Clear and repaint from this line on down
771 DisplayInput (m_current_line_index);
772 MoveCursor (CursorLocation::BlockEnd, CursorLocation::EditingCursor);
777 Editline::DeletePreviousCharCommand (int ch)
779 LineInfoW * info = const_cast<LineInfoW *>(el_wline (m_editline));
781 // Just delete the previous character normally when not at the start of a line
782 if (info->cursor > info->buffer)
784 el_deletestr (m_editline, 1);
788 // No prior line and no prior character? Let the user know
789 if (m_current_line_index == 0)
792 // No prior character, but prior line? Combine with the line above
794 SetCurrentLine (m_current_line_index - 1);
795 auto priorLine = m_input_lines[m_current_line_index];
796 m_input_lines.erase (m_input_lines.begin() + m_current_line_index);
797 m_input_lines[m_current_line_index] = priorLine + m_input_lines[m_current_line_index];
799 // Repaint from the new line down
800 fprintf (m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N, CountRowsForLine (priorLine), 1);
801 DisplayInput (m_current_line_index);
803 // Put the cursor back where libedit expects it to be before returning to editing
804 // by telling libedit about the newly inserted text
805 MoveCursor (CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
806 el_winsertstr (m_editline, priorLine.c_str());
811 Editline::PreviousLineCommand (int ch)
815 if (m_current_line_index == 0) {
816 return RecallHistory (true);
819 // Start from a known location
820 MoveCursor (CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
822 // Treat moving up from a blank last line as a deletion of that line
823 if (m_current_line_index == m_input_lines.size() - 1 && IsOnlySpaces())
825 m_input_lines.erase (m_input_lines.begin() + m_current_line_index);
826 fprintf (m_output_file, ANSI_CLEAR_BELOW);
829 SetCurrentLine (m_current_line_index - 1);
830 fprintf (m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
831 CountRowsForLine (m_input_lines[m_current_line_index]), 1);
836 Editline::NextLineCommand (int ch)
840 // Handle attempts to move down from the last line
841 if (m_current_line_index == m_input_lines.size() - 1)
843 // Don't add an extra line if the existing last line is blank, move through history instead
846 return RecallHistory (false);
849 // Determine indentation for the new line
851 if (m_fix_indentation_callback)
853 StringList lines = GetInputAsStringList();
854 lines.AppendString("");
855 indentation = m_fix_indentation_callback (this, lines, 0, m_fix_indentation_callback_baton);
857 m_input_lines.insert (m_input_lines.end(), EditLineStringType (indentation, EditLineCharType(' ')));
860 // Move down past the current line using newlines to force scrolling if needed
861 SetCurrentLine (m_current_line_index + 1);
862 const LineInfoW * info = el_wline (m_editline);
863 int cursor_position = (int)((info->cursor - info->buffer) + GetPromptWidth());
864 int cursor_row = cursor_position / m_terminal_width;
865 for (int line_count = 0; line_count < m_current_line_rows - cursor_row; line_count++)
867 fprintf (m_output_file, "\n");
873 Editline::PreviousHistoryCommand(int ch)
877 return RecallHistory(true);
881 Editline::NextHistoryCommand(int ch)
885 return RecallHistory(false);
889 Editline::FixIndentationCommand(int ch)
891 if (!m_fix_indentation_callback)
894 // Insert the character typed before proceeding
895 EditLineCharType inserted[] = { (EditLineCharType)ch, 0 };
896 el_winsertstr (m_editline, inserted);
897 LineInfoW * info = const_cast<LineInfoW *>(el_wline (m_editline));
898 int cursor_position = info->cursor - info->buffer;
900 // Save the edits and determine the correct indentation level
902 StringList lines = GetInputAsStringList (m_current_line_index + 1);
903 int indent_correction = m_fix_indentation_callback (this, lines, cursor_position, m_fix_indentation_callback_baton);
905 // If it is already correct no special work is needed
906 if (indent_correction == 0)
909 // Change the indentation level of the line
910 std::string currentLine = lines.GetStringAtIndex (m_current_line_index);
911 if (indent_correction > 0)
913 currentLine = currentLine.insert (0, indent_correction, ' ');
917 currentLine = currentLine.erase (0, -indent_correction);
919 #if LLDB_EDITLINE_USE_WCHAR
920 m_input_lines[m_current_line_index] = m_utf8conv.from_bytes (currentLine);
922 m_input_lines[m_current_line_index] = currentLine;
925 // Update the display to reflect the change
926 MoveCursor (CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
927 DisplayInput (m_current_line_index);
929 // Reposition the cursor back on the original line and prepare to restart editing
930 // with a new cursor position
931 SetCurrentLine (m_current_line_index);
932 MoveCursor (CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
933 m_revert_cursor_index = cursor_position + indent_correction;
938 Editline::RevertLineCommand (int ch)
940 el_winsertstr (m_editline, m_input_lines[m_current_line_index].c_str());
941 if (m_revert_cursor_index >= 0)
943 LineInfoW * info = const_cast<LineInfoW *>(el_wline (m_editline));
944 info->cursor = info->buffer + m_revert_cursor_index;
945 if (info->cursor > info->lastchar)
947 info->cursor = info->lastchar;
949 m_revert_cursor_index = -1;
955 Editline::BufferStartCommand (int ch)
958 MoveCursor (CursorLocation::EditingCursor, CursorLocation::BlockStart);
960 m_revert_cursor_index = 0;
965 Editline::BufferEndCommand (int ch)
968 MoveCursor (CursorLocation::EditingCursor, CursorLocation::BlockEnd);
969 SetCurrentLine ((int)m_input_lines.size() - 1);
970 MoveCursor (CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
975 Editline::TabCommand (int ch)
977 if (m_completion_callback == nullptr)
980 const LineInfo *line_info = el_line (m_editline);
981 StringList completions;
984 const int num_completions = m_completion_callback (line_info->buffer,
987 0, // Don't skip any matches (start at match zero)
988 -1, // Get all the matches
990 m_completion_callback_baton);
992 if (num_completions == 0)
994 // if (num_completions == -1)
996 // el_insertstr (m_editline, m_completion_key);
997 // return CC_REDISPLAY;
1000 if (num_completions == -2)
1002 // Replace the entire line with the first string...
1003 el_deletestr (m_editline, line_info->cursor - line_info->buffer);
1004 el_insertstr (m_editline, completions.GetStringAtIndex (0));
1005 return CC_REDISPLAY;
1008 // If we get a longer match display that first.
1009 const char *completion_str = completions.GetStringAtIndex (0);
1010 if (completion_str != nullptr && *completion_str != '\0')
1012 el_insertstr (m_editline, completion_str);
1013 return CC_REDISPLAY;
1016 if (num_completions > 1)
1018 int num_elements = num_completions + 1;
1019 fprintf (m_output_file, "\n" ANSI_CLEAR_BELOW "Available completions:");
1020 if (num_completions < page_size)
1022 for (int i = 1; i < num_elements; i++)
1024 completion_str = completions.GetStringAtIndex (i);
1025 fprintf (m_output_file, "\n\t%s", completion_str);
1027 fprintf (m_output_file, "\n");
1034 while (cur_pos < num_elements)
1036 int endpoint = cur_pos + page_size;
1037 if (endpoint > num_elements)
1038 endpoint = num_elements;
1039 for (; cur_pos < endpoint; cur_pos++)
1041 completion_str = completions.GetStringAtIndex (cur_pos);
1042 fprintf (m_output_file, "\n\t%s", completion_str);
1045 if (cur_pos >= num_elements)
1047 fprintf (m_output_file, "\n");
1051 fprintf (m_output_file, "\nMore (Y/n/a): ");
1053 got_char = el_getc(m_editline, &reply);
1054 if (got_char == -1 || reply == 'n')
1057 page_size = num_elements - cur_pos;
1061 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
1063 return CC_REDISPLAY;
1067 Editline::ConfigureEditor (bool multiline)
1069 if (m_editline && m_multiline_enabled == multiline)
1071 m_multiline_enabled = multiline;
1075 // Disable edit mode to stop the terminal from flushing all input
1076 // during the call to el_end() since we expect to have multiple editline
1077 // instances in this program.
1078 el_set (m_editline, EL_EDITMODE, 0);
1079 el_end (m_editline);
1082 m_editline = el_init (m_editor_name.c_str(), m_input_file, m_output_file, m_error_file);
1083 TerminalSizeChanged();
1085 if (m_history_sp && m_history_sp->IsValid())
1087 m_history_sp->Load();
1088 el_wset (m_editline, EL_HIST, history, m_history_sp->GetHistoryPtr());
1090 el_set (m_editline, EL_CLIENTDATA, this);
1091 el_set (m_editline, EL_SIGNAL, 0);
1092 el_set (m_editline, EL_EDITOR, "emacs");
1093 el_set (m_editline, EL_PROMPT, (EditlinePromptCallbackType)([] (EditLine *editline) {
1094 return Editline::InstanceFor (editline)->Prompt();
1097 el_wset (m_editline, EL_GETCFN,
1098 (EditlineGetCharCallbackType)([] (EditLine * editline, EditLineCharType * c) {
1099 return Editline::InstanceFor (editline)->GetCharacter (c);
1102 // Commands used for multiline support, registered whether or not they're used
1103 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-break-line"), EditLineConstString("Insert a line break"),
1104 (EditlineCommandCallbackType)(
1105 [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->BreakLineCommand(ch); }));
1106 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-end-or-add-line"),
1107 EditLineConstString("End editing or continue when incomplete"),
1108 (EditlineCommandCallbackType)(
1109 [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->EndOrAddLineCommand(ch); }));
1110 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-delete-next-char"),
1111 EditLineConstString("Delete next character"), (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1112 return Editline::InstanceFor(editline)->DeleteNextCharCommand(ch);
1114 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-delete-previous-char"),
1115 EditLineConstString("Delete previous character"),
1116 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1117 return Editline::InstanceFor(editline)->DeletePreviousCharCommand(ch);
1119 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-line"),
1120 EditLineConstString("Move to previous line"), (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1121 return Editline::InstanceFor(editline)->PreviousLineCommand(ch);
1123 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-line"), EditLineConstString("Move to next line"),
1124 (EditlineCommandCallbackType)(
1125 [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->NextLineCommand(ch); }));
1126 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-history"),
1127 EditLineConstString("Move to previous history"),
1128 (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1129 return Editline::InstanceFor(editline)->PreviousHistoryCommand(ch);
1131 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-history"), EditLineConstString("Move to next history"),
1132 (EditlineCommandCallbackType)(
1133 [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->NextHistoryCommand(ch); }));
1134 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-start"),
1135 EditLineConstString("Move to start of buffer"),
1136 (EditlineCommandCallbackType)(
1137 [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->BufferStartCommand(ch); }));
1138 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-end"), EditLineConstString("Move to end of buffer"),
1139 (EditlineCommandCallbackType)(
1140 [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->BufferEndCommand(ch); }));
1141 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-fix-indentation"),
1142 EditLineConstString("Fix line indentation"), (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1143 return Editline::InstanceFor (editline)->FixIndentationCommand (ch);
1146 // Register the complete callback under two names for compatibility with older clients using
1147 // custom .editrc files (largely becuase libedit has a bad bug where if you have a bind command
1148 // that tries to bind to a function name that doesn't exist, it can corrupt the heap and
1149 // crash your process later.)
1150 EditlineCommandCallbackType complete_callback = [] (EditLine * editline, int ch) {
1151 return Editline::InstanceFor (editline)->TabCommand (ch);
1153 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-complete"), EditLineConstString("Invoke completion"),
1155 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb_complete"), EditLineConstString("Invoke completion"),
1158 // General bindings we don't mind being overridden
1160 el_set (m_editline, EL_BIND, "^r", "em-inc-search-prev", NULL); // Cycle through backwards search, entering string
1162 el_set (m_editline, EL_BIND, "^w", "ed-delete-prev-word", NULL); // Delete previous word, behave like bash in emacs mode
1163 el_set (m_editline, EL_BIND, "\t", "lldb-complete", NULL); // Bind TAB to auto complete
1165 // Allow user-specific customization prior to registering bindings we absolutely require
1166 el_source (m_editline, NULL);
1168 // Register an internal binding that external developers shouldn't use
1169 el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-revert-line"),
1170 EditLineConstString("Revert line to saved state"),
1171 (EditlineCommandCallbackType)(
1172 [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->RevertLineCommand(ch); }));
1174 // Register keys that perform auto-indent correction
1175 if (m_fix_indentation_callback && m_fix_indentation_callback_chars)
1177 char bind_key[2] = { 0, 0 };
1178 const char * indent_chars = m_fix_indentation_callback_chars;
1179 while (*indent_chars)
1181 bind_key[0] = *indent_chars;
1182 el_set (m_editline, EL_BIND, bind_key, "lldb-fix-indentation", NULL);
1187 // Multi-line editor bindings
1190 el_set(m_editline, EL_BIND, "\n", "lldb-end-or-add-line", NULL);
1191 el_set(m_editline, EL_BIND, "\r", "lldb-end-or-add-line", NULL);
1192 el_set(m_editline, EL_BIND, ESCAPE "\n", "lldb-break-line", NULL);
1193 el_set(m_editline, EL_BIND, ESCAPE "\r", "lldb-break-line", NULL);
1194 el_set (m_editline, EL_BIND, "^p", "lldb-previous-line", NULL);
1195 el_set (m_editline, EL_BIND, "^n", "lldb-next-line", NULL);
1196 el_set (m_editline, EL_BIND, "^?", "lldb-delete-previous-char", NULL);
1197 el_set (m_editline, EL_BIND, "^d", "lldb-delete-next-char", NULL);
1198 el_set (m_editline, EL_BIND, ESCAPE "[3~", "lldb-delete-next-char", NULL);
1199 el_set (m_editline, EL_BIND, ESCAPE "[\\^", "lldb-revert-line", NULL);
1201 // Editor-specific bindings
1204 el_set (m_editline, EL_BIND, ESCAPE "<", "lldb-buffer-start", NULL);
1205 el_set (m_editline, EL_BIND, ESCAPE ">", "lldb-buffer-end", NULL);
1206 el_set (m_editline, EL_BIND, ESCAPE "[A", "lldb-previous-line", NULL);
1207 el_set (m_editline, EL_BIND, ESCAPE "[B", "lldb-next-line", NULL);
1208 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[A", "lldb-previous-history", NULL);
1209 el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[B", "lldb-next-history", NULL);
1210 el_set(m_editline, EL_BIND, ESCAPE "[1;3A", "lldb-previous-history", NULL);
1211 el_set(m_editline, EL_BIND, ESCAPE "[1;3B", "lldb-next-history", NULL);
1215 el_set (m_editline, EL_BIND, "^H", "lldb-delete-previous-char", NULL);
1217 el_set (m_editline, EL_BIND, "-a", ESCAPE "[A", "lldb-previous-line", NULL);
1218 el_set (m_editline, EL_BIND, "-a", ESCAPE "[B", "lldb-next-line", NULL);
1219 el_set (m_editline, EL_BIND, "-a", "x", "lldb-delete-next-char", NULL);
1220 el_set (m_editline, EL_BIND, "-a", "^H", "lldb-delete-previous-char", NULL);
1221 el_set (m_editline, EL_BIND, "-a", "^?", "lldb-delete-previous-char", NULL);
1223 // Escape is absorbed exiting edit mode, so re-register important sequences
1224 // without the prefix
1225 el_set (m_editline, EL_BIND, "-a", "[A", "lldb-previous-line", NULL);
1226 el_set (m_editline, EL_BIND, "-a", "[B", "lldb-next-line", NULL);
1227 el_set (m_editline, EL_BIND, "-a", "[\\^", "lldb-revert-line", NULL);
1232 //------------------------------------------------------------------
1233 // Editline public methods
1234 //------------------------------------------------------------------
1237 Editline::InstanceFor (EditLine * editline)
1240 el_get (editline, EL_CLIENTDATA, &editor);
1244 Editline::Editline (const char * editline_name, FILE * input_file, FILE * output_file, FILE * error_file, bool color_prompts) :
1245 m_editor_status (EditorStatus::Complete),
1246 m_color_prompts(color_prompts),
1247 m_input_file (input_file),
1248 m_output_file (output_file),
1249 m_error_file (error_file),
1250 m_input_connection (fileno(input_file), false)
1252 // Get a shared history instance
1253 m_editor_name = (editline_name == nullptr) ? "lldb-tmp" : editline_name;
1254 m_history_sp = EditlineHistory::GetHistory (m_editor_name);
1256 #ifdef USE_SETUPTERM_WORKAROUND
1259 const int term_fd = fileno(m_output_file);
1262 static std::mutex *g_init_terminal_fds_mutex_ptr = nullptr;
1263 static std::set<int> *g_init_terminal_fds_ptr = nullptr;
1264 static std::once_flag g_once_flag;
1265 std::call_once(g_once_flag, [&]() {
1266 g_init_terminal_fds_mutex_ptr = new std::mutex(); // NOTE: Leak to avoid C++ destructor chain issues
1267 g_init_terminal_fds_ptr = new std::set<int>(); // NOTE: Leak to avoid C++ destructor chain issues
1270 // We must make sure to initialize the terminal a given file descriptor
1271 // only once. If we do this multiple times, we start leaking memory.
1272 std::lock_guard<std::mutex> guard(*g_init_terminal_fds_mutex_ptr);
1273 if (g_init_terminal_fds_ptr->find(term_fd) == g_init_terminal_fds_ptr->end())
1275 g_init_terminal_fds_ptr->insert(term_fd);
1276 setupterm((char *)0, term_fd, (int *)0);
1283 Editline::~Editline()
1287 // Disable edit mode to stop the terminal from flushing all input
1288 // during the call to el_end() since we expect to have multiple editline
1289 // instances in this program.
1290 el_set (m_editline, EL_EDITMODE, 0);
1291 el_end (m_editline);
1292 m_editline = nullptr;
1295 // EditlineHistory objects are sometimes shared between multiple
1296 // Editline instances with the same program name. So just release
1297 // our shared pointer and if we are the last owner, it will save the
1298 // history to the history save file automatically.
1299 m_history_sp.reset();
1303 Editline::SetPrompt (const char * prompt)
1305 m_set_prompt = prompt == nullptr ? "" : prompt;
1309 Editline::SetContinuationPrompt (const char * continuation_prompt)
1311 m_set_continuation_prompt = continuation_prompt == nullptr ? "" : continuation_prompt;
1315 Editline::TerminalSizeChanged()
1317 if (m_editline != nullptr)
1319 el_resize (m_editline);
1321 // Despite the man page claiming non-zero indicates success, it's actually zero
1322 if (el_get (m_editline, EL_GETTC, "co", &columns) == 0)
1324 m_terminal_width = columns;
1325 if (m_current_line_rows != -1)
1327 const LineInfoW * info = el_wline (m_editline);
1328 int lineLength = (int)((info->lastchar - info->buffer) + GetPromptWidth());
1329 m_current_line_rows = (lineLength / columns) + 1;
1334 m_terminal_width = INT_MAX;
1335 m_current_line_rows = 1;
1341 Editline::GetPrompt()
1343 return m_set_prompt.c_str();
1347 Editline::GetCurrentLine()
1349 return m_current_line_index;
1353 Editline::Interrupt()
1356 std::lock_guard<std::mutex> guard(m_output_mutex);
1357 if (m_editor_status == EditorStatus::Editing) {
1358 fprintf(m_output_file, "^C\n");
1359 result = m_input_connection.InterruptRead();
1361 m_editor_status = EditorStatus::Interrupted;
1369 std::lock_guard<std::mutex> guard(m_output_mutex);
1370 if (m_editor_status == EditorStatus::Editing) {
1371 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1372 fprintf(m_output_file, ANSI_CLEAR_BELOW);
1373 result = m_input_connection.InterruptRead();
1375 m_editor_status = EditorStatus::Interrupted;
1380 Editline::SetAutoCompleteCallback (CompleteCallbackType callback, void * baton)
1382 m_completion_callback = callback;
1383 m_completion_callback_baton = baton;
1387 Editline::SetIsInputCompleteCallback (IsInputCompleteCallbackType callback, void * baton)
1389 m_is_input_complete_callback = callback;
1390 m_is_input_complete_callback_baton = baton;
1394 Editline::SetFixIndentationCallback (FixIndentationCallbackType callback,
1396 const char * indent_chars)
1398 m_fix_indentation_callback = callback;
1399 m_fix_indentation_callback_baton = baton;
1400 m_fix_indentation_callback_chars = indent_chars;
1405 Editline::GetLine (std::string &line, bool &interrupted)
1407 ConfigureEditor (false);
1408 m_input_lines = std::vector<EditLineStringType>();
1409 m_input_lines.insert (m_input_lines.begin(), EditLineConstString(""));
1411 std::lock_guard<std::mutex> guard(m_output_mutex);
1413 lldbassert(m_editor_status != EditorStatus::Editing);
1414 if (m_editor_status == EditorStatus::Interrupted)
1416 m_editor_status = EditorStatus::Complete;
1422 m_in_history = false;
1423 m_editor_status = EditorStatus::Editing;
1424 m_revert_cursor_index = -1;
1427 auto input = el_wgets (m_editline, &count);
1429 interrupted = m_editor_status == EditorStatus::Interrupted;
1432 if (input == nullptr)
1434 fprintf (m_output_file, "\n");
1435 m_editor_status = EditorStatus::EndOfInput;
1439 m_history_sp->Enter (input);
1440 #if LLDB_EDITLINE_USE_WCHAR
1441 line = m_utf8conv.to_bytes (SplitLines (input)[0]);
1443 line = SplitLines (input)[0];
1445 m_editor_status = EditorStatus::Complete;
1448 return m_editor_status != EditorStatus::EndOfInput;
1452 Editline::GetLines (int first_line_number, StringList &lines, bool &interrupted)
1454 ConfigureEditor (true);
1456 // Print the initial input lines, then move the cursor back up to the start of input
1457 SetBaseLineNumber (first_line_number);
1458 m_input_lines = std::vector<EditLineStringType>();
1459 m_input_lines.insert (m_input_lines.begin(), EditLineConstString(""));
1461 std::lock_guard<std::mutex> guard(m_output_mutex);
1462 // Begin the line editing loop
1465 MoveCursor (CursorLocation::BlockEnd, CursorLocation::BlockStart);
1466 m_editor_status = EditorStatus::Editing;
1467 m_in_history = false;
1469 m_revert_cursor_index = -1;
1470 while (m_editor_status == EditorStatus::Editing)
1473 m_current_line_rows = -1;
1474 el_wpush (m_editline, EditLineConstString("\x1b[^")); // Revert to the existing line content
1475 el_wgets (m_editline, &count);
1478 interrupted = m_editor_status == EditorStatus::Interrupted;
1481 // Save the completed entry in history before returning
1482 m_history_sp->Enter (CombineLines (m_input_lines).c_str());
1484 lines = GetInputAsStringList();
1486 return m_editor_status != EditorStatus::EndOfInput;
1490 Editline::PrintAsync (Stream *stream, const char *s, size_t len)
1492 std::lock_guard<std::mutex> guard(m_output_mutex);
1493 if (m_editor_status == EditorStatus::Editing)
1495 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1496 fprintf(m_output_file, ANSI_CLEAR_BELOW);
1498 stream->Write (s, len);
1500 if (m_editor_status == EditorStatus::Editing)
1503 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);