xref: /freebsd-src/contrib/llvm-project/lldb/source/Host/common/Editline.cpp (revision 0b57cec536236d46e3dba9bd041533462f33dbb7)
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(nullptr), 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 = nullptr;
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 != nullptr; }
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 =
518         m_input_connection.Read(&ch, 1, llvm::None, status, nullptr);
519     m_output_mutex.lock();
520     if (m_editor_status == EditorStatus::Interrupted) {
521       while (read_count > 0 && status == lldb::eConnectionStatusSuccess)
522         read_count =
523             m_input_connection.Read(&ch, 1, llvm::None, status, nullptr);
524       lldbassert(status == lldb::eConnectionStatusInterrupted);
525       return 0;
526     }
527 
528     if (read_count) {
529       if (CompleteCharacter(ch, *c))
530         return 1;
531     } else {
532       switch (status) {
533       case lldb::eConnectionStatusSuccess: // Success
534         break;
535 
536       case lldb::eConnectionStatusInterrupted:
537         llvm_unreachable("Interrupts should have been handled above.");
538 
539       case lldb::eConnectionStatusError:        // Check GetError() for details
540       case lldb::eConnectionStatusTimedOut:     // Request timed out
541       case lldb::eConnectionStatusEndOfFile:    // End-of-file encountered
542       case lldb::eConnectionStatusNoConnection: // No connection
543       case lldb::eConnectionStatusLostConnection: // Lost connection while
544                                                   // connected to a valid
545                                                   // connection
546         m_editor_status = EditorStatus::EndOfInput;
547         return 0;
548       }
549     }
550   }
551 }
552 
553 const char *Editline::Prompt() {
554   if (m_color_prompts)
555     m_needs_prompt_repaint = true;
556   return m_current_prompt.c_str();
557 }
558 
559 unsigned char Editline::BreakLineCommand(int ch) {
560   // Preserve any content beyond the cursor, truncate and save the current line
561   const LineInfoW *info = el_wline(m_editline);
562   auto current_line =
563       EditLineStringType(info->buffer, info->cursor - info->buffer);
564   auto new_line_fragment =
565       EditLineStringType(info->cursor, info->lastchar - info->cursor);
566   m_input_lines[m_current_line_index] = current_line;
567 
568   // Ignore whitespace-only extra fragments when breaking a line
569   if (::IsOnlySpaces(new_line_fragment))
570     new_line_fragment = EditLineConstString("");
571 
572   // Establish the new cursor position at the start of a line when inserting a
573   // line break
574   m_revert_cursor_index = 0;
575 
576   // Don't perform automatic formatting when pasting
577   if (!IsInputPending(m_input_file)) {
578     // Apply smart indentation
579     if (m_fix_indentation_callback) {
580       StringList lines = GetInputAsStringList(m_current_line_index + 1);
581 #if LLDB_EDITLINE_USE_WCHAR
582       lines.AppendString(m_utf8conv.to_bytes(new_line_fragment));
583 #else
584       lines.AppendString(new_line_fragment);
585 #endif
586 
587       int indent_correction = m_fix_indentation_callback(
588           this, lines, 0, m_fix_indentation_callback_baton);
589       new_line_fragment = FixIndentation(new_line_fragment, indent_correction);
590       m_revert_cursor_index = GetIndentation(new_line_fragment);
591     }
592   }
593 
594   // Insert the new line and repaint everything from the split line on down
595   m_input_lines.insert(m_input_lines.begin() + m_current_line_index + 1,
596                        new_line_fragment);
597   MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
598   DisplayInput(m_current_line_index);
599 
600   // Reposition the cursor to the right line and prepare to edit the new line
601   SetCurrentLine(m_current_line_index + 1);
602   MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
603   return CC_NEWLINE;
604 }
605 
606 unsigned char Editline::EndOrAddLineCommand(int ch) {
607   // Don't perform end of input detection when pasting, always treat this as a
608   // line break
609   if (IsInputPending(m_input_file)) {
610     return BreakLineCommand(ch);
611   }
612 
613   // Save any edits to this line
614   SaveEditedLine();
615 
616   // If this is the end of the last line, consider whether to add a line
617   // instead
618   const LineInfoW *info = el_wline(m_editline);
619   if (m_current_line_index == m_input_lines.size() - 1 &&
620       info->cursor == info->lastchar) {
621     if (m_is_input_complete_callback) {
622       auto lines = GetInputAsStringList();
623       if (!m_is_input_complete_callback(this, lines,
624                                         m_is_input_complete_callback_baton)) {
625         return BreakLineCommand(ch);
626       }
627 
628       // The completion test is allowed to change the input lines when complete
629       m_input_lines.clear();
630       for (unsigned index = 0; index < lines.GetSize(); index++) {
631 #if LLDB_EDITLINE_USE_WCHAR
632         m_input_lines.insert(m_input_lines.end(),
633                              m_utf8conv.from_bytes(lines[index]));
634 #else
635         m_input_lines.insert(m_input_lines.end(), lines[index]);
636 #endif
637       }
638     }
639   }
640   MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
641   fprintf(m_output_file, "\n");
642   m_editor_status = EditorStatus::Complete;
643   return CC_NEWLINE;
644 }
645 
646 unsigned char Editline::DeleteNextCharCommand(int ch) {
647   LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
648 
649   // Just delete the next character normally if possible
650   if (info->cursor < info->lastchar) {
651     info->cursor++;
652     el_deletestr(m_editline, 1);
653     return CC_REFRESH;
654   }
655 
656   // Fail when at the end of the last line, except when ^D is pressed on the
657   // line is empty, in which case it is treated as EOF
658   if (m_current_line_index == m_input_lines.size() - 1) {
659     if (ch == 4 && info->buffer == info->lastchar) {
660       fprintf(m_output_file, "^D\n");
661       m_editor_status = EditorStatus::EndOfInput;
662       return CC_EOF;
663     }
664     return CC_ERROR;
665   }
666 
667   // Prepare to combine this line with the one below
668   MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
669 
670   // Insert the next line of text at the cursor and restore the cursor position
671   const EditLineCharType *cursor = info->cursor;
672   el_winsertstr(m_editline, m_input_lines[m_current_line_index + 1].c_str());
673   info->cursor = cursor;
674   SaveEditedLine();
675 
676   // Delete the extra line
677   m_input_lines.erase(m_input_lines.begin() + m_current_line_index + 1);
678 
679   // Clear and repaint from this line on down
680   DisplayInput(m_current_line_index);
681   MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
682   return CC_REFRESH;
683 }
684 
685 unsigned char Editline::DeletePreviousCharCommand(int ch) {
686   LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
687 
688   // Just delete the previous character normally when not at the start of a
689   // line
690   if (info->cursor > info->buffer) {
691     el_deletestr(m_editline, 1);
692     return CC_REFRESH;
693   }
694 
695   // No prior line and no prior character?  Let the user know
696   if (m_current_line_index == 0)
697     return CC_ERROR;
698 
699   // No prior character, but prior line?  Combine with the line above
700   SaveEditedLine();
701   SetCurrentLine(m_current_line_index - 1);
702   auto priorLine = m_input_lines[m_current_line_index];
703   m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
704   m_input_lines[m_current_line_index] =
705       priorLine + m_input_lines[m_current_line_index];
706 
707   // Repaint from the new line down
708   fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
709           CountRowsForLine(priorLine), 1);
710   DisplayInput(m_current_line_index);
711 
712   // Put the cursor back where libedit expects it to be before returning to
713   // editing by telling libedit about the newly inserted text
714   MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
715   el_winsertstr(m_editline, priorLine.c_str());
716   return CC_REDISPLAY;
717 }
718 
719 unsigned char Editline::PreviousLineCommand(int ch) {
720   SaveEditedLine();
721 
722   if (m_current_line_index == 0) {
723     return RecallHistory(true);
724   }
725 
726   // Start from a known location
727   MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
728 
729   // Treat moving up from a blank last line as a deletion of that line
730   if (m_current_line_index == m_input_lines.size() - 1 && IsOnlySpaces()) {
731     m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
732     fprintf(m_output_file, ANSI_CLEAR_BELOW);
733   }
734 
735   SetCurrentLine(m_current_line_index - 1);
736   fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
737           CountRowsForLine(m_input_lines[m_current_line_index]), 1);
738   return CC_NEWLINE;
739 }
740 
741 unsigned char Editline::NextLineCommand(int ch) {
742   SaveEditedLine();
743 
744   // Handle attempts to move down from the last line
745   if (m_current_line_index == m_input_lines.size() - 1) {
746     // Don't add an extra line if the existing last line is blank, move through
747     // history instead
748     if (IsOnlySpaces()) {
749       return RecallHistory(false);
750     }
751 
752     // Determine indentation for the new line
753     int indentation = 0;
754     if (m_fix_indentation_callback) {
755       StringList lines = GetInputAsStringList();
756       lines.AppendString("");
757       indentation = m_fix_indentation_callback(
758           this, lines, 0, m_fix_indentation_callback_baton);
759     }
760     m_input_lines.insert(
761         m_input_lines.end(),
762         EditLineStringType(indentation, EditLineCharType(' ')));
763   }
764 
765   // Move down past the current line using newlines to force scrolling if
766   // needed
767   SetCurrentLine(m_current_line_index + 1);
768   const LineInfoW *info = el_wline(m_editline);
769   int cursor_position = (int)((info->cursor - info->buffer) + GetPromptWidth());
770   int cursor_row = cursor_position / m_terminal_width;
771   for (int line_count = 0; line_count < m_current_line_rows - cursor_row;
772        line_count++) {
773     fprintf(m_output_file, "\n");
774   }
775   return CC_NEWLINE;
776 }
777 
778 unsigned char Editline::PreviousHistoryCommand(int ch) {
779   SaveEditedLine();
780 
781   return RecallHistory(true);
782 }
783 
784 unsigned char Editline::NextHistoryCommand(int ch) {
785   SaveEditedLine();
786 
787   return RecallHistory(false);
788 }
789 
790 unsigned char Editline::FixIndentationCommand(int ch) {
791   if (!m_fix_indentation_callback)
792     return CC_NORM;
793 
794   // Insert the character typed before proceeding
795   EditLineCharType inserted[] = {(EditLineCharType)ch, 0};
796   el_winsertstr(m_editline, inserted);
797   LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
798   int cursor_position = info->cursor - info->buffer;
799 
800   // Save the edits and determine the correct indentation level
801   SaveEditedLine();
802   StringList lines = GetInputAsStringList(m_current_line_index + 1);
803   int indent_correction = m_fix_indentation_callback(
804       this, lines, cursor_position, m_fix_indentation_callback_baton);
805 
806   // If it is already correct no special work is needed
807   if (indent_correction == 0)
808     return CC_REFRESH;
809 
810   // Change the indentation level of the line
811   std::string currentLine = lines.GetStringAtIndex(m_current_line_index);
812   if (indent_correction > 0) {
813     currentLine = currentLine.insert(0, indent_correction, ' ');
814   } else {
815     currentLine = currentLine.erase(0, -indent_correction);
816   }
817 #if LLDB_EDITLINE_USE_WCHAR
818   m_input_lines[m_current_line_index] = m_utf8conv.from_bytes(currentLine);
819 #else
820   m_input_lines[m_current_line_index] = currentLine;
821 #endif
822 
823   // Update the display to reflect the change
824   MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
825   DisplayInput(m_current_line_index);
826 
827   // Reposition the cursor back on the original line and prepare to restart
828   // editing with a new cursor position
829   SetCurrentLine(m_current_line_index);
830   MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
831   m_revert_cursor_index = cursor_position + indent_correction;
832   return CC_NEWLINE;
833 }
834 
835 unsigned char Editline::RevertLineCommand(int ch) {
836   el_winsertstr(m_editline, m_input_lines[m_current_line_index].c_str());
837   if (m_revert_cursor_index >= 0) {
838     LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
839     info->cursor = info->buffer + m_revert_cursor_index;
840     if (info->cursor > info->lastchar) {
841       info->cursor = info->lastchar;
842     }
843     m_revert_cursor_index = -1;
844   }
845   return CC_REFRESH;
846 }
847 
848 unsigned char Editline::BufferStartCommand(int ch) {
849   SaveEditedLine();
850   MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
851   SetCurrentLine(0);
852   m_revert_cursor_index = 0;
853   return CC_NEWLINE;
854 }
855 
856 unsigned char Editline::BufferEndCommand(int ch) {
857   SaveEditedLine();
858   MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
859   SetCurrentLine((int)m_input_lines.size() - 1);
860   MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
861   return CC_NEWLINE;
862 }
863 
864 /// Prints completions and their descriptions to the given file. Only the
865 /// completions in the interval [start, end) are printed.
866 static void PrintCompletion(FILE *output_file, size_t start, size_t end,
867                             StringList &completions, StringList &descriptions) {
868   // This is an 'int' because of printf.
869   int max_len = 0;
870 
871   for (size_t i = start; i < end; i++) {
872     const char *completion_str = completions.GetStringAtIndex(i);
873     max_len = std::max((int)strlen(completion_str), max_len);
874   }
875 
876   for (size_t i = start; i < end; i++) {
877     const char *completion_str = completions.GetStringAtIndex(i);
878     const char *description_str = descriptions.GetStringAtIndex(i);
879 
880     if (completion_str)
881       fprintf(output_file, "\n\t%-*s", max_len, completion_str);
882 
883     // Print the description if we got one.
884     if (description_str && strlen(description_str))
885       fprintf(output_file, " -- %s", description_str);
886   }
887 }
888 
889 unsigned char Editline::TabCommand(int ch) {
890   if (m_completion_callback == nullptr)
891     return CC_ERROR;
892 
893   const LineInfo *line_info = el_line(m_editline);
894   StringList completions, descriptions;
895   int page_size = 40;
896 
897   const int num_completions = m_completion_callback(
898       line_info->buffer, line_info->cursor, line_info->lastchar,
899       0,  // Don't skip any matches (start at match zero)
900       -1, // Get all the matches
901       completions, descriptions, m_completion_callback_baton);
902 
903   if (num_completions == 0)
904     return CC_ERROR;
905   //    if (num_completions == -1)
906   //    {
907   //        el_insertstr (m_editline, m_completion_key);
908   //        return CC_REDISPLAY;
909   //    }
910   //    else
911   if (num_completions == -2) {
912     // Replace the entire line with the first string...
913     el_deletestr(m_editline, line_info->cursor - line_info->buffer);
914     el_insertstr(m_editline, completions.GetStringAtIndex(0));
915     return CC_REDISPLAY;
916   }
917 
918   // If we get a longer match display that first.
919   const char *completion_str = completions.GetStringAtIndex(0);
920   if (completion_str != nullptr && *completion_str != '\0') {
921     el_insertstr(m_editline, completion_str);
922     return CC_REDISPLAY;
923   }
924 
925   if (num_completions > 1) {
926     int num_elements = num_completions + 1;
927     fprintf(m_output_file, "\n" ANSI_CLEAR_BELOW "Available completions:");
928     if (num_completions < page_size) {
929       PrintCompletion(m_output_file, 1, num_elements, completions,
930                       descriptions);
931       fprintf(m_output_file, "\n");
932     } else {
933       int cur_pos = 1;
934       char reply;
935       int got_char;
936       while (cur_pos < num_elements) {
937         int endpoint = cur_pos + page_size;
938         if (endpoint > num_elements)
939           endpoint = num_elements;
940 
941         PrintCompletion(m_output_file, cur_pos, endpoint, completions,
942                         descriptions);
943         cur_pos = endpoint;
944 
945         if (cur_pos >= num_elements) {
946           fprintf(m_output_file, "\n");
947           break;
948         }
949 
950         fprintf(m_output_file, "\nMore (Y/n/a): ");
951         reply = 'n';
952         got_char = el_getc(m_editline, &reply);
953         if (got_char == -1 || reply == 'n')
954           break;
955         if (reply == 'a')
956           page_size = num_elements - cur_pos;
957       }
958     }
959     DisplayInput();
960     MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
961   }
962   return CC_REDISPLAY;
963 }
964 
965 void Editline::ConfigureEditor(bool multiline) {
966   if (m_editline && m_multiline_enabled == multiline)
967     return;
968   m_multiline_enabled = multiline;
969 
970   if (m_editline) {
971     // Disable edit mode to stop the terminal from flushing all input during
972     // the call to el_end() since we expect to have multiple editline instances
973     // in this program.
974     el_set(m_editline, EL_EDITMODE, 0);
975     el_end(m_editline);
976   }
977 
978   m_editline =
979       el_init(m_editor_name.c_str(), m_input_file, m_output_file, m_error_file);
980   TerminalSizeChanged();
981 
982   if (m_history_sp && m_history_sp->IsValid()) {
983     if (!m_history_sp->Load()) {
984         fputs("Could not load history file\n.", m_output_file);
985     }
986     el_wset(m_editline, EL_HIST, history, m_history_sp->GetHistoryPtr());
987   }
988   el_set(m_editline, EL_CLIENTDATA, this);
989   el_set(m_editline, EL_SIGNAL, 0);
990   el_set(m_editline, EL_EDITOR, "emacs");
991   el_set(m_editline, EL_PROMPT,
992          (EditlinePromptCallbackType)([](EditLine *editline) {
993            return Editline::InstanceFor(editline)->Prompt();
994          }));
995 
996   el_wset(m_editline, EL_GETCFN, (EditlineGetCharCallbackType)([](
997                                      EditLine *editline, EditLineGetCharType *c) {
998             return Editline::InstanceFor(editline)->GetCharacter(c);
999           }));
1000 
1001   // Commands used for multiline support, registered whether or not they're
1002   // used
1003   el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-break-line"),
1004           EditLineConstString("Insert a line break"),
1005           (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1006             return Editline::InstanceFor(editline)->BreakLineCommand(ch);
1007           }));
1008   el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-end-or-add-line"),
1009           EditLineConstString("End editing or continue when incomplete"),
1010           (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1011             return Editline::InstanceFor(editline)->EndOrAddLineCommand(ch);
1012           }));
1013   el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-delete-next-char"),
1014           EditLineConstString("Delete next character"),
1015           (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1016             return Editline::InstanceFor(editline)->DeleteNextCharCommand(ch);
1017           }));
1018   el_wset(
1019       m_editline, EL_ADDFN, EditLineConstString("lldb-delete-previous-char"),
1020       EditLineConstString("Delete previous character"),
1021       (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1022         return Editline::InstanceFor(editline)->DeletePreviousCharCommand(ch);
1023       }));
1024   el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-line"),
1025           EditLineConstString("Move to previous line"),
1026           (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1027             return Editline::InstanceFor(editline)->PreviousLineCommand(ch);
1028           }));
1029   el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-line"),
1030           EditLineConstString("Move to next line"),
1031           (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1032             return Editline::InstanceFor(editline)->NextLineCommand(ch);
1033           }));
1034   el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-history"),
1035           EditLineConstString("Move to previous history"),
1036           (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1037             return Editline::InstanceFor(editline)->PreviousHistoryCommand(ch);
1038           }));
1039   el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-history"),
1040           EditLineConstString("Move to next history"),
1041           (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1042             return Editline::InstanceFor(editline)->NextHistoryCommand(ch);
1043           }));
1044   el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-start"),
1045           EditLineConstString("Move to start of buffer"),
1046           (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1047             return Editline::InstanceFor(editline)->BufferStartCommand(ch);
1048           }));
1049   el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-end"),
1050           EditLineConstString("Move to end of buffer"),
1051           (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1052             return Editline::InstanceFor(editline)->BufferEndCommand(ch);
1053           }));
1054   el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-fix-indentation"),
1055           EditLineConstString("Fix line indentation"),
1056           (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1057             return Editline::InstanceFor(editline)->FixIndentationCommand(ch);
1058           }));
1059 
1060   // Register the complete callback under two names for compatibility with
1061   // older clients using custom .editrc files (largely because libedit has a
1062   // bad bug where if you have a bind command that tries to bind to a function
1063   // name that doesn't exist, it can corrupt the heap and crash your process
1064   // later.)
1065   EditlineCommandCallbackType complete_callback = [](EditLine *editline,
1066                                                      int ch) {
1067     return Editline::InstanceFor(editline)->TabCommand(ch);
1068   };
1069   el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-complete"),
1070           EditLineConstString("Invoke completion"), complete_callback);
1071   el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb_complete"),
1072           EditLineConstString("Invoke completion"), complete_callback);
1073 
1074   // General bindings we don't mind being overridden
1075   if (!multiline) {
1076     el_set(m_editline, EL_BIND, "^r", "em-inc-search-prev",
1077            NULL); // Cycle through backwards search, entering string
1078   }
1079   el_set(m_editline, EL_BIND, "^w", "ed-delete-prev-word",
1080          NULL); // Delete previous word, behave like bash in emacs mode
1081   el_set(m_editline, EL_BIND, "\t", "lldb-complete",
1082          NULL); // Bind TAB to auto complete
1083 
1084   // Allow user-specific customization prior to registering bindings we
1085   // absolutely require
1086   el_source(m_editline, nullptr);
1087 
1088   // Register an internal binding that external developers shouldn't use
1089   el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-revert-line"),
1090           EditLineConstString("Revert line to saved state"),
1091           (EditlineCommandCallbackType)([](EditLine *editline, int ch) {
1092             return Editline::InstanceFor(editline)->RevertLineCommand(ch);
1093           }));
1094 
1095   // Register keys that perform auto-indent correction
1096   if (m_fix_indentation_callback && m_fix_indentation_callback_chars) {
1097     char bind_key[2] = {0, 0};
1098     const char *indent_chars = m_fix_indentation_callback_chars;
1099     while (*indent_chars) {
1100       bind_key[0] = *indent_chars;
1101       el_set(m_editline, EL_BIND, bind_key, "lldb-fix-indentation", NULL);
1102       ++indent_chars;
1103     }
1104   }
1105 
1106   // Multi-line editor bindings
1107   if (multiline) {
1108     el_set(m_editline, EL_BIND, "\n", "lldb-end-or-add-line", NULL);
1109     el_set(m_editline, EL_BIND, "\r", "lldb-end-or-add-line", NULL);
1110     el_set(m_editline, EL_BIND, ESCAPE "\n", "lldb-break-line", NULL);
1111     el_set(m_editline, EL_BIND, ESCAPE "\r", "lldb-break-line", NULL);
1112     el_set(m_editline, EL_BIND, "^p", "lldb-previous-line", NULL);
1113     el_set(m_editline, EL_BIND, "^n", "lldb-next-line", NULL);
1114     el_set(m_editline, EL_BIND, "^?", "lldb-delete-previous-char", NULL);
1115     el_set(m_editline, EL_BIND, "^d", "lldb-delete-next-char", NULL);
1116     el_set(m_editline, EL_BIND, ESCAPE "[3~", "lldb-delete-next-char", NULL);
1117     el_set(m_editline, EL_BIND, ESCAPE "[\\^", "lldb-revert-line", NULL);
1118 
1119     // Editor-specific bindings
1120     if (IsEmacs()) {
1121       el_set(m_editline, EL_BIND, ESCAPE "<", "lldb-buffer-start", NULL);
1122       el_set(m_editline, EL_BIND, ESCAPE ">", "lldb-buffer-end", NULL);
1123       el_set(m_editline, EL_BIND, ESCAPE "[A", "lldb-previous-line", NULL);
1124       el_set(m_editline, EL_BIND, ESCAPE "[B", "lldb-next-line", NULL);
1125       el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[A", "lldb-previous-history",
1126              NULL);
1127       el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[B", "lldb-next-history",
1128              NULL);
1129       el_set(m_editline, EL_BIND, ESCAPE "[1;3A", "lldb-previous-history",
1130              NULL);
1131       el_set(m_editline, EL_BIND, ESCAPE "[1;3B", "lldb-next-history", NULL);
1132     } else {
1133       el_set(m_editline, EL_BIND, "^H", "lldb-delete-previous-char", NULL);
1134 
1135       el_set(m_editline, EL_BIND, "-a", ESCAPE "[A", "lldb-previous-line",
1136              NULL);
1137       el_set(m_editline, EL_BIND, "-a", ESCAPE "[B", "lldb-next-line", NULL);
1138       el_set(m_editline, EL_BIND, "-a", "x", "lldb-delete-next-char", NULL);
1139       el_set(m_editline, EL_BIND, "-a", "^H", "lldb-delete-previous-char",
1140              NULL);
1141       el_set(m_editline, EL_BIND, "-a", "^?", "lldb-delete-previous-char",
1142              NULL);
1143 
1144       // Escape is absorbed exiting edit mode, so re-register important
1145       // sequences without the prefix
1146       el_set(m_editline, EL_BIND, "-a", "[A", "lldb-previous-line", NULL);
1147       el_set(m_editline, EL_BIND, "-a", "[B", "lldb-next-line", NULL);
1148       el_set(m_editline, EL_BIND, "-a", "[\\^", "lldb-revert-line", NULL);
1149     }
1150   }
1151 }
1152 
1153 // Editline public methods
1154 
1155 Editline *Editline::InstanceFor(EditLine *editline) {
1156   Editline *editor;
1157   el_get(editline, EL_CLIENTDATA, &editor);
1158   return editor;
1159 }
1160 
1161 Editline::Editline(const char *editline_name, FILE *input_file,
1162                    FILE *output_file, FILE *error_file, bool color_prompts)
1163     : m_editor_status(EditorStatus::Complete), m_color_prompts(color_prompts),
1164       m_input_file(input_file), m_output_file(output_file),
1165       m_error_file(error_file), m_input_connection(fileno(input_file), false) {
1166   // Get a shared history instance
1167   m_editor_name = (editline_name == nullptr) ? "lldb-tmp" : editline_name;
1168   m_history_sp = EditlineHistory::GetHistory(m_editor_name);
1169 
1170 #ifdef USE_SETUPTERM_WORKAROUND
1171   if (m_output_file) {
1172     const int term_fd = fileno(m_output_file);
1173     if (term_fd != -1) {
1174       static std::mutex *g_init_terminal_fds_mutex_ptr = nullptr;
1175       static std::set<int> *g_init_terminal_fds_ptr = nullptr;
1176       static llvm::once_flag g_once_flag;
1177       llvm::call_once(g_once_flag, [&]() {
1178         g_init_terminal_fds_mutex_ptr =
1179             new std::mutex(); // NOTE: Leak to avoid C++ destructor chain issues
1180         g_init_terminal_fds_ptr = new std::set<int>(); // NOTE: Leak to avoid
1181                                                        // C++ destructor chain
1182                                                        // issues
1183       });
1184 
1185       // We must make sure to initialize the terminal a given file descriptor
1186       // only once. If we do this multiple times, we start leaking memory.
1187       std::lock_guard<std::mutex> guard(*g_init_terminal_fds_mutex_ptr);
1188       if (g_init_terminal_fds_ptr->find(term_fd) ==
1189           g_init_terminal_fds_ptr->end()) {
1190         g_init_terminal_fds_ptr->insert(term_fd);
1191         setupterm((char *)0, term_fd, (int *)0);
1192       }
1193     }
1194   }
1195 #endif
1196 }
1197 
1198 Editline::~Editline() {
1199   if (m_editline) {
1200     // Disable edit mode to stop the terminal from flushing all input during
1201     // the call to el_end() since we expect to have multiple editline instances
1202     // in this program.
1203     el_set(m_editline, EL_EDITMODE, 0);
1204     el_end(m_editline);
1205     m_editline = nullptr;
1206   }
1207 
1208   // EditlineHistory objects are sometimes shared between multiple Editline
1209   // instances with the same program name. So just release our shared pointer
1210   // and if we are the last owner, it will save the history to the history save
1211   // file automatically.
1212   m_history_sp.reset();
1213 }
1214 
1215 void Editline::SetPrompt(const char *prompt) {
1216   m_set_prompt = prompt == nullptr ? "" : prompt;
1217 }
1218 
1219 void Editline::SetContinuationPrompt(const char *continuation_prompt) {
1220   m_set_continuation_prompt =
1221       continuation_prompt == nullptr ? "" : continuation_prompt;
1222 }
1223 
1224 void Editline::TerminalSizeChanged() {
1225   if (m_editline != nullptr) {
1226     el_resize(m_editline);
1227     int columns;
1228     // This function is documenting as taking (const char *, void *) for the
1229     // vararg part, but in reality in was consuming arguments until the first
1230     // null pointer. This was fixed in libedit in April 2019
1231     // <http://mail-index.netbsd.org/source-changes/2019/04/26/msg105454.html>,
1232     // but we're keeping the workaround until a version with that fix is more
1233     // widely available.
1234     if (el_get(m_editline, EL_GETTC, "co", &columns, nullptr) == 0) {
1235       m_terminal_width = columns;
1236       if (m_current_line_rows != -1) {
1237         const LineInfoW *info = el_wline(m_editline);
1238         int lineLength =
1239             (int)((info->lastchar - info->buffer) + GetPromptWidth());
1240         m_current_line_rows = (lineLength / columns) + 1;
1241       }
1242     } else {
1243       m_terminal_width = INT_MAX;
1244       m_current_line_rows = 1;
1245     }
1246   }
1247 }
1248 
1249 const char *Editline::GetPrompt() { return m_set_prompt.c_str(); }
1250 
1251 uint32_t Editline::GetCurrentLine() { return m_current_line_index; }
1252 
1253 bool Editline::Interrupt() {
1254   bool result = true;
1255   std::lock_guard<std::mutex> guard(m_output_mutex);
1256   if (m_editor_status == EditorStatus::Editing) {
1257     fprintf(m_output_file, "^C\n");
1258     result = m_input_connection.InterruptRead();
1259   }
1260   m_editor_status = EditorStatus::Interrupted;
1261   return result;
1262 }
1263 
1264 bool Editline::Cancel() {
1265   bool result = true;
1266   std::lock_guard<std::mutex> guard(m_output_mutex);
1267   if (m_editor_status == EditorStatus::Editing) {
1268     MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1269     fprintf(m_output_file, ANSI_CLEAR_BELOW);
1270     result = m_input_connection.InterruptRead();
1271   }
1272   m_editor_status = EditorStatus::Interrupted;
1273   return result;
1274 }
1275 
1276 void Editline::SetAutoCompleteCallback(CompleteCallbackType callback,
1277                                        void *baton) {
1278   m_completion_callback = callback;
1279   m_completion_callback_baton = baton;
1280 }
1281 
1282 void Editline::SetIsInputCompleteCallback(IsInputCompleteCallbackType callback,
1283                                           void *baton) {
1284   m_is_input_complete_callback = callback;
1285   m_is_input_complete_callback_baton = baton;
1286 }
1287 
1288 bool Editline::SetFixIndentationCallback(FixIndentationCallbackType callback,
1289                                          void *baton,
1290                                          const char *indent_chars) {
1291   m_fix_indentation_callback = callback;
1292   m_fix_indentation_callback_baton = baton;
1293   m_fix_indentation_callback_chars = indent_chars;
1294   return false;
1295 }
1296 
1297 bool Editline::GetLine(std::string &line, bool &interrupted) {
1298   ConfigureEditor(false);
1299   m_input_lines = std::vector<EditLineStringType>();
1300   m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1301 
1302   std::lock_guard<std::mutex> guard(m_output_mutex);
1303 
1304   lldbassert(m_editor_status != EditorStatus::Editing);
1305   if (m_editor_status == EditorStatus::Interrupted) {
1306     m_editor_status = EditorStatus::Complete;
1307     interrupted = true;
1308     return true;
1309   }
1310 
1311   SetCurrentLine(0);
1312   m_in_history = false;
1313   m_editor_status = EditorStatus::Editing;
1314   m_revert_cursor_index = -1;
1315 
1316   int count;
1317   auto input = el_wgets(m_editline, &count);
1318 
1319   interrupted = m_editor_status == EditorStatus::Interrupted;
1320   if (!interrupted) {
1321     if (input == nullptr) {
1322       fprintf(m_output_file, "\n");
1323       m_editor_status = EditorStatus::EndOfInput;
1324     } else {
1325       m_history_sp->Enter(input);
1326 #if LLDB_EDITLINE_USE_WCHAR
1327       line = m_utf8conv.to_bytes(SplitLines(input)[0]);
1328 #else
1329       line = SplitLines(input)[0];
1330 #endif
1331       m_editor_status = EditorStatus::Complete;
1332     }
1333   }
1334   return m_editor_status != EditorStatus::EndOfInput;
1335 }
1336 
1337 bool Editline::GetLines(int first_line_number, StringList &lines,
1338                         bool &interrupted) {
1339   ConfigureEditor(true);
1340 
1341   // Print the initial input lines, then move the cursor back up to the start
1342   // of input
1343   SetBaseLineNumber(first_line_number);
1344   m_input_lines = std::vector<EditLineStringType>();
1345   m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1346 
1347   std::lock_guard<std::mutex> guard(m_output_mutex);
1348   // Begin the line editing loop
1349   DisplayInput();
1350   SetCurrentLine(0);
1351   MoveCursor(CursorLocation::BlockEnd, CursorLocation::BlockStart);
1352   m_editor_status = EditorStatus::Editing;
1353   m_in_history = false;
1354 
1355   m_revert_cursor_index = -1;
1356   while (m_editor_status == EditorStatus::Editing) {
1357     int count;
1358     m_current_line_rows = -1;
1359     el_wpush(m_editline, EditLineConstString(
1360                              "\x1b[^")); // Revert to the existing line content
1361     el_wgets(m_editline, &count);
1362   }
1363 
1364   interrupted = m_editor_status == EditorStatus::Interrupted;
1365   if (!interrupted) {
1366     // Save the completed entry in history before returning
1367     m_history_sp->Enter(CombineLines(m_input_lines).c_str());
1368 
1369     lines = GetInputAsStringList();
1370   }
1371   return m_editor_status != EditorStatus::EndOfInput;
1372 }
1373 
1374 void Editline::PrintAsync(Stream *stream, const char *s, size_t len) {
1375   std::lock_guard<std::mutex> guard(m_output_mutex);
1376   if (m_editor_status == EditorStatus::Editing) {
1377     MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1378     fprintf(m_output_file, ANSI_CLEAR_BELOW);
1379   }
1380   stream->Write(s, len);
1381   stream->Flush();
1382   if (m_editor_status == EditorStatus::Editing) {
1383     DisplayInput();
1384     MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
1385   }
1386 }
1387 
1388 bool Editline::CompleteCharacter(char ch, EditLineGetCharType &out) {
1389 #if !LLDB_EDITLINE_USE_WCHAR
1390   if (ch == (char)EOF)
1391     return false;
1392 
1393   out = (unsigned char)ch;
1394   return true;
1395 #else
1396   std::codecvt_utf8<wchar_t> cvt;
1397   llvm::SmallString<4> input;
1398   for (;;) {
1399     const char *from_next;
1400     wchar_t *to_next;
1401     std::mbstate_t state = std::mbstate_t();
1402     input.push_back(ch);
1403     switch (cvt.in(state, input.begin(), input.end(), from_next, &out, &out + 1,
1404                    to_next)) {
1405     case std::codecvt_base::ok:
1406       return out != WEOF;
1407 
1408     case std::codecvt_base::error:
1409     case std::codecvt_base::noconv:
1410       return false;
1411 
1412     case std::codecvt_base::partial:
1413       lldb::ConnectionStatus status;
1414       size_t read_count = m_input_connection.Read(
1415           &ch, 1, std::chrono::seconds(0), status, nullptr);
1416       if (read_count == 0)
1417         return false;
1418       break;
1419     }
1420   }
1421 #endif
1422 }
1423