normal.cc (106283B)
1 #include "normal.hh" 2 3 #include "array_view.hh" 4 #include "assert.hh" 5 #include "buffer.hh" 6 #include "buffer_manager.hh" 7 #include "buffer_utils.hh" 8 #include "changes.hh" 9 #include "client.hh" 10 #include "command_manager.hh" 11 #include "context.hh" 12 #include "coord.hh" 13 #include "diff.hh" 14 #include "enum.hh" 15 #include "face_registry.hh" 16 #include "file.hh" 17 #include "flags.hh" 18 #include "input_handler.hh" 19 #include "keymap_manager.hh" 20 #include "option_manager.hh" 21 #include "option_types.hh" 22 #include "ranges.hh" 23 #include "regex.hh" 24 #include "register_manager.hh" 25 #include "selectors.hh" 26 #include "shell_manager.hh" 27 #include "string.hh" 28 #include "units.hh" 29 #include "user_interface.hh" 30 #include "unit_tests.hh" 31 #include "window.hh" 32 #include "word_db.hh" 33 34 namespace Kakoune 35 { 36 37 enum class SelectMode 38 { 39 Replace, 40 Extend, 41 Append, 42 }; 43 44 constexpr auto enum_desc(Meta::Type<SelectMode>) 45 { 46 return make_array<EnumDesc<SelectMode>>({ 47 { SelectMode::Replace, "replace" }, 48 { SelectMode::Extend, "extend" }, 49 { SelectMode::Append, "append" }, 50 }); 51 } 52 53 void merge_selections(Selection& sel, const Selection& new_sel) 54 { 55 const bool forward = sel.cursor() >= sel.anchor(); 56 const bool new_forward = new_sel.cursor() > new_sel.anchor(); 57 if (forward and new_forward) 58 sel.anchor() = std::min(sel.anchor(), new_sel.anchor()); 59 const bool backward = sel.cursor() <= sel.anchor(); 60 const bool new_backward = new_sel.cursor() < new_sel.anchor(); 61 if (backward and new_backward) 62 sel.anchor() = std::max(sel.anchor(), new_sel.anchor()); 63 64 sel.cursor() = new_sel.cursor(); 65 } 66 67 UnitTest test_merge_selection{[] { 68 auto merge = [](Selection sel, const Selection& new_sel) { 69 merge_selections(sel, new_sel); 70 return sel; 71 }; 72 kak_assert(merge({{0, 1}, {0, 2} }, {{0, 3}, {0, 4}}) == Selection{{0, 1}, {0, 4}}); 73 kak_assert(merge({{0, 1}, {0, 2} }, {{0, 1}, {0, 2}}) == Selection{{0, 1}, {0, 2}}); 74 kak_assert(merge({{0, 1}, {0, 2} }, {{0, 0}, {0, 0}}) == Selection{{0, 1}, {0, 0}}); 75 kak_assert(merge({{0, 1}, {0, 2} }, {{0, 0}, {0, 3}}) == Selection{{0, 0}, {0, 3}}); 76 kak_assert(merge({{0, 1}, {0, 3} }, {{0, 4}, {0, 2}}) == Selection{{0, 1}, {0, 2}}); 77 kak_assert(merge({{0, 1}, {0, 2} }, {{0, 1}, {0, 1}}) == Selection{{0, 1}, {0, 1}}); 78 }}; 79 80 template<typename T> 81 void select(Context& context, SelectMode mode, T func) 82 { 83 ScopedSelectionEdition selection_edition{context}; 84 auto& selections = context.selections(); 85 if (mode == SelectMode::Append) 86 { 87 auto& sel = selections.main(); 88 if (auto res = func(context, sel)) 89 { 90 if (res->captures().empty()) 91 res->captures() = sel.captures(); 92 selections.push_back(std::move(*res)); 93 selections.set_main_index(selections.size() - 1); 94 } 95 } 96 else 97 { 98 auto main_index = selections.main_index(); 99 size_t new_size = 0; 100 for (size_t i = 0; i < selections.size(); ++i) 101 { 102 auto& sel = selections[i]; 103 auto res = func(context, sel); 104 if (not res) 105 { 106 if (i <= main_index and main_index != 0) 107 --main_index; 108 continue; 109 } 110 111 if (mode == SelectMode::Extend) 112 merge_selections(sel, *res); 113 else 114 { 115 sel.anchor() = res->anchor(); 116 sel.cursor() = res->cursor(); 117 } 118 if (not res->captures().empty()) 119 sel.captures() = std::move(res->captures()); 120 if (i != new_size) 121 selections[new_size] = std::move(sel); 122 ++new_size; 123 } 124 if (new_size == 0) 125 throw no_selections_remaining{}; 126 127 selections.set_main_index(main_index); 128 selections.remove_from(new_size); 129 } 130 131 selections.sort_and_merge_overlapping(); 132 selections.check_invariant(); 133 } 134 135 template<SelectMode mode, Optional<Selection> (*func)(const Context&, const Selection&)> 136 void select(Context& context, NormalParams) 137 { 138 select(context, mode, func); 139 } 140 141 template<typename Func> 142 void select_and_set_last(Context& context, SelectMode mode, Func&& func) 143 { 144 context.set_last_select( 145 [=](Context& context){ select(context, mode, func); }); 146 return select(context, mode, func); 147 } 148 149 template<SelectMode mode = SelectMode::Replace> 150 void select_coord(Context& context, BufferCoord coord) 151 { 152 Buffer& buffer = context.buffer(); 153 ScopedSelectionEdition selection_edition{context}; 154 SelectionList& selections = context.selections(); 155 coord = buffer.clamp(coord); 156 if (mode == SelectMode::Replace) 157 selections = SelectionList{ buffer, coord }; 158 else if (mode == SelectMode::Extend) 159 { 160 for (auto& sel : selections) 161 sel.cursor() = coord; 162 selections.sort_and_merge_overlapping(); 163 } 164 } 165 166 template<InsertMode mode> 167 void enter_insert_mode(Context& context, NormalParams params) 168 { 169 context.input_handler().insert(mode, params.count); 170 } 171 172 void repeat_last_insert(Context& context, NormalParams) 173 { 174 context.input_handler().repeat_last_insert(); 175 } 176 177 void repeat_last_select(Context& context, NormalParams) 178 { 179 context.repeat_last_select(); 180 } 181 182 String build_autoinfo_for_mapping(const Context& context, KeymapMode mode, 183 ConstArrayView<KeyInfo> built_ins) 184 { 185 auto& keymaps = context.keymaps(); 186 187 Vector<std::pair<String, StringView>> descs; 188 for (auto& built_in : built_ins) 189 { 190 String keys = join(built_in.keys | 191 filter([&](Key k){ return keymaps.get_mapping(k, mode) == nullptr; }) | 192 transform((String(*)(Key))to_string), 193 ',', false); 194 if (not keys.empty()) 195 descs.emplace_back(std::move(keys), built_in.docstring); 196 } 197 198 for (auto& key : keymaps.get_mapped_keys(mode)) 199 { 200 auto* mapping = keymaps.get_mapping(key, mode); 201 const String& docstring = mapping->docstring; 202 if (mapping->keys.empty() and docstring.empty()) 203 continue; 204 if (auto it = find_if(descs, [&](auto& elem) { return elem.second == docstring; }); 205 it != descs.end()) 206 it->first += ',' + to_string(key); 207 else 208 descs.emplace_back(to_string(key), docstring); 209 } 210 211 auto max_len = 0_col; 212 for (auto& [keys, docstring] : descs) 213 { 214 auto len = keys.column_length(); 215 if (len > max_len) 216 max_len = len; 217 } 218 219 String res; 220 for (auto& [keys, docstring] : descs) 221 res += format("{}:{}{}\n", 222 keys, 223 String{' ', max_len - keys.column_length() + 1}, 224 docstring); 225 return res; 226 } 227 228 template<SelectMode mode> 229 void goto_commands(Context& context, NormalParams params) 230 { 231 if (params.count != 0) 232 { 233 context.push_jump(); 234 select_coord<mode>(context, LineCount{params.count - 1}); 235 if (context.has_window()) 236 context.window().center_line(LineCount{params.count-1}); 237 } 238 else 239 { 240 on_next_key_with_autoinfo(context, "goto", KeymapMode::Goto, 241 [params](Key key, Context& context) { 242 auto cp = key.codepoint(); 243 if (not cp or key == Key::Escape) 244 return; 245 auto& buffer = context.buffer(); 246 switch (auto lower_cp = to_lower(*cp); lower_cp) 247 { 248 case 'g': 249 case 'k': 250 context.push_jump(); 251 select_coord<mode>(context, BufferCoord{0,0}); 252 break; 253 case 'l': 254 select<mode, select_to_line_end<true>>(context, {}); 255 break; 256 case 'h': 257 select<mode, select_to_line_begin<true>>(context, {}); 258 break; 259 case 'i': 260 select<mode, select_to_first_non_blank>(context, {}); 261 break; 262 case 'j': 263 context.push_jump(); 264 select_coord<mode>(context, buffer.line_count() - 1); 265 break; 266 case 'e': 267 context.push_jump(); 268 select_coord<mode>(context, buffer.back_coord()); 269 break; 270 case 't': 271 if (context.has_window()) 272 { 273 auto line = context.window().position().line; 274 select_coord<mode>(context, line); 275 } 276 break; 277 case 'b': 278 if (context.has_window()) 279 { 280 auto& window = context.window(); 281 auto line = window.position().line + window.dimensions().line - 1; 282 select_coord<mode>(context, line); 283 } 284 break; 285 case 'c': 286 if (context.has_window()) 287 { 288 auto& window = context.window(); 289 auto line = window.position().line + window.dimensions().line / 2; 290 select_coord<mode>(context, line); 291 } 292 break; 293 case 'a': 294 { 295 Buffer* target = context.last_buffer(); 296 if (not target) 297 { 298 throw runtime_error("no last buffer"); 299 } 300 context.push_jump(); 301 context.change_buffer(*target); 302 break; 303 } 304 case 'd': 305 case 'u': 306 { 307 auto offset = (lower_cp == 'd' ? 1_line : -1_line) * std::max(params.count, 1); 308 select(context, mode, [&](Context& context, Selection& sel) -> Optional<Selection> { 309 if (context.has_window()) 310 { 311 auto& cursor = sel.cursor(); 312 auto& window = context.window(); 313 if (auto display_coord = window.display_coord(cursor)) 314 { 315 if (cursor.display_target == -1) 316 cursor.display_target = display_coord->column; 317 display_coord->column = cursor.display_target; 318 if (auto buffer_coord = window.buffer_coord(*display_coord + offset)) 319 return Selection{BufferCoordAndTarget{*buffer_coord, -1, cursor.display_target}}; 320 } 321 } 322 const ColumnCount tabstop = context.options()["tabstop"].get<int>(); 323 return Selection{context.buffer().offset_coord(sel.cursor(), offset, tabstop)}; 324 }); 325 break; 326 } 327 328 case 'f': 329 { 330 static constexpr char forbidden[] = { '\'', '\\', '\0' }; 331 const auto& paths_opt = context.options()["path"].get<Vector<String, MemoryDomain::Options>>(); 332 const auto paths = context.selections() | transform([&](const auto& sel) { 333 auto filename = content(buffer, sel); 334 if (any_of(filename, [](char c){ return contains(forbidden, c); })) 335 throw runtime_error(format("filename contains invalid characters: '{}'", filename)); 336 337 const StringView buffer_dir = split_path(buffer.filename()).first; 338 String path = find_file(filename, buffer_dir, paths_opt); 339 if (path.empty()) 340 throw runtime_error(format("unable to find file '{}'", filename)); 341 342 return path; 343 }); 344 345 Buffer* buffer_main = nullptr; 346 for (auto&& [i, path] : paths | enumerate()) { 347 Buffer* buffer = BufferManager::instance().get_buffer_ifp(path); 348 if (not buffer) 349 { 350 buffer = open_file_buffer(path, context.hooks_disabled() ? 351 Buffer::Flags::NoHooks 352 : Buffer::Flags::None); 353 buffer->flags() &= ~Buffer::Flags::NoHooks; 354 } 355 356 if (i == context.selections().main_index()) 357 buffer_main = buffer; 358 } 359 if (buffer_main and buffer_main != &context.buffer()) 360 { 361 context.push_jump(); 362 context.change_buffer(*buffer_main); 363 } 364 break; 365 } 366 case '.': 367 { 368 context.push_jump(); 369 auto pos = buffer.last_modification_coord(); 370 if (not pos) 371 throw runtime_error("no last modification position"); 372 if (*pos >= buffer.back_coord()) 373 pos = buffer.back_coord(); 374 select_coord<mode>(context, *pos); 375 break; 376 } 377 default: 378 throw runtime_error("key not mapped"); 379 } 380 }, (mode == SelectMode::Extend ? "goto (extend to)" : "goto"), 381 build_autoinfo_for_mapping(context, KeymapMode::Goto, 382 {{{'g','k'},"buffer top"}, 383 {{'l'}, "line end"}, 384 {{'h'}, "line begin"}, 385 {{'u'}, "up display line"}, 386 {{'d'}, "down display line"}, 387 {{'i'}, "line non blank start"}, 388 {{'j'}, "buffer bottom"}, 389 {{'e'}, "buffer end"}, 390 {{'t'}, "window top"}, 391 {{'b'}, "window bottom"}, 392 {{'c'}, "window center"}, 393 {{'a'}, "last buffer"}, 394 {{'f'}, "file"}, 395 {{'.'}, "last buffer change"}})); 396 } 397 } 398 399 template<bool lock> 400 void view_commands(Context& context, NormalParams params) 401 { 402 const int count = params.count; 403 on_next_key_with_autoinfo(context, "view", KeymapMode::View, 404 [count](Key key, Context& context) { 405 context.ensure_cursor_visible = false; 406 if (key == Key::Escape) 407 return; 408 409 if (lock) 410 view_commands<true>(context, { count, 0 }); 411 412 auto cp = key.codepoint(); 413 if (not cp or not context.has_window()) 414 return; 415 416 const BufferCoord cursor = context.selections().main().cursor(); 417 Window& window = context.window(); 418 window.update_display_buffer(context); 419 if (context.has_client()) 420 context.client().force_redraw(false); 421 422 const DisplayCoord scrolloff = context.options()["scrolloff"].get<DisplayCoord>(); 423 const LineCount line_offset{std::min((window.dimensions().line - 1) / 2, scrolloff.line)}; 424 const ColumnCount column_offset{std::min((window.dimensions().column - 1) / 2, scrolloff.column)}; 425 switch (*cp) 426 { 427 case 'v': 428 case 'c': 429 window.center_line(cursor.line); 430 break; 431 case 'm': 432 window.center_column( 433 context.buffer()[cursor.line].column_count_to(cursor.column)); 434 break; 435 case 't': 436 window.display_line_at(cursor.line, line_offset); 437 break; 438 case 'b': 439 window.display_line_at(cursor.line, window.dimensions().line-1-line_offset); 440 break; 441 case '<': 442 window.display_column_at(context.buffer()[cursor.line].column_count_to(cursor.column), 443 column_offset); 444 break; 445 case '>': 446 window.display_column_at(context.buffer()[cursor.line].column_count_to(cursor.column), 447 window.dimensions().column-1-column_offset); 448 break; 449 case 'h': 450 window.scroll(-std::max<ColumnCount>(1, count)); 451 break; 452 case 'j': 453 scroll_window(context, std::max<LineCount>(1, count), OnHiddenCursor::PreserveSelections); 454 break; 455 case 'k': 456 scroll_window(context, -std::max<LineCount>(1, count), OnHiddenCursor::PreserveSelections); 457 break; 458 case 'l': 459 window.scroll( std::max<ColumnCount>(1, count)); 460 break; 461 default: 462 throw runtime_error("key not mapped"); 463 } 464 }, lock ? "view (lock)" : "view", 465 build_autoinfo_for_mapping(context, KeymapMode::View, 466 {{{'v','c'}, "center cursor (vertically)"}, 467 {{'m'}, "center cursor (horizontally)"}, 468 {{'t'}, "cursor on top"}, 469 {{'b'}, "cursor on bottom"}, 470 {{'<'}, "cursor on left"}, 471 {{'>'}, "cursor on right"}, 472 {{'h'}, "scroll left"}, 473 {{'j'}, "scroll down"}, 474 {{'k'}, "scroll up"}, 475 {{'l'}, "scroll right"}})); 476 } 477 478 void replace_with_char(Context& context, NormalParams) 479 { 480 on_next_key_with_autoinfo(context, "replace-char", KeymapMode::None, 481 [](Key key, Context& context) { 482 auto cp = key.codepoint(); 483 if (not cp or key == Key::Escape) 484 return; 485 ScopedEdition edition(context); 486 ScopedSelectionEdition selection_edition{context}; 487 Buffer& buffer = context.buffer(); 488 auto& sels = context.selections(); 489 sels.merge_overlapping(); 490 sels.for_each([&](size_t index, Selection& sel) { 491 CharCount count = char_length(buffer, sel); 492 replace(buffer, sel, String{*cp, count}); 493 }, true); 494 }, "replace with char", "enter char to replace with\n"); 495 } 496 497 Codepoint swap_case(Codepoint cp) 498 { 499 Codepoint res = to_lower(cp); 500 return res == cp ? to_upper(cp) : res; 501 } 502 503 template<Codepoint (*func)(Codepoint)> 504 void for_each_codepoint(Context& context, NormalParams) 505 { 506 using Utf8It = utf8::iterator<BufferIterator>; 507 508 ScopedEdition edition(context); 509 ScopedSelectionEdition selection_edition{context}; 510 Buffer& buffer = context.buffer(); 511 512 context.selections().for_each([&](size_t index, Selection& sel) { 513 String str; 514 for (auto begin = Utf8It{buffer.iterator_at(sel.min()), buffer}, 515 end = Utf8It{buffer.iterator_at(sel.max()), buffer}+1; 516 begin != end; ++begin) 517 utf8::dump(std::back_inserter(str), func(*begin)); 518 replace(buffer, sel, str); 519 }, false); 520 } 521 522 void command(const Context& context, EnvVarMap env_vars, char reg = 0) 523 { 524 if (not CommandManager::has_instance()) 525 throw runtime_error{"commands are not supported"}; 526 527 String default_command = context.main_sel_register_value(reg ? reg : ':').str(); 528 529 context.input_handler().prompt( 530 ":", {}, default_command, 531 context.faces()["Prompt"], PromptFlags::DropHistoryEntriesWithBlankPrefix | PromptFlags::Command, 532 ':', 533 [completer=CommandManager::Completer{}](const Context& context, 534 StringView cmd_line, ByteCount pos) mutable { 535 return completer(context, cmd_line, pos); 536 }, 537 [env_vars = std::move(env_vars), default_command](StringView cmdline, PromptEvent event, Context& context) { 538 if (context.has_client()) 539 { 540 context.client().info_hide(); 541 if (event == PromptEvent::Change) 542 { 543 auto info = CommandManager::instance().command_info(context, cmdline); 544 context.input_handler().set_prompt_face(context.faces()[info or cmdline.empty() ? "Prompt" : "Error"]); 545 546 auto autoinfo = context.options()["autoinfo"].get<AutoInfo>(); 547 if (autoinfo & AutoInfo::Command) 548 { 549 if (cmdline.length() == 1 and is_horizontal_blank(cmdline[0_byte])) 550 context.client().info_show("prompt", 551 "commands preceded by a blank wont be saved to history", 552 {}, InfoStyle::Prompt); 553 else if (info and not info->info.empty()) 554 context.client().info_show(info->name, info->info, {}, InfoStyle::Prompt); 555 } 556 } 557 } 558 if (event == PromptEvent::Validate) 559 { 560 if (cmdline.empty()) 561 cmdline = default_command; 562 563 CommandManager::instance().execute(cmdline, context, { {}, env_vars }); 564 } 565 }); 566 } 567 568 void command(Context& context, NormalParams params) 569 { 570 EnvVarMap env_vars = { 571 { "count", to_string(params.count) }, 572 { "register", String{¶ms.reg, 1} } 573 }; 574 command(context, std::move(env_vars), params.reg); 575 } 576 577 BufferRange apply_diff(Buffer& buffer, BufferCoord pos, ArrayView<StringView> lines_before, StringView after) 578 { 579 BufferCoord first = pos; 580 const auto lines_after = after | split_after<StringView>('\n') | gather<Vector<StringView>>(); 581 582 auto byte_count = [](auto&& lines, int first, int count) { 583 return std::accumulate(lines.begin() + first, lines.begin() + first + count, 0_byte, 584 [](ByteCount l, StringView s) { return l + s.length(); }); 585 }; 586 587 bool tried_to_erase_final_newline = false; 588 for_each_diff(lines_before.begin(), (int)lines_before.size(), 589 lines_after.begin(), (int)lines_after.size(), 590 [&, posA = 0, posB = 0](DiffOp op, int len) mutable { 591 switch (op) 592 { 593 case DiffOp::Keep: 594 kak_assert(not tried_to_erase_final_newline); 595 pos = buffer.advance(pos, byte_count(lines_before, posA, len)); 596 posA += len; 597 posB += len; 598 break; 599 case DiffOp::Add: 600 if (buffer.is_end(pos)) 601 tried_to_erase_final_newline = false; 602 pos = buffer.insert(pos, {lines_after[posB].begin(), 603 lines_after[posB + len - 1].end()}).end; 604 posB += len; 605 break; 606 case DiffOp::Remove: 607 { 608 kak_assert(not tried_to_erase_final_newline); 609 BufferCoord end = buffer.advance(pos, byte_count(lines_before, posA, len)); 610 tried_to_erase_final_newline |= buffer.is_end(end); 611 pos = buffer.erase(pos, end); 612 posA += len; 613 break; 614 } 615 } 616 }); 617 if (tried_to_erase_final_newline) 618 { 619 first = std::min(first, buffer.back_coord()); 620 pos = buffer.erase(buffer.back_coord(), buffer.end_coord()); 621 } 622 return {first, pos}; 623 } 624 625 UnitTest test_apply_diff{[] { 626 using Change = Buffer::Change; 627 auto validate = [&](LineCount line, 628 StringView new_text, 629 BufferRange expected_new_range, 630 ConstArrayView<Change> expected_buffer_changes) 631 { 632 Buffer buffer{"", Buffer::Flags::None, { 633 StringData::create("line1\n"), 634 StringData::create("line2\n"), 635 StringData::create("line3\n"), 636 }}; 637 const size_t timestamp = buffer.timestamp(); 638 Vector<StringView> old_text; 639 for (auto i = line; i < buffer.line_count(); i++) 640 old_text.push_back(buffer[i]); 641 BufferRange new_text_range = apply_diff(buffer, BufferCoord{line, 0}, old_text, new_text); 642 kak_assert(new_text_range == expected_new_range); 643 kak_assert(buffer.changes_since(timestamp) == expected_buffer_changes); 644 }; 645 // When appending at end, we add any missing newline 646 validate( 647 /*line=*/3, 648 "added-line3-missing-eol", 649 BufferRange{{3, 0}, {4, 0}}, 650 { 651 Change{Change::Insert, {3, 0}, {4, 0}}, 652 } 653 ); 654 // Special case: erasing until buffer end also erases the final newline. 655 validate( 656 /*line=*/2, 657 "", 658 BufferRange{{1, 5}, {1, 5}}, 659 { 660 Change{Change::Erase, {2, 0}, {3, 0}}, 661 } 662 ); 663 // Erasing and appending at end still produces forward-only changes. 664 validate( 665 /*line=*/2, 666 "changed-line3\n" 667 "added-line4\n" 668 "added-line5\n", 669 BufferRange{{2, 0}, {5, 0}}, 670 { 671 Change{Change::Erase, {2, 0}, {3, 0}}, 672 Change{Change::Insert, {2, 0}, {5, 0}}, 673 } 674 ); 675 // Same result when append is missing newline. 676 validate( 677 /*line=*/2, 678 "changed-line3\n" 679 "added-line4\n" 680 "added-line5-missing-eol", 681 BufferRange{{2, 0}, {5, 0}}, 682 { 683 Change{Change::Erase, {2, 0}, {3, 0}}, 684 Change{Change::Insert, {2, 0}, {5, 0}}, 685 } 686 ); 687 }}; 688 689 template<bool replace> 690 void pipe(Context& context, NormalParams params) 691 { 692 const char* prompt = replace ? "pipe:" : "pipe-to:"; 693 String default_command = context.main_sel_register_value(params.reg ? params.reg : '|').str(); 694 695 context.input_handler().prompt( 696 prompt, {}, default_command, context.faces()["Prompt"], 697 PromptFlags::DropHistoryEntriesWithBlankPrefix, '|', 698 shell_complete, 699 [default_command, selection_edition=ScopedSelectionEdition(context)] 700 (StringView cmdline, PromptEvent event, Context& context) 701 { 702 if (event != PromptEvent::Validate) 703 return; 704 705 if (cmdline.empty()) 706 cmdline = default_command; 707 708 if (cmdline.empty()) 709 return; 710 711 Buffer& buffer = context.buffer(); 712 if (replace) 713 { 714 buffer.throw_if_read_only(); 715 ScopedEdition edition(context); 716 ForwardChangesTracker changes_tracker; 717 size_t timestamp = buffer.timestamp(); 718 SelectionList selections = context.selections(); 719 for (auto& sel : selections) 720 { 721 const auto first = changes_tracker.get_new_coord_tolerant(sel.min()); 722 const auto last = changes_tracker.get_new_coord_tolerant(sel.max()); 723 724 Vector<StringDataPtr> keep_alive; 725 Vector<StringView> in_lines; 726 for (auto line = first.line; line <= last.line; ++line) 727 { 728 auto& storage = buffer.line_storage(line); 729 keep_alive.push_back(storage); 730 auto content = storage->strview();; 731 if (line == last.line) 732 content = content.substr(0, last.column + utf8::codepoint_size(content[last.column])); 733 if (line == first.line) 734 content = content.substr(first.column); 735 in_lines.push_back(content); 736 } 737 738 // Needed in case we read selections inside the cmdline 739 context.selections_write_only().set({keep_direction(Selection{first, last}, sel)}, 0); 740 741 String out = ShellManager::instance().eval( 742 cmdline, context, 743 [it = in_lines.begin(), end = in_lines.end()]() mutable { 744 return (it != end) ? *it++ : StringView{}; 745 }, ShellManager::Flags::WaitForStdout).first; 746 747 if (in_lines.back().back() != '\n' and not out.empty() and out.back() == '\n') 748 out.resize(out.length()-1, 0); 749 750 auto [new_first, new_end] = apply_diff(buffer, first, in_lines, out); 751 if (new_first != new_end) 752 { 753 auto& min = sel.min(); 754 auto& max = sel.max(); 755 min = new_first; 756 max = buffer.char_prev(new_end); 757 } 758 else 759 { 760 if (new_end != BufferCoord{}) 761 new_end = buffer.char_prev(new_end); 762 sel.set(new_end); 763 } 764 765 changes_tracker.update(buffer, timestamp); 766 } 767 selections.force_timestamp(timestamp); 768 context.selections_write_only() = std::move(selections); 769 } 770 else 771 { 772 SelectionList& selections = context.selections(); 773 const auto old_main = selections.main_index(); 774 for (int i = 0; i < selections.size(); ++i) 775 { 776 selections.set_main_index(i); 777 ShellManager::instance().eval(cmdline, context, 778 content(buffer, selections.main()), 779 ShellManager::Flags::None); 780 } 781 selections.set_main_index(old_main); 782 } 783 }); 784 } 785 786 void yank(Context& context, NormalParams params) 787 { 788 const char reg = params.reg ? params.reg : '"'; 789 RegisterManager::instance()[reg].set(context, context.selections_content()); 790 context.print_status({ format("yanked {} selections to register {}", 791 context.selections().size(), reg), 792 context.faces()["Information"] }); 793 } 794 795 template<bool yank> 796 void erase_selections(Context& context, NormalParams params) 797 { 798 if (yank) 799 { 800 const char reg = params.reg ? params.reg : '"'; 801 RegisterManager::instance()[reg].set(context, context.selections_content()); 802 } 803 ScopedEdition edition(context); 804 ScopedSelectionEdition selection_edition{context}; 805 context.selections().erase(); 806 } 807 808 template<bool yank> 809 void change(Context& context, NormalParams params) 810 { 811 if (yank) 812 { 813 const char reg = params.reg ? params.reg : '"'; 814 RegisterManager::instance()[reg].set(context, context.selections_content()); 815 } 816 enter_insert_mode<InsertMode::Replace>(context, params); 817 } 818 819 BufferCoord paste_pos(Buffer& buffer, BufferCoord min, BufferCoord max, PasteMode mode, bool linewise) 820 { 821 switch (mode) 822 { 823 case PasteMode::Append: 824 if (buffer.is_end(max)) 825 return max; 826 return linewise ? std::min(buffer.line_count(), max.line+1) : buffer.char_next(max); 827 case PasteMode::Insert: 828 return linewise ? min.line : min; 829 default: 830 kak_assert(false); 831 return {}; 832 } 833 } 834 835 template<PasteMode mode> 836 void paste(Context& context, NormalParams params) 837 { 838 const char reg = params.reg ? params.reg : '"'; 839 auto strings = RegisterManager::instance()[reg].get(context); 840 const bool linewise = all_of(strings, [](StringView str) { 841 return not str.empty() and str.back() == '\n'; 842 }); 843 844 auto& buffer = context.buffer(); 845 ScopedEdition edition(context); 846 ScopedSelectionEdition selection_edition{context}; 847 context.selections().for_each([&, last=BufferCoord{}](size_t index, Selection& sel) mutable { 848 auto& str = strings[index % strings.size()]; 849 auto& min = sel.min(); 850 auto& max = sel.max(); 851 BufferRange range = (mode == PasteMode::Replace) ? 852 buffer.replace(min, buffer.char_next(max), str) 853 : buffer.insert(paste_pos(buffer, min, std::max(max, last), mode, linewise), str); 854 min = range.begin; 855 max = range.end > range.begin ? buffer.char_prev(range.end) : range.begin; 856 last = max; 857 }, mode == PasteMode::Append); 858 } 859 860 template<PasteMode mode> 861 void paste_all(Context& context, NormalParams params) 862 { 863 const char reg = params.reg ? params.reg : '"'; 864 auto strings = RegisterManager::instance()[reg].get(context); 865 String all; 866 Vector<std::pair<ByteCount, ByteCount>> offsets; 867 for (auto& str : strings) 868 { 869 if (str.empty()) 870 continue; 871 872 all += str; 873 ByteCount cursor_offset = utf8::previous(str.end(), str.begin()) - str.begin(); 874 offsets.emplace_back(cursor_offset, str.length()); 875 } 876 const bool linewise = all_of(strings, [](StringView str) { 877 return not str.empty() and str.back() == '\n'; 878 }); 879 880 if (offsets.empty()) 881 throw runtime_error("nothing to paste"); 882 883 Buffer& buffer = context.buffer(); 884 Vector<Selection> result; 885 ScopedSelectionEdition selection_edition{context}; 886 auto& selections = context.selections(); 887 { 888 ScopedEdition edition(context); 889 selections.for_each([&](size_t, const Selection& sel) { 890 auto range = (mode == PasteMode::Replace) ? 891 buffer.replace(sel.min(), buffer.char_next(sel.max()), all) 892 : buffer.insert(paste_pos(buffer, sel.min(), sel.max(), mode, linewise), all); 893 894 BufferCoord pos = range.begin; 895 for (auto [cursor_offset, length] : offsets) 896 { 897 BufferCoord cursor = buffer.advance(pos, cursor_offset); 898 result.emplace_back(pos, cursor); 899 pos = buffer.advance(cursor, length - cursor_offset); 900 } 901 }, mode == PasteMode::Append); 902 } 903 selections = std::move(result); 904 } 905 906 template<PasteMode mode> 907 void insert_output(Context& context, NormalParams params) 908 { 909 const char* prompt = mode == PasteMode::Insert ? "insert-output:" : "append-output:"; 910 String default_command = context.main_sel_register_value(params.reg ? params.reg : '|').str(); 911 912 context.input_handler().prompt( 913 prompt, {}, default_command, context.faces()["Prompt"], 914 PromptFlags::DropHistoryEntriesWithBlankPrefix, '|', 915 shell_complete, 916 [default_command, selection_edition=ScopedSelectionEdition(context)] 917 (StringView cmdline, PromptEvent event, Context& context) 918 { 919 if (event != PromptEvent::Validate) 920 return; 921 922 if (cmdline.empty()) 923 cmdline = default_command; 924 925 if (cmdline.empty()) 926 return; 927 928 ScopedEdition edition(context); 929 auto& selections = context.selections(); 930 auto& buffer = context.buffer(); 931 const size_t old_main = selections.main_index(); 932 933 selections.for_each([&](size_t index, Selection& sel) { 934 selections.set_main_index(index); 935 auto [out, status] = ShellManager::instance().eval( 936 cmdline, context, content(context.buffer(), sel), 937 ShellManager::Flags::WaitForStdout); 938 939 auto& min = sel.min(); 940 auto& max = sel.max(); 941 auto range = insert(buffer, sel, paste_pos(buffer, min, max, mode, false), out); 942 min = range.begin; 943 max = range.end > range.begin ? buffer.char_prev(range.end) : range.begin; 944 }, mode == PasteMode::Append); 945 selections.set_main_index(old_main); 946 }); 947 } 948 949 constexpr RegexCompileFlags direction_flags(RegexMode mode) 950 { 951 return (mode & RegexMode::Forward) ? 952 RegexCompileFlags::None : RegexCompileFlags::Backward | RegexCompileFlags::NoForward; 953 } 954 955 template<typename Func> 956 void regex_prompt(Context& context, String prompt, char reg, RegexMode mode, Func func) 957 { 958 kak_assert(is_direction(mode)); 959 DisplayCoord position = context.has_window() ? context.window().position() : DisplayCoord{}; 960 SelectionList selections = context.selections(); 961 auto default_regex = RegisterManager::instance()[reg].get_main(context, context.selections().main_index()); 962 context.input_handler().prompt( 963 std::move(prompt), {}, default_regex, context.faces()["Prompt"], 964 PromptFlags::Search, reg, 965 [](const Context& context, StringView regex, ByteCount pos) -> Completions { 966 auto current_word = [](StringView s) { 967 auto it = s.end(); 968 while (it != s.begin() and is_word(*(it-1))) 969 --it; 970 StringView res{it, s.end()}; 971 if (it == s.begin() or res.empty()) 972 return res; 973 974 int backslashes = 0; 975 for (auto bs = it; bs != s.begin() and *(bs-1) == '\\'; --bs) 976 ++backslashes; 977 return (backslashes % 2 == 1) ? res.substr(1_byte) : res; 978 }; 979 980 const auto word = current_word(regex.substr(0_byte, pos)); 981 auto matches = get_word_db(context.buffer()).find_matching(word); 982 constexpr size_t max_count = 100; 983 CandidateList candidates; 984 candidates.reserve(std::min(matches.size(), max_count)); 985 for_n_best(matches, max_count, [](auto& lhs, auto& rhs) { return rhs < lhs; }, 986 [&](auto&& m) { candidates.push_back(m.candidate().str()); return true; }); 987 return {(int)(word.begin() - regex.begin()), pos, std::move(candidates) }; 988 }, 989 [=, func=std::move(func), saved_reg=RegisterManager::instance()[reg].save(context), 990 selection_edition=ScopedSelectionEdition(context)] 991 (StringView str, PromptEvent event, Context& context) mutable { 992 try 993 { 994 if (event != PromptEvent::Change and context.has_client()) 995 context.client().info_hide(); 996 997 const bool incsearch = context.options()["incsearch"].get<bool>(); 998 if (incsearch) 999 { 1000 selections.update(); 1001 context.selections_write_only() = selections; 1002 if (context.has_window()) 1003 context.window().set_position(position); 1004 1005 context.input_handler().set_prompt_face(context.faces()["Prompt"]); 1006 RegisterManager::instance()[reg].restore(context, saved_reg); 1007 } 1008 1009 switch (event) 1010 { 1011 case PromptEvent::Abort: return; 1012 case PromptEvent::Change: 1013 if (not incsearch) 1014 return; 1015 if (not str.empty()) 1016 RegisterManager::instance()[reg].set(context, str.str()); 1017 break; 1018 case PromptEvent::Validate: 1019 if (not str.empty()) 1020 RegisterManager::instance()[reg].set(context, str.str()); 1021 context.push_jump(); 1022 break; 1023 } 1024 func(Regex{str.empty() ? default_regex : str, direction_flags(mode)}, event, context); 1025 } 1026 catch (regex_error& err) 1027 { 1028 if (event == PromptEvent::Validate) 1029 throw; 1030 else 1031 context.input_handler().set_prompt_face(context.faces()["Error"]); 1032 } 1033 catch (runtime_error&) 1034 { 1035 context.selections_write_only() = selections; 1036 // only validation should propagate errors, 1037 // incremental search should not. 1038 if (event == PromptEvent::Validate) 1039 throw; 1040 } 1041 }); 1042 } 1043 1044 void select_next_matches(Context& context, const Regex& regex, RegexMode mode, int count) 1045 { 1046 auto& selections = context.selections(); 1047 do { 1048 bool wrapped = false; 1049 for (auto& sel : selections) 1050 sel = keep_direction(find_next_match(context, sel, regex, mode, wrapped), sel); 1051 selections.sort_and_merge_overlapping(); 1052 } while (--count > 0); 1053 } 1054 1055 void extend_to_next_matches(Context& context, const Regex& regex, RegexMode mode, int count) 1056 { 1057 Vector<Selection> new_sels; 1058 auto& selections = context.selections(); 1059 do { 1060 bool wrapped = false; 1061 size_t main_index = selections.main_index(); 1062 for (auto& sel : selections) 1063 { 1064 auto new_sel = find_next_match(context, sel, regex, mode, wrapped); 1065 if (not wrapped) 1066 { 1067 new_sels.push_back(sel); 1068 merge_selections(new_sels.back(), new_sel); 1069 } 1070 else if (new_sels.size() <= main_index and main_index != 0) 1071 --main_index; 1072 } 1073 if (new_sels.empty()) 1074 throw runtime_error{"All selections wrapped"}; 1075 1076 selections.set(std::move(new_sels), main_index); 1077 new_sels.clear(); 1078 } while (--count > 0); 1079 } 1080 1081 void search(Context& context, NormalParams params, SelectMode mode, RegexMode regex_mode) 1082 { 1083 kak_assert(is_direction(regex_mode)); 1084 const StringView prompt = mode == SelectMode::Extend ? 1085 (regex_mode & RegexMode::Forward ? "search (extend):" : "reverse search (extend):") 1086 : (regex_mode & RegexMode::Forward ? "search:" : "reverse search:"); 1087 1088 const char reg = to_lower(params.reg ? params.reg : '/'); 1089 const int count = params.count; 1090 1091 regex_prompt(context, prompt.str(), reg, regex_mode, 1092 [=](const Regex& regex, PromptEvent event, Context& context) { 1093 if (regex.empty() or regex.str().empty()) 1094 return; 1095 1096 if (mode == SelectMode::Extend) 1097 extend_to_next_matches(context, regex, regex_mode, count); 1098 else 1099 select_next_matches(context, regex, regex_mode, count); 1100 }); 1101 } 1102 1103 void search_next(Context& context, NormalParams params, SelectMode mode, RegexMode regex_mode) 1104 { 1105 const char reg = to_lower(params.reg ? params.reg : '/'); 1106 StringView str = RegisterManager::instance()[reg].get(context).front(); 1107 if (not str.empty()) 1108 { 1109 Regex regex{str, direction_flags(regex_mode)}; 1110 ScopedSelectionEdition selection_edition{context}; 1111 auto& selections = context.selections(); 1112 bool main_wrapped = false; 1113 do { 1114 bool wrapped = false; 1115 if (mode == SelectMode::Replace) 1116 { 1117 auto& sel = selections.main(); 1118 sel = keep_direction(find_next_match(context, sel, regex, regex_mode, wrapped), sel); 1119 } 1120 else if (mode == SelectMode::Append) 1121 { 1122 auto sel = keep_direction( 1123 find_next_match(context, selections.main(), regex, regex_mode, wrapped), 1124 selections.main()); 1125 selections.push_back(std::move(sel)); 1126 selections.set_main_index(selections.size() - 1); 1127 } 1128 selections.sort_and_merge_overlapping(); 1129 main_wrapped = main_wrapped or wrapped; 1130 } while (--params.count > 0); 1131 1132 if (main_wrapped) 1133 context.print_status({"main selection search wrapped around buffer", context.faces()["Information"]}); 1134 } 1135 else 1136 throw runtime_error("no search pattern"); 1137 } 1138 1139 template<bool smart> 1140 void use_selection_as_search_pattern(Context& context, NormalParams params) 1141 { 1142 const auto& buffer = context.buffer(); 1143 auto patterns = context.selections() | transform([&](auto&& sel) { 1144 const auto beg = sel.min(), end = buffer.char_next(sel.max()); 1145 return format("{}{}{}", 1146 smart and is_bow(buffer, beg) ? "\\b" : "", 1147 escape(buffer.string(beg, end), "^$\\.*+?()[]{}|", '\\'), 1148 smart and is_eow(buffer, end) ? "\\b" : ""); 1149 }) | gather<HashSet<String>>(); 1150 String pattern = join(patterns, '|', false); 1151 1152 const char reg = to_lower(params.reg ? params.reg : '/'); 1153 1154 context.print_status({ 1155 format("register '{}' set to '{}'", reg, pattern), 1156 context.faces()["Information"] }); 1157 1158 RegisterManager::instance()[reg].set(context, {pattern}); 1159 1160 // Hack, as Window do not take register state into account 1161 if (context.has_client()) 1162 context.client().force_redraw(); 1163 } 1164 1165 void select_regex(Context& context, NormalParams params) 1166 { 1167 const char reg = to_lower(params.reg ? params.reg : '/'); 1168 const int capture = params.count; 1169 auto prompt = capture ? format("select (capture {}):", capture) : "select:"_str; 1170 1171 regex_prompt(context, std::move(prompt), reg, RegexMode::Forward, 1172 [capture](Regex ex, PromptEvent event, Context& context) { 1173 auto& selections = context.selections(); 1174 auto& buffer = selections.buffer(); 1175 if (not ex.empty() and not ex.str().empty()) 1176 selections = SelectionList{buffer, select_matches(buffer, selections, ex, capture)}; 1177 }); 1178 } 1179 1180 void split_regex(Context& context, NormalParams params) 1181 { 1182 const char reg = to_lower(params.reg ? params.reg : '/'); 1183 const int capture = params.count; 1184 auto prompt = capture ? format("split (on capture {}):", (int)capture) : "split:"_str; 1185 1186 regex_prompt(context, std::move(prompt), reg, RegexMode::Forward, 1187 [capture](Regex ex, PromptEvent event, Context& context) { 1188 auto& selections = context.selections(); 1189 auto& buffer = selections.buffer(); 1190 if (not ex.empty() and not ex.str().empty()) 1191 selections = SelectionList{buffer, split_on_matches(buffer, selections, ex, capture)}; 1192 }); 1193 } 1194 1195 void split_lines(Context& context, NormalParams params) 1196 { 1197 const LineCount count{params.count == 0 ? 1 : params.count}; 1198 ScopedSelectionEdition selection_edition{context}; 1199 auto& selections = context.selections(); 1200 auto& buffer = context.buffer(); 1201 Vector<Selection> res; 1202 for (auto& sel : selections) 1203 { 1204 if (sel.anchor().line == sel.cursor().line) 1205 { 1206 res.push_back(std::move(sel)); 1207 continue; 1208 } 1209 auto min = sel.min(); 1210 auto max = sel.max(); 1211 for (auto line = min.line; line <= max.line; line += count) 1212 { 1213 auto last_line = std::min(line + count - 1, buffer.line_count() - 1); 1214 res.push_back(keep_direction({ 1215 std::max<BufferCoord>(min, line), 1216 std::min<BufferCoord>(max, {last_line, buffer[last_line].length() - 1}) 1217 }, sel)); 1218 } 1219 } 1220 selections = std::move(res); 1221 } 1222 1223 void select_boundaries(Context& context, NormalParams) 1224 { 1225 ScopedSelectionEdition selection_edition{context}; 1226 auto& selections = context.selections(); 1227 Vector<Selection> res; 1228 for (auto& sel : selections) 1229 { 1230 res.push_back(sel.min()); 1231 if (sel.min() != sel.max()) 1232 res.push_back(sel.max()); 1233 } 1234 selections = std::move(res); 1235 } 1236 1237 void join_lines_select_spaces(Context& context, NormalParams) 1238 { 1239 auto& buffer = context.buffer(); 1240 Vector<Selection> selections; 1241 ScopedSelectionEdition selection_edition{context}; 1242 for (auto& sel : context.selections()) 1243 { 1244 const LineCount min_line = sel.min().line; 1245 const LineCount max_line = sel.max().line; 1246 auto end_line = std::min(buffer.line_count()-1, 1247 max_line + (min_line == max_line ? 1 : 0)); 1248 for (LineCount line = min_line; line < end_line; ++line) 1249 { 1250 auto begin = buffer.iterator_at({line, buffer[line].length()-1}); 1251 auto end = std::find_if_not(begin+1, buffer.end(), is_horizontal_blank); 1252 selections.emplace_back(begin.coord(), (end-1).coord()); 1253 } 1254 } 1255 if (selections.empty()) 1256 return; 1257 context.selections_write_only() = std::move(selections); 1258 context.selections().merge_consecutive(); 1259 ScopedEdition edition(context); 1260 context.selections().replace({" "_str}); 1261 } 1262 1263 void join_lines(Context& context, NormalParams params) 1264 { 1265 ScopedSelectionEdition selection_edition{context}; 1266 SelectionList sels{context.selections()}; 1267 auto restore_sels = OnScopeEnd([&]{ 1268 sels.update(); 1269 context.selections_write_only() = std::move(sels); 1270 }); 1271 1272 join_lines_select_spaces(context, params); 1273 } 1274 1275 template<bool matching> 1276 void keep(Context& context, NormalParams params) 1277 { 1278 constexpr StringView prompt = matching ? "keep matching:" : "keep not matching:"; 1279 1280 const char reg = to_lower(params.reg ? params.reg : '/'); 1281 1282 regex_prompt(context, prompt.str(), reg, RegexMode::Forward, 1283 [selection_edition=ScopedSelectionEdition(context)] 1284 (const Regex& regex, PromptEvent event, Context& context) { 1285 if (regex.empty() or regex.str().empty()) 1286 return; 1287 1288 const Buffer& buffer = context.buffer(); 1289 Vector<Selection> keep; 1290 for (auto& sel : context.selections()) 1291 { 1292 auto begin = buffer.iterator_at(sel.min()); 1293 auto end = utf8::next(buffer.iterator_at(sel.max()), buffer.end()); 1294 // We do not consider if end is on an eol, as it seems to 1295 // give more intuitive behaviours in keep use cases. 1296 const auto flags = match_flags(is_bol(begin.coord()), false, 1297 is_bow(buffer, begin.coord()), 1298 is_eow(buffer, end.coord())); 1299 if (regex_search(begin, end, begin, end, regex, flags, EventManager::handle_urgent_events) == matching) 1300 keep.push_back(sel); 1301 } 1302 if (keep.empty()) 1303 throw no_selections_remaining{}; 1304 context.selections_write_only() = std::move(keep); 1305 }); 1306 } 1307 1308 void keep_pipe(Context& context, NormalParams params) 1309 { 1310 String default_command = context.main_sel_register_value(params.reg ? params.reg : '|').str(); 1311 context.input_handler().prompt( 1312 "keep pipe:", {}, default_command, context.faces()["Prompt"], 1313 PromptFlags::DropHistoryEntriesWithBlankPrefix, '|', shell_complete, 1314 [default_command, selection_edition=ScopedSelectionEdition(context)] 1315 (StringView cmdline, PromptEvent event, Context& context) { 1316 if (event != PromptEvent::Validate) 1317 return; 1318 1319 if (cmdline.empty()) 1320 cmdline = default_command; 1321 1322 if (cmdline.empty()) 1323 return; 1324 1325 const Buffer& buffer = context.buffer(); 1326 auto& shell_manager = ShellManager::instance(); 1327 Vector<Selection> keep; 1328 1329 auto& selections = context.selections(); 1330 const size_t old_main = selections.main_index(); 1331 size_t new_main = -1; 1332 for (int i = 0; i < selections.size(); ++i) 1333 { 1334 auto& sel = selections[i]; 1335 selections.set_main_index(i); 1336 if (shell_manager.eval(cmdline, context, content(buffer, sel), 1337 ShellManager::Flags::None).second == 0) 1338 { 1339 keep.push_back(sel); 1340 if (i >= old_main and new_main == (size_t)-1) 1341 new_main = keep.size() - 1; 1342 } 1343 } 1344 if (keep.empty()) 1345 throw no_selections_remaining{}; 1346 if (new_main == -1) 1347 new_main = keep.size() - 1; 1348 context.selections_write_only().set(std::move(keep), new_main); 1349 }); 1350 } 1351 template<bool indent_empty = false> 1352 void indent(Context& context, NormalParams params) 1353 { 1354 CharCount count = params.count ? params.count : 1; 1355 CharCount indent_width = context.options()["indentwidth"].get<int>(); 1356 String indent = indent_width == 0 ? String{'\t', count} : String{' ', indent_width * count}; 1357 1358 ScopedEdition edition(context); 1359 auto& buffer = context.buffer(); 1360 LineCount last_line = 0; 1361 ScopedSelectionEdition selection_edition{context}; 1362 for (auto& sel : context.selections()) 1363 { 1364 for (auto line = std::max(last_line, sel.min().line); line < sel.max().line+1; ++line) 1365 { 1366 if (indent_empty or buffer[line].length() > 1) 1367 buffer.insert(line, indent); 1368 } 1369 // avoid reindenting the same line if multiple selections are on it 1370 last_line = sel.max().line+1; 1371 } 1372 } 1373 1374 template<bool deindent_incomplete = true> 1375 void deindent(Context& context, NormalParams params) 1376 { 1377 ColumnCount count = params.count ? params.count : 1; 1378 ColumnCount tabstop = context.options()["tabstop"].get<int>(); 1379 ColumnCount indent_width = context.options()["indentwidth"].get<int>(); 1380 if (indent_width == 0) 1381 indent_width = tabstop; 1382 indent_width = indent_width * count; 1383 1384 auto& buffer = context.buffer(); 1385 LineCount last_line = 0; 1386 ScopedSelectionEdition selection_edition{context}; 1387 for (auto& sel : context.selections()) 1388 { 1389 for (auto line = std::max(sel.min().line, last_line); 1390 line < sel.max().line+1; ++line) 1391 { 1392 ColumnCount width = 0; 1393 auto content = buffer[line]; 1394 for (auto column = 0_byte; column < content.length(); ++column) 1395 { 1396 const char c = content[column]; 1397 if (c == '\t') 1398 width = (width / tabstop + 1) * tabstop; 1399 else if (c == ' ') 1400 ++width; 1401 else 1402 { 1403 if (deindent_incomplete and width != 0) 1404 buffer.erase(line, BufferCoord{line, column}); 1405 break; 1406 } 1407 if (width >= indent_width) 1408 { 1409 buffer.erase(line, BufferCoord{line, column+1}); 1410 break; 1411 } 1412 } 1413 } 1414 // avoid reindenting the same line if multiple selections are on it 1415 last_line = sel.max().line + 1; 1416 } 1417 } 1418 1419 void select_object(Context& context, NormalParams params, ObjectFlags flags, SelectMode mode = SelectMode::Replace) 1420 { 1421 auto get_title = [&] { 1422 const auto whole_flags = (ObjectFlags::ToBegin | ObjectFlags::ToEnd); 1423 const bool whole = (flags & whole_flags) == whole_flags; 1424 return format("{} {}{}{} object{}", 1425 mode == SelectMode::Extend ? "extend" : "select", 1426 whole ? "" : "to ", 1427 flags & ObjectFlags::Inner ? "inner " : "", 1428 flags & ObjectFlags::Nested ? "nested" : "surrounding", 1429 whole ? "" : (flags & ObjectFlags::ToBegin ? " begin" : " end")); 1430 }; 1431 1432 on_next_key_with_autoinfo(context,"text-object", KeymapMode::Object, 1433 [=](Key key, Context& context) { 1434 if (key == Key::Escape) 1435 return; 1436 1437 const bool nested = flags & ObjectFlags::Nested; 1438 const int count = params.count <= 0 ? 0 : params.count - 1; 1439 auto select_nested_and_set_last = [count, flags](Context& context, auto&& func) { 1440 context.set_last_select( 1441 [=](Context& context){ 1442 ScopedSelectionEdition selection_edition{context}; 1443 context.selections() = func(context, count, flags); 1444 }); 1445 ScopedSelectionEdition selection_edition{context}; 1446 context.selections() = func(context, count, flags); 1447 }; 1448 1449 static constexpr struct ObjectType 1450 { 1451 Key key; 1452 Optional<Selection> (*func)(const Context&, const Selection&, int, ObjectFlags); 1453 Vector<Selection> (*nested_func)(const Context&, int, ObjectFlags); 1454 } selectors[] = { 1455 { 'w', select_word<Word>, select_nested_words<Word> }, 1456 { alt('w'), select_word<WORD>, select_nested_words<WORD> }, 1457 { 's', select_sentence, select_nested_sentences }, 1458 { 'p', select_paragraph, select_nested_paragraphs }, 1459 { Key::Space, select_whitespaces, select_nested_whitespaces }, 1460 { 'i', select_indent, select_nested_indents }, 1461 { 'n', select_number, select_nested_numbers }, 1462 { 'u', select_argument, select_nested_arguments }, 1463 }; 1464 auto obj_it = find(selectors | transform(&ObjectType::key), key).base(); 1465 if (obj_it != std::end(selectors)) 1466 { 1467 if (nested) 1468 return select_nested_and_set_last(context, obj_it->nested_func); 1469 else 1470 return select_and_set_last( 1471 context, mode, [=](Context& context, Selection& sel) { return obj_it->func(context, sel, count, flags); }); 1472 } 1473 1474 static constexpr auto regex_selector = [=](StringView open, StringView close, int count, ObjectFlags flags) { 1475 return [open=Regex{open, RegexCompileFlags::Backward}, 1476 close=Regex{close, RegexCompileFlags::Backward}, 1477 count, flags](Context& context, Selection& sel) { 1478 return select_surrounding(context, sel, open, close, count, flags); 1479 }; 1480 }; 1481 1482 if (key == 'c') 1483 { 1484 const bool info = show_auto_info_ifn( 1485 "Enter object desc", 1486 "format: <open regex>,<close regex>\n" 1487 " escape commas with '\\'", 1488 AutoInfo::Command, context); 1489 1490 context.input_handler().prompt( 1491 "object desc:", {}, {}, context.faces()["Prompt"], 1492 PromptFlags::None, '_', complete_nothing, 1493 [count,info,mode,nested,flags,select_nested_and_set_last](StringView cmdline, PromptEvent event, Context& context) { 1494 if (event != PromptEvent::Change) 1495 hide_auto_info_ifn(context, info); 1496 if (event != PromptEvent::Validate) 1497 return; 1498 1499 struct error : runtime_error { error(size_t) : runtime_error{"desc parsing failed, expected <open>,<close>"} {} }; 1500 1501 auto params = cmdline | split<StringView>(',', '\\') 1502 | transform(unescape<',', '\\'>) 1503 | static_gather<error, 2>(); 1504 if (params[0].empty() or params[1].empty()) 1505 throw error{0}; 1506 1507 if (nested) 1508 return select_nested_and_set_last(context, [open=Regex{params[0]},close=Regex{params[1]}](Context& context, int count, ObjectFlags flags) { 1509 return open == close ? regex_select_nested(context, open, flags) 1510 : regex_select_nested(context, open, close, count, flags); 1511 }); 1512 else 1513 select_and_set_last(context, mode, regex_selector(params[0], params[1], count, flags)); 1514 }); 1515 return; 1516 } 1517 1518 if (key == alt(';')) 1519 { 1520 EnvVarMap env_vars = { 1521 { "count", to_string(params.count) }, 1522 { "register", String{¶ms.reg, 1} }, 1523 { "select_mode", option_to_string(mode, Quoting::Raw) }, 1524 { "object_flags", option_to_string(flags, Quoting::Raw) } 1525 }; 1526 command(context, std::move(env_vars)); 1527 return; 1528 } 1529 1530 static constexpr struct 1531 { 1532 char open; 1533 char close; 1534 char name; 1535 } surrounding_pairs[] = { 1536 { '(', ')', 'b' }, 1537 { '{', '}', 'B' }, 1538 { '[', ']', 'r' }, 1539 { '<', '>', 'a' }, 1540 { '"', '"', 'Q' }, 1541 { '\'', '\'', 'q' }, 1542 { '`', '`', 'g' }, 1543 }; 1544 if (auto it = find_if(surrounding_pairs, [key](auto s) { return key == s.open or key == s.close or key == s.name; }); 1545 it != std::end(surrounding_pairs)) 1546 { 1547 if (nested) 1548 return select_nested_and_set_last(context, [open=Regex{format("\\Q{}", it->open)},close=Regex{format("\\Q{}", it->close)}](Context& context, int count, ObjectFlags flags) { 1549 return open == close ? regex_select_nested(context, open, flags) 1550 : regex_select_nested(context, open, close, count, flags); 1551 }); 1552 else 1553 return select_and_set_last( 1554 context, mode, regex_selector(format("\\Q{}", it->open), format("\\Q{}", it->close), count, flags)); 1555 } 1556 1557 if (auto cp = key.codepoint(); cp and is_punctuation(*cp, {})) 1558 { 1559 auto re = "\\Q" + to_string(*cp); 1560 if (nested) 1561 return select_nested_and_set_last(context, [re](Context& context, int count, ObjectFlags flags) { 1562 return regex_select_nested(context, Regex{re}, flags); 1563 }); 1564 else 1565 return select_and_set_last(context, mode, regex_selector(re, re, count, flags)); 1566 } 1567 }, get_title(), 1568 build_autoinfo_for_mapping(context, KeymapMode::Object, 1569 {{{'b','(',')'}, "parenthesis block"}, 1570 {{'B','{','}'}, "brace block"}, 1571 {{'r','[',']'}, "bracket block"}, 1572 {{'a','<','>'}, "angle block"}, 1573 {{'"','Q'}, "double quote string"}, 1574 {{'\'','q'}, "single quote string"}, 1575 {{'`','g'}, "grave quote string"}, 1576 {{'w'}, "word"}, 1577 {{alt('w')}, "WORD"}, 1578 {{'s'}, "sentence"}, 1579 {{'p'}, "paragraph"}, 1580 {{Key::Space}, "whitespaces"}, 1581 {{'i'}, "indent"}, 1582 {{'u'}, "argument"}, 1583 {{'n'}, "number"}, 1584 {{'c'}, "custom object desc"}, 1585 {{alt(';')}, "run command in object context"}})); 1586 } 1587 1588 template<ObjectFlags flags, SelectMode mode = SelectMode::Replace> 1589 void select_object(Context& context, NormalParams params) 1590 { 1591 static_assert((not (flags & ObjectFlags::Nested)) or (flags & (ObjectFlags::ToBegin | ObjectFlags::ToEnd)), 1592 "nested selections only can select whole nested objects"); 1593 return select_object(context, params, flags, mode); 1594 } 1595 1596 template<Direction direction, bool half = false> 1597 void scroll(Context& context, NormalParams params) 1598 { 1599 const Window& window = context.window(); 1600 const int count = params.count ? params.count : 1; 1601 const LineCount offset = (window.dimensions().line - 2) / (half ? 2 : 1) * count; 1602 1603 scroll_window(context, offset * direction, OnHiddenCursor::MoveCursorAndAnchor); 1604 } 1605 1606 template<Direction direction> 1607 void copy_selections_on_next_lines(Context& context, NormalParams params) 1608 { 1609 ScopedSelectionEdition selection_edition{context}; 1610 auto& selections = context.selections(); 1611 auto& buffer = context.buffer(); 1612 const ColumnCount tabstop = context.options()["tabstop"].get<int>(); 1613 Vector<Selection> result; 1614 size_t main_index = 0; 1615 for (auto& sel : selections) 1616 { 1617 const bool is_main = (&sel == &selections.main()); 1618 auto anchor = sel.anchor(); 1619 auto cursor = sel.cursor(); 1620 ColumnCount cursor_col = get_column(buffer, tabstop, cursor); 1621 ColumnCount anchor_col = get_column(buffer, tabstop, anchor); 1622 1623 if (is_main) 1624 main_index = result.size(); 1625 result.push_back(std::move(sel)); 1626 const LineCount height = std::max(anchor.line, cursor.line) - std::min(anchor.line, cursor.line) + 1; 1627 const size_t max_lines = std::max(params.count, 1); 1628 1629 for (size_t i = 0, nb_sels = 0; nb_sels < max_lines; ++i) 1630 { 1631 LineCount offset = direction * (i + 1) * height; 1632 1633 const LineCount anchor_line = anchor.line + offset; 1634 const LineCount cursor_line = cursor.line + offset; 1635 1636 if (anchor_line < 0 or cursor_line < 0 or 1637 anchor_line >= buffer.line_count() or cursor_line >= buffer.line_count()) 1638 break; 1639 1640 const ByteCount anchor_byte = get_byte_to_column(buffer, tabstop, {anchor_line, anchor_col}); 1641 const ByteCount cursor_byte = get_byte_to_column(buffer, tabstop, {cursor_line, cursor_col}); 1642 1643 if (anchor_byte != buffer[anchor_line].length() and 1644 cursor_byte != buffer[cursor_line].length()) 1645 { 1646 if (is_main) 1647 main_index = result.size(); 1648 result.emplace_back(BufferCoord{anchor_line, anchor_byte}, 1649 BufferCoordAndTarget{cursor_line, cursor_byte, cursor.target}); 1650 1651 nb_sels++; 1652 } 1653 } 1654 } 1655 selections.set(std::move(result), main_index); 1656 selections.sort_and_merge_overlapping(); 1657 } 1658 1659 template<Direction direction> 1660 void rotate_selections(Context& context, NormalParams params) 1661 { 1662 const int count = params.count ? params.count : 1; 1663 ScopedSelectionEdition selection_edition{context}; 1664 auto& selections = context.selections(); 1665 const int index = selections.main_index(); 1666 const int num = selections.size(); 1667 selections.set_main_index((direction == Forward) ? 1668 (index + count) % num 1669 : (index + (num - count % num)) % num); 1670 } 1671 1672 template<Direction direction> 1673 void rotate_selections_content(Context& context, NormalParams params) 1674 { 1675 size_t group = params.count; 1676 size_t count = 1; 1677 auto strings = context.selections_content(); 1678 if (group == 0 or group > (int)strings.size()) 1679 group = (int)strings.size(); 1680 count = count % group; 1681 ScopedSelectionEdition selection_edition{context}; 1682 auto& selections = context.selections(); 1683 auto main = strings.begin() + selections.main_index(); 1684 for (auto it = strings.begin(); it != strings.end(); ) 1685 { 1686 auto end = std::min(strings.end(), it + group); 1687 auto new_beg = (direction == Direction::Forward) ? end - count : it + count; 1688 std::rotate(it, new_beg, end); 1689 1690 if (it <= main and main < end) 1691 main = main < new_beg ? end - (new_beg - main) : it + (main - new_beg); 1692 it = end; 1693 } 1694 selections.replace(strings); 1695 selections.set_main_index(main - strings.begin()); 1696 } 1697 1698 enum class SelectFlags 1699 { 1700 None = 0, 1701 Reverse = 1, 1702 Inclusive = 2, 1703 Extend = 4 1704 }; 1705 1706 constexpr bool with_bit_ops(Meta::Type<SelectFlags>) { return true; } 1707 1708 void select_to_next_char(Context& context, NormalParams params, SelectFlags flags) 1709 { 1710 auto get_title = [=] { 1711 return format("{} {} {} char", 1712 flags & SelectFlags::Extend ? "extend" : "select", 1713 flags & SelectFlags::Inclusive ? "onto" : "to", 1714 flags & SelectFlags::Reverse ? "previous" : "next"); 1715 }; 1716 1717 on_next_key_with_autoinfo(context, "to-char", KeymapMode::None, 1718 [params, flags](Key key, Context& context) { 1719 auto cp = key.codepoint(); 1720 if (not cp or key == Key::Escape) 1721 return; 1722 auto new_flags = flags & SelectFlags::Extend ? SelectMode::Extend 1723 : SelectMode::Replace; 1724 select_and_set_last( 1725 context, new_flags, [cp=*cp, count=params.count, flags] (auto& context, auto& sel) { 1726 auto& func = flags & SelectFlags::Reverse ? select_to_reverse : select_to; 1727 return func(context, sel, cp, count, flags & SelectFlags::Inclusive); 1728 }); 1729 }, get_title(), "enter char to select to"); 1730 } 1731 1732 template<SelectFlags flags> 1733 void select_to_next_char(Context& context, NormalParams params) 1734 { 1735 select_to_next_char(context, params, flags); 1736 } 1737 1738 void start_or_end_macro_recording(Context& context, NormalParams params) 1739 { 1740 if (context.input_handler().is_recording()) 1741 context.input_handler().stop_recording(); 1742 else 1743 { 1744 const char reg = to_lower(params.reg ? params.reg : '@'); 1745 if (not is_basic_alpha(reg) and reg != '@') 1746 throw runtime_error("macros can only use the '@' and alphabetic registers"); 1747 context.input_handler().start_recording(reg); 1748 } 1749 } 1750 1751 void replay_macro(Context& context, NormalParams params) 1752 { 1753 const char reg = to_lower(params.reg ? params.reg : '@'); 1754 if (not is_basic_alpha(reg) and reg != '@') 1755 throw runtime_error("macros can only use the '@' and alphabetic registers"); 1756 1757 static bool running_macros[27] = {}; 1758 const size_t idx = reg != '@' ? (size_t)(reg - 'a') : 26; 1759 if (running_macros[idx]) 1760 throw runtime_error("recursive macros call detected"); 1761 1762 ConstArrayView<String> reg_val = RegisterManager::instance()[reg].get(context); 1763 if (reg_val.empty() or reg_val[0].empty()) 1764 throw runtime_error(format("register '{}' is empty", reg)); 1765 1766 running_macros[idx] = true; 1767 auto stop = OnScopeEnd([&]{ running_macros[idx] = false; }); 1768 1769 auto keys = parse_keys(reg_val[0]); 1770 ScopedEdition edition(context); 1771 ScopedSelectionEdition selection_edition{context}; 1772 ScopedSetBool disable_keymaps(context.keymaps_disabled()); 1773 do 1774 { 1775 for (auto& key : keys) 1776 context.input_handler().handle_key(key); 1777 } while (--params.count > 0); 1778 } 1779 1780 template<Direction direction> 1781 void jump(Context& context, NormalParams params) 1782 { 1783 const int count = std::max(1, params.count); 1784 auto jump = (direction == Forward) ? 1785 context.jump_list().forward(context, count) : 1786 context.jump_list().backward(context, count); 1787 1788 Buffer* oldbuf = &context.buffer(); 1789 Buffer& buffer = const_cast<Buffer&>(jump.buffer()); 1790 ScopedSelectionEdition selection_edition{context}; 1791 if (&buffer != oldbuf) 1792 context.change_buffer(buffer); 1793 context.selections_write_only() = jump; 1794 } 1795 1796 void push_selections(Context& context, NormalParams) 1797 { 1798 context.push_jump(true); 1799 context.print_status({ format("saved {} selections", context.selections().size()), 1800 context.faces()["Information"] }); 1801 } 1802 1803 void align(Context& context, NormalParams) 1804 { 1805 ScopedSelectionEdition selection_edition{context}; 1806 auto& selections = context.selections(); 1807 auto& buffer = context.buffer(); 1808 const ColumnCount tabstop = context.options()["tabstop"].get<int>(); 1809 1810 Vector<Vector<const Selection*>> columns; 1811 LineCount last_line = -1; 1812 size_t column = 0; 1813 for (auto& sel : selections) 1814 { 1815 auto line = sel.cursor().line; 1816 if (sel.anchor().line != line) 1817 throw runtime_error("align cannot work with multi line selections"); 1818 1819 column = (line == last_line) ? column + 1 : 0; 1820 if (column >= columns.size()) 1821 columns.resize(column+1); 1822 columns[column].push_back(&sel); 1823 last_line = line; 1824 } 1825 1826 const bool use_tabs = context.options()["aligntab"].get<bool>(); 1827 for (auto& col : columns) 1828 { 1829 ColumnCount maxcol = 0; 1830 for (auto& sel : col) 1831 maxcol = std::max(get_column(buffer, tabstop, sel->cursor()), maxcol); 1832 for (auto& sel : col) 1833 { 1834 auto insert_coord = sel->min(); 1835 ColumnCount lastcol = get_column(buffer, tabstop, sel->cursor()); 1836 ColumnCount inscount = maxcol - lastcol; 1837 String padstr; 1838 if (not use_tabs) 1839 padstr = String{ ' ', inscount }; 1840 else 1841 { 1842 ColumnCount inscol = get_column(buffer, tabstop, insert_coord); 1843 ColumnCount targetcol = inscol + inscount; 1844 ColumnCount tabcol = inscol - (inscol % tabstop); 1845 CharCount tabs = (int)((targetcol - tabcol) / tabstop); 1846 CharCount spaces = (int)(targetcol - (tabs ? (tabcol + (int)tabs * tabstop) : inscol)); 1847 padstr = String{ '\t', tabs } + String{ ' ', spaces }; 1848 } 1849 buffer.insert(insert_coord, padstr); 1850 } 1851 selections.update(); 1852 } 1853 } 1854 1855 void copy_indent(Context& context, NormalParams params) 1856 { 1857 int selection = params.count; 1858 auto& buffer = context.buffer(); 1859 ScopedSelectionEdition selection_edition{context}; 1860 auto& selections = context.selections(); 1861 Vector<LineCount> lines; 1862 for (auto sel : selections) 1863 { 1864 for (LineCount l = sel.min().line; l < sel.max().line + 1; ++l) 1865 lines.push_back(l); 1866 } 1867 if (selection > selections.size()) 1868 throw runtime_error("invalid selection index"); 1869 if (selection == 0) 1870 selection = context.selections().main_index() + 1; 1871 1872 auto ref_line = selections[selection-1].min().line; 1873 auto line = buffer[ref_line]; 1874 auto it = line.begin(); 1875 while (it != line.end() and is_horizontal_blank(*it)) 1876 ++it; 1877 const StringView indent = line.substr(0_byte, (int)(it-line.begin())); 1878 1879 ScopedEdition edition{context}; 1880 for (auto& l : lines) 1881 { 1882 if (l == ref_line) 1883 continue; 1884 1885 auto line = buffer[l]; 1886 ByteCount i = 0; 1887 while (i < line.length() and is_horizontal_blank(line[i])) 1888 ++i; 1889 buffer.replace(l, {l, i}, indent); 1890 } 1891 } 1892 1893 void tabs_to_spaces(Context& context, NormalParams params) 1894 { 1895 auto& buffer = context.buffer(); 1896 const ColumnCount opt_tabstop = context.options()["tabstop"].get<int>(); 1897 const ColumnCount tabstop = params.count == 0 ? opt_tabstop : params.count; 1898 Vector<Selection> tabs; 1899 Vector<String> spaces; 1900 ScopedSelectionEdition selection_edition{context}; 1901 ScopedEdition edition{context}; 1902 for (auto& sel : context.selections()) 1903 { 1904 for (auto it = buffer.iterator_at(sel.min()), 1905 end = buffer.iterator_at(sel.max())+1; it != end; ++it) 1906 { 1907 if (*it == '\t') 1908 { 1909 ColumnCount col = get_column(buffer, opt_tabstop, it.coord()); 1910 ColumnCount end_col = (col / tabstop + 1) * tabstop; 1911 tabs.emplace_back(it.coord()); 1912 spaces.emplace_back(' ', end_col - col); 1913 } 1914 } 1915 } 1916 if (not tabs.empty()) 1917 SelectionList{ buffer, std::move(tabs) }.replace(spaces); 1918 } 1919 1920 void spaces_to_tabs(Context& context, NormalParams params) 1921 { 1922 auto& buffer = context.buffer(); 1923 const ColumnCount opt_tabstop = context.options()["tabstop"].get<int>(); 1924 const ColumnCount tabstop = params.count == 0 ? opt_tabstop : params.count; 1925 Vector<Selection> spaces; 1926 ScopedSelectionEdition selection_edition{context}; 1927 ScopedEdition edition{context}; 1928 for (auto& sel : context.selections()) 1929 { 1930 for (auto it = buffer.iterator_at(sel.min()), 1931 end = buffer.iterator_at(sel.max())+1; it != end;) 1932 { 1933 if (*it == ' ') 1934 { 1935 auto spaces_beg = it; 1936 auto spaces_end = spaces_beg+1; 1937 ColumnCount col = get_column(buffer, opt_tabstop, spaces_end.coord()); 1938 while (spaces_end != end and 1939 *spaces_end == ' ' and (col % tabstop) != 0) 1940 { 1941 ++spaces_end; 1942 ++col; 1943 } 1944 if ((col % tabstop) == 0) 1945 spaces.emplace_back(spaces_beg.coord(), (spaces_end-1).coord()); 1946 else if (spaces_end != end and *spaces_end == '\t') 1947 spaces.emplace_back(spaces_beg.coord(), spaces_end.coord()); 1948 it = spaces_end; 1949 } 1950 else 1951 ++it; 1952 } 1953 } 1954 if (not spaces.empty()) 1955 SelectionList{ buffer, std::move(spaces) }.replace("\t"_str); 1956 } 1957 1958 void trim_selections(Context& context, NormalParams) 1959 { 1960 using Utf8It = utf8::iterator<BufferIterator>; 1961 auto& buffer = context.buffer(); 1962 ScopedSelectionEdition selection_edition{context}; 1963 auto& selections = context.selections(); 1964 Vector<int> to_remove; 1965 1966 for (int i = 0; i < (int)selections.size(); ++i) 1967 { 1968 auto& sel = selections[i]; 1969 auto beg = Utf8It{buffer.iterator_at(sel.min()), buffer}; 1970 auto end = Utf8It{buffer.iterator_at(sel.max()), buffer}; 1971 while (beg != end and is_blank(*beg)) 1972 ++beg; 1973 while (beg != end and is_blank(*end)) 1974 --end; 1975 1976 if (beg == end and is_blank(*beg)) 1977 to_remove.push_back(i); 1978 else 1979 { 1980 sel.min() = beg.base().coord(); 1981 sel.max() = end.base().coord(); 1982 } 1983 } 1984 1985 if (to_remove.size() == selections.size()) 1986 throw no_selections_remaining{}; 1987 for (auto& i : to_remove | reverse()) 1988 selections.remove(i); 1989 } 1990 1991 SelectionList read_selections_from_register(char reg, const Context& context) 1992 { 1993 if (not is_basic_alpha(reg) and reg != '^') 1994 throw runtime_error("selections can only be saved to the '^' and alphabetic registers"); 1995 1996 auto content = RegisterManager::instance()[reg].get(context); 1997 1998 if (content.size() < 2) 1999 throw runtime_error(format("register '{}' does not contain a selections desc", reg)); 2000 2001 // Use the last two values for timestamp and main_index to allow the buffer 2002 // name to have @ symbols 2003 struct error : runtime_error { error(size_t) : runtime_error{"expected <buffer>@<timestamp>@main_index"} {} }; 2004 auto end_content = content[0] | reverse() | split('@') | transform([] (auto bounds) { 2005 return StringView{bounds.second.base(), bounds.first.base()}; 2006 }) | static_gather<error, 2, false>(); 2007 2008 const size_t main = str_to_int(end_content[0]); 2009 const size_t timestamp = str_to_int(end_content[1]); 2010 const auto buffer_name = StringView{ content[0].begin (), end_content[1].begin () - 1 }; 2011 Buffer& buffer = BufferManager::instance().get_buffer(buffer_name); 2012 2013 return selection_list_from_strings(buffer, ColumnType::Byte, content.subrange(1), timestamp, main); 2014 } 2015 2016 enum class CombineOp 2017 { 2018 Append, 2019 Union, 2020 Intersect, 2021 SelectLeftmostCursor, 2022 SelectRightmostCursor, 2023 SelectLongest, 2024 SelectShortest, 2025 }; 2026 2027 CombineOp key_to_combine_op(Key key) 2028 { 2029 switch (key.key) 2030 { 2031 case 'a': return CombineOp::Append; 2032 case 'u': return CombineOp::Union; 2033 case 'i': return CombineOp::Intersect; 2034 case '<': return CombineOp::SelectLeftmostCursor; 2035 case '>': return CombineOp::SelectRightmostCursor; 2036 case '+': return CombineOp::SelectLongest; 2037 case '-': return CombineOp::SelectShortest; 2038 } 2039 throw runtime_error{format("no such combine operator: '{}'", key.key)}; 2040 } 2041 2042 void combine_selection(const Buffer& buffer, Selection& sel, const Selection& other, CombineOp op) 2043 { 2044 switch (op) 2045 { 2046 case CombineOp::Union: 2047 sel.set(std::min(sel.min(), other.min()), 2048 std::max(sel.max(), other.max())); 2049 break; 2050 case CombineOp::Intersect: 2051 sel.set(std::max(sel.min(), other.min()), 2052 std::min(sel.max(), other.max())); 2053 break; 2054 case CombineOp::SelectLeftmostCursor: 2055 if (sel.cursor() > other.cursor()) 2056 sel = other; 2057 break; 2058 case CombineOp::SelectRightmostCursor: 2059 if (sel.cursor() < other.cursor()) 2060 sel = other; 2061 break; 2062 case CombineOp::SelectLongest: 2063 if (char_length(buffer, sel) < char_length(buffer, other)) 2064 sel = other; 2065 break; 2066 case CombineOp::SelectShortest: 2067 if (char_length(buffer, sel) > char_length(buffer, other)) 2068 sel = other; 2069 break; 2070 default: kak_assert(false); 2071 } 2072 } 2073 2074 template<typename Func> 2075 void combine_selections(Context& context, SelectionList list, Func func, StringView title) 2076 { 2077 if (&context.buffer() != &list.buffer()) 2078 throw runtime_error{"cannot combine selections from different buffers"}; 2079 2080 on_next_key_with_autoinfo(context, "combine-selections", KeymapMode::Combine, 2081 [func, list](Key key, Context& context) mutable { 2082 if (key == Key::Escape) 2083 return; 2084 2085 const auto op = key_to_combine_op(key); 2086 ScopedSelectionEdition selection_edition{context}; 2087 auto& sels = context.selections(); 2088 list.update(); 2089 if (op == CombineOp::Append) 2090 { 2091 const auto main_index = list.size() + sels.main_index(); 2092 for (auto& sel : sels) 2093 list.push_back(sel); 2094 list.set_main_index(main_index); 2095 list.sort_and_merge_overlapping(); 2096 } 2097 else 2098 { 2099 if (list.size() != sels.size()) 2100 throw runtime_error{format("the two selection lists don't have the same number of elements ({} vs {})", 2101 list.size(), sels.size())}; 2102 for (int i = 0; i < list.size(); ++i) 2103 combine_selection(sels.buffer(), list[i], sels[i], op); 2104 list.set_main_index(sels.main_index()); 2105 } 2106 func(context, std::move(list)); 2107 }, title.str(), 2108 build_autoinfo_for_mapping(context, KeymapMode::Combine, 2109 {{{'a'}, "append lists"}, 2110 {{'u'}, "union"}, 2111 {{'i'}, "intersection"}, 2112 {{'<'}, "select leftmost cursor"}, 2113 {{'>'}, "select rightmost cursor"}, 2114 {{'+'}, "select longest"}, 2115 {{'-'}, "select shortest"}})); 2116 } 2117 2118 template<bool combine> 2119 void save_selections(Context& context, NormalParams params) 2120 { 2121 const char reg = to_lower(params.reg ? params.reg : '^'); 2122 if (not is_basic_alpha(reg) and reg != '^') 2123 throw runtime_error("selections can only be saved to the '^' and alphabetic registers"); 2124 2125 auto content = RegisterManager::instance()[reg].get(context); 2126 const bool empty = content.size() == 1 and content[0].empty(); 2127 2128 auto save_to_reg = [reg](Context& context, const SelectionList& sels) { 2129 auto& buffer = context.buffer(); 2130 auto to_string = [&] (const Selection& sel) { return selection_to_string(ColumnType::Byte, buffer, sel); }; 2131 auto descs = concatenated(ConstArrayView<String>{format("{}@{}@{}", buffer.name(), buffer.timestamp(), sels.main_index())}, 2132 sels | transform(to_string)) | gather<Vector<String>>(); 2133 RegisterManager::instance()[reg].set(context, descs); 2134 2135 context.print_status({format("{} {} selections to register '{}'", 2136 combine ? "Combined" : "Saved", sels.size(), reg), 2137 context.faces()["Information"]}); 2138 }; 2139 2140 if (combine and not empty) 2141 { 2142 ScopedSelectionEdition selection_edition{context}; 2143 combine_selections(context, read_selections_from_register(reg, context), save_to_reg, "combine selections to register"); 2144 } 2145 else 2146 save_to_reg(context, context.selections()); 2147 } 2148 2149 template<bool combine> 2150 void restore_selections(Context& context, NormalParams params) 2151 { 2152 const char reg = to_lower(params.reg ? params.reg : '^'); 2153 auto selections = read_selections_from_register(reg, context); 2154 2155 ScopedSelectionEdition selection_edition{context}; 2156 2157 auto set_selections = [reg](Context& context, SelectionList sels) { 2158 auto size = sels.size(); 2159 context.selections_write_only() = std::move(sels); 2160 context.print_status({format("{} {} selections from register '{}'", 2161 combine ? "Combined" : "Restored", size, reg), 2162 context.faces()["Information"]}); 2163 }; 2164 2165 if (not combine) 2166 { 2167 if (&selections.buffer() != &context.buffer()) 2168 context.change_buffer(selections.buffer()); 2169 set_selections(context, std::move(selections)); 2170 } 2171 else 2172 combine_selections(context, std::move(selections), set_selections, "combine selections from register"); 2173 } 2174 2175 void undo(Context& context, NormalParams params) 2176 { 2177 Buffer& buffer = context.buffer(); 2178 size_t timestamp = buffer.timestamp(); 2179 if (buffer.undo(std::max(1, params.count))) 2180 { 2181 auto ranges = compute_modified_ranges(buffer, timestamp); 2182 if (not ranges.empty()) 2183 context.selections_write_only() = std::move(ranges); 2184 } 2185 else 2186 throw runtime_error("nothing left to undo"); 2187 } 2188 2189 void redo(Context& context, NormalParams params) 2190 { 2191 Buffer& buffer = context.buffer(); 2192 size_t timestamp = buffer.timestamp(); 2193 if (buffer.redo(std::max(1, params.count))) 2194 { 2195 auto ranges = compute_modified_ranges(buffer, timestamp); 2196 if (not ranges.empty()) 2197 context.selections_write_only() = std::move(ranges); 2198 } 2199 else 2200 throw runtime_error("nothing left to redo"); 2201 } 2202 2203 template<Direction direction> 2204 void move_in_history(Context& context, NormalParams params) 2205 { 2206 Buffer& buffer = context.buffer(); 2207 size_t timestamp = buffer.timestamp(); 2208 const int count = std::max(1, params.count); 2209 const int history_id = (size_t)buffer.current_history_id() + direction * count; 2210 const int max_history_id = (int)buffer.next_history_id() - 1; 2211 if (buffer.move_to((Buffer::HistoryId)history_id)) 2212 { 2213 auto ranges = compute_modified_ranges(buffer, timestamp); 2214 if (not ranges.empty()) 2215 context.selections_write_only() = std::move(ranges); 2216 2217 context.print_status({ format("moved to change #{} ({})", 2218 history_id, max_history_id), 2219 context.faces()["Information"] }); 2220 } 2221 else 2222 throw runtime_error(format("no such change: #{} ({})", 2223 history_id, max_history_id)); 2224 } 2225 2226 template<Direction direction> 2227 void undo_selection_change(Context& context, NormalParams params) 2228 { 2229 int count = std::max(1, params.count); 2230 while (count--) 2231 context.undo_selection_change<direction>(); 2232 } 2233 2234 void exec_user_mappings(Context& context, NormalParams params) 2235 { 2236 on_next_key_with_autoinfo(context, "user-mapping", KeymapMode::None, 2237 [params](Key key, Context& context) mutable { 2238 auto* mapping = context.keymaps().get_mapping(key, KeymapMode::User); 2239 if (not mapping) 2240 return; 2241 2242 ScopedSetBool disable_keymaps(context.keymaps_disabled()); 2243 2244 InputHandler::ScopedForceNormal force_normal{context.input_handler(), params}; 2245 2246 ScopedEdition edition(context); 2247 ScopedSelectionEdition selection_edition{context}; 2248 for (auto& key : auto(mapping->keys)) // copy to allow reentrant unmap 2249 context.input_handler().handle_key(key); 2250 }, "user mapping", 2251 build_autoinfo_for_mapping(context, KeymapMode::User, {})); 2252 } 2253 2254 template<bool above> 2255 void add_empty_line(Context& context, NormalParams params) 2256 { 2257 int count = std::max(params.count, 1); 2258 String new_lines{'\n', CharCount{count}}; 2259 auto& buffer = context.buffer(); 2260 ScopedSelectionEdition selection_edition{context}; 2261 auto& sels = context.selections(); 2262 ScopedEdition edition{context}; 2263 for (int i = 0; i < sels.size(); ++i) 2264 { 2265 auto line = (above ? sels[i].min().line : sels[i].max().line + 1) + (i * count); 2266 buffer.insert(line, new_lines); 2267 } 2268 } 2269 2270 template<typename T> 2271 class Repeated 2272 { 2273 public: 2274 constexpr Repeated(T t) : m_func(t) {} 2275 2276 void operator() (Context& context, NormalParams params) 2277 { 2278 ScopedEdition edition(context); 2279 ScopedSelectionEdition selection_edition{context}; 2280 do { m_func(context, {0, params.reg}); } while(--params.count > 0); 2281 } 2282 private: 2283 T m_func; 2284 }; 2285 2286 template<void (*func)(Context&, NormalParams)> 2287 void repeated(Context& context, NormalParams params) 2288 { 2289 ScopedEdition edition(context); 2290 ScopedSelectionEdition selection_edition{context}; 2291 do { func(context, {0, params.reg}); } while(--params.count > 0); 2292 } 2293 2294 template<typename Type> 2295 void move_cursor(Context& context, NormalParams params, Direction direction, SelectMode mode) 2296 { 2297 kak_assert(mode == SelectMode::Replace or mode == SelectMode::Extend); 2298 const Type offset{direction * std::max(params.count,1)}; 2299 const ColumnCount tabstop = context.options()["tabstop"].get<int>(); 2300 ScopedSelectionEdition selection_edition{context}; 2301 auto& selections = context.selections(); 2302 for (auto& sel : selections) 2303 { 2304 auto cursor = context.buffer().offset_coord(sel.cursor(), offset, tabstop); 2305 sel.anchor() = mode == SelectMode::Extend ? sel.anchor() : cursor; 2306 sel.cursor() = cursor; 2307 } 2308 selections.sort_and_merge_overlapping(); 2309 } 2310 2311 template<typename Type, Direction direction, SelectMode mode = SelectMode::Replace> 2312 void move_cursor(Context& context, NormalParams params) 2313 { 2314 move_cursor<Type>(context, params, direction, mode); 2315 } 2316 2317 void select_whole_buffer(Context& context, NormalParams) 2318 { 2319 auto& buffer = context.buffer(); 2320 ScopedSelectionEdition selection_edition{context}; 2321 context.selections_write_only() = SelectionList{buffer, {{0,0}, {buffer.back_coord(), max_column}}}; 2322 } 2323 2324 void keep_selection(Context& context, NormalParams p) 2325 { 2326 ScopedSelectionEdition selection_edition{context}; 2327 auto& selections = context.selections(); 2328 const int index = p.count ? p.count-1 : selections.main_index(); 2329 if (index >= selections.size()) 2330 throw runtime_error{format("invalid selection index: {}", index)}; 2331 2332 selections = SelectionList{ selections.buffer(), std::move(selections[index]) }; 2333 selections.check_invariant(); 2334 } 2335 2336 void remove_selection(Context& context, NormalParams p) 2337 { 2338 ScopedSelectionEdition selection_edition{context}; 2339 auto& selections = context.selections(); 2340 const int index = p.count ? p.count-1 : selections.main_index(); 2341 if (index >= selections.size()) 2342 throw runtime_error{format("invalid selection index: {}", index)}; 2343 if (selections.size() == 1) 2344 throw no_selections_remaining{}; 2345 2346 selections.remove(index); 2347 selections.check_invariant(); 2348 } 2349 2350 void clear_selections(Context& context, NormalParams) 2351 { 2352 ScopedSelectionEdition selection_edition{context}; 2353 for (auto& sel : context.selections()) 2354 sel.anchor() = sel.cursor(); 2355 } 2356 2357 void flip_selections(Context& context, NormalParams) 2358 { 2359 ScopedSelectionEdition selection_edition{context}; 2360 for (auto& sel : context.selections()) 2361 { 2362 const BufferCoord tmp = sel.anchor(); 2363 sel.anchor() = sel.cursor(); 2364 sel.cursor() = tmp; 2365 } 2366 context.selections().check_invariant(); 2367 } 2368 2369 void ensure_forward(Context& context, NormalParams) 2370 { 2371 ScopedSelectionEdition selection_edition{context}; 2372 for (auto& sel : context.selections()) 2373 { 2374 const BufferCoord min = sel.min(), max = sel.max(); 2375 sel.anchor() = min; 2376 sel.cursor() = max; 2377 } 2378 context.selections().check_invariant(); 2379 } 2380 2381 void merge_consecutive(Context& context, NormalParams params) 2382 { 2383 ScopedSelectionEdition selection_edition{context}; 2384 ensure_forward(context, params); 2385 context.selections().merge_consecutive(); 2386 } 2387 2388 void merge_overlapping(Context& context, NormalParams params) 2389 { 2390 ScopedSelectionEdition selection_edition{context}; 2391 ensure_forward(context, params); 2392 context.selections().merge_overlapping(); 2393 } 2394 2395 void duplicate_selections(Context& context, NormalParams params) 2396 { 2397 ScopedSelectionEdition selection_edition{context}; 2398 SelectionList& sels = context.selections(); 2399 Vector<Selection> new_sels; 2400 const int count = params.count ? params.count : 2; 2401 BasicSelection last{BufferCoord{-1,-1}}; 2402 size_t index = 0; 2403 size_t main_index = 0; 2404 for (const auto& sel : sels) 2405 { 2406 new_sels.insert(new_sels.end(), sel != last ? count : 1, sel); 2407 last = sel; 2408 if (index++ == sels.main_index()) 2409 main_index = new_sels.size() - 1; 2410 } 2411 context.selections().set(std::move(new_sels), main_index); 2412 } 2413 2414 void force_redraw(Context& context, NormalParams) 2415 { 2416 if (context.has_client()) 2417 { 2418 context.client().force_redraw(true); 2419 context.client().redraw_ifn(); 2420 } 2421 } 2422 2423 constexpr size_t keymap_max_size = 512; 2424 2425 template<typename T, MemoryDomain domain> 2426 struct KeymapBackend : private Array<T, keymap_max_size> 2427 { 2428 using iterator = const T*; 2429 using const_iterator = const T*; 2430 2431 constexpr KeymapBackend() = default; 2432 constexpr KeymapBackend(std::initializer_list<T> items) 2433 { 2434 resize(items.size()); 2435 for (size_t i = 0; i < items.size(); ++i) 2436 this->m_data[i] = *(items.begin() + i); 2437 } 2438 2439 constexpr void resize(size_t s) 2440 { 2441 if (s > keymap_max_size) 2442 throw runtime_error{"cannot resize"}; 2443 m_size = s; 2444 } 2445 constexpr size_t size() const { return m_size; } 2446 2447 using KeymapBackend::Array::begin; 2448 using KeymapBackend::Array::end; 2449 using KeymapBackend::Array::operator[]; 2450 2451 private: 2452 size_t m_size = 0; 2453 }; 2454 2455 static constexpr HashMap<Key, NormalCmd, MemoryDomain::Undefined, KeymapBackend> keymap = { 2456 { {'h'}, {"move left", move_cursor<CharCount, Backward>} }, 2457 { {'j'}, {"move down", move_cursor<LineCount, Forward>} }, 2458 { {'k'}, {"move up", move_cursor<LineCount, Backward>} }, 2459 { {'l'}, {"move right", move_cursor<CharCount, Forward>} }, 2460 2461 { {'H'}, {"extend left", move_cursor<CharCount, Backward, SelectMode::Extend>} }, 2462 { {'J'}, {"extend down", move_cursor<LineCount, Forward, SelectMode::Extend>} }, 2463 { {'K'}, {"extend up", move_cursor<LineCount, Backward, SelectMode::Extend>} }, 2464 { {'L'}, {"extend right", move_cursor<CharCount, Forward, SelectMode::Extend>} }, 2465 2466 { {'t'}, {"select to next character", select_to_next_char<SelectFlags::None>} }, 2467 { {'f'}, {"select to next character included", select_to_next_char<SelectFlags::Inclusive>} }, 2468 { {'T'}, {"extend to next character", select_to_next_char<SelectFlags::Extend>} }, 2469 { {'F'}, {"extend to next character included", select_to_next_char<SelectFlags::Inclusive | SelectFlags::Extend>} }, 2470 { {alt('t')}, {"select to previous character", select_to_next_char<SelectFlags::Reverse>} }, 2471 { {alt('f')}, {"select to previous character included", select_to_next_char<SelectFlags::Inclusive | SelectFlags::Reverse>} }, 2472 { {alt('T')}, {"extend to previous character", select_to_next_char<SelectFlags::Extend | SelectFlags::Reverse>} }, 2473 { {alt('F')}, {"extend to previous character included", select_to_next_char<SelectFlags::Inclusive | SelectFlags::Extend | SelectFlags::Reverse>} }, 2474 2475 { {'d'}, {"erase selected text", erase_selections<true>} }, 2476 { {alt('d')}, {"erase selected text, without yanking", erase_selections<false>} }, 2477 { {'c'}, {"change selected text", change<true>} }, 2478 { {alt('c')}, {"change selected text, without yanking", change<false>} }, 2479 { {'i'}, {"insert before selected text", enter_insert_mode<InsertMode::Insert>} }, 2480 { {'I'}, {"insert at line begin", enter_insert_mode<InsertMode::InsertAtLineBegin>} }, 2481 { {'a'}, {"insert after selected text", enter_insert_mode<InsertMode::Append>} }, 2482 { {'A'}, {"insert at line end", enter_insert_mode<InsertMode::AppendAtLineEnd>} }, 2483 { {'o'}, {"insert on new line below", enter_insert_mode<InsertMode::OpenLineBelow>} }, 2484 { {'O'}, {"insert on new line above", enter_insert_mode<InsertMode::OpenLineAbove>} }, 2485 { {'r'}, {"replace with character", replace_with_char} }, 2486 2487 { {alt('o')}, {"add a new empty line below", add_empty_line<false>} }, 2488 { {alt('O')}, {"add a new empty line above", add_empty_line<true>} }, 2489 2490 { {'g'}, {"go to location", goto_commands<SelectMode::Replace>} }, 2491 { {'G'}, {"extend to location", goto_commands<SelectMode::Extend>} }, 2492 2493 { {'v'}, {"move view", view_commands<false>} }, 2494 { {'V'}, {"move view (locked)", view_commands<true>} }, 2495 2496 { {'y'}, {"yank selected text", yank} }, 2497 { {'p'}, {"paste after selected text", repeated<paste<PasteMode::Append>>} }, 2498 { {'P'}, {"paste before selected text", repeated<paste<PasteMode::Insert>>} }, 2499 { {alt('p')}, {"paste every yanked selection after selected text", paste_all<PasteMode::Append>} }, 2500 { {alt('P')}, {"paste every yanked selection before selected text", paste_all<PasteMode::Insert>} }, 2501 { {'R'}, {"replace selected text with yanked text", paste<PasteMode::Replace>} }, 2502 { {alt('R')}, {"replace selected text with every yanked text", paste_all<PasteMode::Replace>} }, 2503 2504 { {'s'}, {"select regex matches in selected text", select_regex} }, 2505 { {'S'}, {"split selected text on regex matches", split_regex} }, 2506 { {alt('s')}, {"split selected text on line ends", split_lines} }, 2507 { {alt('S')}, {"select selection boundaries", select_boundaries} }, 2508 2509 { {'.'}, {"repeat last insert command", repeat_last_insert} }, 2510 { {alt('.')}, {"repeat last object select/character find", repeat_last_select} }, 2511 2512 { {'%'}, {"select whole buffer", select_whole_buffer} }, 2513 2514 { {':'}, {"enter command prompt", command} }, 2515 { {'|'}, {"pipe each selection through filter and replace with output", pipe<true>} }, 2516 { {alt('|')}, {"pipe each selection through command and ignore output", pipe<false>} }, 2517 { {'!'}, {"insert command output", insert_output<PasteMode::Insert>} }, 2518 { {alt('!')}, {"append command output", insert_output<PasteMode::Append>} }, 2519 2520 { {','}, {"remove all selections except main", keep_selection} }, 2521 { {alt(',')}, {"remove main selection", remove_selection} }, 2522 { {';'}, {"reduce selections to their cursor", clear_selections} }, 2523 { {alt(';')}, {"swap selections cursor and anchor", flip_selections} }, 2524 { {alt(':')}, {"ensure selection cursor is after anchor", ensure_forward} }, 2525 { {alt('_')}, {"merge consecutive selections", merge_consecutive} }, 2526 { {'+'}, {"duplicate each selection", duplicate_selections} }, 2527 { {alt('+')}, {"merge overlapping selections", merge_overlapping} }, 2528 2529 { {'w'}, {"select to next word start", repeated<&select<SelectMode::Replace, select_to_next_word<Word>>>} }, 2530 { {'e'}, {"select to next word end", repeated<select<SelectMode::Replace, select_to_next_word_end<Word>>>} }, 2531 { {'b'}, {"select to previous word start", repeated<select<SelectMode::Replace, select_to_previous_word<Word>>>} }, 2532 { {'W'}, {"extend to next word start", repeated<select<SelectMode::Extend, select_to_next_word<Word>>>} }, 2533 { {'E'}, {"extend to next word end", repeated<select<SelectMode::Extend, select_to_next_word_end<Word>>>} }, 2534 { {'B'}, {"extend to previous word start", repeated<select<SelectMode::Extend, select_to_previous_word<Word>>>} }, 2535 2536 { {alt('w')}, {"select to next WORD start", repeated<select<SelectMode::Replace, select_to_next_word<WORD>>>} }, 2537 { {alt('e')}, {"select to next WORD end", repeated<select<SelectMode::Replace, select_to_next_word_end<WORD>>>} }, 2538 { {alt('b')}, {"select to previous WORD start", repeated<select<SelectMode::Replace, select_to_previous_word<WORD>>>} }, 2539 { {alt('W')}, {"extend to next WORD start", repeated<select<SelectMode::Extend, select_to_next_word<WORD>>>} }, 2540 { {alt('E')}, {"extend to next WORD end", repeated<select<SelectMode::Extend, select_to_next_word_end<WORD>>>} }, 2541 { {alt('B')}, {"extend to previous WORD start", repeated<select<SelectMode::Extend, select_to_previous_word<WORD>>>} }, 2542 2543 { {alt('l')}, {"select to line end", repeated<select<SelectMode::Replace, select_to_line_end<false>>>} }, 2544 { {alt('L')}, {"extend to line end", repeated<select<SelectMode::Extend, select_to_line_end<false>>>} }, 2545 { {alt('h')}, {"select to line begin", repeated<select<SelectMode::Replace, select_to_line_begin<false>>>} }, 2546 { {alt('H')}, {"extend to line begin", repeated<select<SelectMode::Extend, select_to_line_begin<false>>>} }, 2547 2548 { {'x'}, {"extend selections to whole lines", select<SelectMode::Replace, select_lines>} }, 2549 { {alt('x')}, {"crop selections to whole lines", select<SelectMode::Replace, trim_partial_lines>} }, 2550 2551 { {'m'}, {"select to matching character", select<SelectMode::Replace, select_matching<true>>} }, 2552 { {alt('m')}, {"backward select to matching character", select<SelectMode::Replace, select_matching<false>>} }, 2553 { {'M'}, {"extend to matching character", select<SelectMode::Extend, select_matching<true>>} }, 2554 { {alt('M')}, {"backward extend to matching character", select<SelectMode::Extend, select_matching<false>>} }, 2555 2556 { {'/'}, {"select next given regex match", [](Context& c, NormalParams p) { return search(c, p, SelectMode::Replace, RegexMode::Forward); } } }, 2557 { {'?'}, {"extend with next given regex match", [](Context& c, NormalParams p) { return search(c, p, SelectMode::Extend, RegexMode::Forward); } } }, 2558 { {alt('/')}, {"select previous given regex match", [](Context& c, NormalParams p) { return search(c, p, SelectMode::Replace, RegexMode::Backward); } } }, 2559 { {alt('?')}, {"extend with previous given regex match", [](Context& c, NormalParams p) { return search(c, p, SelectMode::Extend, RegexMode::Backward); } } }, 2560 { {'n'}, {"select next current search pattern match", [](Context& c, NormalParams p) { return search_next(c, p, SelectMode::Replace, RegexMode::Forward); } } }, 2561 { {'N'}, {"extend with next current search pattern match", [](Context& c, NormalParams p) { return search_next(c, p, SelectMode::Append, RegexMode::Forward); } } }, 2562 { {alt('n')}, {"select previous current search pattern match", [](Context& c, NormalParams p) { return search_next(c, p, SelectMode::Replace, RegexMode::Backward); } } }, 2563 { {alt('N')}, {"extend with previous current search pattern match", [](Context& c, NormalParams p) { return search_next(c, p, SelectMode::Append, RegexMode::Backward); } } }, 2564 { {'*'}, {"set search pattern to main selection content", use_selection_as_search_pattern<true>} }, 2565 { {alt('*')}, {"set search pattern to main selection content, do not detect words", use_selection_as_search_pattern<false>} }, 2566 2567 { {'u'}, {"undo", undo} }, 2568 { {'U'}, {"redo", redo} }, 2569 { {ctrl('k')}, {"move backward in history", move_in_history<Direction::Backward>} }, 2570 { {ctrl('j')}, {"move forward in history", move_in_history<Direction::Forward>} }, 2571 2572 { {alt('u')}, {"undo selection change", undo_selection_change<Backward>} }, 2573 { {alt('U')}, {"redo selection change", undo_selection_change<Forward>} }, 2574 2575 { {alt('i')}, {"select inner object", select_object<ObjectFlags::ToBegin | ObjectFlags::ToEnd | ObjectFlags::Inner>} }, 2576 { {alt('a')}, {"select whole object", select_object<ObjectFlags::ToBegin | ObjectFlags::ToEnd>} }, 2577 { {'['}, {"select to object start", select_object<ObjectFlags::ToBegin>} }, 2578 { {']'}, {"select to object end", select_object<ObjectFlags::ToEnd>} }, 2579 { {'{'}, {"extend to object start", select_object<ObjectFlags::ToBegin, SelectMode::Extend>} }, 2580 { {'}'}, {"extend to object end", select_object<ObjectFlags::ToEnd, SelectMode::Extend>} }, 2581 { {alt('[')}, {"select to inner object start", select_object<ObjectFlags::ToBegin | ObjectFlags::Inner>} }, 2582 { {alt(']')}, {"select to inner object end", select_object<ObjectFlags::ToEnd | ObjectFlags::Inner>} }, 2583 { {alt('{')}, {"extend to inner object start", select_object<ObjectFlags::ToBegin | ObjectFlags::Inner, SelectMode::Extend>} }, 2584 { {alt('}')}, {"extend to inner object end", select_object<ObjectFlags::ToEnd | ObjectFlags::Inner, SelectMode::Extend>} }, 2585 { {alt('I')}, {"select nested objects", select_object<ObjectFlags::Nested | ObjectFlags::Inner | ObjectFlags::ToBegin | ObjectFlags::ToEnd>} }, 2586 { {alt('A')}, {"select nested objects", select_object<ObjectFlags::Nested | ObjectFlags::ToBegin | ObjectFlags::ToEnd>} }, 2587 2588 { {alt('j')}, {"join lines", join_lines} }, 2589 { {alt('J')}, {"join lines and select spaces", join_lines_select_spaces} }, 2590 2591 { {alt('k')}, {"keep selections matching given regex", keep<true>} }, 2592 { {alt('K')}, {"keep selections not matching given regex", keep<false>} }, 2593 { {'$'}, {"pipe each selection through shell command and keep the ones whose command succeed", keep_pipe} }, 2594 2595 { {'<'}, {"deindent", deindent<true>} }, 2596 { {'>'}, {"indent", indent<false>} }, 2597 { {alt('>')}, {"indent, including empty lines", indent<true>} }, 2598 { {alt('<')}, {"deindent, not including incomplete indent", deindent<false>} }, 2599 2600 { {ctrl('i')}, {"jump forward in jump list",jump<Forward>} }, 2601 { {ctrl('o')}, {"jump backward in jump list", jump<Backward>} }, 2602 { {ctrl('s')}, {"push current selections in jump list", push_selections} }, 2603 2604 { {')'}, {"rotate main selection forward", rotate_selections<Forward>} }, 2605 { {'('}, {"rotate main selection backward", rotate_selections<Backward>} }, 2606 { {alt(')')}, {"rotate selections content forward", rotate_selections_content<Forward>} }, 2607 { {alt('(')}, {"rotate selections content backward", rotate_selections_content<Backward>} }, 2608 2609 { {'q'}, {"replay recorded macro", replay_macro} }, 2610 { {'Q'}, {"start or end macro recording", start_or_end_macro_recording} }, 2611 2612 { {'`'}, {"convert to lower case in selections", for_each_codepoint<to_lower>} }, 2613 { {'~'}, {"convert to upper case in selections", for_each_codepoint<to_upper>} }, 2614 { {alt('`')}, { "swap case in selections", for_each_codepoint<swap_case>} }, 2615 2616 { {'&'}, {"align selection cursors", align} }, 2617 { {alt('&')}, {"copy indentation", copy_indent} }, 2618 2619 { {'@'}, {"convert tabs to spaces in selections", tabs_to_spaces} }, 2620 { {alt('@')}, {"convert spaces to tabs in selections", spaces_to_tabs} }, 2621 2622 { {'_'}, {"trim selections", trim_selections} }, 2623 2624 { {'C'}, {"duplicate selections on the lines that follow them.", copy_selections_on_next_lines<Forward>} }, 2625 { {alt('C')}, {"duplicate selections on the lines that precede them.", copy_selections_on_next_lines<Backward>} }, 2626 2627 { {Key::Space}, {"user mappings", exec_user_mappings} }, 2628 2629 { {Key::PageUp}, { "scroll one page up", scroll<Backward>} }, 2630 { {Key::PageDown}, {"scroll one page down", scroll<Forward>} }, 2631 2632 { {ctrl('b')}, {"scroll one page up", scroll<Backward >} }, 2633 { {ctrl('f')}, {"scroll one page down", scroll<Forward>} }, 2634 { {ctrl('u')}, {"scroll half a page up", scroll<Backward, true>} }, 2635 { {ctrl('d')}, {"scroll half a page down", scroll<Forward, true>} }, 2636 2637 { {'z'}, {"restore selections from register", restore_selections<false>} }, 2638 { {alt('z')}, {"combine selections from register", restore_selections<true>} }, 2639 { {'Z'}, {"save selections to register", save_selections<false>} }, 2640 { {alt('Z')}, {"combine selections to register", save_selections<true>} }, 2641 2642 { {ctrl('l')}, {"force redraw", force_redraw} }, 2643 }; 2644 2645 Optional<NormalCmd> get_normal_command(Key key) 2646 { 2647 auto it = keymap.find(key); 2648 if (it != keymap.end()) 2649 return it->value; 2650 return {}; 2651 } 2652 2653 }