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