LLDB mainline
Editline.cpp
Go to the documentation of this file.
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
17#include "lldb/Host/Host.h"
22#include "lldb/Utility/Status.h"
26
27#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/Locale.h"
29#include "llvm/Support/Threading.h"
30
31using namespace lldb_private;
32using 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
79bool IsOnlySpaces(const EditLineStringType &content) {
80 for (wchar_t ch : content) {
81 if (ch != EditLineCharType(' '))
82 return false;
83 }
84 return true;
85}
86
87static size_t ColumnWidth(llvm::StringRef str) {
88 return llvm::sys::locale::columnWidth(str);
89}
90
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
124EditLineStringType 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
132std::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
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
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
171bool 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
184namespace lldb_private {
185namespace line_editor {
186typedef std::weak_ptr<EditlineHistory> EditlineHistoryWP;
187
188// EditlineHistory objects are sometimes shared between multiple Editline
189// instances with the same program name.
190
192private:
193 // Use static GetHistory() function to get a EditlineHistorySP to one of
194 // these objects
195 EditlineHistory(const std::string &prefix, uint32_t size, bool unique_entries)
196 : m_prefix(prefix) {
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
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
229public:
231 Save();
232
233 if (m_history) {
235 m_history = nullptr;
236 }
237 }
238
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
257 bool IsValid() const { return m_history != nullptr; }
258
260
261 void Enter(const EditLineCharType *line_cstr) {
262 if (m_history)
263 history_w(m_history, &m_event, H_ENTER, line_cstr);
264 }
265
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
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
288protected:
289 /// The history object.
290 HistoryW *m_history = nullptr;
291 /// The history event needed to contain all history events.
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
304void Editline::SetBaseLineNumber(int line_number) {
305 m_base_line_number = line_number;
307 std::max<int>(3, std::to_string(line_number).length() + 1);
308}
309
310std::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
340void Editline::SetCurrentLine(int line_index) {
341 m_current_line_index = line_index;
342 m_current_prompt = PromptForIndex(line_index);
343}
344
346
348 const char *editor;
349 el_get(m_editline, EL_EDITOR, &editor);
350 return editor[0] == 'e';
351}
352
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
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
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
413void Editline::DisplayInput(int firstIndex) {
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"
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
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
436 const LineInfoW *info = el_wline(m_editline);
438 EditLineStringType(info->buffer, info->lastchar - info->buffer);
439}
440
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
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.)
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:
519 break;
520 default:
521 llvm_unreachable("unsupported history direction");
522 }
524 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
525 return CC_NEWLINE;
526}
527
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)
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);
543 }
544
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);
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) {
563 char ch = 0;
564
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);
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
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
610const char *Editline::Prompt() {
611 if (!m_prompt_ansi_prefix.empty() || !m_prompt_ansi_suffix.empty())
613 return m_current_prompt.c_str();
614}
615
616unsigned 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
632
633 // Don't perform automatic formatting when pasting
635 // Apply smart indentation
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
652 new_line_fragment);
653 MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
655
656 // Reposition the cursor to the right line and prepare to edit the new line
658 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
659 return CC_NEWLINE;
660}
661
662unsigned char Editline::EndOrAddLineCommand(int ch) {
663 // Don't perform end of input detection when pasting, always treat this as a
664 // line break
666 return BreakLineCommand(ch);
667 }
668
669 // Save any edits to this line
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) {
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
701unsigned 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;
728 info->cursor = cursor;
730
731 // Delete the extra line
733
734 // Clear and repaint from this line on down
736 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
737 return CC_REFRESH;
738}
739
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
757 auto priorLine = m_input_lines[m_current_line_index];
761
762 // Repaint from the new line down
764 CountRowsForLine(priorLine), 1);
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
774unsigned char Editline::PreviousLineCommand(int ch) {
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()) {
788 }
789
793 return CC_NEWLINE;
794}
795
796unsigned char Editline::NextLineCommand(int ch) {
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;
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
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
832unsigned char Editline::PreviousHistoryCommand(int ch) {
834
835 return RecallHistory(HistoryOperation::Older);
836}
837
838unsigned char Editline::NextHistoryCommand(int ch) {
840
841 return RecallHistory(HistoryOperation::Newer);
842}
843
844unsigned char Editline::FixIndentationCommand(int ch) {
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
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);
880
881 // Reposition the cursor back on the original line and prepare to restart
882 // editing with a new cursor position
884 MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
885 m_revert_cursor_index = cursor_position + indent_correction;
886 return CC_NEWLINE;
887}
888
889unsigned char Editline::RevertLineCommand(int ch) {
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 }
898 }
899 return CC_REFRESH;
900}
901
902unsigned char Editline::BufferStartCommand(int ch) {
904 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
907 return CC_NEWLINE;
908}
909
910unsigned char Editline::BufferEndCommand(int ch) {
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.
920static void
921PrintCompletion(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
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
990unsigned char Editline::TabCommand(int ch) {
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()) {
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 }
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 }
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
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
1078unsigned 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 =
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
1118 const EditLineCharType *helptext,
1119 EditlineCommandCallbackType callbackFn) {
1120 el_wset(m_editline, EL_ADDFN, command, helptext, callbackFn);
1121}
1122
1124 EditlinePromptCallbackType callbackFn) {
1125 el_set(m_editline, EL_PROMPT, callbackFn);
1126}
1127
1129 el_wset(m_editline, EL_GETCFN, callbackFn);
1130}
1131
1132void 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 =
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
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
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 });
1183 EditLineConstString("lldb-delete-next-char"),
1184 EditLineConstString("Delete next character"),
1185 [](EditLine *editline, int ch) {
1186 return Editline::InstanceFor(editline)->DeleteNextCharCommand(ch);
1187 });
1189 EditLineConstString("lldb-delete-previous-char"),
1190 EditLineConstString("Delete previous character"),
1191 [](EditLine *editline, int ch) {
1193 });
1195 EditLineConstString("lldb-previous-line"),
1196 EditLineConstString("Move to previous line"),
1197 [](EditLine *editline, int ch) {
1198 return Editline::InstanceFor(editline)->PreviousLineCommand(ch);
1199 });
1201 EditLineConstString("lldb-next-line"),
1202 EditLineConstString("Move to next line"), [](EditLine *editline, int ch) {
1203 return Editline::InstanceFor(editline)->NextLineCommand(ch);
1204 });
1206 EditLineConstString("lldb-previous-history"),
1207 EditLineConstString("Move to previous history"),
1208 [](EditLine *editline, int ch) {
1209 return Editline::InstanceFor(editline)->PreviousHistoryCommand(ch);
1210 });
1212 EditLineConstString("lldb-next-history"),
1213 EditLineConstString("Move to next history"),
1214 [](EditLine *editline, int ch) {
1215 return Editline::InstanceFor(editline)->NextHistoryCommand(ch);
1216 });
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 });
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 });
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 };
1246 EditLineConstString("Invoke completion"),
1247 complete_callback);
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
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
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
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
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
1375Editline *Editline::InstanceFor(EditLine *editline) {
1376 Editline *editor;
1377 el_get(editline, EL_CLIENTDATA, &editor);
1378 return editor;
1379}
1380
1381Editline::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;
1391}
1392
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
1410void Editline::SetPrompt(const char *prompt) {
1411 m_set_prompt = prompt == nullptr ? "" : prompt;
1412}
1413
1414void Editline::SetContinuationPrompt(const char *continuation_prompt) {
1416 continuation_prompt == nullptr ? "" : continuation_prompt;
1417}
1418
1420
1422 if (!m_editline)
1423 return;
1424
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;
1445 }
1446}
1447
1448const char *Editline::GetPrompt() { return m_set_prompt.c_str(); }
1449
1451
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");
1458 }
1459 m_editor_status = EditorStatus::Interrupted;
1460 return result;
1461}
1462
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);
1470 }
1471 m_editor_status = EditorStatus::Interrupted;
1472 return result;
1473}
1474
1475bool 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;
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
1515bool 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
1534 while (m_editor_status == EditorStatus::Editing) {
1535 int count;
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
1554void 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) {
1558 MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
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
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:
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}
#define el_wgets
Definition: Editline.cpp:67
EditLineStringType CombineLines(const std::vector< EditLineStringType > &lines)
Definition: Editline.cpp:124
#define EditLineConstString(str)
Definition: Editline.cpp:55
#define ANSI_UP_N_ROWS
Definition: Editline.cpp:45
#define el_wline
Definition: Editline.cpp:73
static void PrintCompletion(FILE *output_file, llvm::ArrayRef< CompletionResult::Completion > results, size_t max_len)
Prints completions and their descriptions to the given file.
Definition: Editline.cpp:921
#define EditLineStringFormatSpec
Definition: Editline.cpp:56
#define LineInfoW
Definition: Editline.cpp:65
EditLineStringType FixIndentation(const EditLineStringType &line, int indent_correction)
Definition: Editline.cpp:152
#define ANSI_DOWN_N_ROWS
Definition: Editline.cpp:46
#define history_wend
Definition: Editline.cpp:62
#define el_winsertstr
Definition: Editline.cpp:74
#define el_wpush
Definition: Editline.cpp:69
#define HistEventW
Definition: Editline.cpp:64
#define history_winit
Definition: Editline.cpp:61
bool IsInputPending(FILE *file)
Definition: Editline.cpp:171
static size_t ColumnWidth(llvm::StringRef str)
Definition: Editline.cpp:87
#define el_wgetc
Definition: Editline.cpp:68
#define ANSI_CLEAR_BELOW
Definition: Editline.cpp:42
#define el_wset
Definition: Editline.cpp:71
#define ANSI_SET_COLUMN_N
Definition: Editline.cpp:44
std::vector< EditLineStringType > SplitLines(const EditLineStringType &input)
Definition: Editline.cpp:132
#define HistoryW
Definition: Editline.cpp:63
bool IsOnlySpaces(const EditLineStringType &content)
Definition: Editline.cpp:79
#define history_w
Definition: Editline.cpp:60
int GetIndentation(const EditLineStringType &line)
Definition: Editline.cpp:161
static int GetOperation(HistoryOperation op)
Definition: Editline.cpp:91
#define ESCAPE
https://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf
Definition: Editline.cpp:41
#define lldbassert(x)
Definition: LLDBAssert.h:15
lldb_private::Status Select()
void FDSetRead(lldb::socket_t fd)
void SetTimeout(const std::chrono::microseconds &timeout)
A command line argument class.
Definition: Args.h:33
size_t size() const
Definition: Args.h:135
bool empty() const
Definition: Args.h:118
"lldb/Utility/ArgCompletionRequest.h"
const Args & GetParsedLine() const
llvm::StringRef GetCursorArgumentPrefix() const
const Args::ArgEntry & GetParsedArg()
A single completion and all associated data.
const std::string & GetCompletion() const
llvm::ArrayRef< Completion > GetResults() const
void GetMatches(StringList &matches) const
Adds all collected completion matches to the given list.
bool InterruptRead() override
Interrupts an ongoing Read() operation.
size_t Read(void *dst, size_t dst_len, const Timeout< std::micro > &timeout, lldb::ConnectionStatus &status, Status *error_ptr) override
The read function that attempts to read from the connection.
Instances of Editline provide an abstraction over libedit's EditLine facility.
Definition: Editline.h:155
IsInputCompleteCallbackType m_is_input_complete_callback
Definition: Editline.h:396
EditorStatus m_editor_status
Definition: Editline.h:378
unsigned char PreviousLineCommand(int ch)
Line navigation command used when ^P or up arrow are pressed in multi-line mode.
Definition: Editline.cpp:774
unsigned char RecallHistory(HistoryOperation op)
Replaces the current multi-line session with the next entry from history.
Definition: Editline.cpp:456
bool IsOnlySpaces()
Returns true if the current EditLine buffer contains nothing but spaces, or is empty.
Definition: Editline.cpp:353
::EditLine * m_editline
Definition: Editline.h:372
void SaveEditedLine()
Save the line currently being edited.
Definition: Editline.cpp:435
void MoveCursor(CursorLocation from, CursorLocation to)
Move the cursor from one well-established location to another using relative line positioning and abs...
Definition: Editline.cpp:384
std::string m_suggestion_ansi_suffix
Definition: Editline.h:407
void SetGetCharacterFunction(EditlineGetCharCallbackType callbackFn)
Definition: Editline.cpp:1128
std::string m_current_prompt
Definition: Editline.h:387
static void DisplayCompletions(Editline &editline, llvm::ArrayRef< CompletionResult::Completion > results)
Definition: Editline.cpp:932
std::string m_set_continuation_prompt
Definition: Editline.h:386
std::size_t m_previous_autosuggestion_size
Definition: Editline.h:409
ConnectionFileDescriptor m_input_connection
Definition: Editline.h:394
unsigned char BufferStartCommand(int ch)
Buffer start command used when Esc < is typed in multi-line emacs mode.
Definition: Editline.cpp:902
const char * Prompt()
Prompt implementation for EditLine.
Definition: Editline.cpp:610
unsigned char EndOrAddLineCommand(int ch)
Command used when return is pressed in multi-line mode.
Definition: Editline.cpp:662
unsigned char DeletePreviousCharCommand(int ch)
Delete command used when backspace is pressed in multi-line mode.
Definition: Editline.cpp:740
int GetLineIndexForLocation(CursorLocation location, int cursor_row)
Helper method used by MoveCursor to determine relative line position.
Definition: Editline.cpp:363
std::string m_prompt_ansi_prefix
Definition: Editline.h:404
bool IsEmacs()
Returns true if the underlying EditLine session's keybindings are Emacs-based, or false if they are V...
Definition: Editline.cpp:347
CompleteCallbackType m_completion_callback
Definition: Editline.h:401
size_t GetPromptWidth()
Determines the width of the prompt in characters.
Definition: Editline.cpp:345
unsigned char PreviousHistoryCommand(int ch)
History navigation command used when Alt + up arrow is pressed in multi-line mode.
Definition: Editline.cpp:832
const char * m_fix_indentation_callback_chars
Definition: Editline.h:399
std::string m_editor_name
Definition: Editline.h:390
uint32_t GetCurrentLine()
Returns the index of the line currently being edited.
Definition: Editline.cpp:1450
void DisplayInput(int firstIndex=0)
Clear from cursor position to bottom of screen and print input lines including prompts,...
Definition: Editline.cpp:413
int GetCharacter(EditLineGetCharType *c)
Character reading implementation for EditLine that supports our multi-line editing trickery.
Definition: Editline.cpp:528
void TerminalSizeChanged()
Call when the terminal size changes.
Definition: Editline.cpp:1419
volatile std::sig_atomic_t m_terminal_size_has_changed
Definition: Editline.h:389
void SetEditLinePromptCallback(EditlinePromptCallbackType callbackFn)
Definition: Editline.cpp:1123
EditlineHistorySP m_history_sp
Definition: Editline.h:373
static Editline * InstanceFor(::EditLine *editline)
Uses the user data storage of EditLine to retrieve an associated instance of Editline.
Definition: Editline.cpp:1375
bool GetLine(std::string &line, bool &interrupted)
Prompts for and reads a single line of user input.
Definition: Editline.cpp:1475
std::string m_set_prompt
Definition: Editline.h:385
void SetCurrentLine(int line_index)
Sets the current line index between line edits to allow free movement between lines.
Definition: Editline.cpp:340
int CountRowsForLine(const EditLineStringType &content)
Counts the number of rows a given line of content will end up occupying, taking into account both the...
Definition: Editline.cpp:428
void ConfigureEditor(bool multiline)
Ensures that the current EditLine instance is properly configured for single or multi-line editing.
Definition: Editline.cpp:1132
unsigned char NextLineCommand(int ch)
Line navigation command used when ^N or down arrow are pressed in multi-line mode.
Definition: Editline.cpp:796
void PrintAsync(Stream *stream, const char *s, size_t len)
Definition: Editline.cpp:1554
std::vector< EditLineStringType > m_live_history_lines
Definition: Editline.h:375
void AddFunctionToEditLine(const EditLineCharType *command, const EditLineCharType *helptext, EditlineCommandCallbackType callbackFn)
Definition: Editline.cpp:1117
std::vector< EditLineStringType > m_input_lines
Definition: Editline.h:377
bool CompleteCharacter(char ch, EditLineGetCharType &out)
Definition: Editline.cpp:1569
bool Cancel()
Cancel this edit and obliterate all trace of it.
Definition: Editline.cpp:1463
unsigned char DeleteNextCharCommand(int ch)
Delete command used when delete is pressed in multi-line mode.
Definition: Editline.cpp:701
std::string m_suggestion_ansi_prefix
Definition: Editline.h:406
SuggestionCallbackType m_suggestion_callback
Definition: Editline.h:402
unsigned char FixIndentationCommand(int ch)
Respond to normal character insertion by fixing line indentation.
Definition: Editline.cpp:844
unsigned char NextHistoryCommand(int ch)
History navigation command used when Alt + down arrow is pressed in multi-line mode.
Definition: Editline.cpp:838
void SetPrompt(const char *prompt)
Sets a string to be used as a prompt, or combined with a line number to form a prompt.
Definition: Editline.cpp:1410
unsigned char BufferEndCommand(int ch)
Buffer end command used when Esc > is typed in multi-line emacs mode.
Definition: Editline.cpp:910
unsigned char TypedCharacter(int ch)
Command used when a character is typed.
Definition: Editline.cpp:1078
unsigned char BreakLineCommand(int ch)
Line break command used when meta+return is pressed in multi-line mode.
Definition: Editline.cpp:616
FixIndentationCallbackType m_fix_indentation_callback
Definition: Editline.h:398
unsigned char ApplyAutosuggestCommand(int ch)
Apply autosuggestion part in gray as editline.
Definition: Editline.cpp:1063
unsigned char TabCommand(int ch)
Context-sensitive tab insertion or code completion command used when the tab key is typed.
Definition: Editline.cpp:990
Editline(const char *editor_name, FILE *input_file, FILE *output_file, FILE *error_file, std::recursive_mutex &output_mutex)
Definition: Editline.cpp:1381
std::recursive_mutex & m_output_mutex
Definition: Editline.h:410
void SetContinuationPrompt(const char *continuation_prompt)
Sets an alternate string to be used as a prompt for the second line and beyond in multi-line editing ...
Definition: Editline.cpp:1414
unsigned m_current_line_index
Definition: Editline.h:381
StringList GetInputAsStringList(int line_count=UINT32_MAX)
Convert the current input lines into a UTF8 StringList.
Definition: Editline.cpp:441
std::string PromptForIndex(int line_index)
Returns the complete prompt by combining the prompt or continuation prompt with line numbers as appro...
Definition: Editline.cpp:310
unsigned char RevertLineCommand(int ch)
Revert line command used when moving between lines.
Definition: Editline.cpp:889
bool Interrupt()
Interrupt the current edit as if ^C was pressed.
Definition: Editline.cpp:1452
const char * GetPrompt()
Returns the prompt established by SetPrompt.
Definition: Editline.cpp:1448
void SetBaseLineNumber(int line_number)
Sets the lowest line number for multi-line editing sessions.
Definition: Editline.cpp:304
bool GetLines(int first_line_number, StringList &lines, bool &interrupted)
Prompts for and reads a multi-line batch of user input.
Definition: Editline.cpp:1515
std::string m_prompt_ansi_suffix
Definition: Editline.h:405
bool GetHomeDirectory(llvm::SmallVectorImpl< char > &path) const
Get the user home directory.
static FileSystem & Instance()
bool Success() const
Test for success condition.
Definition: Status.cpp:278
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
Definition: Stream.h:112
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:134
virtual void Flush()=0
Flush the stream.
void AppendString(const std::string &s)
Definition: StringList.cpp:43
const char * GetStringAtIndex(size_t idx) const
Definition: StringList.cpp:86
std::string LongestCommonPrefix()
Definition: StringList.cpp:107
void Enter(const EditLineCharType *line_cstr)
Definition: Editline.cpp:261
std::string m_path
Path to the history file.
Definition: Editline.cpp:297
std::string m_prefix
The prefix name (usually the editline program name) to use when loading/saving history.
Definition: Editline.cpp:295
HistoryW * m_history
The history object.
Definition: Editline.cpp:290
EditlineHistory(const std::string &prefix, uint32_t size, bool unique_entries)
Definition: Editline.cpp:195
static EditlineHistorySP GetHistory(const std::string &prefix)
Definition: Editline.cpp:239
HistEventW m_event
The history event needed to contain all history events.
Definition: Editline.cpp:292
std::stringstream EditLineStringStreamType
Definition: Editline.h:70
std::weak_ptr< EditlineHistory > EditlineHistoryWP
Definition: Editline.cpp:186
unsigned char(*)(::EditLine *editline, int ch) EditlineCommandCallbackType
Definition: Editline.h:89
const char *(*)(::EditLine *editline) EditlinePromptCallbackType
Definition: Editline.h:90
int(*)(::EditLine *editline, EditLineGetCharType *c) EditlineGetCharCallbackType
Definition: Editline.h:87
std::string EditLineStringType
Definition: Editline.h:69
HistoryOperation
Operation for the history.
Definition: Editline.h:142
std::shared_ptr< EditlineHistory > EditlineHistorySP
Definition: Editline.h:94
EditorStatus
Status used to decide when and how to start editing another line in multi-line sessions.
Definition: Editline.h:109
@ Complete
Editing complete, returns the complete set of edited lines.
CursorLocation
Established locations that can be easily moved among with MoveCursor.
Definition: Editline.h:125
A class that represents a running process on the host machine.
@ Partial
The current token has been partially completed.
@ Normal
The current token has been completed.
@ RewriteLine
The full line has been rewritten by the completion.
ConnectionStatus
Connection Status Types.
@ eConnectionStatusError
Check GetError() for details.
@ eConnectionStatusInterrupted
Interrupted read.
@ eConnectionStatusTimedOut
Request timed out.
@ eConnectionStatusEndOfFile
End-of-file encountered.
@ eConnectionStatusSuccess
Success.
@ eConnectionStatusLostConnection
Lost connection while connected to a valid connection.
@ eConnectionStatusNoConnection
No connection.
bool IsQuoted() const
Returns true if this argument was quoted in any way.
Definition: Args.h:52
char GetQuoteChar() const
Definition: Args.h:53