-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
commands.rs
5597 lines (4855 loc) · 182 KB
/
commands.rs
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
pub(crate) mod dap;
pub(crate) mod lsp;
pub(crate) mod typed;
pub use dap::*;
use helix_vcs::Hunk;
pub use lsp::*;
use tui::widgets::Row;
pub use typed::*;
use helix_core::{
char_idx_at_visual_offset, comment,
doc_formatter::TextFormat,
encoding, find_first_non_whitespace_char, find_workspace, graphemes,
history::UndoKind,
increment, indent,
indent::IndentStyle,
line_ending::{get_line_ending_of_str, line_end_char_index, str_is_line_ending},
match_brackets,
movement::{self, move_vertically_visual, Direction},
object, pos_at_coords,
regex::{self, Regex, RegexBuilder},
search::{self, CharMatcher},
selection, shellwords, surround,
syntax::LanguageServerFeature,
text_annotations::TextAnnotations,
textobject,
tree_sitter::Node,
unicode::width::UnicodeWidthChar,
visual_offset_from_block, Deletion, LineEnding, Position, Range, Rope, RopeGraphemes,
RopeReader, RopeSlice, Selection, SmallVec, Tendril, Transaction,
};
use helix_view::{
document::{FormatterError, Mode, SCRATCH_BUFFER_NAME},
editor::Action,
info::Info,
input::KeyEvent,
keyboard::KeyCode,
tree,
view::View,
Document, DocumentId, Editor, ViewId,
};
use anyhow::{anyhow, bail, ensure, Context as _};
use insert::*;
use movement::Movement;
use crate::{
args,
compositor::{self, Component, Compositor},
filter_picker_entry,
job::Callback,
keymap::ReverseKeymap,
ui::{self, overlay::overlaid, Picker, Popup, Prompt, PromptEvent},
};
use crate::job::{self, Jobs};
use std::{
collections::{HashMap, HashSet},
fmt,
future::Future,
io::Read,
num::NonZeroUsize,
};
use std::{
borrow::Cow,
path::{Path, PathBuf},
};
use once_cell::sync::Lazy;
use serde::de::{self, Deserialize, Deserializer};
use url::Url;
use grep_regex::RegexMatcherBuilder;
use grep_searcher::{sinks, BinaryDetection, SearcherBuilder};
use ignore::{DirEntry, WalkBuilder, WalkState};
pub type OnKeyCallback = Box<dyn FnOnce(&mut Context, KeyEvent)>;
pub struct Context<'a> {
pub register: Option<char>,
pub count: Option<NonZeroUsize>,
pub editor: &'a mut Editor,
pub callback: Vec<crate::compositor::Callback>,
pub on_next_key_callback: Option<OnKeyCallback>,
pub jobs: &'a mut Jobs,
}
impl<'a> Context<'a> {
/// Push a new component onto the compositor.
pub fn push_layer(&mut self, component: Box<dyn Component>) {
self.callback
.push(Box::new(|compositor: &mut Compositor, _| {
compositor.push(component)
}));
}
/// Call `replace_or_push` on the Compositor
pub fn replace_or_push_layer<T: Component>(&mut self, id: &'static str, component: T) {
self.callback
.push(Box::new(move |compositor: &mut Compositor, _| {
compositor.replace_or_push(id, component);
}));
}
#[inline]
pub fn on_next_key(
&mut self,
on_next_key_callback: impl FnOnce(&mut Context, KeyEvent) + 'static,
) {
self.on_next_key_callback = Some(Box::new(on_next_key_callback));
}
#[inline]
pub fn callback<T, F>(
&mut self,
call: impl Future<Output = helix_lsp::Result<serde_json::Value>> + 'static + Send,
callback: F,
) where
T: for<'de> serde::Deserialize<'de> + Send + 'static,
F: FnOnce(&mut Editor, &mut Compositor, T) + Send + 'static,
{
self.jobs.callback(make_job_callback(call, callback));
}
/// Returns 1 if no explicit count was provided
#[inline]
pub fn count(&self) -> usize {
self.count.map_or(1, |v| v.get())
}
}
#[inline]
fn make_job_callback<T, F>(
call: impl Future<Output = helix_lsp::Result<serde_json::Value>> + 'static + Send,
callback: F,
) -> std::pin::Pin<Box<impl Future<Output = Result<Callback, anyhow::Error>>>>
where
T: for<'de> serde::Deserialize<'de> + Send + 'static,
F: FnOnce(&mut Editor, &mut Compositor, T) + Send + 'static,
{
Box::pin(async move {
let json = call.await?;
let response = serde_json::from_value(json)?;
let call: job::Callback = Callback::EditorCompositor(Box::new(
move |editor: &mut Editor, compositor: &mut Compositor| {
callback(editor, compositor, response)
},
));
Ok(call)
})
}
use helix_view::{align_view, Align};
/// A MappableCommand is either a static command like "jump_view_up" or a Typable command like
/// :format. It causes a side-effect on the state (usually by creating and applying a transaction).
/// Both of these types of commands can be mapped with keybindings in the config.toml.
#[derive(Clone)]
pub enum MappableCommand {
Typable {
name: String,
args: Vec<String>,
doc: String,
},
Static {
name: &'static str,
fun: fn(cx: &mut Context),
doc: &'static str,
},
}
macro_rules! static_commands {
( $($name:ident, $doc:literal,)* ) => {
$(
#[allow(non_upper_case_globals)]
pub const $name: Self = Self::Static {
name: stringify!($name),
fun: $name,
doc: $doc
};
)*
pub const STATIC_COMMAND_LIST: &'static [Self] = &[
$( Self::$name, )*
];
}
}
impl MappableCommand {
pub fn execute(&self, cx: &mut Context) {
match &self {
Self::Typable { name, args, doc: _ } => {
let args: Vec<Cow<str>> = args.iter().map(Cow::from).collect();
if let Some(command) = typed::TYPABLE_COMMAND_MAP.get(name.as_str()) {
let mut cx = compositor::Context {
editor: cx.editor,
jobs: cx.jobs,
scroll: None,
};
if let Err(e) = (command.fun)(&mut cx, &args[..], PromptEvent::Validate) {
cx.editor.set_error(format!("{}", e));
}
}
}
Self::Static { fun, .. } => (fun)(cx),
}
}
pub fn name(&self) -> &str {
match &self {
Self::Typable { name, .. } => name,
Self::Static { name, .. } => name,
}
}
pub fn doc(&self) -> &str {
match &self {
Self::Typable { doc, .. } => doc,
Self::Static { doc, .. } => doc,
}
}
#[rustfmt::skip]
static_commands!(
no_op, "Do nothing",
move_char_left, "Move left",
move_char_right, "Move right",
move_line_up, "Move up",
move_line_down, "Move down",
move_visual_line_up, "Move up",
move_visual_line_down, "Move down",
extend_char_left, "Extend left",
extend_char_right, "Extend right",
extend_line_up, "Extend up",
extend_line_down, "Extend down",
extend_visual_line_up, "Extend up",
extend_visual_line_down, "Extend down",
copy_selection_on_next_line, "Copy selection on next line",
copy_selection_on_prev_line, "Copy selection on previous line",
move_next_word_start, "Move to start of next word",
move_prev_word_start, "Move to start of previous word",
move_next_word_end, "Move to end of next word",
move_prev_word_end, "Move to end of previous word",
move_next_long_word_start, "Move to start of next long word",
move_prev_long_word_start, "Move to start of previous long word",
move_next_long_word_end, "Move to end of next long word",
move_prev_long_word_end, "Move to end of previous long word",
move_parent_node_end, "Move to end of the parent node",
move_parent_node_start, "Move to beginning of the parent node",
extend_next_word_start, "Extend to start of next word",
extend_prev_word_start, "Extend to start of previous word",
extend_next_word_end, "Extend to end of next word",
extend_prev_word_end, "Extend to end of previous word",
extend_next_long_word_start, "Extend to start of next long word",
extend_prev_long_word_start, "Extend to start of previous long word",
extend_next_long_word_end, "Extend to end of next long word",
extend_prev_long_word_end, "Extend to end of prev long word",
extend_parent_node_end, "Extend to end of the parent node",
extend_parent_node_start, "Extend to beginning of the parent node",
find_till_char, "Move till next occurrence of char",
find_next_char, "Move to next occurrence of char",
extend_till_char, "Extend till next occurrence of char",
extend_next_char, "Extend to next occurrence of char",
till_prev_char, "Move till previous occurrence of char",
find_prev_char, "Move to previous occurrence of char",
extend_till_prev_char, "Extend till previous occurrence of char",
extend_prev_char, "Extend to previous occurrence of char",
repeat_last_motion, "Repeat last motion",
replace, "Replace with new char",
switch_case, "Switch (toggle) case",
switch_to_uppercase, "Switch to uppercase",
switch_to_lowercase, "Switch to lowercase",
page_up, "Move page up",
page_down, "Move page down",
half_page_up, "Move half page up",
half_page_down, "Move half page down",
select_all, "Select whole document",
select_regex, "Select all regex matches inside selections",
split_selection, "Split selections on regex matches",
split_selection_on_newline, "Split selection on newlines",
merge_selections, "Merge selections",
merge_consecutive_selections, "Merge consecutive selections",
search, "Search for regex pattern",
rsearch, "Reverse search for regex pattern",
search_next, "Select next search match",
search_prev, "Select previous search match",
extend_search_next, "Add next search match to selection",
extend_search_prev, "Add previous search match to selection",
search_selection, "Use current selection as search pattern",
make_search_word_bounded, "Modify current search to make it word bounded",
global_search, "Global search in workspace folder",
extend_line, "Select current line, if already selected, extend to another line based on the anchor",
extend_line_below, "Select current line, if already selected, extend to next line",
extend_line_above, "Select current line, if already selected, extend to previous line",
extend_to_line_bounds, "Extend selection to line bounds",
shrink_to_line_bounds, "Shrink selection to line bounds",
delete_selection, "Delete selection",
delete_selection_noyank, "Delete selection without yanking",
change_selection, "Change selection",
change_selection_noyank, "Change selection without yanking",
collapse_selection, "Collapse selection into single cursor",
flip_selections, "Flip selection cursor and anchor",
ensure_selections_forward, "Ensure all selections face forward",
insert_mode, "Insert before selection",
append_mode, "Append after selection",
command_mode, "Enter command mode",
file_picker, "Open file picker",
file_picker_in_current_buffer_directory, "Open file picker at current buffers's directory",
file_picker_in_current_directory, "Open file picker at current working directory",
code_action, "Perform code action",
buffer_picker, "Open buffer picker",
jumplist_picker, "Open jumplist picker",
symbol_picker, "Open symbol picker",
select_references_to_symbol_under_cursor, "Select symbol references",
workspace_symbol_picker, "Open workspace symbol picker",
diagnostics_picker, "Open diagnostic picker",
workspace_diagnostics_picker, "Open workspace diagnostic picker",
last_picker, "Open last picker",
insert_at_line_start, "Insert at start of line",
insert_at_line_end, "Insert at end of line",
open_below, "Open new line below selection",
open_above, "Open new line above selection",
normal_mode, "Enter normal mode",
select_mode, "Enter selection extend mode",
exit_select_mode, "Exit selection mode",
goto_definition, "Goto definition",
goto_declaration, "Goto declaration",
add_newline_above, "Add newline above",
add_newline_below, "Add newline below",
goto_type_definition, "Goto type definition",
goto_implementation, "Goto implementation",
goto_file_start, "Goto line number <n> else file start",
goto_file_end, "Goto file end",
goto_file, "Goto files/URLs in selections",
goto_file_hsplit, "Goto files in selections (hsplit)",
goto_file_vsplit, "Goto files in selections (vsplit)",
goto_reference, "Goto references",
goto_window_top, "Goto window top",
goto_window_center, "Goto window center",
goto_window_bottom, "Goto window bottom",
goto_last_accessed_file, "Goto last accessed file",
goto_last_modified_file, "Goto last modified file",
goto_last_modification, "Goto last modification",
goto_line, "Goto line",
goto_last_line, "Goto last line",
goto_first_diag, "Goto first diagnostic",
goto_last_diag, "Goto last diagnostic",
goto_next_diag, "Goto next diagnostic",
goto_prev_diag, "Goto previous diagnostic",
goto_next_change, "Goto next change",
goto_prev_change, "Goto previous change",
goto_first_change, "Goto first change",
goto_last_change, "Goto last change",
goto_line_start, "Goto line start",
goto_line_end, "Goto line end",
goto_next_buffer, "Goto next buffer",
goto_previous_buffer, "Goto previous buffer",
goto_line_end_newline, "Goto newline at line end",
goto_first_nonwhitespace, "Goto first non-blank in line",
trim_selections, "Trim whitespace from selections",
extend_to_line_start, "Extend to line start",
extend_to_first_nonwhitespace, "Extend to first non-blank in line",
extend_to_line_end, "Extend to line end",
extend_to_line_end_newline, "Extend to line end",
signature_help, "Show signature help",
smart_tab, "Insert tab if all cursors have all whitespace to their left; otherwise, run a separate command.",
insert_tab, "Insert tab char",
insert_newline, "Insert newline char",
delete_char_backward, "Delete previous char",
delete_char_forward, "Delete next char",
delete_word_backward, "Delete previous word",
delete_word_forward, "Delete next word",
kill_to_line_start, "Delete till start of line",
kill_to_line_end, "Delete till end of line",
undo, "Undo change",
redo, "Redo change",
earlier, "Move backward in history",
later, "Move forward in history",
commit_undo_checkpoint, "Commit changes to new checkpoint",
yank, "Yank selection",
yank_to_clipboard, "Yank selections to clipboard",
yank_to_primary_clipboard, "Yank selections to primary clipboard",
yank_joined, "Join and yank selections",
yank_joined_to_clipboard, "Join and yank selections to clipboard",
yank_main_selection_to_clipboard, "Yank main selection to clipboard",
yank_joined_to_primary_clipboard, "Join and yank selections to primary clipboard",
yank_main_selection_to_primary_clipboard, "Yank main selection to primary clipboard",
replace_with_yanked, "Replace with yanked text",
replace_selections_with_clipboard, "Replace selections by clipboard content",
replace_selections_with_primary_clipboard, "Replace selections by primary clipboard",
paste_after, "Paste after selection",
paste_before, "Paste before selection",
paste_clipboard_after, "Paste clipboard after selections",
paste_clipboard_before, "Paste clipboard before selections",
paste_primary_clipboard_after, "Paste primary clipboard after selections",
paste_primary_clipboard_before, "Paste primary clipboard before selections",
indent, "Indent selection",
unindent, "Unindent selection",
format_selections, "Format selection",
join_selections, "Join lines inside selection",
join_selections_space, "Join lines inside selection and select spaces",
keep_selections, "Keep selections matching regex",
remove_selections, "Remove selections matching regex",
align_selections, "Align selections in column",
keep_primary_selection, "Keep primary selection",
remove_primary_selection, "Remove primary selection",
completion, "Invoke completion popup",
hover, "Show docs for item under cursor",
toggle_comments, "Comment/uncomment selections",
rotate_selections_forward, "Rotate selections forward",
rotate_selections_backward, "Rotate selections backward",
rotate_selection_contents_forward, "Rotate selection contents forward",
rotate_selection_contents_backward, "Rotate selections contents backward",
reverse_selection_contents, "Reverse selections contents",
expand_selection, "Expand selection to parent syntax node",
shrink_selection, "Shrink selection to previously expanded syntax node",
select_next_sibling, "Select next sibling in syntax tree",
select_prev_sibling, "Select previous sibling in syntax tree",
jump_forward, "Jump forward on jumplist",
jump_backward, "Jump backward on jumplist",
save_selection, "Save current selection to jumplist",
jump_view_right, "Jump to right split",
jump_view_left, "Jump to left split",
jump_view_up, "Jump to split above",
jump_view_down, "Jump to split below",
swap_view_right, "Swap with right split",
swap_view_left, "Swap with left split",
swap_view_up, "Swap with split above",
swap_view_down, "Swap with split below",
transpose_view, "Transpose splits",
rotate_view, "Goto next window",
rotate_view_reverse, "Goto previous window",
hsplit, "Horizontal bottom split",
hsplit_new, "Horizontal bottom split scratch buffer",
vsplit, "Vertical right split",
vsplit_new, "Vertical right split scratch buffer",
wclose, "Close window",
wonly, "Close windows except current",
select_register, "Select register",
insert_register, "Insert register",
align_view_middle, "Align view middle",
align_view_top, "Align view top",
align_view_center, "Align view center",
align_view_bottom, "Align view bottom",
scroll_up, "Scroll view up",
scroll_down, "Scroll view down",
match_brackets, "Goto matching bracket",
surround_add, "Surround add",
surround_replace, "Surround replace",
surround_delete, "Surround delete",
select_textobject_around, "Select around object",
select_textobject_inner, "Select inside object",
goto_next_function, "Goto next function",
goto_prev_function, "Goto previous function",
goto_next_class, "Goto next type definition",
goto_prev_class, "Goto previous type definition",
goto_next_parameter, "Goto next parameter",
goto_prev_parameter, "Goto previous parameter",
goto_next_comment, "Goto next comment",
goto_prev_comment, "Goto previous comment",
goto_next_test, "Goto next test",
goto_prev_test, "Goto previous test",
goto_next_paragraph, "Goto next paragraph",
goto_prev_paragraph, "Goto previous paragraph",
dap_launch, "Launch debug target",
dap_restart, "Restart debugging session",
dap_toggle_breakpoint, "Toggle breakpoint",
dap_continue, "Continue program execution",
dap_pause, "Pause program execution",
dap_step_in, "Step in",
dap_step_out, "Step out",
dap_next, "Step to next",
dap_variables, "List variables",
dap_terminate, "End debug session",
dap_edit_condition, "Edit breakpoint condition on current line",
dap_edit_log, "Edit breakpoint log message on current line",
dap_switch_thread, "Switch current thread",
dap_switch_stack_frame, "Switch stack frame",
dap_enable_exceptions, "Enable exception breakpoints",
dap_disable_exceptions, "Disable exception breakpoints",
shell_pipe, "Pipe selections through shell command",
shell_pipe_to, "Pipe selections into shell command ignoring output",
shell_insert_output, "Insert shell command output before selections",
shell_append_output, "Append shell command output after selections",
shell_keep_pipe, "Filter selections with shell predicate",
suspend, "Suspend and return to shell",
rename_symbol, "Rename symbol",
increment, "Increment item under cursor",
decrement, "Decrement item under cursor",
record_macro, "Record macro",
replay_macro, "Replay macro",
command_palette, "Open command palette",
);
}
impl fmt::Debug for MappableCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MappableCommand::Static { name, .. } => {
f.debug_tuple("MappableCommand").field(name).finish()
}
MappableCommand::Typable { name, args, .. } => f
.debug_tuple("MappableCommand")
.field(name)
.field(args)
.finish(),
}
}
}
impl fmt::Display for MappableCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
impl std::str::FromStr for MappableCommand {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Some(suffix) = s.strip_prefix(':') {
let mut typable_command = suffix.split(' ').map(|arg| arg.trim());
let name = typable_command
.next()
.ok_or_else(|| anyhow!("Expected typable command name"))?;
let args = typable_command
.map(|s| s.to_owned())
.collect::<Vec<String>>();
typed::TYPABLE_COMMAND_MAP
.get(name)
.map(|cmd| MappableCommand::Typable {
name: cmd.name.to_owned(),
doc: format!(":{} {:?}", cmd.name, args),
args,
})
.ok_or_else(|| anyhow!("No TypableCommand named '{}'", s))
} else {
MappableCommand::STATIC_COMMAND_LIST
.iter()
.find(|cmd| cmd.name() == s)
.cloned()
.ok_or_else(|| anyhow!("No command named '{}'", s))
}
}
}
impl<'de> Deserialize<'de> for MappableCommand {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
s.parse().map_err(de::Error::custom)
}
}
impl PartialEq for MappableCommand {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(
MappableCommand::Typable {
name: first_name,
args: first_args,
..
},
MappableCommand::Typable {
name: second_name,
args: second_args,
..
},
) => first_name == second_name && first_args == second_args,
(
MappableCommand::Static {
name: first_name, ..
},
MappableCommand::Static {
name: second_name, ..
},
) => first_name == second_name,
_ => false,
}
}
}
fn no_op(_cx: &mut Context) {}
type MoveFn =
fn(RopeSlice, Range, Direction, usize, Movement, &TextFormat, &mut TextAnnotations) -> Range;
fn move_impl(cx: &mut Context, move_fn: MoveFn, dir: Direction, behaviour: Movement) {
let count = cx.count();
let (view, doc) = current!(cx.editor);
let text = doc.text().slice(..);
let text_fmt = doc.text_format(view.inner_area(doc).width, None);
let mut annotations = view.text_annotations(doc, None);
let selection = doc.selection(view.id).clone().transform(|range| {
move_fn(
text,
range,
dir,
count,
behaviour,
&text_fmt,
&mut annotations,
)
});
doc.set_selection(view.id, selection);
}
use helix_core::movement::{move_horizontally, move_vertically};
fn move_char_left(cx: &mut Context) {
move_impl(cx, move_horizontally, Direction::Backward, Movement::Move)
}
fn move_char_right(cx: &mut Context) {
move_impl(cx, move_horizontally, Direction::Forward, Movement::Move)
}
fn move_line_up(cx: &mut Context) {
move_impl(cx, move_vertically, Direction::Backward, Movement::Move)
}
fn move_line_down(cx: &mut Context) {
move_impl(cx, move_vertically, Direction::Forward, Movement::Move)
}
fn move_visual_line_up(cx: &mut Context) {
move_impl(
cx,
move_vertically_visual,
Direction::Backward,
Movement::Move,
)
}
fn move_visual_line_down(cx: &mut Context) {
move_impl(
cx,
move_vertically_visual,
Direction::Forward,
Movement::Move,
)
}
fn extend_char_left(cx: &mut Context) {
move_impl(cx, move_horizontally, Direction::Backward, Movement::Extend)
}
fn extend_char_right(cx: &mut Context) {
move_impl(cx, move_horizontally, Direction::Forward, Movement::Extend)
}
fn extend_line_up(cx: &mut Context) {
move_impl(cx, move_vertically, Direction::Backward, Movement::Extend)
}
fn extend_line_down(cx: &mut Context) {
move_impl(cx, move_vertically, Direction::Forward, Movement::Extend)
}
fn extend_visual_line_up(cx: &mut Context) {
move_impl(
cx,
move_vertically_visual,
Direction::Backward,
Movement::Extend,
)
}
fn extend_visual_line_down(cx: &mut Context) {
move_impl(
cx,
move_vertically_visual,
Direction::Forward,
Movement::Extend,
)
}
fn goto_line_end_impl(view: &mut View, doc: &mut Document, movement: Movement) {
let text = doc.text().slice(..);
let selection = doc.selection(view.id).clone().transform(|range| {
let line = range.cursor_line(text);
let line_start = text.line_to_char(line);
let pos = graphemes::prev_grapheme_boundary(text, line_end_char_index(&text, line))
.max(line_start);
range.put_cursor(text, pos, movement == Movement::Extend)
});
doc.set_selection(view.id, selection);
}
fn goto_line_end(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
goto_line_end_impl(
view,
doc,
if cx.editor.mode == Mode::Select {
Movement::Extend
} else {
Movement::Move
},
)
}
fn extend_to_line_end(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
goto_line_end_impl(view, doc, Movement::Extend)
}
fn goto_line_end_newline_impl(view: &mut View, doc: &mut Document, movement: Movement) {
let text = doc.text().slice(..);
let selection = doc.selection(view.id).clone().transform(|range| {
let line = range.cursor_line(text);
let pos = line_end_char_index(&text, line);
range.put_cursor(text, pos, movement == Movement::Extend)
});
doc.set_selection(view.id, selection);
}
fn goto_line_end_newline(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
goto_line_end_newline_impl(
view,
doc,
if cx.editor.mode == Mode::Select {
Movement::Extend
} else {
Movement::Move
},
)
}
fn extend_to_line_end_newline(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
goto_line_end_newline_impl(view, doc, Movement::Extend)
}
fn goto_line_start_impl(view: &mut View, doc: &mut Document, movement: Movement) {
let text = doc.text().slice(..);
let selection = doc.selection(view.id).clone().transform(|range| {
let line = range.cursor_line(text);
// adjust to start of the line
let pos = text.line_to_char(line);
range.put_cursor(text, pos, movement == Movement::Extend)
});
doc.set_selection(view.id, selection);
}
fn goto_line_start(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
goto_line_start_impl(
view,
doc,
if cx.editor.mode == Mode::Select {
Movement::Extend
} else {
Movement::Move
},
)
}
fn goto_next_buffer(cx: &mut Context) {
goto_buffer(cx.editor, Direction::Forward);
}
fn goto_previous_buffer(cx: &mut Context) {
goto_buffer(cx.editor, Direction::Backward);
}
fn goto_buffer(editor: &mut Editor, direction: Direction) {
let current = view!(editor).doc;
let id = match direction {
Direction::Forward => {
let iter = editor.documents.keys();
let mut iter = iter.skip_while(|id| *id != ¤t);
iter.next(); // skip current item
iter.next().or_else(|| editor.documents.keys().next())
}
Direction::Backward => {
let iter = editor.documents.keys();
let mut iter = iter.rev().skip_while(|id| *id != ¤t);
iter.next(); // skip current item
iter.next().or_else(|| editor.documents.keys().next_back())
}
}
.unwrap();
let id = *id;
editor.switch(id, Action::Replace);
}
fn extend_to_line_start(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
goto_line_start_impl(view, doc, Movement::Extend)
}
fn kill_to_line_start(cx: &mut Context) {
delete_by_selection_insert_mode(
cx,
move |text, range| {
let line = range.cursor_line(text);
let first_char = text.line_to_char(line);
let anchor = range.cursor(text);
let head = if anchor == first_char && line != 0 {
// select until previous line
line_end_char_index(&text, line - 1)
} else if let Some(pos) = find_first_non_whitespace_char(text.line(line)) {
if first_char + pos < anchor {
// select until first non-blank in line if cursor is after it
first_char + pos
} else {
// select until start of line
first_char
}
} else {
// select until start of line
first_char
};
(head, anchor)
},
Direction::Backward,
);
}
fn kill_to_line_end(cx: &mut Context) {
delete_by_selection_insert_mode(
cx,
|text, range| {
let line = range.cursor_line(text);
let line_end_pos = line_end_char_index(&text, line);
let pos = range.cursor(text);
// if the cursor is on the newline char delete that
if pos == line_end_pos {
(pos, text.line_to_char(line + 1))
} else {
(pos, line_end_pos)
}
},
Direction::Forward,
);
}
fn goto_first_nonwhitespace(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
goto_first_nonwhitespace_impl(
view,
doc,
if cx.editor.mode == Mode::Select {
Movement::Extend
} else {
Movement::Move
},
)
}
fn extend_to_first_nonwhitespace(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
goto_first_nonwhitespace_impl(view, doc, Movement::Extend)
}
fn goto_first_nonwhitespace_impl(view: &mut View, doc: &mut Document, movement: Movement) {
let text = doc.text().slice(..);
let selection = doc.selection(view.id).clone().transform(|range| {
let line = range.cursor_line(text);
if let Some(pos) = find_first_non_whitespace_char(text.line(line)) {
let pos = pos + text.line_to_char(line);
range.put_cursor(text, pos, movement == Movement::Extend)
} else {
range
}
});
doc.set_selection(view.id, selection);
}
fn trim_selections(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
let text = doc.text().slice(..);
let ranges: SmallVec<[Range; 1]> = doc
.selection(view.id)
.iter()
.filter_map(|range| {
if range.is_empty() || range.slice(text).chars().all(|ch| ch.is_whitespace()) {
return None;
}
let mut start = range.from();
let mut end = range.to();
start = movement::skip_while(text, start, |x| x.is_whitespace()).unwrap_or(start);
end = movement::backwards_skip_while(text, end, |x| x.is_whitespace()).unwrap_or(end);
Some(Range::new(start, end).with_direction(range.direction()))
})
.collect();
if !ranges.is_empty() {
let primary = doc.selection(view.id).primary();
let idx = ranges
.iter()
.position(|range| range.overlaps(&primary))
.unwrap_or(ranges.len() - 1);
doc.set_selection(view.id, Selection::new(ranges, idx));
} else {
collapse_selection(cx);
keep_primary_selection(cx);
};
}
// align text in selection
#[allow(deprecated)]
fn align_selections(cx: &mut Context) {
use helix_core::visual_coords_at_pos;
let (view, doc) = current!(cx.editor);
let text = doc.text().slice(..);
let selection = doc.selection(view.id);
let tab_width = doc.tab_width();
let mut column_widths: Vec<Vec<_>> = Vec::new();
let mut last_line = text.len_lines() + 1;
let mut col = 0;
for range in selection {
let coords = visual_coords_at_pos(text, range.head, tab_width);
let anchor_coords = visual_coords_at_pos(text, range.anchor, tab_width);
if coords.row != anchor_coords.row {
cx.editor
.set_error("align cannot work with multi line selections");
return;
}
col = if coords.row == last_line { col + 1 } else { 0 };
if col >= column_widths.len() {
column_widths.push(Vec::new());
}
column_widths[col].push((range.from(), coords.col));
last_line = coords.row;
}
let mut changes = Vec::with_capacity(selection.len());
// Account for changes on each row
let len = column_widths.first().map(|cols| cols.len()).unwrap_or(0);
let mut offs = vec![0; len];
for col in column_widths {
let max_col = col
.iter()
.enumerate()
.map(|(row, (_, cursor))| *cursor + offs[row])
.max()
.unwrap_or(0);
for (row, (insert_pos, last_col)) in col.into_iter().enumerate() {
let ins_count = max_col - (last_col + offs[row]);
if ins_count == 0 {
continue;
}
offs[row] += ins_count;
changes.push((insert_pos, insert_pos, Some(" ".repeat(ins_count).into())));
}
}
// The changeset has to be sorted
changes.sort_unstable_by_key(|(from, _, _)| *from);
let transaction = Transaction::change(doc.text(), changes.into_iter());
doc.apply(&transaction, view.id);
exit_select_mode(cx);
}
fn goto_window(cx: &mut Context, align: Align) {
let count = cx.count() - 1;
let config = cx.editor.config();
let (view, doc) = current!(cx.editor);
let height = view.inner_height();
// respect user given count if any