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