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