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