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