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