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