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