-
Notifications
You must be signed in to change notification settings - Fork 722
/
Copy pathnormal.cc
2396 lines (2130 loc) · 92 KB
/
normal.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "normal.hh"
#include "buffer.hh"
#include "buffer_manager.hh"
#include "buffer_utils.hh"
#include "changes.hh"
#include "client_manager.hh"
#include "command_manager.hh"
#include "commands.hh"
#include "context.hh"
#include "diff.hh"
#include "enum.hh"
#include "face_registry.hh"
#include "file.hh"
#include "flags.hh"
#include "option_manager.hh"
#include "option_types.hh"
#include "ranges.hh"
#include "regex.hh"
#include "register_manager.hh"
#include "selectors.hh"
#include "shell_manager.hh"
#include "string.hh"
#include "user_interface.hh"
#include "unit_tests.hh"
#include "window.hh"
#include "word_db.hh"
namespace Kakoune
{
enum class SelectMode
{
Replace,
Extend,
Append,
};
constexpr auto enum_desc(Meta::Type<SelectMode>)
{
return make_array<EnumDesc<SelectMode>>({
{ SelectMode::Replace, "replace" },
{ SelectMode::Extend, "extend" },
{ SelectMode::Append, "append" },
});
}
void merge_selections(Selection& sel, const Selection& new_sel)
{
const bool forward = sel.cursor() >= sel.anchor();
const bool new_forward = new_sel.cursor() > new_sel.anchor();
if (forward and new_forward)
sel.anchor() = std::min(sel.anchor(), new_sel.anchor());
const bool backward = sel.cursor() <= sel.anchor();
const bool new_backward = new_sel.cursor() < new_sel.anchor();
if (backward and new_backward)
sel.anchor() = std::max(sel.anchor(), new_sel.anchor());
sel.cursor() = new_sel.cursor();
}
UnitTest test_merge_selection{[] {
auto merge = [](Selection sel, const Selection& new_sel) {
merge_selections(sel, new_sel);
return sel;
};
kak_assert(merge({{0, 1}, {0, 2} }, {{0, 3}, {0, 4}}) == Selection{{0, 1}, {0, 4}});
kak_assert(merge({{0, 1}, {0, 2} }, {{0, 1}, {0, 2}}) == Selection{{0, 1}, {0, 2}});
kak_assert(merge({{0, 1}, {0, 2} }, {{0, 0}, {0, 0}}) == Selection{{0, 1}, {0, 0}});
kak_assert(merge({{0, 1}, {0, 2} }, {{0, 0}, {0, 3}}) == Selection{{0, 0}, {0, 3}});
kak_assert(merge({{0, 1}, {0, 3} }, {{0, 4}, {0, 2}}) == Selection{{0, 1}, {0, 2}});
kak_assert(merge({{0, 1}, {0, 2} }, {{0, 1}, {0, 1}}) == Selection{{0, 1}, {0, 1}});
}};
template<SelectMode mode, typename T>
void select(Context& context, T func)
{
auto& selections = context.selections();
if (mode == SelectMode::Append)
{
auto& sel = selections.main();
if (auto res = func(context, sel))
{
if (res->captures().empty())
res->captures() = sel.captures();
selections.push_back(std::move(*res));
selections.set_main_index(selections.size() - 1);
}
}
else
{
auto main_index = selections.main_index();
size_t new_size = 0;
for (size_t i = 0; i < selections.size(); ++i)
{
auto& sel = selections[i];
auto res = func(context, sel);
if (not res)
{
if (i <= main_index and main_index != 0)
--main_index;
continue;
}
if (mode == SelectMode::Extend)
merge_selections(sel, *res);
else
{
sel.anchor() = res->anchor();
sel.cursor() = res->cursor();
}
if (not res->captures().empty())
sel.captures() = std::move(res->captures());
if (i != new_size)
selections[new_size] = std::move(sel);
++new_size;
}
if (new_size == 0)
throw no_selections_remaining{};
selections.set_main_index(main_index);
selections.remove_from(new_size);
}
selections.sort_and_merge_overlapping();
selections.check_invariant();
}
template<SelectMode mode, Optional<Selection> (*func)(const Context&, const Selection&)>
void select(Context& context, NormalParams)
{
select<mode>(context, func);
}
template<SelectMode mode, typename Func>
void select_and_set_last(Context& context, Func&& func)
{
context.set_last_select(
[func](Context& context){ select<mode>(context, func); });
return select<mode>(context, func);
}
template<SelectMode mode = SelectMode::Replace>
void select_coord(Buffer& buffer, BufferCoord coord, SelectionList& selections)
{
coord = buffer.clamp(coord);
if (mode == SelectMode::Replace)
selections = SelectionList{ buffer, coord };
else if (mode == SelectMode::Extend)
{
for (auto& sel : selections)
sel.cursor() = coord;
selections.sort_and_merge_overlapping();
}
}
template<InsertMode mode>
void enter_insert_mode(Context& context, NormalParams params)
{
context.input_handler().insert(mode, params.count);
}
void repeat_last_insert(Context& context, NormalParams)
{
context.input_handler().repeat_last_insert();
}
void repeat_last_select(Context& context, NormalParams)
{
context.repeat_last_select();
}
String build_autoinfo_for_mapping(const Context& context, KeymapMode mode,
ConstArrayView<KeyInfo> built_ins)
{
auto& keymaps = context.keymaps();
Vector<std::pair<String, StringView>> descs;
for (auto& built_in : built_ins)
{
String keys = join(built_in.keys |
filter([&](Key k){ return not keymaps.is_mapped(k, mode); }) |
transform(key_to_str),
',', false);
if (not keys.empty())
descs.emplace_back(std::move(keys), built_in.docstring);
}
for (auto& key : keymaps.get_mapped_keys(mode))
descs.emplace_back(key_to_str(key),
keymaps.get_mapping(key, mode).docstring);
auto max_len = 0_col;
for (auto& desc : descs)
{
auto len = desc.first.column_length();
if (len > max_len)
max_len = len;
}
String res;
for (auto& desc : descs)
res += format("{}:{}{}\n",
desc.first,
String{' ', max_len - desc.first.column_length() + 1},
desc.second);
return res;
}
template<SelectMode mode>
void goto_commands(Context& context, NormalParams params)
{
if (params.count != 0)
{
context.push_jump();
select_coord<mode>(context.buffer(), LineCount{params.count - 1}, context.selections());
if (context.has_window())
context.window().center_line(LineCount{params.count-1});
}
else
{
on_next_key_with_autoinfo(context, "goto", KeymapMode::Goto,
[](Key key, Context& context) {
auto cp = key.codepoint();
if (not cp or key == Key::Escape)
return;
auto& buffer = context.buffer();
switch (to_lower(*cp))
{
case 'g':
case 'k':
context.push_jump();
select_coord<mode>(buffer, BufferCoord{0,0}, context.selections());
break;
case 'l':
select<mode, select_to_line_end<true>>(context, {});
break;
case 'h':
select<mode, select_to_line_begin<true>>(context, {});
break;
case 'i':
select<mode, select_to_first_non_blank>(context, {});
break;
case 'j':
context.push_jump();
select_coord<mode>(buffer, buffer.line_count() - 1, context.selections());
break;
case 'e':
context.push_jump();
select_coord<mode>(buffer, buffer.back_coord(), context.selections());
break;
case 't':
if (context.has_window())
{
auto line = context.window().position().line;
select_coord<mode>(buffer, line, context.selections());
}
break;
case 'b':
if (context.has_window())
{
auto& window = context.window();
auto line = window.position().line + window.dimensions().line - 1;
select_coord<mode>(buffer, line, context.selections());
}
break;
case 'c':
if (context.has_window())
{
auto& window = context.window();
auto line = window.position().line + window.dimensions().line / 2;
select_coord<mode>(buffer, line, context.selections());
}
break;
case 'a':
{
Buffer* target = context.last_buffer();
if (not target)
{
throw runtime_error("no last buffer");
}
context.push_jump();
context.change_buffer(*target);
break;
}
case 'f':
{
static constexpr char forbidden[] = { '\'', '\\', '\0' };
const auto& paths_opt = context.options()["path"].get<Vector<String, MemoryDomain::Options>>();
const auto paths = context.selections() | transform([&](const auto& sel) {
auto filename = content(buffer, sel);
if (any_of(filename, [](char c){ return contains(forbidden, c); }))
throw runtime_error(format("filename contains invalid characters: '{}'", filename));
const StringView buffer_dir = split_path(buffer.name()).first;
String path = find_file(filename, buffer_dir, paths_opt);
if (path.empty())
throw runtime_error(format("unable to find file '{}'", filename));
return path;
});
Buffer* buffer_main = nullptr;
for (auto&& [i, path] : paths | enumerate()) {
Buffer* buffer = BufferManager::instance().get_buffer_ifp(path);
if (not buffer)
{
buffer = open_file_buffer(path, context.hooks_disabled() ?
Buffer::Flags::NoHooks
: Buffer::Flags::None);
buffer->flags() &= ~Buffer::Flags::NoHooks;
}
if (i == context.selections().main_index())
buffer_main = buffer;
}
if (buffer_main and buffer_main != &context.buffer())
{
context.push_jump();
context.change_buffer(*buffer_main);
}
break;
}
case '.':
{
context.push_jump();
auto pos = buffer.last_modification_coord();
if (not pos)
throw runtime_error("no last modification position");
if (*pos >= buffer.back_coord())
pos = buffer.back_coord();
select_coord<mode>(buffer, *pos, context.selections());
break;
}
default:
throw runtime_error("key not mapped");
}
}, (mode == SelectMode::Extend ? "goto (extend to)" : "goto"),
build_autoinfo_for_mapping(context, KeymapMode::Goto,
{{{'g','k'},"buffer top"},
{{'l'}, "line end"},
{{'h'}, "line begin"},
{{'i'}, "line non blank start"},
{{'j'}, "buffer bottom"},
{{'e'}, "buffer end"},
{{'t'}, "window top"},
{{'b'}, "window bottom"},
{{'c'}, "window center"},
{{'a'}, "last buffer"},
{{'f'}, "file"},
{{'.'}, "last buffer change"}}));
}
}
template<bool lock>
void view_commands(Context& context, NormalParams params)
{
const int count = params.count;
on_next_key_with_autoinfo(context, "view", KeymapMode::View,
[count](Key key, Context& context) {
if (key == Key::Escape)
return;
if (lock)
view_commands<true>(context, { count, 0 });
auto cp = key.codepoint();
if (not cp or not context.has_window())
return;
const BufferCoord cursor = context.selections().main().cursor();
Window& window = context.window();
switch (*cp)
{
case 'v':
case 'c':
window.center_line(cursor.line);
break;
case 'm':
window.center_column(
context.buffer()[cursor.line].column_count_to(cursor.column));
break;
case 't':
window.display_line_at(cursor.line, 0);
break;
case 'b':
window.display_line_at(cursor.line, window.dimensions().line-1);
break;
case 'h':
window.scroll(-std::max<ColumnCount>(1, count));
break;
case 'j':
scroll_window(context, std::max<LineCount>(1, count));
break;
case 'k':
scroll_window(context, -std::max<LineCount>(1, count));
break;
case 'l':
window.scroll( std::max<ColumnCount>(1, count));
break;
default:
throw runtime_error("key not mapped");
}
}, lock ? "view (lock)" : "view",
build_autoinfo_for_mapping(context, KeymapMode::View,
{{{'v','c'}, "center cursor (vertically)"},
{{'m'}, "center cursor (horizontally)"},
{{'t'}, "cursor on top"},
{{'b'}, "cursor on bottom"},
{{'h'}, "scroll left"},
{{'j'}, "scroll down"},
{{'k'}, "scroll up"},
{{'l'}, "scroll right"}}));
}
void replace_with_char(Context& context, NormalParams)
{
on_next_key_with_autoinfo(context, "replace-char", KeymapMode::None,
[](Key key, Context& context) {
auto cp = key.codepoint();
if (not cp or key == Key::Escape)
return;
ScopedEdition edition(context);
Buffer& buffer = context.buffer();
context.selections().for_each([&](size_t index, Selection& sel) {
CharCount count = char_length(buffer, sel);
replace(buffer, sel, String{*cp, count});
});
}, "replace with char", "enter char to replace with\n");
}
Codepoint swap_case(Codepoint cp)
{
Codepoint res = to_lower(cp);
return res == cp ? to_upper(cp) : res;
}
template<Codepoint (*func)(Codepoint)>
void for_each_codepoint(Context& context, NormalParams)
{
using Utf8It = utf8::iterator<BufferIterator>;
ScopedEdition edition(context);
Buffer& buffer = context.buffer();
context.selections().for_each([&](size_t index, Selection& sel) {
String str;
for (auto begin = Utf8It{buffer.iterator_at(sel.min()), buffer},
end = Utf8It{buffer.iterator_at(sel.max()), buffer}+1;
begin != end; ++begin)
utf8::dump(std::back_inserter(str), func(*begin));
replace(buffer, sel, str);
});
}
void command(const Context& context, EnvVarMap env_vars, char reg = 0)
{
if (not CommandManager::has_instance())
throw runtime_error{"commands are not supported"};
CommandManager::instance().clear_last_complete_command();
String default_command = context.main_sel_register_value(reg ? reg : ':').str();
context.input_handler().prompt(
":", {}, default_command,
context.faces()["Prompt"], PromptFlags::DropHistoryEntriesWithBlankPrefix,
':',
[](const Context& context, CompletionFlags flags,
StringView cmd_line, ByteCount pos) {
return CommandManager::instance().complete(context, flags, cmd_line, pos);
},
[env_vars = std::move(env_vars), default_command](StringView cmdline, PromptEvent event, Context& context) {
if (context.has_client())
{
context.client().info_hide();
if (event == PromptEvent::Change)
{
auto info = CommandManager::instance().command_info(context, cmdline);
context.input_handler().set_prompt_face(context.faces()[info ? "Prompt" : "Error"]);
auto autoinfo = context.options()["autoinfo"].get<AutoInfo>();
if (autoinfo & AutoInfo::Command)
{
if (cmdline.length() == 1 and is_horizontal_blank(cmdline[0_byte]))
context.client().info_show("prompt",
"commands preceded by a blank wont be saved to history",
{}, InfoStyle::Prompt);
else if (info and not info->info.empty())
context.client().info_show(info->name, info->info, {}, InfoStyle::Prompt);
}
}
}
if (event == PromptEvent::Validate)
{
if (cmdline.empty())
cmdline = default_command;
CommandManager::instance().execute(cmdline, context, { {}, env_vars });
}
});
}
void command(Context& context, NormalParams params)
{
EnvVarMap env_vars = {
{ "count", to_string(params.count) },
{ "register", String{¶ms.reg, 1} }
};
command(context, std::move(env_vars), params.reg);
}
BufferCoord apply_diff(Buffer& buffer, BufferCoord pos, StringView before, StringView after)
{
const auto lines_before = before | split_after<StringView>('\n') | gather<Vector<StringView>>();
const auto lines_after = after | split_after<StringView>('\n') | gather<Vector<StringView>>();
auto byte_count = [](auto&& lines, int first, int count) {
return std::accumulate(lines.begin() + first, lines.begin() + first + count, 0_byte,
[](ByteCount l, StringView s) { return l + s.length(); });
};
for_each_diff(lines_before.begin(), (int)lines_before.size(),
lines_after.begin(), (int)lines_after.size(),
[&, posA = 0, posB = 0](DiffOp op, int len) mutable {
switch (op)
{
case DiffOp::Keep:
pos = buffer.advance(pos, byte_count(lines_before, posA, len));
posA += len;
posB += len;
break;
case DiffOp::Add:
pos = buffer.insert(pos, {lines_after[posB].begin(),
lines_after[posB + len - 1].end()}).end;
posB += len;
break;
case DiffOp::Remove:
pos = buffer.erase(pos, buffer.advance(pos, byte_count(lines_before, posA, len)));
posA += len;
break;
}
});
return pos;
}
template<bool replace>
void pipe(Context& context, NormalParams params)
{
const char* prompt = replace ? "pipe:" : "pipe-to:";
String default_command = context.main_sel_register_value(params.reg ? params.reg : '|').str();
context.input_handler().prompt(
prompt, {}, default_command, context.faces()["Prompt"],
PromptFlags::DropHistoryEntriesWithBlankPrefix, '|',
shell_complete,
[default_command](StringView cmdline, PromptEvent event, Context& context)
{
if (event != PromptEvent::Validate)
return;
if (cmdline.empty())
cmdline = default_command;
if (cmdline.empty())
return;
Buffer& buffer = context.buffer();
SelectionList selections = context.selections();
if (replace)
{
ScopedEdition edition(context);
ForwardChangesTracker changes_tracker;
size_t timestamp = buffer.timestamp();
Vector<Selection> new_sels;
for (auto& sel : selections)
{
const auto beg = changes_tracker.get_new_coord_tolerant(sel.min());
const auto end = changes_tracker.get_new_coord_tolerant(sel.max());
String in = buffer.string(beg, buffer.char_next(end));
// Needed in case we read selections inside the cmdline
context.selections_write_only().set({keep_direction(Selection{beg, end}, sel)}, 0);
String out = ShellManager::instance().eval(
cmdline, context, in,
ShellManager::Flags::WaitForStdout).first;
if (in.back() != '\n' and not out.empty() and out.back() == '\n')
out.resize(out.length()-1, 0);
auto new_end = apply_diff(buffer, beg, in, out);
if (new_end != beg)
new_sels.push_back(keep_direction({beg, buffer.char_prev(new_end), std::move(sel.captures())}, sel));
else
{
if (new_end != BufferCoord{})
new_end = buffer.char_prev(new_end);
new_sels.push_back({new_end, new_end, std::move(sel.captures())});
}
changes_tracker.update(buffer, timestamp);
}
context.selections_write_only().set(std::move(new_sels), selections.main_index());
}
else
{
const auto old_main = selections.main_index();
for (int i = 0; i < selections.size(); ++i)
{
selections.set_main_index(i);
ShellManager::instance().eval(cmdline, context,
content(buffer, selections.main()),
ShellManager::Flags::None);
}
selections.set_main_index(old_main);
}
});
}
void yank(Context& context, NormalParams params)
{
const char reg = params.reg ? params.reg : '"';
RegisterManager::instance()[reg].set(context, context.selections_content());
context.print_status({ format("yanked {} selections to register {}",
context.selections().size(), reg),
context.faces()["Information"] });
}
template<bool yank>
void erase_selections(Context& context, NormalParams params)
{
if (yank)
{
const char reg = params.reg ? params.reg : '"';
RegisterManager::instance()[reg].set(context, context.selections_content());
}
ScopedEdition edition(context);
context.selections().erase();
}
template<bool yank>
void change(Context& context, NormalParams params)
{
if (yank)
{
const char reg = params.reg ? params.reg : '"';
RegisterManager::instance()[reg].set(context, context.selections_content());
}
enter_insert_mode<InsertMode::Replace>(context, params);
}
enum class PasteMode
{
Append,
Insert,
Replace
};
BufferCoord paste_pos(Buffer& buffer, const Selection& sel, PasteMode mode, bool linewise)
{
switch (mode)
{
case PasteMode::Append:
return linewise ? std::min(buffer.line_count(), sel.max().line+1) : buffer.char_next(sel.max());
case PasteMode::Insert:
return linewise ? sel.min().line : sel.min();
default:
kak_assert(false);
return {};
}
}
template<PasteMode mode>
void paste(Context& context, NormalParams params)
{
const char reg = params.reg ? params.reg : '"';
auto strings = RegisterManager::instance()[reg].get(context);
const bool linewise = any_of(strings, [](StringView str) {
return not str.empty() and str.back() == '\n';
});
auto& buffer = context.buffer();
ScopedEdition edition(context);
context.selections().for_each([&](size_t index, Selection& sel) {
auto& str = strings[std::min(strings.size()-1, index)];
auto& min = sel.min();
auto& max = sel.max();
BufferRange range = (mode == PasteMode::Replace) ?
buffer.replace(min, buffer.char_next(max), str)
: buffer.insert(paste_pos(buffer, sel, mode, linewise), str);
min = range.begin;
max = range.end > range.begin ? buffer.char_prev(range.end) : range.begin;
});
}
template<PasteMode mode>
void paste_all(Context& context, NormalParams params)
{
const char reg = params.reg ? params.reg : '"';
auto strings = RegisterManager::instance()[reg].get(context);
bool linewise = false;
String all;
Vector<ByteCount> offsets;
for (auto& str : strings)
{
if (str.empty())
continue;
if (str.back() == '\n')
linewise = true;
all += str;
offsets.push_back(all.length());
}
if (offsets.empty())
throw runtime_error("nothing to paste");
Buffer& buffer = context.buffer();
Vector<Selection> result;
auto& selections = context.selections();
{
ScopedEdition edition(context);
selections.for_each([&](size_t, const Selection& sel) {
auto range = (mode == PasteMode::Replace) ?
buffer.replace(sel.min(), buffer.char_next(sel.max()), all)
: buffer.insert(paste_pos(buffer, sel, mode, linewise), all);
ByteCount pos_offset = 0;
BufferCoord pos = range.begin;
for (auto offset : offsets)
{
BufferCoord end = buffer.advance(pos, offset - pos_offset - 1);
result.emplace_back(pos, end);
pos = buffer.next(end);
pos_offset = offset;
}
});
}
selections = std::move(result);
}
template<PasteMode mode>
void insert_output(Context& context, NormalParams params)
{
const char* prompt = mode == PasteMode::Insert ? "insert-output:" : "append-output:";
String default_command = context.main_sel_register_value(params.reg ? params.reg : '|').str();
context.input_handler().prompt(
prompt, {}, default_command, context.faces()["Prompt"],
PromptFlags::DropHistoryEntriesWithBlankPrefix, '|',
shell_complete,
[default_command](StringView cmdline, PromptEvent event, Context& context)
{
if (event != PromptEvent::Validate)
return;
if (cmdline.empty())
cmdline = default_command;
if (cmdline.empty())
return;
ScopedEdition edition(context);
auto& selections = context.selections();
auto& buffer = context.buffer();
const size_t old_main = selections.main_index();
Vector<BufferRange> ins_range;
selections.for_each([&](size_t index, Selection& sel) {
selections.set_main_index(index);
auto [out, status] = ShellManager::instance().eval(
cmdline, context, content(context.buffer(), sel),
ShellManager::Flags::WaitForStdout);
auto range = insert(buffer, sel, paste_pos(buffer, sel, mode, false), out);
ins_range.push_back(range);
});
selections.set(ins_range | transform([&buffer](auto& range) {
if (range.empty())
return Selection{range.begin, range.end};
return Selection{range.begin,
buffer.char_prev(range.end)};
}) | gather<Vector>(), old_main);
});
}
constexpr RegexCompileFlags direction_flags(RegexMode mode)
{
return (mode & RegexMode::Forward) ?
RegexCompileFlags::None : RegexCompileFlags::Backward | RegexCompileFlags::NoForward;
}
template<RegexMode mode = RegexMode::Forward, typename T>
void regex_prompt(Context& context, String prompt, char reg, T func)
{
static_assert(is_direction(mode));
DisplayCoord position = context.has_window() ? context.window().position() : DisplayCoord{};
SelectionList selections = context.selections();
auto default_regex = RegisterManager::instance()[reg].get_main(context, context.selections().main_index());
context.input_handler().prompt(
std::move(prompt), {}, default_regex, context.faces()["Prompt"],
PromptFlags::Search, reg,
[](const Context& context, CompletionFlags, StringView regex, ByteCount pos) -> Completions {
auto current_word = [](StringView s) {
auto it = s.end();
while (it != s.begin() and is_word(*(it-1)))
--it;
StringView res{it, s.end()};
if (it == s.begin() or res.empty())
return res;
int backslashes = 0;
for (auto bs = it; bs != s.begin() && *(bs-1) == '\\'; --bs)
++backslashes;
return (backslashes % 2 == 1) ? res.substr(1_byte) : res;
};
const auto word = current_word(regex.substr(0_byte, pos));
auto matches = get_word_db(context.buffer()).find_matching(word);
constexpr size_t max_count = 100;
CandidateList candidates;
candidates.reserve(std::min(matches.size(), max_count));
for_n_best(matches, max_count, [](auto& lhs, auto& rhs) { return rhs < lhs; },
[&](auto&& m) { candidates.push_back(m.candidate().str()); return true; });
return {(int)(word.begin() - regex.begin()), pos, std::move(candidates) };
},
[=, func=T(std::move(func))](StringView str, PromptEvent event, Context& context) mutable {
try
{
if (event != PromptEvent::Change and context.has_client())
context.client().info_hide();
const bool incsearch = context.options()["incsearch"].get<bool>();
if (incsearch)
{
selections.update();
context.selections_write_only() = selections;
if (context.has_window())
context.window().set_position(position);
context.input_handler().set_prompt_face(context.faces()["Prompt"]);
}
if (not incsearch and event == PromptEvent::Change)
return;
if (event == PromptEvent::Validate)
context.push_jump();
if (not str.empty() or event == PromptEvent::Validate)
func(Regex{str.empty() ? default_regex : str, direction_flags(mode)}, event, context);
}
catch (regex_error& err)
{
if (event == PromptEvent::Validate)
throw;
else
context.input_handler().set_prompt_face(context.faces()["Error"]);
}
catch (runtime_error&)
{
context.selections_write_only() = selections;
// only validation should propagate errors,
// incremental search should not.
if (event == PromptEvent::Validate)
throw;
}
});
}
template<RegexMode mode>
void select_next_matches(Context& context, const Regex& regex, int count)
{
auto& selections = context.selections();
do {
bool wrapped = false;
for (auto& sel : selections)
sel = keep_direction(find_next_match<mode>(context, sel, regex, wrapped), sel);
selections.sort_and_merge_overlapping();
} while (--count > 0);
}
template<RegexMode mode>
void extend_to_next_matches(Context& context, const Regex& regex, int count)
{
Vector<Selection> new_sels;
auto& selections = context.selections();
do {
bool wrapped = false;
size_t main_index = selections.main_index();
for (auto& sel : selections)
{
auto new_sel = find_next_match<mode>(context, sel, regex, wrapped);
if (not wrapped)
{
new_sels.push_back(sel);
merge_selections(new_sels.back(), new_sel);
}
else if (new_sels.size() <= main_index)
--main_index;
}
if (new_sels.empty())
throw runtime_error{"All selections wrapped"};
selections.set(std::move(new_sels), main_index);
new_sels.clear();
} while (--count > 0);
}
template<SelectMode mode, RegexMode regex_mode>
void search(Context& context, NormalParams params)
{
static_assert(is_direction(regex_mode));
constexpr StringView prompt = mode == SelectMode::Extend ?
(regex_mode & RegexMode::Forward ? "search (extend):" : "reverse search (extend):")
: (regex_mode & RegexMode::Forward ? "search:" : "reverse search:");
const char reg = to_lower(params.reg ? params.reg : '/');
const int count = params.count;
regex_prompt<regex_mode>(context, prompt.str(), reg,
[reg, count, saved_reg = RegisterManager::instance()[reg].save(context)]
(const Regex& regex, PromptEvent event, Context& context) {
RegisterManager::instance()[reg].restore(context, saved_reg);
if (event == PromptEvent::Abort)
return;
RegisterManager::instance()[reg].set(context, regex.str());
if (regex.empty() or regex.str().empty())
return;
if (mode == SelectMode::Extend)
extend_to_next_matches<regex_mode>(context, regex, count);
else
select_next_matches<regex_mode>(context, regex, count);
});
}
template<SelectMode mode, RegexMode regex_mode>
void search_next(Context& context, NormalParams params)
{
const char reg = to_lower(params.reg ? params.reg : '/');
StringView str = RegisterManager::instance()[reg].get(context).front();
if (not str.empty())
{
Regex regex{str, direction_flags(regex_mode)};
auto& selections = context.selections();
bool main_wrapped = false;
do {
bool wrapped = false;
if (mode == SelectMode::Replace)
{
auto& sel = selections.main();
sel = keep_direction(find_next_match<regex_mode>(context, sel, regex, wrapped), sel);
}
else if (mode == SelectMode::Append)
{
auto sel = keep_direction(
find_next_match<regex_mode>(context, selections.main(), regex, wrapped),
selections.main());
selections.push_back(std::move(sel));
selections.set_main_index(selections.size() - 1);
}
selections.sort_and_merge_overlapping();
main_wrapped = main_wrapped or wrapped;
} while (--params.count > 0);
if (main_wrapped)
context.print_status({"main selection search wrapped around buffer", context.faces()["Information"]});
}
else
throw runtime_error("no search pattern");
}
template<bool smart>
void use_selection_as_search_pattern(Context& context, NormalParams params)
{
const auto& buffer = context.buffer();
auto patterns = context.selections() | transform([&](auto&& sel) {
const auto beg = sel.min(), end = buffer.char_next(sel.max());
return format("{}{}{}",
smart and is_bow(buffer, beg) ? "\\b" : "",
escape(buffer.string(beg, end), "^$\\.*+?()[]{}|", '\\'),
smart and is_eow(buffer, end) ? "\\b" : "");
}) | gather<HashSet>();
String pattern = join(patterns, '|', false);
const char reg = to_lower(params.reg ? params.reg : '/');
context.print_status({
format("register '{}' set to '{}'", reg, pattern),
context.faces()["Information"] });
RegisterManager::instance()[reg].set(context, {pattern});
// Hack, as Window do not take register state into account
if (context.has_window())
context.window().force_redraw();
}