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