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