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