-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
commands.rs
6026 lines (5279 loc) · 195 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
use helix_core::{
comment, coords_at_pos, find_first_non_whitespace_char, find_root, graphemes,
history::UndoKind,
increment::date_time::DateTimeIncrementor,
increment::{number::NumberIncrementor, Increment},
indent,
indent::IndentStyle,
line_ending::{get_line_ending_of_str, line_end_char_index, str_is_line_ending},
match_brackets,
movement::{self, Direction},
object, pos_at_coords,
regex::{self, Regex, RegexBuilder},
search, selection, shellwords, surround, textobject,
unicode::width::UnicodeWidthChar,
LineEnding, Position, Range, Rope, RopeGraphemes, RopeSlice, Selection, SmallVec, Tendril,
Transaction,
};
use helix_view::{
clipboard::ClipboardType,
document::{Mode, SCRATCH_BUFFER_NAME},
editor::{Action, Motion},
input::KeyEvent,
keyboard::KeyCode,
view::View,
Document, DocumentId, Editor, ViewId,
};
use anyhow::{anyhow, bail, ensure, Context as _};
use helix_lsp::{
block_on, lsp,
util::{lsp_pos_to_pos, lsp_range_to_range, pos_to_lsp_pos, range_to_lsp_range},
OffsetEncoding,
};
use insert::*;
use movement::Movement;
use crate::{
compositor::{self, Component, Compositor},
ui::{self, FilePicker, Picker, Popup, Prompt, PromptEvent},
};
use crate::job::{self, Job, Jobs};
use futures_util::{FutureExt, StreamExt};
use std::{collections::HashSet, num::NonZeroUsize};
use std::{fmt, future::Future};
use std::{
borrow::Cow,
path::{Path, PathBuf},
};
use once_cell::sync::Lazy;
use serde::de::{self, Deserialize, Deserializer};
use grep_regex::RegexMatcherBuilder;
use grep_searcher::{sinks, BinaryDetection, SearcherBuilder};
use ignore::{DirEntry, WalkBuilder, WalkState};
use tokio_stream::wrappers::UnboundedReceiverStream;
pub struct Context<'a> {
pub register: Option<char>,
pub count: Option<NonZeroUsize>,
pub editor: &'a mut Editor,
pub callback: Option<crate::compositor::Callback>,
pub on_next_key_callback: Option<Box<dyn FnOnce(&mut Context, KeyEvent)>>,
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 = Some(Box::new(|compositor: &mut Compositor, _| {
compositor.push(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,
{
let callback = Box::pin(async move {
let json = call.await?;
let response = serde_json::from_value(json)?;
let call: job::Callback =
Box::new(move |editor: &mut Editor, compositor: &mut Compositor| {
callback(editor, compositor, response)
});
Ok(call)
});
self.jobs.callback(callback);
}
/// Returns 1 if no explicit count was provided
#[inline]
pub fn count(&self) -> usize {
self.count.map_or(1, |v| v.get())
}
}
enum Align {
Top,
Center,
Bottom,
}
fn align_view(doc: &Document, view: &mut View, align: Align) {
let pos = doc
.selection(view.id)
.primary()
.cursor(doc.text().slice(..));
let line = doc.text().char_to_line(pos);
let height = view.inner_area().height as usize;
let relative = match align {
Align::Center => height / 2,
Align::Top => 0,
Align::Bottom => height,
};
view.offset.row = line.saturating_sub(relative);
}
/// 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 {
MappableCommand::Typable { name, args, doc: _ } => {
let args: Vec<Cow<str>> = args.iter().map(Cow::from).collect();
if let Some(command) = cmd::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));
}
}
}
MappableCommand::Static { fun, .. } => (fun)(cx),
}
}
pub fn name(&self) -> &str {
match &self {
MappableCommand::Typable { name, .. } => name,
MappableCommand::Static { name, .. } => name,
}
}
pub fn doc(&self) -> &str {
match &self {
MappableCommand::Typable { doc, .. } => doc,
MappableCommand::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",
extend_char_left, "Extend left",
extend_char_right, "Extend right",
extend_line_up, "Extend up",
extend_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 beginning of next word",
move_prev_word_start, "Move to beginning of previous word",
move_prev_word_end, "Move to end of previous word",
move_next_word_end, "Move to end of next word",
move_next_long_word_start, "Move to beginning of next long word",
move_prev_long_word_start, "Move to beginning of previous long word",
move_next_long_word_end, "Move to end of next long word",
extend_next_word_start, "Extend to beginning of next word",
extend_prev_word_start, "Extend to beginning of previous word",
extend_next_long_word_start, "Extend to beginning of next long word",
extend_prev_long_word_start, "Extend to beginning of previous long word",
extend_next_long_word_end, "Extend to end of next long word",
extend_next_word_end, "Extend to end of next word",
find_till_char, "Move till next occurance of char",
find_next_char, "Move to next occurance of char",
extend_till_char, "Extend till next occurance of char",
extend_next_char, "Extend to next occurance of char",
till_prev_char, "Move till previous occurance of char",
find_prev_char, "Move to previous occurance of char",
extend_till_prev_char, "Extend till previous occurance of char",
extend_prev_char, "Extend to previous occurance of char",
repeat_last_motion, "repeat last motion(extend_next_char, extend_till_char, find_next_char, find_till_char...)",
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 selection into subselections on regex matches",
split_selection_on_newline, "Split selection on newlines",
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",
global_search, "Global Search in workspace folder",
extend_line, "Select current line, if already selected, extend to next line",
extend_to_line_bounds, "Extend selection to line bounds (line-wise selection)",
delete_selection, "Delete selection",
delete_selection_noyank, "Delete selection, without yanking",
change_selection, "Change selection (delete and enter insert mode)",
change_selection_noyank, "Change selection (delete and enter insert mode, without yanking)",
collapse_selection, "Collapse selection onto a single cursor",
flip_selections, "Flip selection cursor and anchor",
insert_mode, "Insert before selection",
append_mode, "Insert after selection (append)",
command_mode, "Enter command mode",
file_picker, "Open file picker",
code_action, "Perform code action",
buffer_picker, "Open buffer picker",
symbol_picker, "Open symbol picker",
workspace_symbol_picker, "Open workspace symbol picker",
last_picker, "Open last picker",
prepend_to_line, "Insert at start of line",
append_to_line, "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",
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 in selection",
goto_file_hsplit, "Goto files in selection (hsplit)",
goto_file_vsplit, "Goto files in selection (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_line_start, "Goto line start",
goto_line_end, "Goto line end",
goto_next_buffer, "Goto next buffer",
goto_previous_buffer, "Goto previous buffer",
// TODO: different description ?
goto_line_end_newline, "Goto 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_line_end, "Extend to line end",
extend_to_line_end_newline, "Extend to line end",
signature_help, "Show signature help",
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 content till the start of the line",
kill_to_line_end, "Delete content till the end of the line",
undo, "Undo change",
redo, "Redo change",
earlier, "Move backward in history",
later, "Move forward in history",
yank, "Yank selection",
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 content",
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",
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",
expand_selection, "Expand selection to parent syntax node",
jump_forward, "Jump forward on jumplist",
jump_backward, "Jump backward on jumplist",
save_selection, "Save the current selection to the jumplist",
jump_view_right, "Jump to the split to the right",
jump_view_left, "Jump to the split to the left",
jump_view_up, "Jump to the split above",
jump_view_down, "Jump to the split below",
rotate_view, "Goto next window",
hsplit, "Horizontal bottom split",
vsplit, "Vertical right split",
wclose, "Close window",
wonly, "Current window only",
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",
shell_pipe, "Pipe selections through shell command",
shell_pipe_to, "Pipe selections into shell command, ignoring command output",
shell_insert_output, "Insert output of shell command before each selection",
shell_append_output, "Append output of shell command after each selection",
shell_keep_pipe, "Filter selections with shell predicate",
suspend, "Suspend",
rename_symbol, "Rename symbol",
increment, "Increment",
decrement, "Decrement",
record_macro, "Record macro",
play_macro, "Play macro",
);
}
impl fmt::Debug for MappableCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("MappableCommand")
.field(&self.name())
.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(' ').into_iter().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>>();
cmd::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()
.cloned()
.find(|cmd| cmd.name() == s)
.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, ..
},
MappableCommand::Typable {
name: second_name, ..
},
) => first_name == second_name,
(
MappableCommand::Static {
name: first_name, ..
},
MappableCommand::Static {
name: second_name, ..
},
) => first_name == second_name,
_ => false,
}
}
}
fn no_op(_cx: &mut Context) {}
fn move_impl<F>(cx: &mut Context, move_fn: F, dir: Direction, behaviour: Movement)
where
F: Fn(RopeSlice, Range, Direction, usize, Movement) -> Range,
{
let count = cx.count();
let (view, doc) = current!(cx.editor);
let text = doc.text().slice(..);
let selection = doc
.selection(view.id)
.clone()
.transform(|range| move_fn(text, range, dir, count, behaviour));
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 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 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 doc.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 doc.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 doc.mode == Mode::Select {
Movement::Extend
} else {
Movement::Move
},
)
}
fn goto_next_buffer(cx: &mut Context) {
goto_buffer(cx, Direction::Forward);
}
fn goto_previous_buffer(cx: &mut Context) {
goto_buffer(cx, Direction::Backward);
}
fn goto_buffer(cx: &mut Context, direction: Direction) {
let current = view!(cx.editor).doc;
let id = match direction {
Direction::Forward => {
let iter = cx.editor.documents.keys();
let mut iter = iter.skip_while(|id| *id != ¤t);
iter.next(); // skip current item
iter.next().or_else(|| cx.editor.documents.keys().next())
}
Direction::Backward => {
let iter = cx.editor.documents.keys();
let mut iter = iter.rev().skip_while(|id| *id != ¤t);
iter.next(); // skip current item
iter.next()
.or_else(|| cx.editor.documents.keys().rev().next())
}
}
.unwrap();
let id = *id;
cx.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) {
let (view, doc) = current!(cx.editor);
let text = doc.text().slice(..);
let selection = doc.selection(view.id).clone().transform(|range| {
let line = range.cursor_line(text);
range.put_cursor(text, text.line_to_char(line), true)
});
delete_selection_insert_mode(doc, view, &selection);
}
fn kill_to_line_end(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
let text = doc.text().slice(..);
let selection = doc.selection(view.id).clone().transform(|range| {
let line = range.cursor_line(text);
let line_end_pos = line_end_char_index(&text, line);
let pos = range.cursor(text);
let mut new_range = range.put_cursor(text, line_end_pos, true);
// don't want to remove the line separator itself if the cursor doesn't reach the end of line.
if pos != line_end_pos {
new_range.head = line_end_pos;
}
new_range
});
delete_selection_insert_mode(doc, view, &selection);
}
fn goto_first_nonwhitespace(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
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, doc.mode == Mode::Select)
} 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.fragment(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);
if range.anchor < range.head {
Some(Range::new(start, end))
} else {
Some(Range::new(end, start))
}
})
.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
fn align_selections(cx: &mut Context) {
let align_style = cx.count();
if align_style > 3 {
cx.editor.set_error(
"align only accept 1,2,3 as count to set left/center/right align".to_string(),
);
return;
}
let (view, doc) = current!(cx.editor);
let text = doc.text().slice(..);
let selection = doc.selection(view.id);
let mut column_widths = vec![];
let mut last_line = text.len_lines();
let mut column = 0;
// first of all, we need compute all column's width, let use max width of the selections in a column
for sel in selection {
let (l1, l2) = sel.line_range(text);
if l1 != l2 {
cx.editor
.set_error("align cannot work with multi line selections".to_string());
return;
}
// if the selection is not in the same line with last selection, we set the column to 0
column = if l1 != last_line { 0 } else { column + 1 };
last_line = l1;
if column < column_widths.len() {
if sel.to() - sel.from() > column_widths[column] {
column_widths[column] = sel.to() - sel.from();
}
} else {
// a new column, current selection width is the temp width of the column
column_widths.push(sel.to() - sel.from());
}
}
last_line = text.len_lines();
// once we get the with of each column, we transform each selection with to it's column width based on the align style
let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
let l = range.cursor_line(text);
column = if l != last_line { 0 } else { column + 1 };
last_line = l;
(
range.from(),
range.to(),
Some(
align_fragment_to_width(&range.fragment(text), column_widths[column], align_style)
.into(),
),
)
});
doc.apply(&transaction, view.id);
doc.append_changes_to_history(view.id);
}
fn align_fragment_to_width(fragment: &str, width: usize, align_style: usize) -> String {
let trimed = fragment.trim_matches(|c| c == ' ');
let mut s = " ".repeat(width - trimed.chars().count());
match align_style {
1 => s.insert_str(0, trimed), // left align
2 => s.insert_str(s.len() / 2, trimed), // center align
3 => s.push_str(trimed), // right align
n => unimplemented!("{}", n),
}
s
}
fn goto_window(cx: &mut Context, align: Align) {
let count = cx.count() - 1;
let (view, doc) = current!(cx.editor);
let height = view.inner_area().height as usize;
// respect user given count if any
// - 1 so we have at least one gap in the middle.
// a height of 6 with padding of 3 on each side will keep shifting the view back and forth
// as we type
let scrolloff = cx.editor.config.scrolloff.min(height.saturating_sub(1) / 2);
let last_line = view.last_line(doc);
let line = match align {
Align::Top => (view.offset.row + scrolloff + count),
Align::Center => (view.offset.row + ((last_line - view.offset.row) / 2)),
Align::Bottom => last_line.saturating_sub(scrolloff + count),
}
.max(view.offset.row + scrolloff)
.min(last_line.saturating_sub(scrolloff));
let pos = doc.text().line_to_char(line);
doc.set_selection(view.id, Selection::point(pos));
}
fn goto_window_top(cx: &mut Context) {
goto_window(cx, Align::Top)
}
fn goto_window_center(cx: &mut Context) {
goto_window(cx, Align::Center)
}
fn goto_window_bottom(cx: &mut Context) {
goto_window(cx, Align::Bottom)
}
fn move_word_impl<F>(cx: &mut Context, move_fn: F)
where
F: Fn(RopeSlice, Range, usize) -> Range,
{
let count = cx.count();
let (view, doc) = current!(cx.editor);
let text = doc.text().slice(..);
let selection = doc
.selection(view.id)
.clone()
.transform(|range| move_fn(text, range, count));
doc.set_selection(view.id, selection);
}
fn move_next_word_start(cx: &mut Context) {
move_word_impl(cx, movement::move_next_word_start)
}
fn move_prev_word_start(cx: &mut Context) {
move_word_impl(cx, movement::move_prev_word_start)
}
fn move_prev_word_end(cx: &mut Context) {
move_word_impl(cx, movement::move_prev_word_end)
}
fn move_next_word_end(cx: &mut Context) {
move_word_impl(cx, movement::move_next_word_end)
}
fn move_next_long_word_start(cx: &mut Context) {
move_word_impl(cx, movement::move_next_long_word_start)
}
fn move_prev_long_word_start(cx: &mut Context) {
move_word_impl(cx, movement::move_prev_long_word_start)
}
fn move_next_long_word_end(cx: &mut Context) {
move_word_impl(cx, movement::move_next_long_word_end)
}
fn goto_file_start(cx: &mut Context) {
if cx.count.is_some() {
goto_line(cx);
} else {
push_jump(cx.editor);
let (view, doc) = current!(cx.editor);
let text = doc.text().slice(..);
let selection = doc
.selection(view.id)
.clone()
.transform(|range| range.put_cursor(text, 0, doc.mode == Mode::Select));
doc.set_selection(view.id, selection);
}
}
fn goto_file_end(cx: &mut Context) {
push_jump(cx.editor);
let (view, doc) = current!(cx.editor);
let text = doc.text().slice(..);
let pos = doc.text().len_chars();
let selection = doc
.selection(view.id)
.clone()
.transform(|range| range.put_cursor(text, pos, doc.mode == Mode::Select));
doc.set_selection(view.id, selection);
}
fn goto_file(cx: &mut Context) {
goto_file_impl(cx, Action::Replace);
}
fn goto_file_hsplit(cx: &mut Context) {
goto_file_impl(cx, Action::HorizontalSplit);
}
fn goto_file_vsplit(cx: &mut Context) {
goto_file_impl(cx, Action::VerticalSplit);
}
fn goto_file_impl(cx: &mut Context, action: Action) {
let (view, doc) = current_ref!(cx.editor);
let text = doc.text();
let selections = doc.selection(view.id);
let mut paths: Vec<_> = selections
.iter()
.map(|r| text.slice(r.from()..r.to()).to_string())
.collect();
let primary = selections.primary();
if selections.len() == 1 && primary.to() - primary.from() == 1 {
let current_word = movement::move_next_long_word_start(
text.slice(..),
movement::move_prev_long_word_start(text.slice(..), primary, 1),
1,
);
paths.clear();
paths.push(
text.slice(current_word.from()..current_word.to())
.to_string(),
);
}
for sel in paths {
let p = sel.trim();
if !p.is_empty() {
if let Err(e) = cx.editor.open(PathBuf::from(p), action) {
cx.editor.set_error(format!("Open file failed: {:?}", e));
}
}
}
}
fn extend_word_impl<F>(cx: &mut Context, extend_fn: F)
where
F: Fn(RopeSlice, Range, usize) -> Range,
{
let count = cx.count();
let (view, doc) = current!(cx.editor);
let text = doc.text().slice(..);
let selection = doc.selection(view.id).clone().transform(|range| {
let word = extend_fn(text, range, count);
let pos = word.cursor(text);
range.put_cursor(text, pos, true)
});
doc.set_selection(view.id, selection);
}
fn extend_next_word_start(cx: &mut Context) {
extend_word_impl(cx, movement::move_next_word_start)
}
fn extend_prev_word_start(cx: &mut Context) {
extend_word_impl(cx, movement::move_prev_word_start)
}
fn extend_next_word_end(cx: &mut Context) {
extend_word_impl(cx, movement::move_next_word_end)
}
fn extend_next_long_word_start(cx: &mut Context) {
extend_word_impl(cx, movement::move_next_long_word_start)
}
fn extend_prev_long_word_start(cx: &mut Context) {
extend_word_impl(cx, movement::move_prev_long_word_start)
}
fn extend_next_long_word_end(cx: &mut Context) {