Debian Codegraph @

helix-term/src/commands.rs

raw symbols SCIP
1 pub(crate) mod dap;
2 pub(crate) mod lsp;
3 pub(crate) mod syntax;
4 pub(crate) mod typed;
5
6 pub use dap::*;
7 use futures_util::FutureExt;
8 use helix_event::status;
9 use helix_stdx::{
10 path::{self, find_paths},
11 rope::{self, RopeSliceExt},
12 };
13 use helix_vcs::{FileChange, Hunk};
14 pub use lsp::*;
15 pub use syntax::*;
16 use tui::{
17 text::{Span, Spans},
18 widgets::Cell,
19 };
20 pub use typed::*;
21
22 use helix_core::{
23 char_idx_at_visual_offset,
24 chars::char_is_word,
25 command_line::{self, Args},
26 comment,
27 doc_formatter::TextFormat,
28 encoding, find_workspace,
29 graphemes::{self, next_grapheme_boundary},
30 history::UndoKind,
31 increment,
32 indent::{self, IndentStyle},
33 line_ending::{get_line_ending_of_str, line_end_char_index},
34 match_brackets,
35 movement::{self, move_vertically_visual, Direction},
36 object, pos_at_coords,
37 regex::{self, Regex},
38 search::{self},
39 selection, surround,
40 syntax::config::{BlockCommentToken, LanguageServerFeature},
41 text_annotations::{Overlay, TextAnnotations},
42 textobject,
43 unicode::width::UnicodeWidthChar,
44 visual_offset_from_block, Deletion, LineEnding, Position, Range, Rope, RopeReader, RopeSlice,
45 Selection, SmallVec, Syntax, Tendril, Transaction,
46 };
47 use helix_view::{
48 document::{FormatterError, Mode, SCRATCH_BUFFER_NAME},
49 editor::{Action, Motion},
50 expansion,
51 info::Info,
52 input::KeyEvent,
53 keyboard::KeyCode,
54 theme::Style,
55 tree,
56 view::View,
57 Document, DocumentId, Editor, ViewId,
58 };
59
60 use anyhow::{anyhow, bail, ensure, Context as _};
61 use arc_swap::access::DynAccess;
62 use insert::*;
63 use movement::Movement;
64
65 use crate::{
66 compositor::{self, Component, Compositor},
67 filter_picker_entry,
68 job::Callback,
69 ui::{self, overlay::overlaid, Picker, PickerColumn, Popup, Prompt, PromptEvent},
70 };
71
72 use crate::job::{self, Jobs};
73 use std::{
74 char::{ToLowercase, ToUppercase},
75 cmp::Ordering,
76 collections::{HashMap, HashSet},
77 error::Error,
78 fmt,
79 future::Future,
80 io::Read,
81 num::NonZeroUsize,
82 };
83
84 use std::{
85 borrow::Cow,
86 path::{Path, PathBuf},
87 };
88
89 use helix_stdx::Url;
90 use once_cell::sync::Lazy;
91 use serde::de::{self, Deserialize, Deserializer};
92
93 use grep_regex::RegexMatcherBuilder;
94 use grep_searcher::{sinks, BinaryDetection, SearcherBuilder};
95 use ignore::{DirEntry, WalkBuilder, WalkState};
96
97 pub type OnKeyCallback = Box<dyn FnOnce(&mut Context, KeyEvent)>;
98 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
99 pub enum OnKeyCallbackKind {
100 PseudoPending,
101 Fallback,
102 }
103
104 pub struct Context<'a> {
105 pub register: Option<char>,
106 pub count: Option<NonZeroUsize>,
107 pub editor: &'a mut Editor,
108
109 pub callback: Vec<crate::compositor::Callback>,
110 pub on_next_key_callback: Option<(OnKeyCallback, OnKeyCallbackKind)>,
111 pub jobs: &'a mut Jobs,
112 }
113
114 impl Context<'_> {
115 /// Push a new component onto the compositor.
116 pub fn push_layer(&mut self, component: Box<dyn Component>) {
117 self.callback
118 .push(Box::new(|compositor: &mut Compositor, _| {
119 compositor.push(component)
120 }));
121 }
122
123 /// Call `replace_or_push` on the Compositor
124 pub fn replace_or_push_layer<T: Component>(&mut self, id: &'static str, component: T) {
125 self.callback
126 .push(Box::new(move |compositor: &mut Compositor, _| {
127 compositor.replace_or_push(id, component);
128 }));
129 }
130
131 #[inline]
132 pub fn on_next_key(
133 &mut self,
134 on_next_key_callback: impl FnOnce(&mut Context, KeyEvent) + 'static,
135 ) {
136 self.on_next_key_callback = Some((
137 Box::new(on_next_key_callback),
138 OnKeyCallbackKind::PseudoPending,
139 ));
140 }
141
142 #[inline]
143 pub fn on_next_key_fallback(
144 &mut self,
145 on_next_key_callback: impl FnOnce(&mut Context, KeyEvent) + 'static,
146 ) {
147 self.on_next_key_callback =
148 Some((Box::new(on_next_key_callback), OnKeyCallbackKind::Fallback));
149 }
150
151 #[inline]
152 pub fn callback<T, F>(
153 &mut self,
154 call: impl Future<Output = helix_lsp::Result<T>> + 'static + Send,
155 callback: F,
156 ) where
157 T: Send + 'static,
158 F: FnOnce(&mut Editor, &mut Compositor, T) + Send + 'static,
159 {
160 self.jobs.callback(make_job_callback(call, callback));
161 }
162
163 /// Returns 1 if no explicit count was provided
164 #[inline]
165 pub fn count(&self) -> usize {
166 self.count.map_or(1, |v| v.get())
167 }
168
169 /// Waits on all pending jobs, and then tries to flush all pending write
170 /// operations for all documents.
171 pub fn block_try_flush_writes(&mut self) -> anyhow::Result<()> {
172 compositor::Context {
173 editor: self.editor,
174 jobs: self.jobs,
175 scroll: None,
176 }
177 .block_try_flush_writes()
178 }
179 }
180
181 #[inline]
182 fn make_job_callback<T, F>(
183 call: impl Future<Output = helix_lsp::Result<T>> + 'static + Send,
184 callback: F,
185 ) -> std::pin::Pin<Box<impl Future<Output = Result<Callback, anyhow::Error>>>>
186 where
187 T: Send + 'static,
188 F: FnOnce(&mut Editor, &mut Compositor, T) + Send + 'static,
189 {
190 Box::pin(async move {
191 let response = call.await?;
192 let call: job::Callback = Callback::EditorCompositor(Box::new(
193 move |editor: &mut Editor, compositor: &mut Compositor| {
194 callback(editor, compositor, response)
195 },
196 ));
197 Ok(call)
198 })
199 }
200
201 use helix_view::{align_view, Align};
202
203 /// MappableCommands are commands that can be bound to keys, executable in
204 /// normal, insert or select mode.
205 ///
206 /// There are three kinds:
207 ///
208 /// * Static: commands usually bound to keys and used for editing, movement,
209 /// etc., for example `move_char_left`.
210 /// * Typable: commands executable from command mode, prefixed with a `:`,
211 /// for example `:write!`.
212 /// * Macro: a sequence of keys to execute, for example `@miw`.
213 #[derive(Clone)]
214 pub enum MappableCommand {
215 Typable {
216 name: String,
217 args: String,
218 doc: String,
219 },
220 Static {
221 name: &'static str,
222 fun: fn(cx: &mut Context),
223 doc: &'static str,
224 },
225 Macro {
226 name: String,
227 keys: Vec<KeyEvent>,
228 },
229 }
230
231 macro_rules! static_commands {
232 ( $($name:ident, $doc:literal,)* ) => {
233 $(
234 #[allow(non_upper_case_globals)]
235 pub const $name: Self = Self::Static {
236 name: stringify!($name),
237 fun: $name,
238 doc: $doc
239 };
240 )*
241
242 pub const STATIC_COMMAND_LIST: &'static [Self] = &[
243 $( Self::$name, )*
244 ];
245 }
246 }
247
248 impl MappableCommand {
249 pub fn execute(&self, cx: &mut Context) {
250 match &self {
251 Self::Typable { name, args, doc: _ } => {
252 if let Some(command) = typed::TYPABLE_COMMAND_MAP.get(name.as_str()) {
253 let mut cx = compositor::Context {
254 editor: cx.editor,
255 jobs: cx.jobs,
256 scroll: None,
257 };
258 if let Err(e) =
259 typed::execute_command(&mut cx, command, args, PromptEvent::Validate)
260 {
261 cx.editor.set_error(format!("{}", e));
262 }
263 } else {
264 cx.editor.set_error(format!("no such command: '{name}'"));
265 }
266 }
267 Self::Static { fun, .. } => (fun)(cx),
268 Self::Macro { keys, .. } => {
269 // Protect against recursive macros.
270 if cx.editor.macro_replaying.contains(&'@') {
271 cx.editor.set_error(
272 "Cannot execute macro because the [@] register is already playing a macro",
273 );
274 return;
275 }
276 cx.editor.macro_replaying.push('@');
277 let keys = keys.clone();
278 cx.callback.push(Box::new(move |compositor, cx| {
279 for key in keys.into_iter() {
280 compositor.handle_event(&compositor::Event::Key(key), cx);
281 }
282 cx.editor.macro_replaying.pop();
283 }));
284 }
285 }
286 }
287
288 pub fn name(&self) -> &str {
289 match &self {
290 Self::Typable { name, .. } => name,
291 Self::Static { name, .. } => name,
292 Self::Macro { name, .. } => name,
293 }
294 }
295
296 pub fn doc(&self) -> &str {
297 match &self {
298 Self::Typable { doc, .. } => doc,
299 Self::Static { doc, .. } => doc,
300 Self::Macro { name, .. } => name,
301 }
302 }
303
304 #[rustfmt::skip]
305 static_commands!(
306 no_op, "Do nothing",
307 move_char_left, "Move left",
308 move_char_right, "Move right",
309 move_line_up, "Move up",
310 move_line_down, "Move down",
311 move_visual_line_up, "Move up",
312 move_visual_line_down, "Move down",
313 extend_char_left, "Extend left",
314 extend_char_right, "Extend right",
315 extend_line_up, "Extend up",
316 extend_line_down, "Extend down",
317 extend_visual_line_up, "Extend up",
318 extend_visual_line_down, "Extend down",
319 copy_selection_on_next_line, "Copy selection on next line",
320 copy_selection_on_prev_line, "Copy selection on previous line",
321 move_next_word_start, "Move to start of next word",
322 move_prev_word_start, "Move to start of previous word",
323 move_next_word_end, "Move to end of next word",
324 move_prev_word_end, "Move to end of previous word",
325 move_next_long_word_start, "Move to start of next long word",
326 move_prev_long_word_start, "Move to start of previous long word",
327 move_next_long_word_end, "Move to end of next long word",
328 move_prev_long_word_end, "Move to end of previous long word",
329 move_next_sub_word_start, "Move to start of next sub word",
330 move_prev_sub_word_start, "Move to start of previous sub word",
331 move_next_sub_word_end, "Move to end of next sub word",
332 move_prev_sub_word_end, "Move to end of previous sub word",
333 move_parent_node_end, "Move to end of the parent node",
334 move_parent_node_start, "Move to beginning of the parent node",
335 extend_next_word_start, "Extend to start of next word",
336 extend_prev_word_start, "Extend to start of previous word",
337 extend_next_word_end, "Extend to end of next word",
338 extend_prev_word_end, "Extend to end of previous word",
339 extend_next_long_word_start, "Extend to start of next long word",
340 extend_prev_long_word_start, "Extend to start of previous long word",
341 extend_next_long_word_end, "Extend to end of next long word",
342 extend_prev_long_word_end, "Extend to end of prev long word",
343 extend_next_sub_word_start, "Extend to start of next sub word",
344 extend_prev_sub_word_start, "Extend to start of previous sub word",
345 extend_next_sub_word_end, "Extend to end of next sub word",
346 extend_prev_sub_word_end, "Extend to end of prev sub word",
347 extend_parent_node_end, "Extend to end of the parent node",
348 extend_parent_node_start, "Extend to beginning of the parent node",
349 find_till_char, "Move till next occurrence of char",
350 find_next_char, "Move to next occurrence of char",
351 extend_till_char, "Extend till next occurrence of char",
352 extend_next_char, "Extend to next occurrence of char",
353 till_prev_char, "Move till previous occurrence of char",
354 find_prev_char, "Move to previous occurrence of char",
355 extend_till_prev_char, "Extend till previous occurrence of char",
356 extend_prev_char, "Extend to previous occurrence of char",
357 repeat_last_motion, "Repeat last motion",
358 replace, "Replace with new char",
359 switch_case, "Switch (toggle) case",
360 switch_to_uppercase, "Switch to uppercase",
361 switch_to_lowercase, "Switch to lowercase",
362 page_up, "Move page up",
363 page_down, "Move page down",
364 half_page_up, "Move half page up",
365 half_page_down, "Move half page down",
366 page_cursor_up, "Move page and cursor up",
367 page_cursor_down, "Move page and cursor down",
368 page_cursor_half_up, "Move page and cursor half up",
369 page_cursor_half_down, "Move page and cursor half down",
370 select_all, "Select whole document",
371 select_regex, "Select all regex matches inside selections",
372 split_selection, "Split selections on regex matches",
373 split_selection_on_newline, "Split selection on newlines",
374 merge_selections, "Merge selections",
375 merge_consecutive_selections, "Merge consecutive selections",
376 search, "Search for regex pattern",
377 rsearch, "Reverse search for regex pattern",
378 search_next, "Select next search match",
379 search_prev, "Select previous search match",
380 extend_search_next, "Add next search match to selection",
381 extend_search_prev, "Add previous search match to selection",
382 search_selection, "Use current selection as search pattern",
383 search_selection_detect_word_boundaries, "Use current selection as the search pattern, automatically wrapping with `\\b` on word boundaries",
384 make_search_word_bounded, "Modify current search to make it word bounded",
385 global_search, "Global search in workspace folder",
386 extend_line, "Select current line, if already selected, extend to another line based on the anchor",
387 extend_line_below, "Select current line, if already selected, extend to next line",
388 extend_line_above, "Select current line, if already selected, extend to previous line",
389 select_line_above, "Select current line, if already selected, extend or shrink line above based on the anchor",
390 select_line_below, "Select current line, if already selected, extend or shrink line below based on the anchor",
391 extend_to_line_bounds, "Extend selection to line bounds",
392 shrink_to_line_bounds, "Shrink selection to line bounds",
393 delete_selection, "Delete selection",
394 delete_selection_noyank, "Delete selection without yanking",
395 change_selection, "Change selection",
396 change_selection_noyank, "Change selection without yanking",
397 collapse_selection, "Collapse selection into single cursor",
398 flip_selections, "Flip selection cursor and anchor",
399 ensure_selections_forward, "Ensure all selections face forward",
400 insert_mode, "Insert before selection",
401 append_mode, "Append after selection",
402 command_mode, "Enter command mode",
403 file_picker, "Open file picker",
404 file_picker_in_current_buffer_directory, "Open file picker at current buffer's directory",
405 file_picker_in_current_directory, "Open file picker at current working directory",
406 file_explorer, "Open file explorer in workspace root",
407 file_explorer_in_current_buffer_directory, "Open file explorer at current buffer's directory",
408 file_explorer_in_current_directory, "Open file explorer at current working directory",
409 code_action, "Perform code action",
410 buffer_picker, "Open buffer picker",
411 jumplist_picker, "Open jumplist picker",
412 symbol_picker, "Open symbol picker",
413 syntax_symbol_picker, "Open symbol picker from syntax information",
414 lsp_or_syntax_symbol_picker, "Open symbol picker from LSP or syntax information",
415 changed_file_picker, "Open changed file picker",
416 select_references_to_symbol_under_cursor, "Select symbol references",
417 workspace_symbol_picker, "Open workspace symbol picker",
418 syntax_workspace_symbol_picker, "Open workspace symbol picker from syntax information",
419 lsp_or_syntax_workspace_symbol_picker, "Open workspace symbol picker from LSP or syntax information",
420 diagnostics_picker, "Open diagnostic picker",
421 workspace_diagnostics_picker, "Open workspace diagnostic picker",
422 last_picker, "Open last picker",
423 insert_at_line_start, "Insert at start of line",
424 insert_at_line_end, "Insert at end of line",
425 open_below, "Open new line below selection",
426 open_above, "Open new line above selection",
427 normal_mode, "Enter normal mode",
428 select_mode, "Enter selection extend mode",
429 exit_select_mode, "Exit selection mode",
430 goto_definition, "Goto definition",
431 goto_declaration, "Goto declaration",
432 add_newline_above, "Add newline above",
433 add_newline_below, "Add newline below",
434 goto_type_definition, "Goto type definition",
435 goto_implementation, "Goto implementation",
436 goto_file_start, "Goto line number `<n>` else file start",
437 goto_file_end, "Goto file end",
438 extend_to_file_start, "Extend to line number `<n>` else file start",
439 extend_to_file_end, "Extend to file end",
440 goto_file, "Goto files/URLs in selections",
441 goto_file_hsplit, "Goto files in selections (hsplit)",
442 goto_file_vsplit, "Goto files in selections (vsplit)",
443 goto_reference, "Goto references",
444 goto_window_top, "Goto window top",
445 goto_window_center, "Goto window center",
446 goto_window_bottom, "Goto window bottom",
447 goto_last_accessed_file, "Goto last accessed file",
448 goto_last_modified_file, "Goto last modified file",
449 goto_last_modification, "Goto last modification",
450 goto_line, "Goto line",
451 goto_last_line, "Goto last line",
452 extend_to_last_line, "Extend to last line",
453 goto_first_diag, "Goto first diagnostic",
454 goto_last_diag, "Goto last diagnostic",
455 goto_next_diag, "Goto next diagnostic",
456 goto_prev_diag, "Goto previous diagnostic",
457 goto_next_change, "Goto next change",
458 goto_prev_change, "Goto previous change",
459 goto_first_change, "Goto first change",
460 goto_last_change, "Goto last change",
461 goto_line_start, "Goto line start",
462 goto_line_end, "Goto line end",
463 goto_column, "Goto column",
464 extend_to_column, "Extend to column",
465 goto_next_buffer, "Goto next buffer",
466 goto_previous_buffer, "Goto previous buffer",
467 goto_line_end_newline, "Goto newline at line end",
468 goto_first_nonwhitespace, "Goto first non-blank in line",
469 trim_selections, "Trim whitespace from selections",
470 extend_to_line_start, "Extend to line start",
471 extend_to_first_nonwhitespace, "Extend to first non-blank in line",
472 extend_to_line_end, "Extend to line end",
473 extend_to_line_end_newline, "Extend to line end",
474 signature_help, "Show signature help",
475 smart_tab, "Insert tab if all cursors have all whitespace to their left; otherwise, run a separate command.",
476 insert_tab, "Insert tab char",
477 insert_newline, "Insert newline char",
478 insert_char_interactive, "Insert an interactively-chosen char",
479 append_char_interactive, "Append an interactively-chosen char",
480 delete_char_backward, "Delete previous char",
481 delete_char_forward, "Delete next char",
482 delete_word_backward, "Delete previous word",
483 delete_word_forward, "Delete next word",
484 kill_to_line_start, "Delete till start of line",
485 kill_to_line_end, "Delete till end of line",
486 undo, "Undo change",
487 redo, "Redo change",
488 earlier, "Move backward in history",
489 later, "Move forward in history",
490 commit_undo_checkpoint, "Commit changes to new checkpoint",
491 yank, "Yank selection",
492 yank_to_clipboard, "Yank selections to clipboard",
493 yank_to_primary_clipboard, "Yank selections to primary clipboard",
494 yank_joined, "Join and yank selections",
495 yank_joined_to_clipboard, "Join and yank selections to clipboard",
496 yank_main_selection_to_clipboard, "Yank main selection to clipboard",
497 yank_joined_to_primary_clipboard, "Join and yank selections to primary clipboard",
498 yank_main_selection_to_primary_clipboard, "Yank main selection to primary clipboard",
499 replace_with_yanked, "Replace with yanked text",
500 replace_selections_with_clipboard, "Replace selections by clipboard content",
501 replace_selections_with_primary_clipboard, "Replace selections by primary clipboard",
502 paste_after, "Paste after selection",
503 paste_before, "Paste before selection",
504 paste_clipboard_after, "Paste clipboard after selections",
505 paste_clipboard_before, "Paste clipboard before selections",
506 paste_primary_clipboard_after, "Paste primary clipboard after selections",
507 paste_primary_clipboard_before, "Paste primary clipboard before selections",
508 indent, "Indent selection",
509 unindent, "Unindent selection",
510 format_selections, "Format selection",
511 join_selections, "Join lines inside selection",
512 join_selections_space, "Join lines inside selection and select spaces",
513 keep_selections, "Keep selections matching regex",
514 remove_selections, "Remove selections matching regex",
515 align_selections, "Align selections in column",
516 keep_primary_selection, "Keep primary selection",
517 remove_primary_selection, "Remove primary selection",
518 completion, "Invoke completion popup",
519 hover, "Show docs for item under cursor",
520 toggle_comments, "Comment/uncomment selections",
521 toggle_line_comments, "Line comment/uncomment selections",
522 toggle_block_comments, "Block comment/uncomment selections",
523 rotate_selections_forward, "Rotate selections forward",
524 rotate_selections_backward, "Rotate selections backward",
525 rotate_selection_contents_forward, "Rotate selection contents forward",
526 rotate_selection_contents_backward, "Rotate selections contents backward",
527 reverse_selection_contents, "Reverse selections contents",
528 expand_selection, "Expand selection to parent syntax node",
529 shrink_selection, "Shrink selection to previously expanded syntax node",
530 select_next_sibling, "Select next sibling in the syntax tree",
531 select_prev_sibling, "Select previous sibling the in syntax tree",
532 select_all_siblings, "Select all siblings of the current node",
533 select_all_children, "Select all children of the current node",
534 jump_forward, "Jump forward on jumplist",
535 jump_backward, "Jump backward on jumplist",
536 save_selection, "Save current selection to jumplist",
537 jump_view_right, "Jump to right split",
538 jump_view_left, "Jump to left split",
539 jump_view_up, "Jump to split above",
540 jump_view_down, "Jump to split below",
541 swap_view_right, "Swap with right split",
542 swap_view_left, "Swap with left split",
543 swap_view_up, "Swap with split above",
544 swap_view_down, "Swap with split below",
545 transpose_view, "Transpose splits",
546 rotate_view, "Goto next window",
547 rotate_view_reverse, "Goto previous window",
548 hsplit, "Horizontal bottom split",
549 hsplit_new, "Horizontal bottom split scratch buffer",
550 vsplit, "Vertical right split",
551 vsplit_new, "Vertical right split scratch buffer",
552 wclose, "Close window",
553 wonly, "Close windows except current",
554 select_register, "Select register",
555 insert_register, "Insert register",
556 copy_between_registers, "Copy between two registers",
557 align_view_middle, "Align view middle",
558 align_view_top, "Align view top",
559 align_view_center, "Align view center",
560 align_view_bottom, "Align view bottom",
561 scroll_up, "Scroll view up",
562 scroll_down, "Scroll view down",
563 match_brackets, "Goto matching bracket",
564 surround_add, "Surround add",
565 surround_replace, "Surround replace",
566 surround_delete, "Surround delete",
567 select_textobject_around, "Select around object",
568 select_textobject_inner, "Select inside object",
569 goto_next_function, "Goto next function",
570 goto_prev_function, "Goto previous function",
571 goto_next_class, "Goto next type definition",
572 goto_prev_class, "Goto previous type definition",
573 goto_next_parameter, "Goto next parameter",
574 goto_prev_parameter, "Goto previous parameter",
575 goto_next_comment, "Goto next comment",
576 goto_prev_comment, "Goto previous comment",
577 goto_next_test, "Goto next test",
578 goto_prev_test, "Goto previous test",
579 goto_next_xml_element, "Goto next (X)HTML element",
580 goto_prev_xml_element, "Goto previous (X)HTML element",
581 goto_next_entry, "Goto next pairing",
582 goto_prev_entry, "Goto previous pairing",
583 goto_next_paragraph, "Goto next paragraph",
584 goto_prev_paragraph, "Goto previous paragraph",
585 dap_launch, "Launch debug target",
586 dap_restart, "Restart debugging session",
587 dap_toggle_breakpoint, "Toggle breakpoint",
588 dap_continue, "Continue program execution",
589 dap_pause, "Pause program execution",
590 dap_step_in, "Step in",
591 dap_step_out, "Step out",
592 dap_next, "Step to next",
593 dap_variables, "List variables",
594 dap_terminate, "End debug session",
595 dap_edit_condition, "Edit breakpoint condition on current line",
596 dap_edit_log, "Edit breakpoint log message on current line",
597 dap_switch_thread, "Switch current thread",
598 dap_switch_stack_frame, "Switch stack frame",
599 dap_enable_exceptions, "Enable exception breakpoints",
600 dap_disable_exceptions, "Disable exception breakpoints",
601 shell_pipe, "Pipe selections through shell command",
602 shell_pipe_to, "Pipe selections into shell command ignoring output",
603 shell_insert_output, "Insert shell command output before selections",
604 shell_append_output, "Append shell command output after selections",
605 shell_keep_pipe, "Filter selections with shell predicate",
606 suspend, "Suspend and return to shell",
607 rename_symbol, "Rename symbol",
608 increment, "Increment item under cursor",
609 decrement, "Decrement item under cursor",
610 record_macro, "Record macro",
611 replay_macro, "Replay macro",
612 command_palette, "Open command palette",
613 goto_word, "Jump to a two-character label",
614 extend_to_word, "Extend to a two-character label",
615 goto_next_tabstop, "Goto next snippet placeholder",
616 goto_prev_tabstop, "Goto next snippet placeholder",
617 rotate_selections_first, "Make the first selection your primary one",
618 rotate_selections_last, "Make the last selection your primary one",
619 );
620 }
621
622 impl fmt::Debug for MappableCommand {
623 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
624 match self {
625 MappableCommand::Static { name, .. } => {
626 f.debug_tuple("MappableCommand").field(name).finish()
627 }
628 MappableCommand::Typable { name, args, .. } => f
629 .debug_tuple("MappableCommand")
630 .field(name)
631 .field(args)
632 .finish(),
633 MappableCommand::Macro { name, keys, .. } => f
634 .debug_tuple("MappableCommand")
635 .field(name)
636 .field(keys)
637 .finish(),
638 }
639 }
640 }
641
642 impl fmt::Display for MappableCommand {
643 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
644 f.write_str(self.name())
645 }
646 }
647
648 impl std::str::FromStr for MappableCommand {
649 type Err = anyhow::Error;
650
651 fn from_str(s: &str) -> Result<Self, Self::Err> {
652 if let Some(suffix) = s.strip_prefix(':') {
653 let (name, args, _) = command_line::split(suffix);
654 ensure!(!name.is_empty(), "Expected typable command name");
655 typed::TYPABLE_COMMAND_MAP
656 .get(name)
657 .map(|cmd| {
658 let doc = if args.is_empty() {
659 cmd.doc.to_string()
660 } else {
661 format!(":{} {:?}", cmd.name, args)
662 };
663 MappableCommand::Typable {
664 name: cmd.name.to_owned(),
665 doc,
666 args: args.to_string(),
667 }
668 })
669 .ok_or_else(|| anyhow!("No TypableCommand named '{}'", s))
670 } else if let Some(suffix) = s.strip_prefix('@') {
671 helix_view::input::parse_macro(suffix).map(|keys| Self::Macro {
672 name: s.to_string(),
673 keys,
674 })
675 } else {
676 MappableCommand::STATIC_COMMAND_LIST
677 .iter()
678 .find(|cmd| cmd.name() == s)
679 .cloned()
680 .ok_or_else(|| anyhow!("No command named '{}'", s))
681 }
682 }
683 }
684
685 impl<'de> Deserialize<'de> for MappableCommand {
686 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
687 where
688 D: Deserializer<'de>,
689 {
690 let s = String::deserialize(deserializer)?;
691 s.parse().map_err(de::Error::custom)
692 }
693 }
694
695 impl PartialEq for MappableCommand {
696 fn eq(&self, other: &Self) -> bool {
697 match (self, other) {
698 (
699 MappableCommand::Typable {
700 name: first_name,
701 args: first_args,
702 ..
703 },
704 MappableCommand::Typable {
705 name: second_name,
706 args: second_args,
707 ..
708 },
709 ) => first_name == second_name && first_args == second_args,
710 (
711 MappableCommand::Static {
712 name: first_name, ..
713 },
714 MappableCommand::Static {
715 name: second_name, ..
716 },
717 ) => first_name == second_name,
718 _ => false,
719 }
720 }
721 }
722
723 fn no_op(_cx: &mut Context) {}
724
725 type MoveFn =
726 fn(RopeSlice, Range, Direction, usize, Movement, &TextFormat, &mut TextAnnotations) -> Range;
727
728 fn move_impl(cx: &mut Context, move_fn: MoveFn, dir: Direction, behaviour: Movement) {
729 let count = cx.count();
730 let (view, doc) = current!(cx.editor);
731 let text = doc.text().slice(..);
732 let text_fmt = doc.text_format(view.inner_area(doc).width, None);
733 let mut annotations = view.text_annotations(doc, None);
734
735 let selection = doc.selection(view.id).clone().transform(|range| {
736 move_fn(
737 text,
738 range,
739 dir,
740 count,
741 behaviour,
742 &text_fmt,
743 &mut annotations,
744 )
745 });
746 drop(annotations);
747 doc.set_selection(view.id, selection);
748 }
749
750 use helix_core::movement::{move_horizontally, move_vertically};
751
752 fn move_char_left(cx: &mut Context) {
753 move_impl(cx, move_horizontally, Direction::Backward, Movement::Move)
754 }
755
756 fn move_char_right(cx: &mut Context) {
757 move_impl(cx, move_horizontally, Direction::Forward, Movement::Move)
758 }
759
760 fn move_line_up(cx: &mut Context) {
761 move_impl(cx, move_vertically, Direction::Backward, Movement::Move)
762 }
763
764 fn move_line_down(cx: &mut Context) {
765 move_impl(cx, move_vertically, Direction::Forward, Movement::Move)
766 }
767
768 fn move_visual_line_up(cx: &mut Context) {
769 move_impl(
770 cx,
771 move_vertically_visual,
772 Direction::Backward,
773 Movement::Move,
774 )
775 }
776
777 fn move_visual_line_down(cx: &mut Context) {
778 move_impl(
779 cx,
780 move_vertically_visual,
781 Direction::Forward,
782 Movement::Move,
783 )
784 }
785
786 fn extend_char_left(cx: &mut Context) {
787 move_impl(cx, move_horizontally, Direction::Backward, Movement::Extend)
788 }
789
790 fn extend_char_right(cx: &mut Context) {
791 move_impl(cx, move_horizontally, Direction::Forward, Movement::Extend)
792 }
793
794 fn extend_line_up(cx: &mut Context) {
795 move_impl(cx, move_vertically, Direction::Backward, Movement::Extend)
796 }
797
798 fn extend_line_down(cx: &mut Context) {
799 move_impl(cx, move_vertically, Direction::Forward, Movement::Extend)
800 }
801
802 fn extend_visual_line_up(cx: &mut Context) {
803 move_impl(
804 cx,
805 move_vertically_visual,
806 Direction::Backward,
807 Movement::Extend,
808 )
809 }
810
811 fn extend_visual_line_down(cx: &mut Context) {
812 move_impl(
813 cx,
814 move_vertically_visual,
815 Direction::Forward,
816 Movement::Extend,
817 )
818 }
819
820 fn goto_line_end_impl(view: &mut View, doc: &mut Document, movement: Movement) {
821 let text = doc.text().slice(..);
822
823 let selection = doc.selection(view.id).clone().transform(|range| {
824 let line = range.cursor_line(text);
825 let line_start = text.line_to_char(line);
826
827 let pos = graphemes::prev_grapheme_boundary(text, line_end_char_index(&text, line))
828 .max(line_start);
829
830 range.put_cursor(text, pos, movement == Movement::Extend)
831 });
832 doc.set_selection(view.id, selection);
833 }
834
835 fn goto_line_end(cx: &mut Context) {
836 let (view, doc) = current!(cx.editor);
837 goto_line_end_impl(
838 view,
839 doc,
840 if cx.editor.mode == Mode::Select {
841 Movement::Extend
842 } else {
843 Movement::Move
844 },
845 )
846 }
847
848 fn extend_to_line_end(cx: &mut Context) {
849 let (view, doc) = current!(cx.editor);
850 goto_line_end_impl(view, doc, Movement::Extend)
851 }
852
853 fn goto_line_end_newline_impl(view: &mut View, doc: &mut Document, movement: Movement) {
854 let text = doc.text().slice(..);
855
856 let selection = doc.selection(view.id).clone().transform(|range| {
857 let line = range.cursor_line(text);
858 let pos = line_end_char_index(&text, line);
859
860 range.put_cursor(text, pos, movement == Movement::Extend)
861 });
862 doc.set_selection(view.id, selection);
863 }
864
865 fn goto_line_end_newline(cx: &mut Context) {
866 let (view, doc) = current!(cx.editor);
867 goto_line_end_newline_impl(
868 view,
869 doc,
870 if cx.editor.mode == Mode::Select {
871 Movement::Extend
872 } else {
873 Movement::Move
874 },
875 )
876 }
877
878 fn extend_to_line_end_newline(cx: &mut Context) {
879 let (view, doc) = current!(cx.editor);
880 goto_line_end_newline_impl(view, doc, Movement::Extend)
881 }
882
883 fn goto_line_start_impl(view: &mut View, doc: &mut Document, movement: Movement) {
884 let text = doc.text().slice(..);
885
886 let selection = doc.selection(view.id).clone().transform(|range| {
887 let line = range.cursor_line(text);
888
889 // adjust to start of the line
890 let pos = text.line_to_char(line);
891 range.put_cursor(text, pos, movement == Movement::Extend)
892 });
893 doc.set_selection(view.id, selection);
894 }
895
896 fn goto_line_start(cx: &mut Context) {
897 let (view, doc) = current!(cx.editor);
898 goto_line_start_impl(
899 view,
900 doc,
901 if cx.editor.mode == Mode::Select {
902 Movement::Extend
903 } else {
904 Movement::Move
905 },
906 )
907 }
908
909 fn goto_next_buffer(cx: &mut Context) {
910 goto_buffer(cx.editor, Direction::Forward, cx.count());
911 }
912
913 fn goto_previous_buffer(cx: &mut Context) {
914 goto_buffer(cx.editor, Direction::Backward, cx.count());
915 }
916
917 fn goto_buffer(editor: &mut Editor, direction: Direction, count: usize) {
918 let current = view!(editor).doc;
919
920 let id = match direction {
921 Direction::Forward => {
922 let iter = editor.documents.keys();
923 // skip 'count' times past current buffer
924 iter.cycle().skip_while(|id| *id != &current).nth(count)
925 }
926 Direction::Backward => {
927 let iter = editor.documents.keys();
928 // skip 'count' times past current buffer
929 iter.rev()
930 .cycle()
931 .skip_while(|id| *id != &current)
932 .nth(count)
933 }
934 }
935 .unwrap();
936
937 let id = *id;
938
939 editor.switch(id, Action::Replace);
940 }
941
942 fn extend_to_line_start(cx: &mut Context) {
943 let (view, doc) = current!(cx.editor);
944 goto_line_start_impl(view, doc, Movement::Extend)
945 }
946
947 fn kill_to_line_start(cx: &mut Context) {
948 delete_by_selection_insert_mode(
949 cx,
950 move |text, range| {
951 let line = range.cursor_line(text);
952 let first_char = text.line_to_char(line);
953 let anchor = range.cursor(text);
954 let head = if anchor == first_char && line != 0 {
955 // select until previous line
956 line_end_char_index(&text, line - 1)
957 } else if let Some(pos) = text.line(line).first_non_whitespace_char() {
958 if first_char + pos < anchor {
959 // select until first non-blank in line if cursor is after it
960 first_char + pos
961 } else {
962 // select until start of line
963 first_char
964 }
965 } else {
966 // select until start of line
967 first_char
968 };
969 (head, anchor)
970 },
971 Direction::Backward,
972 );
973 }
974
975 fn kill_to_line_end(cx: &mut Context) {
976 delete_by_selection_insert_mode(
977 cx,
978 |text, range| {
979 let line = range.cursor_line(text);
980 let line_end_pos = line_end_char_index(&text, line);
981 let pos = range.cursor(text);
982
983 // if the cursor is on the newline char delete that
984 if pos == line_end_pos {
985 (pos, text.line_to_char(line + 1))
986 } else {
987 (pos, line_end_pos)
988 }
989 },
990 Direction::Forward,
991 );
992 }
993
994 fn goto_first_nonwhitespace(cx: &mut Context) {
995 let (view, doc) = current!(cx.editor);
996
997 goto_first_nonwhitespace_impl(
998 view,
999 doc,
1000 if cx.editor.mode == Mode::Select {
1001 Movement::Extend
1002 } else {
1003 Movement::Move
1004 },
1005 )
1006 }
1007
1008 fn extend_to_first_nonwhitespace(cx: &mut Context) {
1009 let (view, doc) = current!(cx.editor);
1010 goto_first_nonwhitespace_impl(view, doc, Movement::Extend)
1011 }
1012
1013 fn goto_first_nonwhitespace_impl(view: &mut View, doc: &mut Document, movement: Movement) {
1014 let text = doc.text().slice(..);
1015
1016 let selection = doc.selection(view.id).clone().transform(|range| {
1017 let line = range.cursor_line(text);
1018
1019 if let Some(pos) = text.line(line).first_non_whitespace_char() {
1020 let pos = pos + text.line_to_char(line);
1021 range.put_cursor(text, pos, movement == Movement::Extend)
1022 } else {
1023 range
1024 }
1025 });
1026 doc.set_selection(view.id, selection);
1027 }
1028
1029 fn trim_selections(cx: &mut Context) {
1030 let (view, doc) = current!(cx.editor);
1031 let text = doc.text().slice(..);
1032
1033 let ranges: SmallVec<[Range; 1]> = doc
1034 .selection(view.id)
1035 .iter()
1036 .filter_map(|range| {
1037 if range.is_empty() || range.slice(text).chars().all(|ch| ch.is_whitespace()) {
1038 return None;
1039 }
1040 let mut start = range.from();
1041 let mut end = range.to();
1042 start = movement::skip_while(text, start, |x| x.is_whitespace()).unwrap_or(start);
1043 end = movement::backwards_skip_while(text, end, |x| x.is_whitespace()).unwrap_or(end);
1044 Some(Range::new(start, end).with_direction(range.direction()))
1045 })
1046 .collect();
1047
1048 if !ranges.is_empty() {
1049 let primary = doc.selection(view.id).primary();
1050 let idx = ranges
1051 .iter()
1052 .position(|range| range.overlaps(&primary))
1053 .unwrap_or(ranges.len() - 1);
1054 doc.set_selection(view.id, Selection::new(ranges, idx));
1055 } else {
1056 collapse_selection(cx);
1057 keep_primary_selection(cx);
1058 };
1059 }
1060
1061 // align text in selection
1062 #[allow(deprecated)]
1063 fn align_selections(cx: &mut Context) {
1064 use helix_core::visual_coords_at_pos;
1065
1066 let (view, doc) = current!(cx.editor);
1067 let text = doc.text().slice(..);
1068 let selection = doc.selection(view.id);
1069
1070 let tab_width = doc.tab_width();
1071
1072 let mut column_widths: Vec<usize> = Vec::new();
1073 let mut coordinates = Vec::with_capacity(selection.len());
1074
1075 let mut previous_line = usize::MAX;
1076 let mut col_idx = 0;
1077 let mut running_offset = 0;
1078
1079 for range in selection {
1080 let coords = visual_coords_at_pos(text, range.head, tab_width);
1081 let anchor_coords = visual_coords_at_pos(text, range.anchor, tab_width);
1082
1083 if coords.row != anchor_coords.row {
1084 cx.editor
1085 .set_error("align cannot work with multi line selections");
1086 return;
1087 }
1088 if coords.row != previous_line {
1089 col_idx = 0;
1090 running_offset = 0;
1091 previous_line = coords.row;
1092 }
1093
1094 let width = coords.col - running_offset;
1095
1096 match column_widths.get_mut(col_idx) {
1097 Some(n) => *n = (*n).max(width),
1098 None => column_widths.push(width),
1099 }
1100
1101 coordinates.push(coords);
1102
1103 running_offset += width;
1104 col_idx += 1;
1105 }
1106
1107 let column_positions: Vec<_> = column_widths
1108 .into_iter()
1109 .scan(0, |sum, n| {
1110 *sum += n;
1111 Some(*sum)
1112 })
1113 .collect();
1114
1115 previous_line = usize::MAX;
1116
1117 let changes = coordinates
1118 .into_iter()
1119 .zip(selection)
1120 .map(|(coords, range)| {
1121 if coords.row != previous_line {
1122 col_idx = 0;
1123 running_offset = 0;
1124 previous_line = coords.row;
1125 }
1126 let current_inserts = column_positions[col_idx] - coords.col - running_offset;
1127 let insert_pos = range.from();
1128
1129 col_idx += 1;
1130 running_offset += current_inserts;
1131
1132 (
1133 insert_pos,
1134 insert_pos,
1135 Some(" ".repeat(current_inserts).into()),
1136 )
1137 });
1138
1139 let transaction = Transaction::change(doc.text(), changes);
1140 doc.apply(&transaction, view.id);
1141 exit_select_mode(cx);
1142 }
1143
1144 fn goto_window(cx: &mut Context, align: Align) {
1145 let count = cx.count() - 1;
1146 let config = cx.editor.config();
1147 let (view, doc) = current!(cx.editor);
1148 let view_offset = doc.view_offset(view.id);
1149
1150 let height = view.inner_height();
1151
1152 // respect user given count if any
1153 // - 1 so we have at least one gap in the middle.
1154 // a height of 6 with padding of 3 on each side will keep shifting the view back and forth
1155 // as we type
1156 let scrolloff = config.scrolloff.min(height.saturating_sub(1) / 2);
1157
1158 let last_visual_line = view.last_visual_line(doc);
1159
1160 let visual_line = match align {
1161 Align::Top => view_offset.vertical_offset + scrolloff + count,
1162 Align::Center => view_offset.vertical_offset + (last_visual_line / 2),
1163 Align::Bottom => {
1164 view_offset.vertical_offset + last_visual_line.saturating_sub(scrolloff + count)
1165 }
1166 };
1167 let visual_line = visual_line
1168 .max(view_offset.vertical_offset + scrolloff)
1169 .min(view_offset.vertical_offset + last_visual_line.saturating_sub(scrolloff));
1170
1171 let pos = view
1172 .pos_at_visual_coords(doc, visual_line as u16, 0, false)
1173 .expect("visual_line was constrained to the view area");
1174
1175 let text = doc.text().slice(..);
1176 let selection = doc
1177 .selection(view.id)
1178 .clone()
1179 .transform(|range| range.put_cursor(text, pos, cx.editor.mode == Mode::Select));
1180 doc.set_selection(view.id, selection);
1181 }
1182
1183 fn goto_window_top(cx: &mut Context) {
1184 goto_window(cx, Align::Top)
1185 }
1186
1187 fn goto_window_center(cx: &mut Context) {
1188 goto_window(cx, Align::Center)
1189 }
1190
1191 fn goto_window_bottom(cx: &mut Context) {
1192 goto_window(cx, Align::Bottom)
1193 }
1194
1195 fn move_word_impl<F>(cx: &mut Context, move_fn: F)
1196 where
1197 F: Fn(RopeSlice, Range, usize) -> Range,
1198 {
1199 let count = cx.count();
1200 let (view, doc) = current!(cx.editor);
1201 let text = doc.text().slice(..);
1202
1203 let selection = doc
1204 .selection(view.id)
1205 .clone()
1206 .transform(|range| move_fn(text, range, count));
1207 doc.set_selection(view.id, selection);
1208 }
1209
1210 fn move_next_word_start(cx: &mut Context) {
1211 move_word_impl(cx, movement::move_next_word_start)
1212 }
1213
1214 fn move_prev_word_start(cx: &mut Context) {
1215 move_word_impl(cx, movement::move_prev_word_start)
1216 }
1217
1218 fn move_prev_word_end(cx: &mut Context) {
1219 move_word_impl(cx, movement::move_prev_word_end)
1220 }
1221
1222 fn move_next_word_end(cx: &mut Context) {
1223 move_word_impl(cx, movement::move_next_word_end)
1224 }
1225
1226 fn move_next_long_word_start(cx: &mut Context) {
1227 move_word_impl(cx, movement::move_next_long_word_start)
1228 }
1229
1230 fn move_prev_long_word_start(cx: &mut Context) {
1231 move_word_impl(cx, movement::move_prev_long_word_start)
1232 }
1233
1234 fn move_prev_long_word_end(cx: &mut Context) {
1235 move_word_impl(cx, movement::move_prev_long_word_end)
1236 }
1237
1238 fn move_next_long_word_end(cx: &mut Context) {
1239 move_word_impl(cx, movement::move_next_long_word_end)
1240 }
1241
1242 fn move_next_sub_word_start(cx: &mut Context) {
1243 move_word_impl(cx, movement::move_next_sub_word_start)
1244 }
1245
1246 fn move_prev_sub_word_start(cx: &mut Context) {
1247 move_word_impl(cx, movement::move_prev_sub_word_start)
1248 }
1249
1250 fn move_prev_sub_word_end(cx: &mut Context) {
1251 move_word_impl(cx, movement::move_prev_sub_word_end)
1252 }
1253
1254 fn move_next_sub_word_end(cx: &mut Context) {
1255 move_word_impl(cx, movement::move_next_sub_word_end)
1256 }
1257
1258 fn goto_para_impl<F>(cx: &mut Context, move_fn: F)
1259 where
1260 F: Fn(RopeSlice, Range, usize, Movement) -> Range + 'static,
1261 {
1262 let count = cx.count();
1263 let motion = move |editor: &mut Editor| {
1264 let (view, doc) = current!(editor);
1265 let text = doc.text().slice(..);
1266 let behavior = if editor.mode == Mode::Select {
1267 Movement::Extend
1268 } else {
1269 Movement::Move
1270 };
1271
1272 let selection = doc
1273 .selection(view.id)
1274 .clone()
1275 .transform(|range| move_fn(text, range, count, behavior));
1276 doc.set_selection(view.id, selection);
1277 };
1278 cx.editor.apply_motion(motion)
1279 }
1280
1281 fn goto_prev_paragraph(cx: &mut Context) {
1282 goto_para_impl(cx, movement::move_prev_paragraph)
1283 }
1284
1285 fn goto_next_paragraph(cx: &mut Context) {
1286 goto_para_impl(cx, movement::move_next_paragraph)
1287 }
1288
1289 fn goto_file_start(cx: &mut Context) {
1290 goto_file_start_impl(cx, Movement::Move);
1291 }
1292
1293 fn extend_to_file_start(cx: &mut Context) {
1294 goto_file_start_impl(cx, Movement::Extend);
1295 }
1296
1297 fn goto_file_start_impl(cx: &mut Context, movement: Movement) {
1298 if cx.count.is_some() {
1299 goto_line_impl(cx, movement);
1300 } else {
1301 let (view, doc) = current!(cx.editor);
1302 let text = doc.text().slice(..);
1303 let selection = doc
1304 .selection(view.id)
1305 .clone()
1306 .transform(|range| range.put_cursor(text, 0, movement == Movement::Extend));
1307 push_jump(view, doc);
1308 doc.set_selection(view.id, selection);
1309 }
1310 }
1311
1312 fn goto_file_end(cx: &mut Context) {
1313 goto_file_end_impl(cx, Movement::Move);
1314 }
1315
1316 fn extend_to_file_end(cx: &mut Context) {
1317 goto_file_end_impl(cx, Movement::Extend)
1318 }
1319
1320 fn goto_file_end_impl(cx: &mut Context, movement: Movement) {
1321 let (view, doc) = current!(cx.editor);
1322 let text = doc.text().slice(..);
1323 let pos = doc.text().len_chars();
1324 let selection = doc
1325 .selection(view.id)
1326 .clone()
1327 .transform(|range| range.put_cursor(text, pos, movement == Movement::Extend));
1328 push_jump(view, doc);
1329 doc.set_selection(view.id, selection);
1330 }
1331
1332 fn goto_file(cx: &mut Context) {
1333 goto_file_impl(cx, Action::Replace);
1334 }
1335
1336 fn goto_file_hsplit(cx: &mut Context) {
1337 goto_file_impl(cx, Action::HorizontalSplit);
1338 }
1339
1340 fn goto_file_vsplit(cx: &mut Context) {
1341 goto_file_impl(cx, Action::VerticalSplit);
1342 }
1343
1344 /// Returns true when a selection overlaps an LSP document link range.
1345 fn selection_overlaps_document_link(
1346 selection: &Range,
1347 link: &helix_view::document::DocumentLink,
1348 ) -> bool {
1349 if selection.is_empty() {
1350 let pos = selection.from();
1351 link.start <= pos && pos < link.end
1352 } else {
1353 selection.from() < link.end && selection.to() > link.start
1354 }
1355 }
1356
1357 /// Create a document link resolve request when the target isn't already present.
1358 ///
1359 /// This only builds the LSP request. The request is awaited from a background
1360 /// job so `goto_file_impl` does not block the UI thread while the language
1361 /// server resolves the target.
1362 fn resolve_document_link_request(
1363 editor: &Editor,
1364 link: &helix_view::document::DocumentLink,
1365 ) -> Option<impl Future<Output = helix_lsp::Result<helix_lsp::lsp::DocumentLink>> + Send + 'static>
1366 {
1367 let language_server = editor.language_server_by_id(link.language_server_id)?;
1368 let supports_resolve = language_server
1369 .capabilities()
1370 .document_link_provider
1371 .as_ref()?
1372 .resolve_provider
1373 .unwrap_or(false);
1374
1375 if !supports_resolve {
1376 return None;
1377 }
1378
1379 language_server.resolve_document_link(link.link.clone())
1380 }
1381
1382 /// Goto files/URLs in selection.
1383 ///
1384 /// Prefers LSP document links when the cursor/selection overlaps a link range,
1385 /// falling back to the built-in path/URL detection otherwise.
1386 fn goto_file_impl(cx: &mut Context, action: Action) {
1387 let (view, doc) = current_ref!(cx.editor);
1388 let text = doc.text().clone();
1389 let selections = doc.selection(view.id).ranges().to_vec();
1390 let rel_path = doc
1391 .relative_path()
1392 .map(|path| path.parent().unwrap().to_path_buf())
1393 .unwrap_or_default();
1394 let text = text.slice(..);
1395
1396 let mut lsp_targets = Vec::new();
1397 let mut lsp_targets_seen = HashSet::new();
1398 let mut unresolved_links = HashSet::new();
1399 let mut resolve_requests = Vec::new();
1400 let mut fallback_ranges = Vec::new();
1401
1402 if doc.document_links.is_empty() {
1403 fallback_ranges.extend_from_slice(&selections);
1404 } else {
1405 for selection in &selections {
1406 let mut matched = false;
1407 for link in &doc.document_links {
1408 if !selection_overlaps_document_link(selection, link) {
1409 continue;
1410 }
1411 matched = true;
1412 if let Some(target) = link.link.target.clone() {
1413 if lsp_targets_seen.insert(target.clone()) {
1414 lsp_targets.push(target);
1415 }
1416 } else if unresolved_links.insert((link.start, link.end, link.language_server_id)) {
1417 if let Some(request) = resolve_document_link_request(cx.editor, link) {
1418 resolve_requests.push(request);
1419 }
1420 }
1421 }
1422 if !matched {
1423 fallback_ranges.push(*selection);
1424 }
1425 }
1426 }
1427
1428 for target in lsp_targets {
1429 open_url(cx, target, action);
1430 }
1431
1432 if !resolve_requests.is_empty() {
1433 let rel_path = rel_path.clone();
1434 cx.jobs.callback(async move {
1435 let mut targets = Vec::new();
1436 let mut seen = HashSet::new();
1437
1438 // Resolve links off the main thread, then hand the resulting URLs
1439 // back to the editor/compositor callback once all requests finish.
1440 for request in resolve_requests {
1441 match request.await {
1442 Ok(link) => {
1443 if let Some(target) = link.target {
1444 if seen.insert(target.clone()) {
1445 targets.push(target);
1446 }
1447 }
1448 }
1449 Err(err) => log::warn!("Failed to resolve document link: {err}"),
1450 }
1451 }
1452
1453 Ok(Callback::EditorCompositor(Box::new(
1454 move |editor, compositor| {
1455 for target in targets {
1456 open_url_in_callback(editor, compositor, target, action, &rel_path);
1457 }
1458 },
1459 )))
1460 });
1461 }
1462
1463 if fallback_ranges.is_empty() {
1464 return;
1465 }
1466
1467 let paths: Vec<_> = if fallback_ranges.len() == 1 && fallback_ranges[0].len() == 1 {
1468 let selection = fallback_ranges[0];
1469 // Cap the search at roughly 1k bytes around the cursor.
1470 let lookaround = 1000;
1471 let pos = text.char_to_byte(selection.cursor(text));
1472 let search_start = text
1473 .line_to_byte(text.byte_to_line(pos))
1474 .max(text.floor_char_boundary(pos.saturating_sub(lookaround)));
1475 let search_end = text
1476 .line_to_byte(text.byte_to_line(pos) + 1)
1477 .min(text.ceil_char_boundary(pos + lookaround));
1478 let search_range = text.byte_slice(search_start..search_end);
1479 // we also allow paths that are next to the cursor (can be ambiguous but
1480 // rarely so in practice) so that gf on quoted/braced path works (not sure about this
1481 // but apparently that is how gf has worked historically in helix)
1482 let path = find_paths(search_range, true)
1483 .take_while(|range| search_start + range.start <= pos + 1)
1484 .find(|range| pos <= search_start + range.end)
1485 .map(|range| Cow::from(search_range.byte_slice(range)));
1486 log::debug!("goto_file auto-detected path: {path:?}");
1487 let path = path.unwrap_or_else(|| selection.fragment(text));
1488 vec![path.into_owned()]
1489 } else {
1490 // Otherwise use each selection, trimmed.
1491 fallback_ranges
1492 .iter()
1493 .map(|range| range.fragment(text).trim().to_owned())
1494 .filter(|sel| !sel.is_empty())
1495 .collect()
1496 };
1497
1498 for sel in paths {
1499 if let Ok(url) = Url::parse(&sel) {
1500 open_url(cx, url, action);
1501 continue;
1502 }
1503
1504 let path = path::expand(&sel);
1505 let path = &rel_path.join(path);
1506 if path.is_dir() {
1507 let picker = ui::file_picker(cx.editor, path.into());
1508 cx.push_layer(Box::new(overlaid(picker)));
1509 } else if let Err(e) = cx.editor.open(path, action) {
1510 cx.editor.set_error(format!("Open file failed: {:?}", e));
1511 }
1512 }
1513 }
1514
1515 /// Opens the given url. If the URL points to a valid textual file it is open in helix.
1516 /// Otherwise, the file is open using external program.
1517 fn open_url(cx: &mut Context, url: Url, action: Action) {
1518 let doc = doc!(cx.editor);
1519 let rel_path = doc
1520 .relative_path()
1521 .map(|path| path.parent().unwrap().to_path_buf())
1522 .unwrap_or_default();
1523
1524 if should_open_url_externally(&url) {
1525 return cx.jobs.callback(crate::open_external_url_callback(url));
1526 }
1527
1528 let path = &rel_path.join(url.path());
1529 if path.is_dir() {
1530 let picker = ui::file_picker(cx.editor, path.into());
1531 cx.push_layer(Box::new(overlaid(picker)));
1532 } else if let Err(e) = cx.editor.open(path, action) {
1533 cx.editor.set_error(format!("Open file failed: {:?}", e));
1534 }
1535 }
1536
1537 /// Open a URL from an editor/compositor callback.
1538 ///
1539 /// This mirrors `open_url` but does not require a full `Context`, which makes
1540 /// it usable from async job completions such as deferred document link
1541 /// resolves.
1542 fn open_url_in_callback(
1543 editor: &mut Editor,
1544 compositor: &mut Compositor,
1545 url: Url,
1546 action: Action,
1547 rel_path: &Path,
1548 ) {
1549 if should_open_url_externally(&url) {
1550 tokio::spawn(async move {
1551 match crate::open_external_url_callback(url).await {
1552 Ok(callback) => job::dispatch_callback(callback).await,
1553 Err(err) => status::report(err).await,
1554 }
1555 });
1556 return;
1557 }
1558
1559 let path = &rel_path.join(url.path());
1560 if path.is_dir() {
1561 let picker = ui::file_picker(editor, path.into());
1562 compositor.push(Box::new(overlaid(picker)));
1563 } else if let Err(e) = editor.open(path, action) {
1564 editor.set_error(format!("Open file failed: {:?}", e));
1565 }
1566 }
1567
1568 /// Returns whether a URL should opened externally.
1569 ///
1570 /// Non-`file` URLs always open externally. `file` URLs are opened externally
1571 /// only when the target looks like a binary file (a non-textual file that can't
1572 /// be viewed in helix).
1573 fn should_open_url_externally(url: &Url) -> bool {
1574 if url.scheme() != "file" {
1575 return true;
1576 }
1577
1578 let is_binary = std::fs::File::open(url.path()).and_then(|file| {
1579 // Read up to 1kb to detect the content type
1580 let mut read_buffer = Vec::new();
1581 let n = file.take(1024).read_to_end(&mut read_buffer)?;
1582 Ok(crate::is_binary(&read_buffer[..n]))
1583 });
1584
1585 matches!(is_binary, Ok(true))
1586 }
1587
1588 fn extend_word_impl<F>(cx: &mut Context, extend_fn: F)
1589 where
1590 F: Fn(RopeSlice, Range, usize) -> Range,
1591 {
1592 let count = cx.count();
1593 let (view, doc) = current!(cx.editor);
1594 let text = doc.text().slice(..);
1595
1596 let selection = doc.selection(view.id).clone().transform(|range| {
1597 let word = extend_fn(text, range, count);
1598 let pos = word.cursor(text);
1599 range.put_cursor(text, pos, true)
1600 });
1601 doc.set_selection(view.id, selection);
1602 }
1603
1604 fn extend_next_word_start(cx: &mut Context) {
1605 extend_word_impl(cx, movement::move_next_word_start)
1606 }
1607
1608 fn extend_prev_word_start(cx: &mut Context) {
1609 extend_word_impl(cx, movement::move_prev_word_start)
1610 }
1611
1612 fn extend_next_word_end(cx: &mut Context) {
1613 extend_word_impl(cx, movement::move_next_word_end)
1614 }
1615
1616 fn extend_prev_word_end(cx: &mut Context) {
1617 extend_word_impl(cx, movement::move_prev_word_end)
1618 }
1619
1620 fn extend_next_long_word_start(cx: &mut Context) {
1621 extend_word_impl(cx, movement::move_next_long_word_start)
1622 }
1623
1624 fn extend_prev_long_word_start(cx: &mut Context) {
1625 extend_word_impl(cx, movement::move_prev_long_word_start)
1626 }
1627
1628 fn extend_prev_long_word_end(cx: &mut Context) {
1629 extend_word_impl(cx, movement::move_prev_long_word_end)
1630 }
1631
1632 fn extend_next_long_word_end(cx: &mut Context) {
1633 extend_word_impl(cx, movement::move_next_long_word_end)
1634 }
1635
1636 fn extend_next_sub_word_start(cx: &mut Context) {
1637 extend_word_impl(cx, movement::move_next_sub_word_start)
1638 }
1639
1640 fn extend_prev_sub_word_start(cx: &mut Context) {
1641 extend_word_impl(cx, movement::move_prev_sub_word_start)
1642 }
1643
1644 fn extend_prev_sub_word_end(cx: &mut Context) {
1645 extend_word_impl(cx, movement::move_prev_sub_word_end)
1646 }
1647
1648 fn extend_next_sub_word_end(cx: &mut Context) {
1649 extend_word_impl(cx, movement::move_next_sub_word_end)
1650 }
1651
1652 /// Separate branch to find_char designed only for `<ret>` char.
1653 //
1654 // This is necessary because the one document can have different line endings inside. And we
1655 // cannot predict what character to find when <ret> is pressed. On the current line it can be `lf`
1656 // but on the next line it can be `crlf`. That's why [`find_char_impl`] cannot be applied here.
1657 fn find_char_line_ending_motion(
1658 editor: &mut Editor,
1659 count: usize,
1660 direction: Direction,
1661 inclusive: bool,
1662 extend: bool,
1663 ) {
1664 let (view, doc) = current!(editor);
1665 let text = doc.text().slice(..);
1666
1667 let selection = doc.selection(view.id).clone().transform(|range| {
1668 let cursor_anchor = range.cursor(text);
1669 let cursor_head = next_grapheme_boundary(text, cursor_anchor);
1670 let cursor_line = range.cursor_line(text);
1671
1672 let pos = match direction {
1673 Direction::Forward => {
1674 let line_end = line_end_char_index(&text, cursor_line);
1675 let on_edge = if inclusive {
1676 line_end == cursor_anchor
1677 } else {
1678 line_end == cursor_head || line_end == cursor_anchor
1679 };
1680 let line = cursor_line + count - 1 + on_edge as usize;
1681 if line >= text.len_lines() - 1 {
1682 return range;
1683 }
1684 line_end_char_index(&text, line) - !inclusive as usize
1685 }
1686 Direction::Backward => {
1687 if inclusive {
1688 let line = cursor_line as isize - count as isize;
1689 if line < 0 {
1690 return range;
1691 }
1692 line_end_char_index(&text, line as usize)
1693 } else {
1694 let on_edge = text.line_to_char(cursor_line) == cursor_anchor;
1695 let line = cursor_line as isize - count as isize + 1 - on_edge as isize;
1696 if line <= 0 {
1697 return range;
1698 }
1699 text.line_to_char(line as usize)
1700 }
1701 }
1702 };
1703
1704 if extend {
1705 range.put_cursor(text, pos, true)
1706 } else {
1707 Range::point(range.cursor(text)).put_cursor(text, pos, true)
1708 }
1709 });
1710 doc.set_selection(view.id, selection);
1711 }
1712
1713 fn find_char(cx: &mut Context, direction: Direction, inclusive: bool, extend: bool) {
1714 // TODO: count is reset to 1 before next key so we move it into the closure here.
1715 // Would be nice to carry over.
1716 let count = cx.count();
1717
1718 // need to wait for next key
1719 // TODO: should this be done by grapheme rather than char? For example,
1720 // we can't properly handle the line-ending CRLF case here in terms of char.
1721 cx.on_next_key(move |cx, event| {
1722 let motion: Motion = if event.code == KeyCode::Enter {
1723 Box::new(move |editor: &mut Editor| {
1724 find_char_line_ending_motion(editor, count, direction, inclusive, extend);
1725 })
1726 } else if let Some(ch) = match event.code {
1727 KeyCode::Tab => Some('\t'),
1728 KeyCode::Char(ch) => Some(ch),
1729 _ => None,
1730 } {
1731 Box::new(move |editor: &mut Editor| {
1732 let (view, doc) = current!(editor);
1733 let text = doc.text().slice(..);
1734
1735 let selection = doc.selection(view.id).clone().transform(|range| {
1736 let cursor_anchor = range.cursor(text);
1737 let cursor_head = next_grapheme_boundary(text, cursor_anchor);
1738
1739 // Exclusive search skips the next char after cursor to enable repeated application
1740 let search_start_pos = match (inclusive, direction) {
1741 (true, Direction::Forward) => cursor_head,
1742 (true, Direction::Backward) => cursor_anchor,
1743 (false, Direction::Forward) => cursor_head + 1,
1744 (false, Direction::Backward) => cursor_anchor.saturating_sub(1),
1745 };
1746
1747 search::find_nth_char(count, text, ch, search_start_pos, direction)
1748 // Exclusive search should stop on previous character
1749 .map(|pos| match (inclusive, direction) {
1750 (true, Direction::Forward) => pos,
1751 (true, Direction::Backward) => pos,
1752 (false, Direction::Forward) => pos - 1,
1753 (false, Direction::Backward) => pos + 1,
1754 })
1755 .map_or(range, |pos| {
1756 if extend {
1757 range.put_cursor(text, pos, true)
1758 } else {
1759 Range::point(range.cursor(text)).put_cursor(text, pos, true)
1760 }
1761 })
1762 });
1763
1764 doc.set_selection(view.id, selection);
1765 })
1766 } else {
1767 return;
1768 };
1769
1770 cx.editor.apply_motion(motion);
1771 })
1772 }
1773
1774 fn find_till_char(cx: &mut Context) {
1775 find_char(cx, Direction::Forward, false, false);
1776 }
1777
1778 fn find_next_char(cx: &mut Context) {
1779 find_char(cx, Direction::Forward, true, false)
1780 }
1781
1782 fn extend_till_char(cx: &mut Context) {
1783 find_char(cx, Direction::Forward, false, true)
1784 }
1785
1786 fn extend_next_char(cx: &mut Context) {
1787 find_char(cx, Direction::Forward, true, true)
1788 }
1789
1790 fn till_prev_char(cx: &mut Context) {
1791 find_char(cx, Direction::Backward, false, false)
1792 }
1793
1794 fn find_prev_char(cx: &mut Context) {
1795 find_char(cx, Direction::Backward, true, false)
1796 }
1797
1798 fn extend_till_prev_char(cx: &mut Context) {
1799 find_char(cx, Direction::Backward, false, true)
1800 }
1801
1802 fn extend_prev_char(cx: &mut Context) {
1803 find_char(cx, Direction::Backward, true, true)
1804 }
1805
1806 fn repeat_last_motion(cx: &mut Context) {
1807 cx.editor.repeat_last_motion(cx.count())
1808 }
1809
1810 fn replace(cx: &mut Context) {
1811 let mut buf = [0u8; 4]; // To hold utf8 encoded char.
1812
1813 // need to wait for next key
1814 cx.on_next_key(move |cx, event| {
1815 let (view, doc) = current!(cx.editor);
1816 let ch: Option<&str> = match event {
1817 KeyEvent {
1818 code: KeyCode::Char(ch),
1819 ..
1820 } => Some(ch.encode_utf8(&mut buf[..])),
1821 KeyEvent {
1822 code: KeyCode::Enter,
1823 ..
1824 } => Some(doc.line_ending.as_str()),
1825 KeyEvent {
1826 code: KeyCode::Tab, ..
1827 } => Some("\t"),
1828 _ => None,
1829 };
1830
1831 let selection = doc.selection(view.id);
1832
1833 if let Some(ch) = ch {
1834 let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
1835 if !range.is_empty() {
1836 let text: Tendril = doc
1837 .text()
1838 .slice(range.from()..range.to())
1839 .graphemes()
1840 .map(|_g| ch)
1841 .collect();
1842 (range.from(), range.to(), Some(text))
1843 } else {
1844 // No change.
1845 (range.from(), range.to(), None)
1846 }
1847 });
1848
1849 doc.apply(&transaction, view.id);
1850 exit_select_mode(cx);
1851 }
1852 })
1853 }
1854
1855 fn switch_case_impl<F>(cx: &mut Context, change_fn: F)
1856 where
1857 F: Fn(RopeSlice) -> Tendril,
1858 {
1859 let (view, doc) = current!(cx.editor);
1860 let selection = doc.selection(view.id);
1861 let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
1862 let text: Tendril = change_fn(range.slice(doc.text().slice(..)));
1863
1864 (range.from(), range.to(), Some(text))
1865 });
1866
1867 doc.apply(&transaction, view.id);
1868 exit_select_mode(cx);
1869 }
1870
1871 enum CaseSwitcher {
1872 Upper(ToUppercase),
1873 Lower(ToLowercase),
1874 Keep(Option<char>),
1875 }
1876
1877 impl Iterator for CaseSwitcher {
1878 type Item = char;
1879
1880 fn next(&mut self) -> Option<Self::Item> {
1881 match self {
1882 CaseSwitcher::Upper(upper) => upper.next(),
1883 CaseSwitcher::Lower(lower) => lower.next(),
1884 CaseSwitcher::Keep(ch) => ch.take(),
1885 }
1886 }
1887
1888 fn size_hint(&self) -> (usize, Option<usize>) {
1889 match self {
1890 CaseSwitcher::Upper(upper) => upper.size_hint(),
1891 CaseSwitcher::Lower(lower) => lower.size_hint(),
1892 CaseSwitcher::Keep(ch) => {
1893 let n = if ch.is_some() { 1 } else { 0 };
1894 (n, Some(n))
1895 }
1896 }
1897 }
1898 }
1899
1900 impl ExactSizeIterator for CaseSwitcher {}
1901
1902 fn switch_case(cx: &mut Context) {
1903 switch_case_impl(cx, |string| {
1904 string
1905 .chars()
1906 .flat_map(|ch| {
1907 if ch.is_lowercase() {
1908 CaseSwitcher::Upper(ch.to_uppercase())
1909 } else if ch.is_uppercase() {
1910 CaseSwitcher::Lower(ch.to_lowercase())
1911 } else {
1912 CaseSwitcher::Keep(Some(ch))
1913 }
1914 })
1915 .collect()
1916 });
1917 }
1918
1919 fn switch_to_uppercase(cx: &mut Context) {
1920 switch_case_impl(cx, |string| {
1921 string.chunks().map(|chunk| chunk.to_uppercase()).collect()
1922 });
1923 }
1924
1925 fn switch_to_lowercase(cx: &mut Context) {
1926 switch_case_impl(cx, |string| {
1927 string.chunks().map(|chunk| chunk.to_lowercase()).collect()
1928 });
1929 }
1930
1931 pub fn scroll(cx: &mut Context, offset: usize, direction: Direction, sync_cursor: bool) {
1932 use Direction::*;
1933 let config = cx.editor.config();
1934 let (view, doc) = current!(cx.editor);
1935 let mut view_offset = doc.view_offset(view.id);
1936
1937 let range = doc.selection(view.id).primary();
1938 let text = doc.text().slice(..);
1939
1940 let cursor = range.cursor(text);
1941 let height = view.inner_height();
1942
1943 let scrolloff = config.scrolloff.min(height.saturating_sub(1) / 2);
1944 let offset = match direction {
1945 Forward => offset as isize,
1946 Backward => -(offset as isize),
1947 };
1948
1949 let doc_text = doc.text().slice(..);
1950 let viewport = view.inner_area(doc);
1951 let text_fmt = doc.text_format(viewport.width, None);
1952 (view_offset.anchor, view_offset.vertical_offset) = char_idx_at_visual_offset(
1953 doc_text,
1954 view_offset.anchor,
1955 view_offset.vertical_offset as isize + offset,
1956 0,
1957 &text_fmt,
1958 // &annotations,
1959 &view.text_annotations(&*doc, None),
1960 );
1961 doc.set_view_offset(view.id, view_offset);
1962
1963 let doc_text = doc.text().slice(..);
1964 let mut annotations = view.text_annotations(&*doc, None);
1965
1966 if sync_cursor {
1967 let movement = match cx.editor.mode {
1968 Mode::Select => Movement::Extend,
1969 _ => Movement::Move,
1970 };
1971 // TODO: When inline diagnostics gets merged- 1. move_vertically_visual removes
1972 // line annotations/diagnostics so the cursor may jump further than the view.
1973 // 2. If the cursor lands on a complete line of virtual text, the cursor will
1974 // jump a different distance than the view.
1975 let selection = doc.selection(view.id).clone().transform(|range| {
1976 move_vertically_visual(
1977 doc_text,
1978 range,
1979 direction,
1980 offset.unsigned_abs(),
1981 movement,
1982 &text_fmt,
1983 &mut annotations,
1984 )
1985 });
1986 drop(annotations);
1987 doc.set_selection(view.id, selection);
1988 return;
1989 }
1990
1991 let view_offset = doc.view_offset(view.id);
1992
1993 let mut head;
1994 match direction {
1995 Forward => {
1996 let off;
1997 (head, off) = char_idx_at_visual_offset(
1998 doc_text,
1999 view_offset.anchor,
2000 (view_offset.vertical_offset + scrolloff) as isize,
2001 0,
2002 &text_fmt,
2003 &annotations,
2004 );
2005 head += (off != 0) as usize;
2006 if head <= cursor {
2007 return;
2008 }
2009 }
2010 Backward => {
2011 head = char_idx_at_visual_offset(
2012 doc_text,
2013 view_offset.anchor,
2014 (view_offset.vertical_offset + height - scrolloff - 1) as isize,
2015 0,
2016 &text_fmt,
2017 &annotations,
2018 )
2019 .0;
2020 if head >= cursor {
2021 return;
2022 }
2023 }
2024 }
2025
2026 let anchor = if cx.editor.mode == Mode::Select {
2027 range.anchor
2028 } else {
2029 head
2030 };
2031
2032 // replace primary selection with an empty selection at cursor pos
2033 let prim_sel = Range::new(anchor, head);
2034 let mut sel = doc.selection(view.id).clone();
2035 let idx = sel.primary_index();
2036 sel = sel.replace(idx, prim_sel);
2037 drop(annotations);
2038 doc.set_selection(view.id, sel);
2039 }
2040
2041 fn page_up(cx: &mut Context) {
2042 let view = view!(cx.editor);
2043 let offset = view.inner_height();
2044 scroll(cx, offset, Direction::Backward, false);
2045 }
2046
2047 fn page_down(cx: &mut Context) {
2048 let view = view!(cx.editor);
2049 let offset = view.inner_height();
2050 scroll(cx, offset, Direction::Forward, false);
2051 }
2052
2053 fn half_page_up(cx: &mut Context) {
2054 let view = view!(cx.editor);
2055 let offset = view.inner_height() / 2;
2056 scroll(cx, offset, Direction::Backward, false);
2057 }
2058
2059 fn half_page_down(cx: &mut Context) {
2060 let view = view!(cx.editor);
2061 let offset = view.inner_height() / 2;
2062 scroll(cx, offset, Direction::Forward, false);
2063 }
2064
2065 fn page_cursor_up(cx: &mut Context) {
2066 let view = view!(cx.editor);
2067 let offset = view.inner_height();
2068 scroll(cx, offset, Direction::Backward, true);
2069 }
2070
2071 fn page_cursor_down(cx: &mut Context) {
2072 let view = view!(cx.editor);
2073 let offset = view.inner_height();
2074 scroll(cx, offset, Direction::Forward, true);
2075 }
2076
2077 fn page_cursor_half_up(cx: &mut Context) {
2078 let view = view!(cx.editor);
2079 let offset = view.inner_height() / 2;
2080 scroll(cx, offset, Direction::Backward, true);
2081 }
2082
2083 fn page_cursor_half_down(cx: &mut Context) {
2084 let view = view!(cx.editor);
2085 let offset = view.inner_height() / 2;
2086 scroll(cx, offset, Direction::Forward, true);
2087 }
2088
2089 #[allow(deprecated)]
2090 // currently uses the deprecated `visual_coords_at_pos`/`pos_at_visual_coords` functions
2091 // as this function ignores softwrapping (and virtual text) and instead only cares
2092 // about "text visual position"
2093 //
2094 // TODO: implement a variant of that uses visual lines and respects virtual text
2095 fn copy_selection_on_line(cx: &mut Context, direction: Direction) {
2096 use helix_core::{pos_at_visual_coords, visual_coords_at_pos};
2097
2098 let count = cx.count();
2099 let (view, doc) = current!(cx.editor);
2100 let text = doc.text().slice(..);
2101 let selection = doc.selection(view.id);
2102 let mut ranges = SmallVec::with_capacity(selection.ranges().len() * (count + 1));
2103 ranges.extend_from_slice(selection.ranges());
2104 let mut primary_index = 0;
2105 for range in selection.iter() {
2106 let is_primary = *range == selection.primary();
2107
2108 // The range is always head exclusive
2109 let (head, anchor) = if range.anchor < range.head {
2110 (range.head - 1, range.anchor)
2111 } else {
2112 (range.head, range.anchor.saturating_sub(1))
2113 };
2114
2115 let tab_width = doc.tab_width();
2116
2117 let head_pos = visual_coords_at_pos(text, head, tab_width);
2118 let anchor_pos = visual_coords_at_pos(text, anchor, tab_width);
2119
2120 let height = std::cmp::max(head_pos.row, anchor_pos.row)
2121 - std::cmp::min(head_pos.row, anchor_pos.row)
2122 + 1;
2123
2124 if is_primary {
2125 primary_index = ranges.len();
2126 }
2127 ranges.push(*range);
2128
2129 let mut sels = 0;
2130 let mut i = 0;
2131 while sels < count {
2132 let offset = (i + 1) * height;
2133
2134 let anchor_row = match direction {
2135 Direction::Forward => anchor_pos.row + offset,
2136 Direction::Backward => anchor_pos.row.saturating_sub(offset),
2137 };
2138
2139 let head_row = match direction {
2140 Direction::Forward => head_pos.row + offset,
2141 Direction::Backward => head_pos.row.saturating_sub(offset),
2142 };
2143
2144 if anchor_row >= text.len_lines() || head_row >= text.len_lines() {
2145 break;
2146 }
2147
2148 let anchor =
2149 pos_at_visual_coords(text, Position::new(anchor_row, anchor_pos.col), tab_width);
2150 let head = pos_at_visual_coords(text, Position::new(head_row, head_pos.col), tab_width);
2151
2152 // skip lines that are too short
2153 if visual_coords_at_pos(text, anchor, tab_width).col == anchor_pos.col
2154 && visual_coords_at_pos(text, head, tab_width).col == head_pos.col
2155 {
2156 if is_primary {
2157 primary_index = ranges.len();
2158 }
2159 // This is Range::new(anchor, head), but it will place the cursor on the correct column
2160 ranges.push(Range::point(anchor).put_cursor(text, head, true));
2161 sels += 1;
2162 }
2163
2164 if anchor_row == 0 && head_row == 0 {
2165 break;
2166 }
2167
2168 i += 1;
2169 }
2170 }
2171
2172 let selection = Selection::new(ranges, primary_index);
2173 doc.set_selection(view.id, selection);
2174 }
2175
2176 fn copy_selection_on_prev_line(cx: &mut Context) {
2177 copy_selection_on_line(cx, Direction::Backward)
2178 }
2179
2180 fn copy_selection_on_next_line(cx: &mut Context) {
2181 copy_selection_on_line(cx, Direction::Forward)
2182 }
2183
2184 fn select_all(cx: &mut Context) {
2185 let (view, doc) = current!(cx.editor);
2186
2187 let end = doc.text().len_chars();
2188 doc.set_selection(view.id, Selection::single(0, end))
2189 }
2190
2191 fn select_regex(cx: &mut Context) {
2192 let reg = cx.register.unwrap_or('/');
2193 ui::regex_prompt(
2194 cx,
2195 "select:".into(),
2196 Some(reg),
2197 ui::completers::none,
2198 move |cx, regex, event| {
2199 let (view, doc) = current!(cx.editor);
2200 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
2201 return;
2202 }
2203 let text = doc.text().slice(..);
2204 if let Some(selection) =
2205 selection::select_on_matches(text, doc.selection(view.id), &regex)
2206 {
2207 doc.set_selection(view.id, selection);
2208 } else if event == PromptEvent::Validate {
2209 cx.editor.set_error("nothing selected");
2210 }
2211 },
2212 );
2213 }
2214
2215 fn split_selection(cx: &mut Context) {
2216 let reg = cx.register.unwrap_or('/');
2217 ui::regex_prompt(
2218 cx,
2219 "split:".into(),
2220 Some(reg),
2221 ui::completers::none,
2222 move |cx, regex, event| {
2223 let (view, doc) = current!(cx.editor);
2224 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
2225 return;
2226 }
2227 let text = doc.text().slice(..);
2228 let selection = selection::split_on_matches(text, doc.selection(view.id), &regex);
2229 doc.set_selection(view.id, selection);
2230 },
2231 );
2232 }
2233
2234 fn split_selection_on_newline(cx: &mut Context) {
2235 let (view, doc) = current!(cx.editor);
2236 let text = doc.text().slice(..);
2237 let selection = selection::split_on_newline(text, doc.selection(view.id));
2238 doc.set_selection(view.id, selection);
2239 }
2240
2241 fn merge_selections(cx: &mut Context) {
2242 let (view, doc) = current!(cx.editor);
2243 let selection = doc.selection(view.id).clone().merge_ranges();
2244 doc.set_selection(view.id, selection);
2245 }
2246
2247 fn merge_consecutive_selections(cx: &mut Context) {
2248 let (view, doc) = current!(cx.editor);
2249 let selection = doc.selection(view.id).clone().merge_consecutive_ranges();
2250 doc.set_selection(view.id, selection);
2251 }
2252
2253 #[allow(clippy::too_many_arguments)]
2254 fn search_impl(
2255 editor: &mut Editor,
2256 regex: &rope::Regex,
2257 movement: Movement,
2258 direction: Direction,
2259 scrolloff: usize,
2260 wrap_around: bool,
2261 show_warnings: bool,
2262 ) {
2263 let (view, doc) = current!(editor);
2264 let text = doc.text().slice(..);
2265 let selection = doc.selection(view.id);
2266
2267 // Get the right side of the primary block cursor for forward search, or the
2268 // grapheme before the start of the selection for reverse search.
2269 let start = match direction {
2270 Direction::Forward => text.char_to_byte(graphemes::ensure_grapheme_boundary_next(
2271 text,
2272 selection.primary().to(),
2273 )),
2274 Direction::Backward => text.char_to_byte(graphemes::ensure_grapheme_boundary_prev(
2275 text,
2276 selection.primary().from(),
2277 )),
2278 };
2279
2280 // A regex::Match returns byte-positions in the str. In the case where we
2281 // do a reverse search and wraparound to the end, we don't need to search
2282 // the text before the current cursor position for matches, but by slicing
2283 // it out, we need to add it back to the position of the selection.
2284 let doc = doc!(editor).text().slice(..);
2285
2286 // use find_at to find the next match after the cursor, loop around the end
2287 // Careful, `Regex` uses `bytes` as offsets, not character indices!
2288 let mut mat = match direction {
2289 Direction::Forward => regex.find(doc.regex_input_at_bytes(start..)),
2290 Direction::Backward => regex.find_iter(doc.regex_input_at_bytes(..start)).last(),
2291 };
2292
2293 if mat.is_none() {
2294 if wrap_around {
2295 mat = match direction {
2296 Direction::Forward => regex.find(doc.regex_input()),
2297 Direction::Backward => regex.find_iter(doc.regex_input_at_bytes(start..)).last(),
2298 };
2299 }
2300 if show_warnings {
2301 if wrap_around && mat.is_some() {
2302 editor.set_status("Wrapped around document");
2303 } else {
2304 editor.set_error("No more matches");
2305 }
2306 }
2307 }
2308
2309 let (view, doc) = current!(editor);
2310 let text = doc.text().slice(..);
2311 let selection = doc.selection(view.id);
2312
2313 if let Some(mat) = mat {
2314 let start = text.byte_to_char(mat.start());
2315 let end = text.byte_to_char(mat.end());
2316
2317 if end == 0 {
2318 // skip empty matches that don't make sense
2319 return;
2320 }
2321
2322 // Determine range direction based on the primary range
2323 let primary = selection.primary();
2324 let range = Range::new(start, end).with_direction(primary.direction());
2325
2326 let selection = match movement {
2327 Movement::Extend => selection.clone().push(range),
2328 Movement::Move => selection.clone().replace(selection.primary_index(), range),
2329 };
2330
2331 doc.set_selection(view.id, selection);
2332 view.ensure_cursor_in_view_center(doc, scrolloff);
2333 };
2334 }
2335
2336 fn search_completions(cx: &mut Context, reg: Option<char>) -> Vec<String> {
2337 let mut items = reg
2338 .and_then(|reg| cx.editor.registers.read(reg, cx.editor))
2339 .map_or(Vec::new(), |reg| reg.take(200).collect());
2340 items.sort_unstable();
2341 items.dedup();
2342 items.into_iter().map(|value| value.to_string()).collect()
2343 }
2344
2345 fn search(cx: &mut Context) {
2346 searcher(cx, Direction::Forward)
2347 }
2348
2349 fn rsearch(cx: &mut Context) {
2350 searcher(cx, Direction::Backward)
2351 }
2352
2353 fn searcher(cx: &mut Context, direction: Direction) {
2354 let reg = cx.register.unwrap_or('/');
2355 let config = cx.editor.config();
2356 let scrolloff = config.scrolloff;
2357 let wrap_around = config.search.wrap_around;
2358 let movement = if cx.editor.mode() == Mode::Select {
2359 Movement::Extend
2360 } else {
2361 Movement::Move
2362 };
2363
2364 // TODO: could probably share with select_on_matches?
2365 let completions = search_completions(cx, Some(reg));
2366
2367 ui::regex_prompt(
2368 cx,
2369 "search:".into(),
2370 Some(reg),
2371 move |_editor: &Editor, input: &str| {
2372 completions
2373 .iter()
2374 .filter(|comp| comp.starts_with(input))
2375 .map(|comp| (0.., comp.clone().into()))
2376 .collect()
2377 },
2378 move |cx, regex, event| {
2379 if event == PromptEvent::Validate {
2380 cx.editor.registers.last_search_register = reg;
2381 } else if event != PromptEvent::Update {
2382 return;
2383 }
2384 search_impl(
2385 cx.editor,
2386 &regex,
2387 movement,
2388 direction,
2389 scrolloff,
2390 wrap_around,
2391 false,
2392 );
2393 },
2394 );
2395 }
2396
2397 fn search_next_or_prev_impl(cx: &mut Context, movement: Movement, direction: Direction) {
2398 let count = cx.count();
2399 let register = cx
2400 .register
2401 .unwrap_or(cx.editor.registers.last_search_register);
2402 let config = cx.editor.config();
2403 let scrolloff = config.scrolloff;
2404 if let Some(query) = cx.editor.registers.first(register, cx.editor) {
2405 let search_config = &config.search;
2406 let case_insensitive = if search_config.smart_case {
2407 !query.chars().any(char::is_uppercase)
2408 } else {
2409 false
2410 };
2411 let wrap_around = search_config.wrap_around;
2412 let is_crlf = doc!(cx.editor).line_ending == LineEnding::Crlf;
2413 if let Ok(regex) = rope::RegexBuilder::new()
2414 .syntax(
2415 rope::Config::new()
2416 .case_insensitive(case_insensitive)
2417 .multi_line(true)
2418 .crlf(is_crlf),
2419 )
2420 .build(&query)
2421 {
2422 for _ in 0..count {
2423 search_impl(
2424 cx.editor,
2425 &regex,
2426 movement,
2427 direction,
2428 scrolloff,
2429 wrap_around,
2430 true,
2431 );
2432 }
2433 } else {
2434 let error = format!("Invalid regex: {}", query);
2435 cx.editor.set_error(error);
2436 }
2437 }
2438 }
2439
2440 fn search_next(cx: &mut Context) {
2441 search_next_or_prev_impl(cx, Movement::Move, Direction::Forward);
2442 }
2443
2444 fn search_prev(cx: &mut Context) {
2445 search_next_or_prev_impl(cx, Movement::Move, Direction::Backward);
2446 }
2447 fn extend_search_next(cx: &mut Context) {
2448 search_next_or_prev_impl(cx, Movement::Extend, Direction::Forward);
2449 }
2450
2451 fn extend_search_prev(cx: &mut Context) {
2452 search_next_or_prev_impl(cx, Movement::Extend, Direction::Backward);
2453 }
2454
2455 fn search_selection(cx: &mut Context) {
2456 search_selection_impl(cx, false)
2457 }
2458
2459 fn search_selection_detect_word_boundaries(cx: &mut Context) {
2460 search_selection_impl(cx, true)
2461 }
2462
2463 fn search_selection_impl(cx: &mut Context, detect_word_boundaries: bool) {
2464 fn is_at_word_start(text: RopeSlice, index: usize) -> bool {
2465 // This can happen when the cursor is at the last character in
2466 // the document +1 (ge + j), in this case text.char(index) will panic as
2467 // it will index out of bounds. See https://github.com/helix-editor/helix/issues/12609
2468 if index == text.len_chars() {
2469 return false;
2470 }
2471 let ch = text.char(index);
2472 if index == 0 {
2473 return char_is_word(ch);
2474 }
2475 let prev_ch = text.char(index - 1);
2476
2477 !char_is_word(prev_ch) && char_is_word(ch)
2478 }
2479
2480 fn is_at_word_end(text: RopeSlice, index: usize) -> bool {
2481 if index == 0 || index == text.len_chars() {
2482 return false;
2483 }
2484 let ch = text.char(index);
2485 let prev_ch = text.char(index - 1);
2486
2487 char_is_word(prev_ch) && !char_is_word(ch)
2488 }
2489
2490 let register = cx.register.unwrap_or('/');
2491 let (view, doc) = current!(cx.editor);
2492 let text = doc.text().slice(..);
2493
2494 let regex = doc
2495 .selection(view.id)
2496 .iter()
2497 .map(|selection| {
2498 let add_boundary_prefix =
2499 detect_word_boundaries && is_at_word_start(text, selection.from());
2500 let add_boundary_suffix =
2501 detect_word_boundaries && is_at_word_end(text, selection.to());
2502
2503 let prefix = if add_boundary_prefix { "\\b" } else { "" };
2504 let suffix = if add_boundary_suffix { "\\b" } else { "" };
2505
2506 let word = regex::escape(&selection.fragment(text));
2507 format!("{}{}{}", prefix, word, suffix)
2508 })
2509 .collect::<HashSet<_>>() // Collect into hashset to deduplicate identical regexes
2510 .into_iter()
2511 .collect::<Vec<_>>()
2512 .join("|");
2513
2514 let msg = format!("register '{}' set to '{}'", register, &regex);
2515 match cx.editor.registers.push(register, regex) {
2516 Ok(_) => {
2517 cx.editor.registers.last_search_register = register;
2518 cx.editor.set_status(msg)
2519 }
2520 Err(err) => cx.editor.set_error(err.to_string()),
2521 }
2522 }
2523
2524 fn make_search_word_bounded(cx: &mut Context) {
2525 // Defaults to the active search register instead `/` to be more ergonomic assuming most people
2526 // would use this command following `search_selection`. This avoids selecting the register
2527 // twice.
2528 let register = cx
2529 .register
2530 .unwrap_or(cx.editor.registers.last_search_register);
2531 let regex = match cx.editor.registers.first(register, cx.editor) {
2532 Some(regex) => regex,
2533 None => return,
2534 };
2535 let start_anchored = regex.starts_with("\\b");
2536 let end_anchored = regex.ends_with("\\b");
2537
2538 if start_anchored && end_anchored {
2539 return;
2540 }
2541
2542 let mut new_regex = String::with_capacity(
2543 regex.len() + if start_anchored { 0 } else { 2 } + if end_anchored { 0 } else { 2 },
2544 );
2545
2546 if !start_anchored {
2547 new_regex.push_str("\\b");
2548 }
2549 new_regex.push_str(&regex);
2550 if !end_anchored {
2551 new_regex.push_str("\\b");
2552 }
2553
2554 let msg = format!("register '{}' set to '{}'", register, &new_regex);
2555 match cx.editor.registers.push(register, new_regex) {
2556 Ok(_) => {
2557 cx.editor.registers.last_search_register = register;
2558 cx.editor.set_status(msg)
2559 }
2560 Err(err) => cx.editor.set_error(err.to_string()),
2561 }
2562 }
2563
2564 fn global_search(cx: &mut Context) {
2565 #[derive(Debug)]
2566 struct FileResult<'a> {
2567 path: Cow<'a, Path>,
2568 /// 0 indexed line start
2569 line_start: usize,
2570 /// 0 indexed line end
2571 line_end: usize,
2572 }
2573
2574 impl FileResult<'_> {
2575 fn new(path: &Path, line_start: usize, line_end: usize) -> Self {
2576 Self {
2577 path: helix_stdx::path::get_relative_path(path.to_path_buf()),
2578 line_start,
2579 line_end,
2580 }
2581 }
2582 }
2583
2584 struct GlobalSearchConfig {
2585 smart_case: bool,
2586 file_picker_config: helix_view::editor::FilePickerConfig,
2587 style: PathStyleConfig,
2588 }
2589
2590 let config = cx.editor.config();
2591 let config = GlobalSearchConfig {
2592 smart_case: config.search.smart_case,
2593 file_picker_config: config.file_picker.clone(),
2594 style: PathStyleConfig::new(&cx.editor.theme),
2595 };
2596
2597 let columns = [
2598 PickerColumn::new("path", |item: &FileResult, config: &GlobalSearchConfig| {
2599 config
2600 .style
2601 .stylize(Some(&item.path), Some(item.line_start))
2602 }),
2603 PickerColumn::hidden("contents"),
2604 ];
2605
2606 let get_files = |query: &str,
2607 editor: &mut Editor,
2608 config: std::sync::Arc<GlobalSearchConfig>,
2609 injector: &ui::picker::Injector<_, _>| {
2610 if query.is_empty() {
2611 return async { Ok(()) }.boxed();
2612 }
2613
2614 let search_root = helix_stdx::env::current_working_dir();
2615 if !search_root.exists() {
2616 return async { Err(anyhow::anyhow!("Current working directory does not exist")) }
2617 .boxed();
2618 }
2619
2620 let documents: Vec<_> = editor
2621 .documents()
2622 .map(|doc| (doc.path().map(ToOwned::to_owned), doc.text().to_owned()))
2623 .collect();
2624
2625 let matcher = match RegexMatcherBuilder::new()
2626 .case_smart(config.smart_case)
2627 .multi_line(true)
2628 .build(query)
2629 {
2630 Ok(matcher) => {
2631 // Clear any "Failed to compile regex" errors out of the statusline.
2632 editor.clear_status();
2633 matcher
2634 }
2635 Err(err) => {
2636 log::info!("Failed to compile search pattern in global search: {}", err);
2637 return async { Err(anyhow::anyhow!("Failed to compile regex")) }.boxed();
2638 }
2639 };
2640
2641 let dedup_symlinks = config.file_picker_config.deduplicate_links;
2642 let absolute_root = search_root
2643 .canonicalize()
2644 .unwrap_or_else(|_| search_root.clone());
2645
2646 let injector = injector.clone();
2647 async move {
2648 let searcher = SearcherBuilder::new()
2649 .binary_detection(BinaryDetection::quit(b'\x00'))
2650 .multi_line(true)
2651 .build();
2652 WalkBuilder::new(search_root)
2653 .hidden(config.file_picker_config.hidden)
2654 .parents(config.file_picker_config.parents)
2655 .ignore(config.file_picker_config.ignore)
2656 .follow_links(config.file_picker_config.follow_symlinks)
2657 .git_ignore(config.file_picker_config.git_ignore)
2658 .git_global(config.file_picker_config.git_global)
2659 .git_exclude(config.file_picker_config.git_exclude)
2660 .max_depth(config.file_picker_config.max_depth)
2661 .filter_entry(move |entry| {
2662 filter_picker_entry(entry, &absolute_root, dedup_symlinks)
2663 })
2664 .add_custom_ignore_filename(helix_loader::config_dir().join("ignore"))
2665 .add_custom_ignore_filename(".helix/ignore")
2666 .build_parallel()
2667 .run(|| {
2668 let mut searcher = searcher.clone();
2669 let matcher = matcher.clone();
2670 let injector = injector.clone();
2671 let documents = &documents;
2672 Box::new(move |entry: Result<DirEntry, ignore::Error>| -> WalkState {
2673 let entry = match entry {
2674 Ok(entry) => entry,
2675 Err(_) => return WalkState::Continue,
2676 };
2677
2678 if !entry.path().is_file() {
2679 return WalkState::Continue;
2680 }
2681
2682 let mut stop = false;
2683 let sink = sinks::UTF8(|line_start, line_content| {
2684 let line_start = line_start as usize - 1;
2685 let line_end = line_start + line_content.lines().count() - 1;
2686 stop = injector
2687 .push(FileResult::new(entry.path(), line_start, line_end))
2688 .is_err();
2689
2690 Ok(!stop)
2691 });
2692 let doc = documents.iter().find(|&(doc_path, _)| {
2693 doc_path
2694 .as_ref()
2695 .is_some_and(|doc_path| doc_path == entry.path())
2696 });
2697
2698 let result = if let Some((_, doc)) = doc {
2699 // there is already a buffer for this file
2700 // search the buffer instead of the file because it's faster
2701 // and captures new edits without requiring a save
2702 if searcher.multi_line_with_matcher(&matcher) {
2703 // in this case a continuous buffer is required
2704 // convert the rope to a string
2705 let text = doc.to_string();
2706 searcher.search_slice(&matcher, text.as_bytes(), sink)
2707 } else {
2708 searcher.search_reader(
2709 &matcher,
2710 RopeReader::new(doc.slice(..)),
2711 sink,
2712 )
2713 }
2714 } else {
2715 searcher.search_path(&matcher, entry.path(), sink)
2716 };
2717
2718 if let Err(err) = result {
2719 log::error!("Global search error: {}, {}", entry.path().display(), err);
2720 }
2721 if stop {
2722 WalkState::Quit
2723 } else {
2724 WalkState::Continue
2725 }
2726 })
2727 });
2728 Ok(())
2729 }
2730 .boxed()
2731 };
2732
2733 let reg = cx.register.unwrap_or('/');
2734 cx.editor.registers.last_search_register = reg;
2735
2736 let picker = Picker::new(
2737 columns,
2738 1, // contents
2739 [],
2740 config,
2741 move |cx,
2742 FileResult {
2743 path,
2744 line_start,
2745 line_end,
2746 ..
2747 },
2748 action| {
2749 let doc = match cx.editor.open(path, action) {
2750 Ok(id) => doc_mut!(cx.editor, &id),
2751 Err(e) => {
2752 cx.editor
2753 .set_error(format!("Failed to open file '{}': {}", path.display(), e));
2754 return;
2755 }
2756 };
2757
2758 let line_start = *line_start;
2759 let line_end = *line_end;
2760 let view = view_mut!(cx.editor);
2761 let text = doc.text();
2762 if line_start >= text.len_lines() {
2763 cx.editor.set_error(
2764 "The line you jumped to does not exist anymore because the file has changed.",
2765 );
2766 return;
2767 }
2768 let start = text.line_to_char(line_start);
2769 let end = text.line_to_char((line_end + 1).min(text.len_lines()));
2770
2771 doc.set_selection(view.id, Selection::single(start, end));
2772 if action.align_view(view, doc.id()) {
2773 align_view(doc, view, Align::Center);
2774 }
2775 },
2776 )
2777 .with_preview(
2778 |_editor,
2779 FileResult {
2780 path,
2781 line_start,
2782 line_end,
2783 ..
2784 }| { Some((path.as_ref().into(), Some((*line_start, *line_end)))) },
2785 )
2786 .with_history_register(Some(reg))
2787 .with_dynamic_query(get_files, Some(275));
2788
2789 cx.push_layer(Box::new(overlaid(picker)));
2790 }
2791
2792 enum Extend {
2793 Above,
2794 Below,
2795 }
2796
2797 fn extend_line(cx: &mut Context) {
2798 let (view, doc) = current_ref!(cx.editor);
2799 let extend = match doc.selection(view.id).primary().direction() {
2800 Direction::Forward => Extend::Below,
2801 Direction::Backward => Extend::Above,
2802 };
2803 extend_line_impl(cx, extend);
2804 }
2805
2806 fn extend_line_below(cx: &mut Context) {
2807 extend_line_impl(cx, Extend::Below);
2808 }
2809
2810 fn extend_line_above(cx: &mut Context) {
2811 extend_line_impl(cx, Extend::Above);
2812 }
2813 fn extend_line_impl(cx: &mut Context, extend: Extend) {
2814 let count = cx.count();
2815 let (view, doc) = current!(cx.editor);
2816
2817 let text = doc.text();
2818 let selection = doc.selection(view.id).clone().transform(|range| {
2819 let (start_line, end_line) = range.line_range(text.slice(..));
2820
2821 let start = text.line_to_char(start_line);
2822 let end = text.line_to_char(
2823 (end_line + 1) // newline of end_line
2824 .min(text.len_lines()),
2825 );
2826
2827 // extend to previous/next line if current line is selected
2828 let (anchor, head) = if range.from() == start && range.to() == end {
2829 match extend {
2830 Extend::Above => (end, text.line_to_char(start_line.saturating_sub(count))),
2831 Extend::Below => (
2832 start,
2833 text.line_to_char((end_line + count + 1).min(text.len_lines())),
2834 ),
2835 }
2836 } else {
2837 match extend {
2838 Extend::Above => (end, text.line_to_char(start_line.saturating_sub(count - 1))),
2839 Extend::Below => (
2840 start,
2841 text.line_to_char((end_line + count).min(text.len_lines())),
2842 ),
2843 }
2844 };
2845
2846 Range::new(anchor, head)
2847 });
2848
2849 doc.set_selection(view.id, selection);
2850 }
2851 fn select_line_below(cx: &mut Context) {
2852 select_line_impl(cx, Extend::Below);
2853 }
2854 fn select_line_above(cx: &mut Context) {
2855 select_line_impl(cx, Extend::Above);
2856 }
2857 fn select_line_impl(cx: &mut Context, extend: Extend) {
2858 let mut count = cx.count();
2859 let (view, doc) = current!(cx.editor);
2860 let text = doc.text();
2861 let saturating_add = |a: usize, b: usize| (a + b).min(text.len_lines());
2862 let selection = doc.selection(view.id).clone().transform(|range| {
2863 let (start_line, end_line) = range.line_range(text.slice(..));
2864 let start = text.line_to_char(start_line);
2865 let end = text.line_to_char(saturating_add(end_line, 1));
2866 let direction = range.direction();
2867
2868 // Extending to line bounds is counted as one step
2869 if range.from() != start || range.to() != end {
2870 count = count.saturating_sub(1)
2871 }
2872 let (anchor_line, head_line) = match (&extend, direction) {
2873 (Extend::Above, Direction::Forward) => (start_line, end_line.saturating_sub(count)),
2874 (Extend::Above, Direction::Backward) => (end_line, start_line.saturating_sub(count)),
2875 (Extend::Below, Direction::Forward) => (start_line, saturating_add(end_line, count)),
2876 (Extend::Below, Direction::Backward) => (end_line, saturating_add(start_line, count)),
2877 };
2878 let (anchor, head) = match anchor_line.cmp(&head_line) {
2879 Ordering::Less => (
2880 text.line_to_char(anchor_line),
2881 text.line_to_char(saturating_add(head_line, 1)),
2882 ),
2883 Ordering::Equal => match extend {
2884 Extend::Above => (
2885 text.line_to_char(saturating_add(anchor_line, 1)),
2886 text.line_to_char(head_line),
2887 ),
2888 Extend::Below => (
2889 text.line_to_char(head_line),
2890 text.line_to_char(saturating_add(anchor_line, 1)),
2891 ),
2892 },
2893
2894 Ordering::Greater => (
2895 text.line_to_char(saturating_add(anchor_line, 1)),
2896 text.line_to_char(head_line),
2897 ),
2898 };
2899 Range::new(anchor, head)
2900 });
2901
2902 doc.set_selection(view.id, selection);
2903 }
2904
2905 fn extend_to_line_bounds(cx: &mut Context) {
2906 let (view, doc) = current!(cx.editor);
2907
2908 doc.set_selection(
2909 view.id,
2910 doc.selection(view.id).clone().transform(|range| {
2911 let text = doc.text();
2912
2913 let (start_line, end_line) = range.line_range(text.slice(..));
2914 let start = text.line_to_char(start_line);
2915 let end = text.line_to_char((end_line + 1).min(text.len_lines()));
2916
2917 Range::new(start, end).with_direction(range.direction())
2918 }),
2919 );
2920 }
2921
2922 fn shrink_to_line_bounds(cx: &mut Context) {
2923 let (view, doc) = current!(cx.editor);
2924
2925 doc.set_selection(
2926 view.id,
2927 doc.selection(view.id).clone().transform(|range| {
2928 let text = doc.text();
2929
2930 let (start_line, end_line) = range.line_range(text.slice(..));
2931
2932 // Do nothing if the selection is within one line to prevent
2933 // conditional logic for the behavior of this command
2934 if start_line == end_line {
2935 return range;
2936 }
2937
2938 let mut start = text.line_to_char(start_line);
2939
2940 // line_to_char gives us the start position of the line, so
2941 // we need to get the start position of the next line. In
2942 // the editor, this will correspond to the cursor being on
2943 // the EOL whitespace character, which is what we want.
2944 let mut end = text.line_to_char((end_line + 1).min(text.len_lines()));
2945
2946 if start != range.from() {
2947 start = text.line_to_char((start_line + 1).min(text.len_lines()));
2948 }
2949
2950 if end != range.to() {
2951 end = text.line_to_char(end_line);
2952 }
2953
2954 Range::new(start, end).with_direction(range.direction())
2955 }),
2956 );
2957 }
2958
2959 enum Operation {
2960 Delete,
2961 Change,
2962 }
2963
2964 fn selection_is_linewise(selection: &Selection, text: &Rope) -> bool {
2965 selection.ranges().iter().all(|range| {
2966 let text = text.slice(..);
2967 if range.slice(text).len_lines() < 2 {
2968 return false;
2969 }
2970 // If the start of the selection is at the start of a line and the end at the end of a line.
2971 let (start_line, end_line) = range.line_range(text);
2972 let start = text.line_to_char(start_line);
2973 let end = text.line_to_char((end_line + 1).min(text.len_lines()));
2974 start == range.from() && end == range.to()
2975 })
2976 }
2977
2978 enum YankAction {
2979 Yank,
2980 NoYank,
2981 }
2982
2983 fn delete_selection_impl(cx: &mut Context, op: Operation, yank: YankAction) {
2984 let (view, doc) = current!(cx.editor);
2985
2986 let selection = doc.selection(view.id);
2987 let only_whole_lines = selection_is_linewise(selection, doc.text());
2988
2989 if cx.register != Some('_') && matches!(yank, YankAction::Yank) {
2990 // yank the selection
2991 let text = doc.text().slice(..);
2992 let values: Vec<String> = selection.fragments(text).map(Cow::into_owned).collect();
2993 let reg_name = cx
2994 .register
2995 .unwrap_or_else(|| cx.editor.config.load().default_yank_register);
2996 if let Err(err) = cx.editor.registers.write(reg_name, values) {
2997 cx.editor.set_error(err.to_string());
2998 return;
2999 }
3000 }
3001
3002 // delete the selection
3003 let transaction =
3004 Transaction::delete_by_selection(doc.text(), selection, |range| (range.from(), range.to()));
3005 doc.apply(&transaction, view.id);
3006
3007 match op {
3008 Operation::Delete => {
3009 // exit select mode, if currently in select mode
3010 exit_select_mode(cx);
3011 }
3012 Operation::Change => {
3013 if only_whole_lines {
3014 open(cx, Open::Above, CommentContinuation::Disabled);
3015 } else {
3016 enter_insert_mode(cx);
3017 }
3018 }
3019 }
3020 }
3021
3022 #[inline]
3023 fn delete_by_selection_insert_mode(
3024 cx: &mut Context,
3025 mut f: impl FnMut(RopeSlice, &Range) -> Deletion,
3026 direction: Direction,
3027 ) {
3028 let (view, doc) = current!(cx.editor);
3029 let text = doc.text().slice(..);
3030 let mut selection = SmallVec::new();
3031 let mut insert_newline = false;
3032 let text_len = text.len_chars();
3033 let mut transaction =
3034 Transaction::delete_by_selection(doc.text(), doc.selection(view.id), |range| {
3035 let (start, end) = f(text, range);
3036 if direction == Direction::Forward {
3037 let mut range = *range;
3038 if range.head > range.anchor {
3039 insert_newline |= end == text_len;
3040 // move the cursor to the right so that the selection
3041 // doesn't shrink when deleting forward (so the text appears to
3042 // move to left)
3043 // += 1 is enough here as the range is normalized to grapheme boundaries
3044 // later anyway
3045 range.head += 1;
3046 }
3047 selection.push(range);
3048 }
3049 (start, end)
3050 });
3051
3052 // in case we delete the last character and the cursor would be moved to the EOF char
3053 // insert a newline, just like when entering append mode
3054 if insert_newline {
3055 transaction = transaction.insert_at_eof(doc.line_ending.as_str().into());
3056 }
3057
3058 if direction == Direction::Forward {
3059 doc.set_selection(
3060 view.id,
3061 Selection::new(selection, doc.selection(view.id).primary_index()),
3062 );
3063 }
3064 doc.apply(&transaction, view.id);
3065 }
3066
3067 fn delete_selection(cx: &mut Context) {
3068 delete_selection_impl(cx, Operation::Delete, YankAction::Yank);
3069 }
3070
3071 fn delete_selection_noyank(cx: &mut Context) {
3072 delete_selection_impl(cx, Operation::Delete, YankAction::NoYank);
3073 }
3074
3075 fn change_selection(cx: &mut Context) {
3076 delete_selection_impl(cx, Operation::Change, YankAction::Yank);
3077 }
3078
3079 fn change_selection_noyank(cx: &mut Context) {
3080 delete_selection_impl(cx, Operation::Change, YankAction::NoYank);
3081 }
3082
3083 fn collapse_selection(cx: &mut Context) {
3084 let (view, doc) = current!(cx.editor);
3085 let text = doc.text().slice(..);
3086
3087 let selection = doc.selection(view.id).clone().transform(|range| {
3088 let pos = range.cursor(text);
3089 Range::new(pos, pos)
3090 });
3091 doc.set_selection(view.id, selection);
3092 }
3093
3094 fn flip_selections(cx: &mut Context) {
3095 let (view, doc) = current!(cx.editor);
3096
3097 let selection = doc
3098 .selection(view.id)
3099 .clone()
3100 .transform(|range| range.flip());
3101 doc.set_selection(view.id, selection);
3102 }
3103
3104 fn ensure_selections_forward(cx: &mut Context) {
3105 let (view, doc) = current!(cx.editor);
3106
3107 let selection = doc
3108 .selection(view.id)
3109 .clone()
3110 .transform(|r| r.with_direction(Direction::Forward));
3111
3112 doc.set_selection(view.id, selection);
3113 }
3114
3115 fn enter_insert_mode(cx: &mut Context) {
3116 cx.editor.mode = Mode::Insert;
3117 }
3118
3119 // inserts at the start of each selection
3120 fn insert_mode(cx: &mut Context) {
3121 enter_insert_mode(cx);
3122 let (view, doc) = current!(cx.editor);
3123
3124 log::trace!(
3125 "entering insert mode with sel: {:?}, text: {:?}",
3126 doc.selection(view.id),
3127 doc.text().to_string()
3128 );
3129
3130 let selection = doc
3131 .selection(view.id)
3132 .clone()
3133 .transform(|range| Range::new(range.to(), range.from()));
3134
3135 doc.set_selection(view.id, selection);
3136 }
3137
3138 // inserts at the end of each selection
3139 fn append_mode(cx: &mut Context) {
3140 enter_insert_mode(cx);
3141 let (view, doc) = current!(cx.editor);
3142 doc.restore_cursor = true;
3143 let text = doc.text().slice(..);
3144
3145 // Make sure there's room at the end of the document if the last
3146 // selection butts up against it.
3147 let end = text.len_chars();
3148 let last_range = doc
3149 .selection(view.id)
3150 .iter()
3151 .last()
3152 .expect("selection should always have at least one range");
3153 if !last_range.is_empty() && last_range.to() == end {
3154 let transaction = Transaction::change(
3155 doc.text(),
3156 [(end, end, Some(doc.line_ending.as_str().into()))].into_iter(),
3157 );
3158 doc.apply(&transaction, view.id);
3159 }
3160
3161 let selection = doc.selection(view.id).clone().transform(|range| {
3162 Range::new(
3163 range.from(),
3164 graphemes::next_grapheme_boundary(doc.text().slice(..), range.to()),
3165 )
3166 });
3167 doc.set_selection(view.id, selection);
3168 }
3169
3170 fn file_picker(cx: &mut Context) {
3171 let root = find_workspace().0;
3172 if !root.exists() {
3173 cx.editor.set_error("Workspace directory does not exist");
3174 return;
3175 }
3176 let picker = ui::file_picker(cx.editor, root);
3177 cx.push_layer(Box::new(overlaid(picker)));
3178 }
3179
3180 fn file_picker_in_current_buffer_directory(cx: &mut Context) {
3181 let doc_dir = doc!(cx.editor)
3182 .path()
3183 .and_then(|path| path.parent().map(|path| path.to_path_buf()));
3184
3185 let path = match doc_dir {
3186 Some(path) => path,
3187 None => {
3188 let cwd = helix_stdx::env::current_working_dir();
3189 if !cwd.exists() {
3190 cx.editor.set_error(
3191 "Current buffer has no parent and current working directory does not exist",
3192 );
3193 return;
3194 }
3195 cx.editor.set_error(
3196 "Current buffer has no parent, opening file picker in current working directory",
3197 );
3198 cwd
3199 }
3200 };
3201
3202 let picker = ui::file_picker(cx.editor, path);
3203 cx.push_layer(Box::new(overlaid(picker)));
3204 }
3205
3206 fn file_picker_in_current_directory(cx: &mut Context) {
3207 let cwd = helix_stdx::env::current_working_dir();
3208 if !cwd.exists() {
3209 cx.editor
3210 .set_error("Current working directory does not exist");
3211 return;
3212 }
3213 let picker = ui::file_picker(cx.editor, cwd);
3214 cx.push_layer(Box::new(overlaid(picker)));
3215 }
3216
3217 fn file_explorer(cx: &mut Context) {
3218 let root = find_workspace().0;
3219 if !root.exists() {
3220 cx.editor.set_error("Workspace directory does not exist");
3221 return;
3222 }
3223
3224 if let Ok(picker) = ui::file_explorer(root, cx.editor) {
3225 cx.push_layer(Box::new(overlaid(picker)));
3226 }
3227 }
3228
3229 fn file_explorer_in_current_buffer_directory(cx: &mut Context) {
3230 let doc_dir = doc!(cx.editor)
3231 .path()
3232 .and_then(|path| path.parent().map(|path| path.to_path_buf()));
3233
3234 let path = match doc_dir {
3235 Some(path) => path,
3236 None => {
3237 let cwd = helix_stdx::env::current_working_dir();
3238 if !cwd.exists() {
3239 cx.editor.set_error(
3240 "Current buffer has no parent and current working directory does not exist",
3241 );
3242 return;
3243 }
3244 cx.editor.set_error(
3245 "Current buffer has no parent, opening file explorer in current working directory",
3246 );
3247 cwd
3248 }
3249 };
3250
3251 if let Ok(picker) = ui::file_explorer(path, cx.editor) {
3252 cx.push_layer(Box::new(overlaid(picker)));
3253 }
3254 }
3255
3256 fn file_explorer_in_current_directory(cx: &mut Context) {
3257 let cwd = helix_stdx::env::current_working_dir();
3258 if !cwd.exists() {
3259 cx.editor
3260 .set_error("Current working directory does not exist");
3261 return;
3262 }
3263
3264 if let Ok(picker) = ui::file_explorer(cwd, cx.editor) {
3265 cx.push_layer(Box::new(overlaid(picker)));
3266 }
3267 }
3268
3269 struct PathStyleConfig {
3270 directory_style: Style,
3271 number_style: Style,
3272 colon_style: Style,
3273 }
3274
3275 impl PathStyleConfig {
3276 fn new(theme: &helix_view::Theme) -> Self {
3277 Self {
3278 directory_style: theme.get("ui.text.directory"),
3279 number_style: theme.get("constant.numeric.integer"),
3280 colon_style: theme.get("punctuation"),
3281 }
3282 }
3283
3284 fn stylize<'a>(&self, path: Option<&'a Path>, line: Option<usize>) -> Cell<'a> {
3285 let mut spans = Vec::new();
3286 if let Some(path) = path {
3287 let directories = path
3288 .parent()
3289 .filter(|p| !p.as_os_str().is_empty())
3290 .map(|p| format!("{}{}", p.display(), std::path::MAIN_SEPARATOR))
3291 .unwrap_or_default();
3292 spans.push(Span::styled(directories, self.directory_style));
3293 }
3294 let filename = path.as_ref().map_or(SCRATCH_BUFFER_NAME.into(), |path| {
3295 path.file_name()
3296 .expect("all document names are normalized (can't end in `..`)")
3297 .to_string_lossy()
3298 });
3299 spans.push(Span::raw(filename));
3300 if let Some(line) = line {
3301 spans.extend([
3302 Span::styled(":", self.colon_style),
3303 Span::styled((line + 1).to_string(), self.number_style),
3304 ]);
3305 }
3306
3307 Cell::from(Spans::from(spans))
3308 }
3309 }
3310
3311 fn buffer_picker(cx: &mut Context) {
3312 let current = view!(cx.editor).doc;
3313
3314 struct BufferMeta<'a> {
3315 id: DocumentId,
3316 path: Option<Cow<'a, Path>>,
3317 is_modified: bool,
3318 is_current: bool,
3319 focused_at: std::time::Instant,
3320 }
3321
3322 let new_meta = |doc: &Document| BufferMeta {
3323 id: doc.id(),
3324 path: doc
3325 .path()
3326 .map(ToOwned::to_owned)
3327 .map(helix_stdx::path::get_relative_path),
3328 is_modified: doc.is_modified(),
3329 is_current: doc.id() == current,
3330 focused_at: doc.focused_at,
3331 };
3332
3333 let mut items = cx
3334 .editor
3335 .documents
3336 .values()
3337 .map(new_meta)
3338 .collect::<Vec<BufferMeta>>();
3339
3340 // mru
3341 items.sort_unstable_by_key(|item| std::cmp::Reverse(item.focused_at));
3342
3343 let columns = [
3344 PickerColumn::new("id", |meta: &BufferMeta, _| meta.id.to_string().into()),
3345 PickerColumn::new("flags", |meta: &BufferMeta, _| {
3346 let mut flags = String::new();
3347 if meta.is_modified {
3348 flags.push('+');
3349 }
3350 if meta.is_current {
3351 flags.push('*');
3352 }
3353 flags.into()
3354 }),
3355 PickerColumn::new("path", |meta: &BufferMeta, config: &PathStyleConfig| {
3356 config.stylize(meta.path.as_deref(), None)
3357 }),
3358 ];
3359
3360 let initial_cursor = if cx
3361 .editor
3362 .config()
3363 .buffer_picker
3364 .start_position
3365 .is_previous()
3366 && !items.is_empty()
3367 {
3368 1
3369 } else {
3370 0
3371 };
3372
3373 let picker = Picker::new(
3374 columns,
3375 2,
3376 items,
3377 PathStyleConfig::new(&cx.editor.theme),
3378 |cx, meta, action| {
3379 cx.editor.switch(meta.id, action);
3380 },
3381 )
3382 .with_initial_cursor(initial_cursor)
3383 .with_preview(|editor, meta| {
3384 let doc = &editor.documents.get(&meta.id)?;
3385 let lines = doc.selections().values().next().map(|selection| {
3386 let cursor_line = selection.primary().cursor_line(doc.text().slice(..));
3387 (cursor_line, cursor_line)
3388 });
3389 Some((meta.id.into(), lines))
3390 });
3391 cx.push_layer(Box::new(overlaid(picker)));
3392 }
3393
3394 fn jumplist_picker(cx: &mut Context) {
3395 struct JumpMeta<'a> {
3396 id: DocumentId,
3397 path: Option<Cow<'a, Path>>,
3398 selection: Selection,
3399 line_start: usize,
3400 text: String,
3401 is_current: bool,
3402 }
3403
3404 for (view, _) in cx.editor.tree.views_mut() {
3405 for doc_id in view.jumps.iter().map(|e| e.0).collect::<Vec<_>>().iter() {
3406 let doc = doc_mut!(cx.editor, doc_id);
3407 view.sync_changes(doc);
3408 }
3409 }
3410
3411 let new_meta = |view: &View, doc_id: DocumentId, selection: Selection| {
3412 let doc = doc!(cx.editor, &doc_id);
3413 let text = doc.text().slice(..);
3414 let contents = selection
3415 .fragments(text)
3416 .map(Cow::into_owned)
3417 .collect::<Vec<_>>()
3418 .join(" ");
3419 let line_start = selection.primary().cursor_line(text);
3420
3421 JumpMeta {
3422 id: doc_id,
3423 path: doc
3424 .path()
3425 .map(ToOwned::to_owned)
3426 .map(helix_stdx::path::get_relative_path),
3427 selection,
3428 line_start,
3429 text: contents,
3430 is_current: view.doc == doc_id,
3431 }
3432 };
3433
3434 let columns = [
3435 ui::PickerColumn::new("id", |item: &JumpMeta, _| item.id.to_string().into()),
3436 ui::PickerColumn::new("path", |item: &JumpMeta, config: &PathStyleConfig| {
3437 config.stylize(item.path.as_deref(), Some(item.line_start))
3438 }),
3439 ui::PickerColumn::new("flags", |item: &JumpMeta, _| {
3440 let mut flags = Vec::new();
3441 if item.is_current {
3442 flags.push("*");
3443 }
3444
3445 if flags.is_empty() {
3446 "".into()
3447 } else {
3448 format!(" ({})", flags.join("")).into()
3449 }
3450 }),
3451 ui::PickerColumn::new("contents", |item: &JumpMeta, _| item.text.as_str().into()),
3452 ];
3453
3454 let picker = Picker::new(
3455 columns,
3456 1, // path
3457 cx.editor.tree.views().flat_map(|(view, _)| {
3458 view.jumps
3459 .iter()
3460 .rev()
3461 .map(|(doc_id, selection)| new_meta(view, *doc_id, selection.clone()))
3462 }),
3463 PathStyleConfig::new(&cx.editor.theme),
3464 |cx, meta, action| {
3465 cx.editor.switch(meta.id, action);
3466 let config = cx.editor.config();
3467 let (view, doc) = (view_mut!(cx.editor), doc_mut!(cx.editor, &meta.id));
3468 doc.set_selection(view.id, meta.selection.clone());
3469 if action.align_view(view, doc.id()) {
3470 view.ensure_cursor_in_view_center(doc, config.scrolloff);
3471 }
3472 },
3473 )
3474 .with_preview(|editor, meta| {
3475 let doc = &editor.documents.get(&meta.id)?;
3476 let line = meta.selection.primary().cursor_line(doc.text().slice(..));
3477 Some((meta.id.into(), Some((line, line))))
3478 });
3479 cx.push_layer(Box::new(overlaid(picker)));
3480 }
3481
3482 fn changed_file_picker(cx: &mut Context) {
3483 pub struct FileChangeData {
3484 cwd: PathBuf,
3485 style_untracked: Style,
3486 style_modified: Style,
3487 style_conflict: Style,
3488 style_deleted: Style,
3489 style_renamed: Style,
3490 }
3491
3492 let cwd = helix_stdx::env::current_working_dir();
3493 if !cwd.exists() {
3494 cx.editor
3495 .set_error("Current working directory does not exist");
3496 return;
3497 }
3498
3499 let added = cx.editor.theme.get("diff.plus");
3500 let modified = cx.editor.theme.get("diff.delta");
3501 let conflict = cx.editor.theme.get("diff.delta.conflict");
3502 let deleted = cx.editor.theme.get("diff.minus");
3503 let renamed = cx.editor.theme.get("diff.delta.moved");
3504
3505 let columns = [
3506 PickerColumn::new("change", |change: &FileChange, data: &FileChangeData| {
3507 match change {
3508 FileChange::Untracked { .. } => Span::styled("+ untracked", data.style_untracked),
3509 FileChange::Modified { .. } => Span::styled("~ modified", data.style_modified),
3510 FileChange::Conflict { .. } => Span::styled("x conflict", data.style_conflict),
3511 FileChange::Deleted { .. } => Span::styled("- deleted", data.style_deleted),
3512 FileChange::Renamed { .. } => Span::styled("> renamed", data.style_renamed),
3513 }
3514 .into()
3515 }),
3516 PickerColumn::new("path", |change: &FileChange, data: &FileChangeData| {
3517 let display_path = |path: &PathBuf| {
3518 path.strip_prefix(&data.cwd)
3519 .unwrap_or(path)
3520 .display()
3521 .to_string()
3522 };
3523 match change {
3524 FileChange::Untracked { path } => display_path(path),
3525 FileChange::Modified { path } => display_path(path),
3526 FileChange::Conflict { path } => display_path(path),
3527 FileChange::Deleted { path } => display_path(path),
3528 FileChange::Renamed { from_path, to_path } => {
3529 format!("{} -> {}", display_path(from_path), display_path(to_path))
3530 }
3531 }
3532 .into()
3533 }),
3534 ];
3535
3536 let picker = Picker::new(
3537 columns,
3538 1, // path
3539 [],
3540 FileChangeData {
3541 cwd: cwd.clone(),
3542 style_untracked: added,
3543 style_modified: modified,
3544 style_conflict: conflict,
3545 style_deleted: deleted,
3546 style_renamed: renamed,
3547 },
3548 |cx, meta: &FileChange, action| {
3549 let path_to_open = meta.path();
3550 if let Err(e) = cx.editor.open(path_to_open, action) {
3551 let err = if let Some(err) = e.source() {
3552 format!("{}", err)
3553 } else {
3554 format!("unable to open \"{}\"", path_to_open.display())
3555 };
3556 cx.editor.set_error(err);
3557 }
3558 },
3559 )
3560 .with_preview(|_editor, meta| Some((meta.path().into(), None)));
3561 let injector = picker.injector();
3562
3563 let trust_full = cx
3564 .editor
3565 .workspace_trust
3566 .query(
3567 &helix_loader::find_workspace_in(&cwd).0,
3568 helix_loader::workspace_trust::TrustQuery::Git,
3569 )
3570 .is_trusted();
3571 cx.editor
3572 .diff_providers
3573 .clone()
3574 .for_each_changed_file(cwd, trust_full, move |change| match change {
3575 Ok(change) => injector.push(change).is_ok(),
3576 Err(err) => {
3577 status::report_blocking(err);
3578 true
3579 }
3580 });
3581 cx.push_layer(Box::new(overlaid(picker)));
3582 }
3583
3584 pub fn command_palette(cx: &mut Context) {
3585 let register = cx.register;
3586 let count = cx.count;
3587
3588 cx.callback.push(Box::new(
3589 move |compositor: &mut Compositor, cx: &mut compositor::Context| {
3590 let keymap = compositor.find::<ui::EditorView>().unwrap().keymaps.map()
3591 [&cx.editor.mode]
3592 .reverse_map();
3593
3594 let commands = MappableCommand::STATIC_COMMAND_LIST.iter().cloned().chain(
3595 typed::TYPABLE_COMMAND_LIST
3596 .iter()
3597 .map(|cmd| MappableCommand::Typable {
3598 name: cmd.name.to_owned(),
3599 args: String::new(),
3600 doc: cmd.doc.to_owned(),
3601 }),
3602 );
3603
3604 let columns = [
3605 ui::PickerColumn::new("name", |item, _| match item {
3606 MappableCommand::Typable { name, .. } => format!(":{name}").into(),
3607 MappableCommand::Static { name, .. } => (*name).into(),
3608 MappableCommand::Macro { .. } => {
3609 unreachable!("macros aren't included in the command palette")
3610 }
3611 }),
3612 ui::PickerColumn::new(
3613 "bindings",
3614 |item: &MappableCommand, keymap: &crate::keymap::ReverseKeymap| {
3615 keymap
3616 .get(item.name())
3617 .map(|bindings| {
3618 bindings.iter().fold(String::new(), |mut acc, bind| {
3619 if !acc.is_empty() {
3620 acc.push(' ');
3621 }
3622 for key in bind {
3623 acc.push_str(&key.key_sequence_format());
3624 }
3625 acc
3626 })
3627 })
3628 .unwrap_or_default()
3629 .into()
3630 },
3631 ),
3632 ui::PickerColumn::new("doc", |item: &MappableCommand, _| item.doc().into()),
3633 ];
3634
3635 let picker = Picker::new(columns, 0, commands, keymap, move |cx, command, _action| {
3636 let mut ctx = Context {
3637 register,
3638 count,
3639 editor: cx.editor,
3640 callback: Vec::new(),
3641 on_next_key_callback: None,
3642 jobs: cx.jobs,
3643 };
3644 let focus = view!(ctx.editor).id;
3645
3646 command.execute(&mut ctx);
3647
3648 if ctx.editor.tree.contains(focus) {
3649 let config = ctx.editor.config();
3650 let mode = ctx.editor.mode();
3651 let view = view_mut!(ctx.editor, focus);
3652 let doc = doc_mut!(ctx.editor, &view.doc);
3653
3654 view.ensure_cursor_in_view(doc, config.scrolloff);
3655
3656 if mode != Mode::Insert {
3657 doc.append_changes_to_history(view);
3658 }
3659 }
3660 });
3661 compositor.push(Box::new(overlaid(picker)));
3662 },
3663 ));
3664 }
3665
3666 fn last_picker(cx: &mut Context) {
3667 // TODO: last picker does not seem to work well with buffer_picker
3668 cx.callback.push(Box::new(|compositor, cx| {
3669 if let Some(picker) = compositor.last_picker.take() {
3670 compositor.push(picker);
3671 } else {
3672 cx.editor.set_error("no last picker")
3673 }
3674 }));
3675 }
3676
3677 /// Fallback position to use for [`insert_with_indent`].
3678 enum IndentFallbackPos {
3679 LineStart,
3680 LineEnd,
3681 }
3682
3683 // `I` inserts at the first nonwhitespace character of each line with a selection.
3684 // If the line is empty, automatically indent.
3685 fn insert_at_line_start(cx: &mut Context) {
3686 insert_with_indent(cx, IndentFallbackPos::LineStart);
3687 }
3688
3689 // `A` inserts at the end of each line with a selection.
3690 // If the line is empty, automatically indent.
3691 fn insert_at_line_end(cx: &mut Context) {
3692 insert_with_indent(cx, IndentFallbackPos::LineEnd);
3693 }
3694
3695 // Enter insert mode and auto-indent the current line if it is empty.
3696 // If the line is not empty, move the cursor to the specified fallback position.
3697 fn insert_with_indent(cx: &mut Context, cursor_fallback: IndentFallbackPos) {
3698 let was_select_mode = cx.editor.mode == Mode::Select;
3699 enter_insert_mode(cx);
3700
3701 let (view, doc) = current!(cx.editor);
3702 let loader = cx.editor.syn_loader.load();
3703
3704 let text = doc.text().slice(..);
3705 let contents = doc.text();
3706 let selection = doc.selection(view.id);
3707
3708 let syntax = doc.syntax();
3709 let tab_width = doc.tab_width();
3710
3711 let mut ranges = SmallVec::with_capacity(selection.len());
3712 let mut offs = 0;
3713
3714 let mut transaction = Transaction::change_by_selection(contents, selection, |range| {
3715 let cursor_line = range.cursor_line(text);
3716 let cursor_line_start = text.line_to_char(cursor_line);
3717
3718 if line_end_char_index(&text, cursor_line) == cursor_line_start {
3719 // line is empty => auto indent
3720 let line_end_index = cursor_line_start;
3721
3722 let indent = indent::indent_for_newline(
3723 &loader,
3724 syntax,
3725 &doc.config.load().indent_heuristic,
3726 &doc.indent_style,
3727 tab_width,
3728 text,
3729 cursor_line,
3730 line_end_index,
3731 cursor_line,
3732 );
3733
3734 // calculate new selection ranges
3735 let pos = offs + cursor_line_start;
3736 let indent_width = indent.chars().count();
3737 ranges.push(Range::point(pos + indent_width));
3738 offs += indent_width;
3739
3740 (line_end_index, line_end_index, Some(indent.into()))
3741 } else {
3742 // move cursor to the fallback position
3743 let pos = match cursor_fallback {
3744 IndentFallbackPos::LineStart => text
3745 .line(cursor_line)
3746 .first_non_whitespace_char()
3747 .map(|ws_offset| ws_offset + cursor_line_start)
3748 .unwrap_or(cursor_line_start),
3749 IndentFallbackPos::LineEnd => line_end_char_index(&text, cursor_line),
3750 };
3751
3752 ranges.push(range.put_cursor(text, pos + offs, was_select_mode));
3753
3754 (cursor_line_start, cursor_line_start, None)
3755 }
3756 });
3757
3758 transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
3759 doc.apply(&transaction, view.id);
3760 }
3761
3762 // Creates an LspCallback that waits for formatting changes to be computed. When they're done,
3763 // it applies them, but only if the doc hasn't changed.
3764 //
3765 // TODO: provide some way to cancel this, probably as part of a more general job cancellation
3766 // scheme
3767 async fn make_format_callback(
3768 doc_id: DocumentId,
3769 doc_version: i32,
3770 view_id: ViewId,
3771 format: impl Future<Output = Result<Transaction, FormatterError>> + Send + 'static,
3772 write: Option<(Option<PathBuf>, bool)>,
3773 ) -> anyhow::Result<job::Callback> {
3774 let format = format.await;
3775
3776 let call: job::Callback = Callback::Editor(Box::new(move |editor| {
3777 if !editor.documents.contains_key(&doc_id) || !editor.tree.contains(view_id) {
3778 return;
3779 }
3780
3781 let scrolloff = editor.config().scrolloff;
3782 let doc = doc_mut!(editor, &doc_id);
3783 let view = view_mut!(editor, view_id);
3784
3785 match format {
3786 Ok(format) => {
3787 if doc.version() == doc_version {
3788 doc.apply(&format, view.id);
3789 doc.append_changes_to_history(view);
3790 doc.detect_indent_and_line_ending();
3791 view.ensure_cursor_in_view(doc, scrolloff);
3792 } else {
3793 log::info!("discarded formatting changes because the document changed");
3794 }
3795 }
3796 Err(err) => {
3797 if write.is_none() {
3798 editor.set_error(err.to_string());
3799 return;
3800 }
3801 log::info!("failed to format '{}': {err}", doc.display_name());
3802 }
3803 }
3804
3805 if let Some((path, force)) = write {
3806 let id = doc.id();
3807 if let Err(err) = editor.save(id, path, force) {
3808 editor.set_error(format!("Error saving: {}", err));
3809 }
3810 }
3811 }));
3812
3813 Ok(call)
3814 }
3815
3816 #[derive(PartialEq, Eq)]
3817 pub enum Open {
3818 Below,
3819 Above,
3820 }
3821
3822 #[derive(PartialEq)]
3823 pub enum CommentContinuation {
3824 Enabled,
3825 Disabled,
3826 }
3827
3828 fn open(cx: &mut Context, open: Open, comment_continuation: CommentContinuation) {
3829 let count = cx.count();
3830 enter_insert_mode(cx);
3831 let config = cx.editor.config();
3832 let (view, doc) = current!(cx.editor);
3833 let loader = cx.editor.syn_loader.load();
3834
3835 let text = doc.text().slice(..);
3836 let contents = doc.text();
3837 let selection = doc.selection(view.id);
3838 let mut offs = 0;
3839
3840 let mut ranges = SmallVec::with_capacity(selection.len());
3841
3842 let mut transaction = Transaction::change_by_selection(contents, selection, |range| {
3843 // the line number, where the cursor is currently
3844 let curr_line_num = text.char_to_line(match open {
3845 Open::Below => graphemes::prev_grapheme_boundary(text, range.to()),
3846 Open::Above => range.from(),
3847 });
3848
3849 // the next line number, where the cursor will be, after finishing the transaction
3850 let next_new_line_num = match open {
3851 Open::Below => curr_line_num + 1,
3852 Open::Above => curr_line_num,
3853 };
3854
3855 let above_next_new_line_num = next_new_line_num.saturating_sub(1);
3856
3857 // Continue the comment leader using the comment tokens of the layer at the current line.
3858 let continue_comment_token =
3859 if comment_continuation == CommentContinuation::Enabled && config.continue_comments {
3860 text.line(curr_line_num)
3861 .first_non_whitespace_char()
3862 .map(|c| text.char_to_byte(text.line_to_char(curr_line_num) + c))
3863 .and_then(|byte| doc.language_config_at(&loader, byte))
3864 .and_then(|config| config.comment_tokens.as_ref())
3865 .and_then(|tokens| comment::get_comment_token(text, tokens, curr_line_num))
3866 } else {
3867 None
3868 };
3869
3870 // Index to insert newlines after, as well as the char width
3871 // to use to compensate for those inserted newlines.
3872 let (above_next_line_end_index, above_next_line_end_width) = if next_new_line_num == 0 {
3873 (0, 0)
3874 } else {
3875 (
3876 line_end_char_index(&text, above_next_new_line_num),
3877 doc.line_ending.len_chars(),
3878 )
3879 };
3880
3881 let line = text.line(curr_line_num);
3882 let indent = match line.first_non_whitespace_char() {
3883 Some(pos) if continue_comment_token.is_some() => line.slice(..pos).to_string(),
3884 _ => indent::indent_for_newline(
3885 &loader,
3886 doc.syntax(),
3887 &config.indent_heuristic,
3888 &doc.indent_style,
3889 doc.tab_width(),
3890 text,
3891 above_next_new_line_num,
3892 above_next_line_end_index,
3893 curr_line_num,
3894 ),
3895 };
3896
3897 let indent_len = indent.len();
3898 let mut text = String::with_capacity(1 + indent_len);
3899
3900 if open == Open::Above && next_new_line_num == 0 {
3901 text.push_str(&indent);
3902 if let Some(token) = continue_comment_token {
3903 text.push_str(token);
3904 text.push(' ');
3905 }
3906 text.push_str(doc.line_ending.as_str());
3907 } else {
3908 text.push_str(doc.line_ending.as_str());
3909 text.push_str(&indent);
3910
3911 if let Some(token) = continue_comment_token {
3912 text.push_str(token);
3913 text.push(' ');
3914 }
3915 }
3916
3917 let text = text.repeat(count);
3918
3919 // calculate new selection ranges
3920 let pos = offs + above_next_line_end_index + above_next_line_end_width;
3921 let comment_len = continue_comment_token
3922 .map(|token| token.len() + 1) // `+ 1` for the extra space added
3923 .unwrap_or_default();
3924 for i in 0..count {
3925 // pos -> beginning of reference line,
3926 // + (i * (line_ending_len + indent_len + comment_len)) -> beginning of i'th line from pos (possibly including comment token)
3927 // + indent_len + comment_len -> -> indent for i'th line
3928 ranges.push(Range::point(
3929 pos + (i * (doc.line_ending.len_chars() + indent_len + comment_len))
3930 + indent_len
3931 + comment_len,
3932 ));
3933 }
3934
3935 // update the offset for the next range
3936 offs += text.chars().count();
3937
3938 (
3939 above_next_line_end_index,
3940 above_next_line_end_index,
3941 Some(text.into()),
3942 )
3943 });
3944
3945 transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
3946
3947 doc.apply(&transaction, view.id);
3948 }
3949
3950 // o inserts a new line after each line with a selection
3951 fn open_below(cx: &mut Context) {
3952 open(cx, Open::Below, CommentContinuation::Enabled)
3953 }
3954
3955 // O inserts a new line before each line with a selection
3956 fn open_above(cx: &mut Context) {
3957 open(cx, Open::Above, CommentContinuation::Enabled)
3958 }
3959
3960 fn normal_mode(cx: &mut Context) {
3961 cx.editor.enter_normal_mode();
3962 }
3963
3964 // Store a jump on the jumplist.
3965 fn push_jump(view: &mut View, doc: &mut Document) {
3966 doc.append_changes_to_history(view);
3967 let jump = (doc.id(), doc.selection(view.id).clone());
3968 view.push_jump(doc, jump);
3969 }
3970
3971 fn goto_line(cx: &mut Context) {
3972 goto_line_impl(cx, Movement::Move);
3973 }
3974
3975 fn goto_line_impl(cx: &mut Context, movement: Movement) {
3976 if cx.count.is_some() {
3977 let (view, doc) = current!(cx.editor);
3978 push_jump(view, doc);
3979
3980 goto_line_without_jumplist(cx.editor, cx.count, movement);
3981 }
3982 }
3983
3984 fn goto_line_without_jumplist(
3985 editor: &mut Editor,
3986 count: Option<NonZeroUsize>,
3987 movement: Movement,
3988 ) {
3989 if let Some(count) = count {
3990 let (view, doc) = current!(editor);
3991 let text = doc.text().slice(..);
3992 let max_line = if text.line(text.len_lines() - 1).len_chars() == 0 {
3993 // If the last line is blank, don't jump to it.
3994 text.len_lines().saturating_sub(2)
3995 } else {
3996 text.len_lines() - 1
3997 };
3998 let line_idx = std::cmp::min(count.get() - 1, max_line);
3999 let pos = text.line_to_char(line_idx);
4000 let selection = doc
4001 .selection(view.id)
4002 .clone()
4003 .transform(|range| range.put_cursor(text, pos, movement == Movement::Extend));
4004
4005 doc.set_selection(view.id, selection);
4006 }
4007 }
4008
4009 fn goto_last_line(cx: &mut Context) {
4010 goto_last_line_impl(cx, Movement::Move)
4011 }
4012
4013 fn extend_to_last_line(cx: &mut Context) {
4014 goto_last_line_impl(cx, Movement::Extend)
4015 }
4016
4017 fn goto_last_line_impl(cx: &mut Context, movement: Movement) {
4018 let (view, doc) = current!(cx.editor);
4019 let text = doc.text().slice(..);
4020 let line_idx = if text.line(text.len_lines() - 1).len_chars() == 0 {
4021 // If the last line is blank, don't jump to it.
4022 text.len_lines().saturating_sub(2)
4023 } else {
4024 text.len_lines() - 1
4025 };
4026 let pos = text.line_to_char(line_idx);
4027 let selection = doc
4028 .selection(view.id)
4029 .clone()
4030 .transform(|range| range.put_cursor(text, pos, movement == Movement::Extend));
4031
4032 push_jump(view, doc);
4033 doc.set_selection(view.id, selection);
4034 }
4035
4036 fn goto_column(cx: &mut Context) {
4037 goto_column_impl(cx, Movement::Move);
4038 }
4039
4040 fn extend_to_column(cx: &mut Context) {
4041 goto_column_impl(cx, Movement::Extend);
4042 }
4043
4044 fn goto_column_impl(cx: &mut Context, movement: Movement) {
4045 let count = cx.count();
4046 let (view, doc) = current!(cx.editor);
4047 let text = doc.text().slice(..);
4048 let selection = doc.selection(view.id).clone().transform(|range| {
4049 let line = range.cursor_line(text);
4050 let line_start = text.line_to_char(line);
4051 let line_end = line_end_char_index(&text, line);
4052 let pos = graphemes::nth_next_grapheme_boundary(text, line_start, count - 1).min(line_end);
4053 range.put_cursor(text, pos, movement == Movement::Extend)
4054 });
4055 push_jump(view, doc);
4056 doc.set_selection(view.id, selection);
4057 }
4058
4059 fn goto_last_accessed_file(cx: &mut Context) {
4060 let view = view_mut!(cx.editor);
4061 if let Some(alt) = view.docs_access_history.pop() {
4062 cx.editor.switch(alt, Action::Replace);
4063 } else {
4064 cx.editor.set_error("no last accessed buffer")
4065 }
4066 }
4067
4068 fn goto_last_modification(cx: &mut Context) {
4069 let (view, doc) = current!(cx.editor);
4070 let pos = doc.history.get_mut().last_edit_pos();
4071 let text = doc.text().slice(..);
4072 if let Some(pos) = pos {
4073 let selection = doc
4074 .selection(view.id)
4075 .clone()
4076 .transform(|range| range.put_cursor(text, pos, cx.editor.mode == Mode::Select));
4077 push_jump(view, doc);
4078 doc.set_selection(view.id, selection);
4079 }
4080 }
4081
4082 fn goto_last_modified_file(cx: &mut Context) {
4083 let view = view!(cx.editor);
4084 let alternate_file = view
4085 .last_modified_docs
4086 .into_iter()
4087 .flatten()
4088 .find(|&id| id != view.doc);
4089 if let Some(alt) = alternate_file {
4090 cx.editor.switch(alt, Action::Replace);
4091 } else {
4092 cx.editor.set_error("no last modified buffer")
4093 }
4094 }
4095
4096 fn select_mode(cx: &mut Context) {
4097 let (view, doc) = current!(cx.editor);
4098 let text = doc.text().slice(..);
4099
4100 // Make sure end-of-document selections are also 1-width.
4101 // (With the exception of being in an empty document, of course.)
4102 let selection = doc.selection(view.id).clone().transform(|range| {
4103 if range.is_empty() && range.head == text.len_chars() {
4104 Range::new(
4105 graphemes::prev_grapheme_boundary(text, range.anchor),
4106 range.head,
4107 )
4108 } else {
4109 range
4110 }
4111 });
4112 doc.set_selection(view.id, selection);
4113
4114 cx.editor.mode = Mode::Select;
4115 }
4116
4117 fn exit_select_mode(cx: &mut Context) {
4118 if cx.editor.mode == Mode::Select {
4119 cx.editor.mode = Mode::Normal;
4120 }
4121 }
4122
4123 fn goto_first_diag(cx: &mut Context) {
4124 let (view, doc) = current!(cx.editor);
4125 let selection = match doc.diagnostics().first() {
4126 Some(diag) => Selection::single(diag.range.start, diag.range.end),
4127 None => return,
4128 };
4129 push_jump(view, doc);
4130 doc.set_selection(view.id, selection);
4131 view.diagnostics_handler
4132 .immediately_show_diagnostic(doc, view.id);
4133 }
4134
4135 fn goto_last_diag(cx: &mut Context) {
4136 let (view, doc) = current!(cx.editor);
4137 let selection = match doc.diagnostics().last() {
4138 Some(diag) => Selection::single(diag.range.start, diag.range.end),
4139 None => return,
4140 };
4141 push_jump(view, doc);
4142 doc.set_selection(view.id, selection);
4143 view.diagnostics_handler
4144 .immediately_show_diagnostic(doc, view.id);
4145 }
4146
4147 fn goto_next_diag(cx: &mut Context) {
4148 let motion = move |editor: &mut Editor| {
4149 let (view, doc) = current!(editor);
4150
4151 let cursor_pos = doc
4152 .selection(view.id)
4153 .primary()
4154 .cursor(doc.text().slice(..));
4155
4156 let diag = doc
4157 .diagnostics()
4158 .iter()
4159 .find(|diag| diag.range.start > cursor_pos);
4160
4161 let selection = match diag {
4162 Some(diag) => Selection::single(diag.range.start, diag.range.end),
4163 None => return,
4164 };
4165 push_jump(view, doc);
4166 doc.set_selection(view.id, selection);
4167 view.diagnostics_handler
4168 .immediately_show_diagnostic(doc, view.id);
4169 };
4170
4171 cx.editor.apply_motion(motion);
4172 }
4173
4174 fn goto_prev_diag(cx: &mut Context) {
4175 let motion = move |editor: &mut Editor| {
4176 let (view, doc) = current!(editor);
4177
4178 let cursor_pos = doc
4179 .selection(view.id)
4180 .primary()
4181 .cursor(doc.text().slice(..));
4182
4183 let diag = doc
4184 .diagnostics()
4185 .iter()
4186 .rev()
4187 .find(|diag| diag.range.start < cursor_pos);
4188
4189 let selection = match diag {
4190 // NOTE: the selection is reversed because we're jumping to the
4191 // previous diagnostic.
4192 Some(diag) => Selection::single(diag.range.end, diag.range.start),
4193 None => return,
4194 };
4195 push_jump(view, doc);
4196 doc.set_selection(view.id, selection);
4197 view.diagnostics_handler
4198 .immediately_show_diagnostic(doc, view.id);
4199 };
4200 cx.editor.apply_motion(motion)
4201 }
4202
4203 fn goto_first_change(cx: &mut Context) {
4204 goto_first_change_impl(cx, false);
4205 }
4206
4207 fn goto_last_change(cx: &mut Context) {
4208 goto_first_change_impl(cx, true);
4209 }
4210
4211 fn goto_first_change_impl(cx: &mut Context, reverse: bool) {
4212 let editor = &mut cx.editor;
4213 let (view, doc) = current!(editor);
4214 if let Some(handle) = doc.diff_handle() {
4215 let hunk = {
4216 let diff = handle.load();
4217 let idx = if reverse {
4218 diff.len().saturating_sub(1)
4219 } else {
4220 0
4221 };
4222 diff.nth_hunk(idx)
4223 };
4224 if hunk != Hunk::NONE {
4225 let range = hunk_range(hunk, doc.text().slice(..));
4226 push_jump(view, doc);
4227 doc.set_selection(view.id, Selection::single(range.anchor, range.head));
4228 }
4229 }
4230 }
4231
4232 fn goto_next_change(cx: &mut Context) {
4233 goto_next_change_impl(cx, Direction::Forward)
4234 }
4235
4236 fn goto_prev_change(cx: &mut Context) {
4237 goto_next_change_impl(cx, Direction::Backward)
4238 }
4239
4240 fn goto_next_change_impl(cx: &mut Context, direction: Direction) {
4241 let count = cx.count() as u32 - 1;
4242 let motion = move |editor: &mut Editor| {
4243 let (view, doc) = current!(editor);
4244 let doc_text = doc.text().slice(..);
4245 let diff_handle = if let Some(diff_handle) = doc.diff_handle() {
4246 diff_handle
4247 } else {
4248 editor.set_status("Diff is not available in current buffer");
4249 return;
4250 };
4251
4252 let selection = doc.selection(view.id).clone().transform(|range| {
4253 let cursor_line = range.cursor_line(doc_text) as u32;
4254
4255 let diff = diff_handle.load();
4256 let hunk_idx = match direction {
4257 Direction::Forward => diff
4258 .next_hunk(cursor_line)
4259 .map(|idx| (idx + count).min(diff.len() - 1)),
4260 Direction::Backward => diff
4261 .prev_hunk(cursor_line)
4262 .map(|idx| idx.saturating_sub(count)),
4263 };
4264 let Some(hunk_idx) = hunk_idx else {
4265 return range;
4266 };
4267 let hunk = diff.nth_hunk(hunk_idx);
4268 let new_range = hunk_range(hunk, doc_text);
4269 if editor.mode == Mode::Select {
4270 let head = if new_range.head < range.anchor {
4271 new_range.anchor
4272 } else {
4273 new_range.head
4274 };
4275
4276 Range::new(range.anchor, head)
4277 } else {
4278 new_range.with_direction(direction)
4279 }
4280 });
4281
4282 push_jump(view, doc);
4283 doc.set_selection(view.id, selection)
4284 };
4285 cx.editor.apply_motion(motion);
4286 }
4287
4288 /// Returns the [Range] for a [Hunk] in the given text.
4289 /// Additions and modifications cover the added and modified ranges.
4290 /// Deletions are represented as the point at the start of the deletion hunk.
4291 fn hunk_range(hunk: Hunk, text: RopeSlice) -> Range {
4292 let anchor = text.line_to_char(hunk.after.start as usize);
4293 let head = if hunk.after.is_empty() {
4294 anchor + 1
4295 } else {
4296 text.line_to_char(hunk.after.end as usize)
4297 };
4298
4299 Range::new(anchor, head)
4300 }
4301
4302 pub mod insert {
4303 use crate::{events::PostInsertChar, key};
4304
4305 use super::*;
4306 pub type Hook = fn(&Rope, &Selection, char) -> Option<Transaction>;
4307
4308 /// Exclude the cursor in range.
4309 fn exclude_cursor(text: RopeSlice, range: Range, cursor: Range) -> Range {
4310 if range.to() == cursor.to() && text.len_chars() != cursor.to() {
4311 Range::new(
4312 range.from(),
4313 graphemes::prev_grapheme_boundary(text, cursor.to()),
4314 )
4315 } else {
4316 range
4317 }
4318 }
4319
4320 use helix_core::auto_pairs;
4321 use helix_view::editor::SmartTabConfig;
4322
4323 pub fn insert_char(cx: &mut Context, c: char) {
4324 let (view, doc) = current_ref!(cx.editor);
4325 let text = doc.text();
4326 let selection = doc.selection(view.id);
4327
4328 let loader: &helix_core::syntax::Loader = &cx.editor.syn_loader.load();
4329 let auto_pairs = doc.auto_pairs(cx.editor, loader, view);
4330
4331 let insert_char = |range: Range, ch: char| {
4332 let cursor = range.cursor(text.slice(..));
4333 let t = Tendril::from_iter([ch]);
4334 ((cursor, cursor, Some(t)), None)
4335 };
4336
4337 let transaction = Transaction::change_by_and_with_selection(text, selection, |range| {
4338 auto_pairs
4339 .as_ref()
4340 .and_then(|ap| {
4341 auto_pairs::hook_insert(text, range, c, ap)
4342 .map(|(change, range)| (change, Some(range)))
4343 .or_else(|| Some(insert_char(*range, c)))
4344 })
4345 .unwrap_or_else(|| insert_char(*range, c))
4346 });
4347
4348 let doc = doc_mut!(cx.editor, &doc.id());
4349 doc.apply(&transaction, view.id);
4350
4351 helix_event::dispatch(PostInsertChar { c, cx });
4352 }
4353
4354 pub fn smart_tab(cx: &mut Context) {
4355 let (view, doc) = current_ref!(cx.editor);
4356 let view_id = view.id;
4357
4358 if matches!(
4359 cx.editor.config().smart_tab,
4360 Some(SmartTabConfig { enable: true, .. })
4361 ) {
4362 let cursors_after_whitespace = doc.selection(view_id).ranges().iter().all(|range| {
4363 let cursor = range.cursor(doc.text().slice(..));
4364 let current_line_num = doc.text().char_to_line(cursor);
4365 let current_line_start = doc.text().line_to_char(current_line_num);
4366 let left = doc.text().slice(current_line_start..cursor);
4367 left.chars().all(|c| c.is_whitespace())
4368 });
4369
4370 if !cursors_after_whitespace {
4371 if doc.active_snippet.is_some() {
4372 goto_next_tabstop(cx);
4373 } else {
4374 move_parent_node_end(cx);
4375 }
4376 return;
4377 }
4378 }
4379
4380 insert_tab(cx);
4381 }
4382
4383 pub fn insert_tab(cx: &mut Context) {
4384 insert_tab_impl(cx, 1)
4385 }
4386
4387 fn insert_tab_impl(cx: &mut Context, count: usize) {
4388 let (view, doc) = current!(cx.editor);
4389
4390 let transaction = Transaction::change(
4391 doc.text(),
4392 doc.selection(view.id).ranges().iter().map(|range| {
4393 let cursor = range.cursor(doc.text().slice(..));
4394 let indent = if let IndentStyle::Spaces(indent_width) = doc.indent_style {
4395 let line = range.cursor_line(doc.text().slice(..));
4396 let line_start = doc.text().line_to_char(line);
4397 let offset = (cursor - line_start) % indent_width as usize;
4398
4399 Tendril::from(doc.indent_style.as_str().repeat(count)).split_off(offset)
4400 } else {
4401 Tendril::from(doc.indent_style.as_str().repeat(count))
4402 };
4403
4404 (cursor, cursor, Some(indent))
4405 }),
4406 );
4407 doc.apply(&transaction, view.id);
4408 }
4409
4410 pub fn append_char_interactive(cx: &mut Context) {
4411 // Save the current mode, so we can restore it later.
4412 let mode = cx.editor.mode;
4413 append_mode(cx);
4414 insert_selection_interactive(cx, mode);
4415 }
4416
4417 pub fn insert_char_interactive(cx: &mut Context) {
4418 let mode = cx.editor.mode;
4419 insert_mode(cx);
4420 insert_selection_interactive(cx, mode);
4421 }
4422
4423 fn insert_selection_interactive(cx: &mut Context, old_mode: Mode) {
4424 let count = cx.count();
4425
4426 // need to wait for next key
4427 cx.on_next_key(move |cx, event| {
4428 match event {
4429 KeyEvent {
4430 code: KeyCode::Char(ch),
4431 ..
4432 } => {
4433 for _ in 0..count {
4434 insert::insert_char(cx, ch)
4435 }
4436 }
4437 key!(Enter) => {
4438 if count != 1 {
4439 cx.editor
4440 .set_error("inserting multiple newlines not yet supported");
4441 return;
4442 }
4443 insert_newline(cx)
4444 }
4445 key!(Tab) => insert_tab_impl(cx, count),
4446 _ => (),
4447 };
4448 // Restore the old mode.
4449 cx.editor.mode = old_mode;
4450 });
4451 }
4452
4453 pub fn insert_newline(cx: &mut Context) {
4454 let config = cx.editor.config();
4455 let (view, doc) = current_ref!(cx.editor);
4456 let loader = cx.editor.syn_loader.load();
4457 let text = doc.text().slice(..);
4458 let line_ending = doc.line_ending.as_str();
4459
4460 let contents = doc.text();
4461 let selection = doc.selection(view.id);
4462 let mut ranges = SmallVec::with_capacity(selection.len());
4463
4464 // TODO: this is annoying, but we need to do it to properly calculate pos after edits
4465 let mut global_offs = 0;
4466 let mut new_text = String::new();
4467
4468 let mut last_pos = 0;
4469 let mut transaction = Transaction::change_by_selection(contents, selection, |range| {
4470 // Tracks the number of trailing whitespace characters deleted by this selection.
4471 let mut chars_deleted = 0;
4472 let pos = range.cursor(text);
4473
4474 let prev = if pos == 0 {
4475 ' '
4476 } else {
4477 contents.char(pos - 1)
4478 };
4479 let curr = contents.get_char(pos).unwrap_or(' ');
4480
4481 let current_line = text.char_to_line(pos);
4482 let line_start = text.line_to_char(current_line);
4483
4484 // Continue the comment leader using the comment tokens of the layer at the comment
4485 // leader (i.e. the first non-whitespace char on the line). Looking up at the cursor
4486 // would land inside an injected layer (e.g. `comment`, or markdown in a doc comment)
4487 // and miss the host language's tokens.
4488 let continue_comment_token = if config.continue_comments {
4489 text.line(current_line)
4490 .first_non_whitespace_char()
4491 .map(|c| text.char_to_byte(line_start + c))
4492 .and_then(|byte| doc.language_config_at(&loader, byte))
4493 .and_then(|config| config.comment_tokens.as_ref())
4494 .and_then(|tokens| comment::get_comment_token(text, tokens, current_line))
4495 } else {
4496 None
4497 };
4498
4499 let (from, to, local_offs) = if let Some(idx) =
4500 text.slice(line_start..pos).last_non_whitespace_char()
4501 {
4502 let first_trailing_whitespace_char = (line_start + idx + 1).clamp(last_pos, pos);
4503 last_pos = pos;
4504 let line = text.line(current_line);
4505
4506 let indent = match line.first_non_whitespace_char() {
4507 Some(pos) if continue_comment_token.is_some() => line.slice(..pos).to_string(),
4508 _ => indent::indent_for_newline(
4509 &loader,
4510 doc.syntax(),
4511 &config.indent_heuristic,
4512 &doc.indent_style,
4513 doc.tab_width(),
4514 text,
4515 current_line,
4516 pos,
4517 current_line,
4518 ),
4519 };
4520
4521 let loader: &helix_core::syntax::Loader = &cx.editor.syn_loader.load();
4522 // If we are between pairs (such as brackets), we want to
4523 // insert an additional line which is indented one level
4524 // more and place the cursor there
4525 let on_auto_pair = doc
4526 .auto_pairs(cx.editor, loader, view)
4527 .and_then(|pairs| pairs.get(prev))
4528 .is_some_and(|pair| pair.open == prev && pair.close == curr);
4529
4530 let local_offs = if let Some(token) = continue_comment_token {
4531 new_text.reserve_exact(line_ending.len() + indent.len() + token.len() + 1);
4532 new_text.push_str(line_ending);
4533 new_text.push_str(&indent);
4534 new_text.push_str(token);
4535 new_text.push(' ');
4536 new_text.chars().count()
4537 } else if on_auto_pair {
4538 // line where the cursor will be
4539 let inner_indent = indent.clone() + doc.indent_style.as_str();
4540 new_text
4541 .reserve_exact(line_ending.len() * 2 + indent.len() + inner_indent.len());
4542 new_text.push_str(line_ending);
4543 new_text.push_str(&inner_indent);
4544
4545 // line where the matching pair will be
4546 let local_offs = new_text.chars().count();
4547 new_text.push_str(line_ending);
4548 new_text.push_str(&indent);
4549
4550 local_offs
4551 } else {
4552 new_text.reserve_exact(line_ending.len() + indent.len());
4553 new_text.push_str(line_ending);
4554 new_text.push_str(&indent);
4555
4556 new_text.chars().count()
4557 };
4558
4559 // Note that `first_trailing_whitespace_char` is at least `pos` so this unsigned
4560 // subtraction cannot underflow.
4561 chars_deleted = pos - first_trailing_whitespace_char;
4562
4563 (
4564 first_trailing_whitespace_char,
4565 pos,
4566 local_offs as isize - chars_deleted as isize,
4567 )
4568 } else {
4569 // If the current line is all whitespace, insert a line ending at the beginning of
4570 // the current line. This makes the current line empty and the new line contain the
4571 // indentation of the old line.
4572 new_text.push_str(line_ending);
4573
4574 (line_start, line_start, new_text.chars().count() as isize)
4575 };
4576
4577 let new_range = if range.cursor(text) > range.anchor {
4578 // when appending, extend the range by local_offs
4579 Range::new(
4580 (range.anchor as isize + global_offs) as usize,
4581 (range.head as isize + local_offs + global_offs) as usize,
4582 )
4583 } else {
4584 // when inserting, slide the range by local_offs
4585 Range::new(
4586 (range.anchor as isize + local_offs + global_offs) as usize,
4587 (range.head as isize + local_offs + global_offs) as usize,
4588 )
4589 };
4590
4591 // TODO: range replace or extend
4592 // range.replace(|range| range.is_empty(), head); -> fn extend if cond true, new head pos
4593 // can be used with cx.mode to do replace or extend on most changes
4594 ranges.push(new_range);
4595 global_offs += new_text.chars().count() as isize - chars_deleted as isize;
4596 let tendril = Tendril::from(&new_text);
4597 new_text.clear();
4598
4599 (from, to, Some(tendril))
4600 });
4601
4602 transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
4603
4604 let (view, doc) = current!(cx.editor);
4605 doc.apply(&transaction, view.id);
4606 }
4607
4608 fn dedent(doc: &Document, range: &Range) -> Option<Deletion> {
4609 let text = doc.text().slice(..);
4610 let pos = range.cursor(text);
4611 let line_start_pos = text.line_to_char(range.cursor_line(text));
4612
4613 // consider to delete by indent level if all characters before `pos` are indent units.
4614 let fragment = Cow::from(text.slice(line_start_pos..pos));
4615
4616 if fragment.is_empty() || !fragment.chars().all(|ch| ch == ' ' || ch == '\t') {
4617 return None;
4618 }
4619
4620 if text.get_char(pos.saturating_sub(1)) == Some('\t') {
4621 // fast path, delete one char
4622 return Some((graphemes::nth_prev_grapheme_boundary(text, pos, 1), pos));
4623 }
4624
4625 let tab_width = doc.tab_width();
4626 let indent_width = doc.indent_width();
4627
4628 let width: usize = fragment
4629 .chars()
4630 .map(|ch| {
4631 if ch == '\t' {
4632 tab_width
4633 } else {
4634 // it can be none if it still meet control characters other than '\t'
4635 // here just set the width to 1 (or some value better?).
4636 ch.width().unwrap_or(1)
4637 }
4638 })
4639 .sum();
4640
4641 // round down to nearest unit
4642 let mut drop = width % indent_width;
4643
4644 // if it's already at a unit, consume a whole unit
4645 if drop == 0 {
4646 drop = indent_width
4647 };
4648
4649 let mut chars = fragment.chars().rev();
4650 let mut start = pos;
4651
4652 for _ in 0..drop {
4653 // delete up to `drop` spaces
4654 match chars.next() {
4655 Some(' ') => start -= 1,
4656 _ => break,
4657 }
4658 }
4659
4660 Some((start, pos)) // delete!
4661 }
4662
4663 pub fn delete_char_backward(cx: &mut Context) {
4664 let count = cx.count();
4665 let (view, doc) = current_ref!(cx.editor);
4666 let text = doc.text().slice(..);
4667
4668 let loader: &helix_core::syntax::Loader = &cx.editor.syn_loader.load();
4669 let auto_pairs = doc.auto_pairs(cx.editor, loader, view);
4670
4671 let transaction = Transaction::delete_by_and_with_selection(
4672 doc.text(),
4673 doc.selection(view.id),
4674 |range| {
4675 let pos = range.cursor(text);
4676
4677 log::debug!("cursor: {}, len: {}", pos, text.len_chars());
4678
4679 if pos == 0 {
4680 return ((pos, pos), None);
4681 }
4682
4683 dedent(doc, range)
4684 .map(|dedent| (dedent, None))
4685 .or_else(|| {
4686 // [TODO] should this be fixed to get the auto pairs for
4687 // each selection after 46af40017c0704142516b5740cf1a000ba4fd7c1 ?
4688 auto_pairs::hook_delete(doc.text(), range, auto_pairs?)
4689 .map(|(delete, new_range)| (delete, Some(new_range)))
4690 })
4691 .unwrap_or_else(|| {
4692 (
4693 (graphemes::nth_prev_grapheme_boundary(text, pos, count), pos),
4694 None,
4695 )
4696 })
4697 },
4698 );
4699
4700 log::debug!("delete_char_backward transaction: {:?}", transaction);
4701
4702 let doc = doc_mut!(cx.editor, &doc.id());
4703 doc.apply(&transaction, view.id);
4704 }
4705
4706 pub fn delete_char_forward(cx: &mut Context) {
4707 let count = cx.count();
4708 delete_by_selection_insert_mode(
4709 cx,
4710 |text, range| {
4711 let pos = range.cursor(text);
4712 (pos, graphemes::nth_next_grapheme_boundary(text, pos, count))
4713 },
4714 Direction::Forward,
4715 )
4716 }
4717
4718 pub fn delete_word_backward(cx: &mut Context) {
4719 let count = cx.count();
4720 delete_by_selection_insert_mode(
4721 cx,
4722 |text, range| {
4723 let anchor = movement::move_prev_word_start(text, *range, count).from();
4724 let next = Range::new(anchor, range.cursor(text));
4725 let range = exclude_cursor(text, next, *range);
4726 (range.from(), range.to())
4727 },
4728 Direction::Backward,
4729 );
4730 }
4731
4732 pub fn delete_word_forward(cx: &mut Context) {
4733 let count = cx.count();
4734 delete_by_selection_insert_mode(
4735 cx,
4736 |text, range| {
4737 let head = movement::move_next_word_end(text, *range, count).to();
4738 (range.cursor(text), head)
4739 },
4740 Direction::Forward,
4741 );
4742 }
4743 }
4744
4745 // Undo / Redo
4746
4747 fn undo(cx: &mut Context) {
4748 let count = cx.count();
4749 let (view, doc) = current!(cx.editor);
4750 for _ in 0..count {
4751 if !doc.undo(view) {
4752 cx.editor.set_status("Already at oldest change");
4753 break;
4754 }
4755 }
4756 }
4757
4758 fn redo(cx: &mut Context) {
4759 let count = cx.count();
4760 let (view, doc) = current!(cx.editor);
4761 for _ in 0..count {
4762 if !doc.redo(view) {
4763 cx.editor.set_status("Already at newest change");
4764 break;
4765 }
4766 }
4767 }
4768
4769 fn earlier(cx: &mut Context) {
4770 let count = cx.count();
4771 let (view, doc) = current!(cx.editor);
4772 for _ in 0..count {
4773 // rather than doing in batch we do this so get error halfway
4774 if !doc.earlier(view, UndoKind::Steps(1)) {
4775 cx.editor.set_status("Already at oldest change");
4776 break;
4777 }
4778 }
4779 }
4780
4781 fn later(cx: &mut Context) {
4782 let count = cx.count();
4783 let (view, doc) = current!(cx.editor);
4784 for _ in 0..count {
4785 // rather than doing in batch we do this so get error halfway
4786 if !doc.later(view, UndoKind::Steps(1)) {
4787 cx.editor.set_status("Already at newest change");
4788 break;
4789 }
4790 }
4791 }
4792
4793 fn commit_undo_checkpoint(cx: &mut Context) {
4794 let (view, doc) = current!(cx.editor);
4795 doc.append_changes_to_history(view);
4796 }
4797
4798 // Yank / Paste
4799
4800 fn yank(cx: &mut Context) {
4801 yank_impl(
4802 cx.editor,
4803 cx.register
4804 .unwrap_or(cx.editor.config().default_yank_register),
4805 );
4806 exit_select_mode(cx);
4807 }
4808
4809 fn yank_to_clipboard(cx: &mut Context) {
4810 yank_impl(cx.editor, '+');
4811 exit_select_mode(cx);
4812 }
4813
4814 fn yank_to_primary_clipboard(cx: &mut Context) {
4815 yank_impl(cx.editor, '*');
4816 exit_select_mode(cx);
4817 }
4818
4819 fn yank_impl(editor: &mut Editor, register: char) {
4820 let (view, doc) = current!(editor);
4821 let text = doc.text().slice(..);
4822
4823 let values: Vec<String> = doc
4824 .selection(view.id)
4825 .fragments(text)
4826 .map(Cow::into_owned)
4827 .collect();
4828 let selections = values.len();
4829
4830 match editor.registers.write(register, values) {
4831 Ok(_) => editor.set_status(format!(
4832 "yanked {selections} selection{} to register {register}",
4833 if selections == 1 { "" } else { "s" }
4834 )),
4835 Err(err) => editor.set_error(err.to_string()),
4836 }
4837 }
4838
4839 fn yank_joined_impl(editor: &mut Editor, separator: &str, register: char) {
4840 let (view, doc) = current!(editor);
4841 let text = doc.text().slice(..);
4842
4843 let selection = doc.selection(view.id);
4844 let selections = selection.len();
4845 let joined = selection
4846 .fragments(text)
4847 .fold(String::new(), |mut acc, fragment| {
4848 if !acc.is_empty() {
4849 acc.push_str(separator);
4850 }
4851 acc.push_str(&fragment);
4852 acc
4853 });
4854
4855 match editor.registers.write(register, vec![joined]) {
4856 Ok(_) => editor.set_status(format!(
4857 "joined and yanked {selections} selection{} to register {register}",
4858 if selections == 1 { "" } else { "s" }
4859 )),
4860 Err(err) => editor.set_error(err.to_string()),
4861 }
4862 }
4863
4864 fn yank_joined(cx: &mut Context) {
4865 let separator = doc!(cx.editor).line_ending.as_str();
4866 yank_joined_impl(
4867 cx.editor,
4868 separator,
4869 cx.register
4870 .unwrap_or(cx.editor.config().default_yank_register),
4871 );
4872 exit_select_mode(cx);
4873 }
4874
4875 fn yank_joined_to_clipboard(cx: &mut Context) {
4876 let line_ending = doc!(cx.editor).line_ending;
4877 yank_joined_impl(cx.editor, line_ending.as_str(), '+');
4878 exit_select_mode(cx);
4879 }
4880
4881 fn yank_joined_to_primary_clipboard(cx: &mut Context) {
4882 let line_ending = doc!(cx.editor).line_ending;
4883 yank_joined_impl(cx.editor, line_ending.as_str(), '*');
4884 exit_select_mode(cx);
4885 }
4886
4887 pub(crate) fn yank_main_selection_to_register(editor: &mut Editor, register: char) {
4888 let (view, doc) = current!(editor);
4889 let text = doc.text().slice(..);
4890
4891 let selection = doc.selection(view.id).primary().fragment(text).to_string();
4892
4893 match editor.registers.write(register, vec![selection]) {
4894 Ok(_) => editor.set_status(format!("yanked primary selection to register {register}",)),
4895 Err(err) => editor.set_error(err.to_string()),
4896 }
4897 }
4898
4899 fn yank_main_selection_to_clipboard(cx: &mut Context) {
4900 yank_main_selection_to_register(cx.editor, '+');
4901 exit_select_mode(cx);
4902 }
4903
4904 fn yank_main_selection_to_primary_clipboard(cx: &mut Context) {
4905 yank_main_selection_to_register(cx.editor, '*');
4906 exit_select_mode(cx);
4907 }
4908
4909 #[derive(Copy, Clone)]
4910 pub(crate) enum Paste {
4911 Before,
4912 After,
4913 Cursor,
4914 }
4915
4916 static LINE_ENDING_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"\r\n|\r|\n").unwrap());
4917
4918 fn paste_impl(
4919 values: &[String],
4920 doc: &mut Document,
4921 view: &mut View,
4922 action: Paste,
4923 count: usize,
4924 mode: Mode,
4925 ) {
4926 if values.is_empty() {
4927 return;
4928 }
4929
4930 if mode == Mode::Insert {
4931 doc.append_changes_to_history(view);
4932 }
4933
4934 // if any of values ends with a line ending, it's linewise paste
4935 let linewise = values
4936 .iter()
4937 .any(|value| get_line_ending_of_str(value).is_some());
4938
4939 let map_value = |value| {
4940 let value = LINE_ENDING_REGEX.replace_all(value, doc.line_ending.as_str());
4941 let mut out = Tendril::from(value.as_ref());
4942 for _ in 1..count {
4943 out.push_str(&value);
4944 }
4945 out
4946 };
4947
4948 let repeat = std::iter::repeat(
4949 // `values` is asserted to have at least one entry above.
4950 map_value(values.last().unwrap()),
4951 );
4952
4953 let mut values = values.iter().map(|value| map_value(value)).chain(repeat);
4954
4955 let text = doc.text();
4956 let selection = doc.selection(view.id);
4957
4958 let mut offset = 0;
4959 let mut ranges = SmallVec::with_capacity(selection.len());
4960
4961 let mut transaction = Transaction::change_by_selection(text, selection, |range| {
4962 let pos = match (action, linewise) {
4963 // paste linewise before
4964 (Paste::Before, true) => text.line_to_char(text.char_to_line(range.from())),
4965 // paste linewise after
4966 (Paste::After, true) => {
4967 let line = range.line_range(text.slice(..)).1;
4968 text.line_to_char((line + 1).min(text.len_lines()))
4969 }
4970 // paste insert
4971 (Paste::Before, false) => range.from(),
4972 // paste append
4973 (Paste::After, false) => range.to(),
4974 // paste at cursor
4975 (Paste::Cursor, _) => range.cursor(text.slice(..)),
4976 };
4977
4978 let value = values.next();
4979
4980 let value_len = value
4981 .as_ref()
4982 .map(|content| content.chars().count())
4983 .unwrap_or_default();
4984 let anchor = offset + pos;
4985
4986 let new_range = Range::new(anchor, anchor + value_len).with_direction(range.direction());
4987 ranges.push(new_range);
4988 offset += value_len;
4989
4990 (pos, pos, value)
4991 });
4992
4993 if mode == Mode::Normal {
4994 transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
4995 }
4996
4997 doc.apply(&transaction, view.id);
4998 doc.append_changes_to_history(view);
4999 }
5000
5001 pub(crate) fn paste_bracketed_value(cx: &mut Context, contents: String) {
5002 let count = cx.count();
5003 let paste = match cx.editor.mode {
5004 Mode::Insert | Mode::Select => Paste::Cursor,
5005 Mode::Normal => Paste::Before,
5006 };
5007 let (view, doc) = current!(cx.editor);
5008 paste_impl(&[contents], doc, view, paste, count, cx.editor.mode);
5009 exit_select_mode(cx);
5010 }
5011
5012 fn paste_clipboard_after(cx: &mut Context) {
5013 paste(cx.editor, '+', Paste::After, cx.count());
5014 exit_select_mode(cx);
5015 }
5016
5017 fn paste_clipboard_before(cx: &mut Context) {
5018 paste(cx.editor, '+', Paste::Before, cx.count());
5019 exit_select_mode(cx);
5020 }
5021
5022 fn paste_primary_clipboard_after(cx: &mut Context) {
5023 paste(cx.editor, '*', Paste::After, cx.count());
5024 exit_select_mode(cx);
5025 }
5026
5027 fn paste_primary_clipboard_before(cx: &mut Context) {
5028 paste(cx.editor, '*', Paste::Before, cx.count());
5029 exit_select_mode(cx);
5030 }
5031
5032 fn replace_with_yanked(cx: &mut Context) {
5033 replace_selections_with_register(
5034 cx.editor,
5035 cx.register
5036 .unwrap_or(cx.editor.config().default_yank_register),
5037 cx.count(),
5038 );
5039 exit_select_mode(cx);
5040 }
5041
5042 pub(crate) fn replace_selections_with_register(editor: &mut Editor, register: char, count: usize) {
5043 let Some(values) = editor
5044 .registers
5045 .read(register, editor)
5046 .filter(|values| values.len() > 0)
5047 else {
5048 return;
5049 };
5050 let scrolloff = editor.config().scrolloff;
5051 let (view, doc) = current_ref!(editor);
5052
5053 let map_value = |value: &Cow<str>| {
5054 let value = LINE_ENDING_REGEX.replace_all(value, doc.line_ending.as_str());
5055 let mut out = Tendril::from(value.as_ref());
5056 for _ in 1..count {
5057 out.push_str(&value);
5058 }
5059 out
5060 };
5061 let mut values_rev = values.rev().peekable();
5062 // `values` is asserted to have at least one entry above.
5063 let last = values_rev.peek().unwrap();
5064 let repeat = std::iter::repeat(map_value(last));
5065 let mut values = values_rev
5066 .rev()
5067 .map(|value| map_value(&value))
5068 .chain(repeat);
5069 let selection = doc.selection(view.id);
5070 let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
5071 if !range.is_empty() {
5072 (range.from(), range.to(), Some(values.next().unwrap()))
5073 } else {
5074 (range.from(), range.to(), None)
5075 }
5076 });
5077 drop(values);
5078
5079 let (view, doc) = current!(editor);
5080 doc.apply(&transaction, view.id);
5081 doc.append_changes_to_history(view);
5082 view.ensure_cursor_in_view(doc, scrolloff);
5083 }
5084
5085 fn replace_selections_with_clipboard(cx: &mut Context) {
5086 replace_selections_with_register(cx.editor, '+', cx.count());
5087 exit_select_mode(cx);
5088 }
5089
5090 fn replace_selections_with_primary_clipboard(cx: &mut Context) {
5091 replace_selections_with_register(cx.editor, '*', cx.count());
5092 exit_select_mode(cx);
5093 }
5094
5095 pub(crate) fn paste(editor: &mut Editor, register: char, pos: Paste, count: usize) {
5096 let Some(values) = editor.registers.read(register, editor) else {
5097 return;
5098 };
5099 let values: Vec<_> = values.map(|value| value.to_string()).collect();
5100
5101 let (view, doc) = current!(editor);
5102 paste_impl(&values, doc, view, pos, count, editor.mode);
5103 }
5104
5105 fn paste_after(cx: &mut Context) {
5106 paste(
5107 cx.editor,
5108 cx.register
5109 .unwrap_or(cx.editor.config().default_yank_register),
5110 Paste::After,
5111 cx.count(),
5112 );
5113 exit_select_mode(cx);
5114 }
5115
5116 fn paste_before(cx: &mut Context) {
5117 paste(
5118 cx.editor,
5119 cx.register
5120 .unwrap_or(cx.editor.config().default_yank_register),
5121 Paste::Before,
5122 cx.count(),
5123 );
5124 exit_select_mode(cx);
5125 }
5126
5127 fn get_lines(doc: &Document, view_id: ViewId) -> Vec<usize> {
5128 let mut lines = Vec::new();
5129
5130 // Get all line numbers
5131 for range in doc.selection(view_id) {
5132 let (start, end) = range.line_range(doc.text().slice(..));
5133
5134 for line in start..=end {
5135 lines.push(line)
5136 }
5137 }
5138 lines.sort_unstable(); // sorting by usize so _unstable is preferred
5139 lines.dedup();
5140 lines
5141 }
5142
5143 fn indent(cx: &mut Context) {
5144 let count = cx.count();
5145 let (view, doc) = current!(cx.editor);
5146 let lines = get_lines(doc, view.id);
5147
5148 // Indent by one level
5149 let indent = Tendril::from(doc.indent_style.as_str().repeat(count));
5150
5151 let transaction = Transaction::change(
5152 doc.text(),
5153 lines.into_iter().filter_map(|line| {
5154 let is_blank = doc.text().line(line).chunks().all(|s| s.trim().is_empty());
5155 if is_blank {
5156 return None;
5157 }
5158 let pos = doc.text().line_to_char(line);
5159
5160 let indent = if let IndentStyle::Spaces(indent_width) = doc.indent_style {
5161 let line = doc.text().line(line);
5162 let offset = line.first_non_whitespace_char().unwrap_or(0) % indent_width as usize;
5163 indent.clone().split_off(offset)
5164 } else {
5165 indent.clone()
5166 };
5167
5168 Some((pos, pos, Some(indent)))
5169 }),
5170 );
5171 doc.apply(&transaction, view.id);
5172 exit_select_mode(cx);
5173 }
5174
5175 fn unindent(cx: &mut Context) {
5176 let count = cx.count();
5177 let (view, doc) = current!(cx.editor);
5178 let lines = get_lines(doc, view.id);
5179 let mut changes = Vec::with_capacity(lines.len());
5180 let tab_width = doc.tab_width();
5181 let indent_width = count * doc.indent_width();
5182
5183 for line_idx in lines {
5184 let line = doc.text().line(line_idx);
5185 let mut width = 0;
5186 let mut pos = 0;
5187
5188 for ch in line.chars() {
5189 match ch {
5190 ' ' => width += 1,
5191 '\t' => width = (width / tab_width + 1) * tab_width,
5192 _ => break,
5193 }
5194
5195 pos += 1;
5196
5197 if width >= indent_width {
5198 break;
5199 }
5200 }
5201
5202 // now delete from start to first non-blank
5203 if pos > 0 {
5204 let start = doc.text().line_to_char(line_idx);
5205 changes.push((start, start + pos, None))
5206 }
5207 }
5208
5209 let transaction = Transaction::change(doc.text(), changes.into_iter());
5210
5211 doc.apply(&transaction, view.id);
5212 exit_select_mode(cx);
5213 }
5214
5215 fn format_selections(cx: &mut Context) {
5216 use helix_lsp::{lsp, util::range_to_lsp_range};
5217
5218 let (view, doc) = current!(cx.editor);
5219 let view_id = view.id;
5220
5221 // via lsp if available
5222 // TODO: else via tree-sitter indentation calculations
5223
5224 if doc.selection(view_id).len() != 1 {
5225 cx.editor
5226 .set_error("format_selections only supports a single selection for now");
5227 return;
5228 }
5229
5230 // TODO extra LanguageServerFeature::FormatSelections?
5231 // maybe such that LanguageServerFeature::Format contains it as well
5232 let Some(language_server) = doc
5233 .language_servers_with_feature(LanguageServerFeature::Format)
5234 .find(|ls| {
5235 matches!(
5236 ls.capabilities().document_range_formatting_provider,
5237 Some(lsp::OneOf::Left(true) | lsp::OneOf::Right(_))
5238 )
5239 })
5240 else {
5241 cx.editor
5242 .set_error("No configured language server supports range formatting");
5243 return;
5244 };
5245
5246 let offset_encoding = language_server.offset_encoding();
5247 let ranges: Vec<lsp::Range> = doc
5248 .selection(view_id)
5249 .iter()
5250 .map(|range| range_to_lsp_range(doc.text(), *range, offset_encoding))
5251 .collect();
5252
5253 // TODO: handle fails
5254 // TODO: concurrent map over all ranges
5255
5256 let range = ranges[0];
5257
5258 let future = language_server
5259 .text_document_range_formatting(
5260 doc.identifier(),
5261 range,
5262 lsp::FormattingOptions {
5263 tab_size: doc.tab_width() as u32,
5264 insert_spaces: matches!(doc.indent_style, IndentStyle::Spaces(_)),
5265 ..Default::default()
5266 },
5267 None,
5268 )
5269 .unwrap();
5270
5271 let text = doc.text().clone();
5272 let doc_id = doc.id();
5273 let doc_version = doc.version();
5274
5275 tokio::spawn(async move {
5276 match future.await {
5277 Ok(Some(res)) => {
5278 let transaction =
5279 helix_lsp::util::generate_transaction_from_edits(&text, res, offset_encoding);
5280 job::dispatch(move |editor, _compositor| {
5281 let Some(doc) = editor.document_mut(doc_id) else {
5282 return;
5283 };
5284 // Updating a desynced document causes problems with applying the transaction
5285 if doc.version() != doc_version {
5286 return;
5287 }
5288 doc.apply(&transaction, view_id);
5289 })
5290 .await
5291 }
5292 Err(err) => log::error!("format sections failed: {err}"),
5293 Ok(None) => (),
5294 }
5295 });
5296 }
5297
5298 fn join_selections_impl(cx: &mut Context, select_space: bool) {
5299 use movement::skip_while;
5300 let loader = cx.editor.syn_loader.load();
5301 let (view, doc) = current!(cx.editor);
5302 let text = doc.text();
5303 let slice = text.slice(..);
5304
5305 let mut changes = Vec::new();
5306
5307 for selection in doc.selection(view.id) {
5308 let (start, mut end) = selection.line_range(slice);
5309 if start == end {
5310 end = (end + 1).min(text.len_lines() - 1);
5311 }
5312 let lines = start..end;
5313
5314 changes.reserve(lines.len());
5315
5316 // Strip the comment leader of joined lines using the comment tokens of the layer at this selection.
5317 let byte = slice.char_to_byte(slice.line_to_char(start));
5318 let comment_tokens = doc
5319 .language_config_at(&loader, byte)
5320 .and_then(|config| config.comment_tokens.as_deref())
5321 .unwrap_or(&[]);
5322 // Sort by length to handle Rust's /// vs //
5323 let mut comment_tokens: Vec<&str> = comment_tokens.iter().map(|x| x.as_str()).collect();
5324 comment_tokens.sort_unstable_by_key(|x| std::cmp::Reverse(x.len()));
5325
5326 let first_line_idx = slice.line_to_char(start);
5327 let first_line_idx = skip_while(slice, first_line_idx, |ch| matches!(ch, ' ' | '\t'))
5328 .unwrap_or(first_line_idx);
5329 let first_line = slice.slice(first_line_idx..);
5330 let mut current_comment_token = comment_tokens
5331 .iter()
5332 .find(|token| first_line.starts_with(token));
5333
5334 for line in lines {
5335 let start = line_end_char_index(&slice, line);
5336 let mut end = text.line_to_char(line + 1);
5337 end = skip_while(slice, end, |ch| matches!(ch, ' ' | '\t')).unwrap_or(end);
5338 let slice_from_end = slice.slice(end..);
5339 if let Some(token) = comment_tokens
5340 .iter()
5341 .find(|token| slice_from_end.starts_with(token))
5342 {
5343 if Some(token) == current_comment_token {
5344 end += token.chars().count();
5345 end = skip_while(slice, end, |ch| matches!(ch, ' ' | '\t')).unwrap_or(end);
5346 } else {
5347 // update current token, but don't delete this one.
5348 current_comment_token = Some(token);
5349 }
5350 }
5351
5352 let separator = if end == line_end_char_index(&slice, line + 1) {
5353 // the joining line contains only space-characters => don't include a whitespace when joining
5354 None
5355 } else {
5356 Some(Tendril::from(" "))
5357 };
5358 changes.push((start, end, separator));
5359 }
5360 }
5361
5362 // nothing to do, bail out early to avoid crashes later
5363 if changes.is_empty() {
5364 return;
5365 }
5366
5367 changes.sort_unstable_by_key(|(from, _to, _text)| *from);
5368 changes.dedup();
5369
5370 // select inserted spaces
5371 let transaction = if select_space {
5372 let mut offset: usize = 0;
5373 let ranges: SmallVec<_> = changes
5374 .iter()
5375 .filter_map(|change| {
5376 if change.2.is_some() {
5377 let range = Range::point(change.0 - offset);
5378 offset += change.1 - change.0 - 1; // -1 adjusts for the replacement of the range by a space
5379 Some(range)
5380 } else {
5381 offset += change.1 - change.0;
5382 None
5383 }
5384 })
5385 .collect();
5386 let t = Transaction::change(text, changes.into_iter());
5387 if ranges.is_empty() {
5388 t
5389 } else {
5390 let selection = Selection::new(ranges, 0);
5391 t.with_selection(selection)
5392 }
5393 } else {
5394 Transaction::change(text, changes.into_iter())
5395 };
5396
5397 doc.apply(&transaction, view.id);
5398 }
5399
5400 fn keep_or_remove_selections_impl(cx: &mut Context, remove: bool) {
5401 // keep or remove selections matching regex
5402 let reg = cx.register.unwrap_or('/');
5403 ui::regex_prompt(
5404 cx,
5405 if remove { "remove:" } else { "keep:" }.into(),
5406 Some(reg),
5407 ui::completers::none,
5408 move |cx, regex, event| {
5409 let (view, doc) = current!(cx.editor);
5410 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
5411 return;
5412 }
5413 let text = doc.text().slice(..);
5414
5415 if let Some(selection) =
5416 selection::keep_or_remove_matches(text, doc.selection(view.id), &regex, remove)
5417 {
5418 doc.set_selection(view.id, selection);
5419 } else if event == PromptEvent::Validate {
5420 cx.editor.set_error("no selections remaining");
5421 }
5422 },
5423 )
5424 }
5425
5426 fn join_selections(cx: &mut Context) {
5427 join_selections_impl(cx, false)
5428 }
5429
5430 fn join_selections_space(cx: &mut Context) {
5431 join_selections_impl(cx, true)
5432 }
5433
5434 fn keep_selections(cx: &mut Context) {
5435 keep_or_remove_selections_impl(cx, false)
5436 }
5437
5438 fn remove_selections(cx: &mut Context) {
5439 keep_or_remove_selections_impl(cx, true)
5440 }
5441
5442 fn keep_primary_selection(cx: &mut Context) {
5443 let (view, doc) = current!(cx.editor);
5444 // TODO: handle count
5445
5446 let range = doc.selection(view.id).primary();
5447 doc.set_selection(view.id, Selection::single(range.anchor, range.head));
5448 }
5449
5450 fn remove_primary_selection(cx: &mut Context) {
5451 let (view, doc) = current!(cx.editor);
5452 // TODO: handle count
5453
5454 let selection = doc.selection(view.id);
5455 if selection.len() == 1 {
5456 cx.editor.set_error("no selections remaining");
5457 return;
5458 }
5459 let index = selection.primary_index();
5460 let selection = selection.clone().remove(index);
5461
5462 doc.set_selection(view.id, selection);
5463 }
5464
5465 pub fn completion(cx: &mut Context) {
5466 let (view, doc) = current!(cx.editor);
5467 let range = doc.selection(view.id).primary();
5468 let text = doc.text().slice(..);
5469 let cursor = range.cursor(text);
5470
5471 cx.editor
5472 .handlers
5473 .trigger_completions(cursor, doc.id(), view.id);
5474 }
5475
5476 // comments
5477 type CommentTransactionFn = fn(
5478 line_token: Option<&str>,
5479 block_tokens: Option<&[BlockCommentToken]>,
5480 doc: &Rope,
5481 selection: &Selection,
5482 ) -> Transaction;
5483
5484 fn toggle_comments_impl(cx: &mut Context, comment_transaction: CommentTransactionFn) {
5485 let loader: &helix_core::syntax::Loader = &cx.editor.syn_loader.load();
5486 let (view, doc) = current!(cx.editor);
5487 let cursor = doc
5488 .selection(view.id)
5489 .primary()
5490 .cursor(doc.text().slice(..));
5491 let byte_pos = doc.text().char_to_byte(cursor);
5492 // Resolve the comment tokens from the enclosing injection layer that owns the comment,
5493 // not the innermost layer at the cursor. Prefer the innermost layer that defines
5494 // *line* comment tokens, falling back to the innermost layer with block tokens.
5495 let mut line_layer = None;
5496 let mut block_layer = None;
5497 if let Some(syntax) = doc.syntax() {
5498 for layer in syntax.layers_for_byte_range(byte_pos as u32, byte_pos as u32) {
5499 let language = syntax.layer(layer).language;
5500 let config = loader.language(language).config();
5501 if config.comment_tokens.is_some() {
5502 line_layer = Some(language);
5503 }
5504 if config.block_comment_tokens.is_some() {
5505 block_layer = Some(language);
5506 }
5507 }
5508 }
5509 let lang_config = line_layer
5510 .or(block_layer)
5511 .map(|language| &**loader.language(language).config())
5512 .or_else(|| doc.language_config());
5513
5514 // Pick the token the cursor's line is already commented with (longest match, so `///` wins over `//`).
5515 // If the line isn't commented yet, fall back to the primary token for adding a comment.
5516 let cursor_line = doc.text().char_to_line(cursor);
5517 let line_token: Option<&str> = lang_config
5518 .and_then(|lc| lc.comment_tokens.as_ref())
5519 .and_then(|tokens| {
5520 comment::get_comment_token(doc.text().slice(..), tokens, cursor_line)
5521 .or_else(|| tokens.first().map(|token| token.as_str()))
5522 });
5523 let block_tokens: Option<&[BlockCommentToken]> = lang_config
5524 .and_then(|lc| lc.block_comment_tokens.as_ref())
5525 .map(|tc| &tc[..]);
5526
5527 let transaction =
5528 comment_transaction(line_token, block_tokens, doc.text(), doc.selection(view.id));
5529
5530 doc.apply(&transaction, view.id);
5531 exit_select_mode(cx);
5532 }
5533
5534 /// commenting behavior:
5535 /// 1. only line comment tokens -> line comment
5536 /// 2. each line block commented -> uncomment all lines
5537 /// 3. whole selection block commented -> uncomment selection
5538 /// 4. all lines not commented and block tokens -> comment uncommented lines
5539 /// 5. no comment tokens and not block commented -> line comment
5540 fn toggle_comments(cx: &mut Context) {
5541 toggle_comments_impl(cx, |line_token, block_tokens, doc, selection| {
5542 let text = doc.slice(..);
5543
5544 // only have line comment tokens
5545 if line_token.is_some() && block_tokens.is_none() {
5546 return comment::toggle_line_comments(doc, selection, line_token);
5547 }
5548
5549 let split_lines = comment::split_lines_of_selection(text, selection);
5550
5551 let default_block_tokens = &[BlockCommentToken::default()];
5552 let block_comment_tokens = block_tokens.unwrap_or(default_block_tokens);
5553
5554 let (line_commented, line_comment_changes) =
5555 comment::find_block_comments(block_comment_tokens, text, &split_lines);
5556
5557 // block commented by line would also be block commented so check this first
5558 if line_commented {
5559 return comment::create_block_comment_transaction(
5560 doc,
5561 &split_lines,
5562 line_commented,
5563 line_comment_changes,
5564 )
5565 .0;
5566 }
5567
5568 let (block_commented, comment_changes) =
5569 comment::find_block_comments(block_comment_tokens, text, selection);
5570
5571 // check if selection has block comments
5572 if block_commented {
5573 return comment::create_block_comment_transaction(
5574 doc,
5575 selection,
5576 block_commented,
5577 comment_changes,
5578 )
5579 .0;
5580 }
5581
5582 // not commented and only have block comment tokens
5583 if line_token.is_none() && block_tokens.is_some() {
5584 return comment::create_block_comment_transaction(
5585 doc,
5586 &split_lines,
5587 line_commented,
5588 line_comment_changes,
5589 )
5590 .0;
5591 }
5592
5593 // not block commented at all and don't have any tokens
5594 comment::toggle_line_comments(doc, selection, line_token)
5595 })
5596 }
5597
5598 fn toggle_line_comments(cx: &mut Context) {
5599 toggle_comments_impl(cx, |line_token, block_tokens, doc, selection| {
5600 if line_token.is_none() && block_tokens.is_some() {
5601 let default_block_tokens = &[BlockCommentToken::default()];
5602 let block_comment_tokens = block_tokens.unwrap_or(default_block_tokens);
5603 comment::toggle_block_comments(
5604 doc,
5605 &comment::split_lines_of_selection(doc.slice(..), selection),
5606 block_comment_tokens,
5607 )
5608 } else {
5609 comment::toggle_line_comments(doc, selection, line_token)
5610 }
5611 });
5612 }
5613
5614 fn toggle_block_comments(cx: &mut Context) {
5615 toggle_comments_impl(cx, |line_token, block_tokens, doc, selection| {
5616 if line_token.is_some() && block_tokens.is_none() {
5617 comment::toggle_line_comments(doc, selection, line_token)
5618 } else {
5619 let default_block_tokens = &[BlockCommentToken::default()];
5620 let block_comment_tokens = block_tokens.unwrap_or(default_block_tokens);
5621 comment::toggle_block_comments(doc, selection, block_comment_tokens)
5622 }
5623 });
5624 }
5625
5626 fn rotate_selections(cx: &mut Context, direction: Direction) {
5627 let count = cx.count();
5628 let (view, doc) = current!(cx.editor);
5629 let mut selection = doc.selection(view.id).clone();
5630 let index = selection.primary_index();
5631 let len = selection.len();
5632 selection.set_primary_index(match direction {
5633 Direction::Forward => (index + count) % len,
5634 Direction::Backward => (index + (len.saturating_sub(count) % len)) % len,
5635 });
5636 doc.set_selection(view.id, selection);
5637 }
5638 fn rotate_selections_forward(cx: &mut Context) {
5639 rotate_selections(cx, Direction::Forward)
5640 }
5641 fn rotate_selections_backward(cx: &mut Context) {
5642 rotate_selections(cx, Direction::Backward)
5643 }
5644
5645 fn rotate_selections_first(cx: &mut Context) {
5646 let (view, doc) = current!(cx.editor);
5647 let mut selection = doc.selection(view.id).clone();
5648 selection.set_primary_index(0);
5649 doc.set_selection(view.id, selection);
5650 }
5651
5652 fn rotate_selections_last(cx: &mut Context) {
5653 let (view, doc) = current!(cx.editor);
5654 let mut selection = doc.selection(view.id).clone();
5655 let len = selection.len();
5656 selection.set_primary_index(len - 1);
5657 doc.set_selection(view.id, selection);
5658 }
5659
5660 #[derive(Debug)]
5661 enum ReorderStrategy {
5662 RotateForward,
5663 RotateBackward,
5664 Reverse,
5665 }
5666
5667 fn reorder_selection_contents(cx: &mut Context, strategy: ReorderStrategy) {
5668 let count = cx.count;
5669 let (view, doc) = current!(cx.editor);
5670 let text = doc.text().slice(..);
5671
5672 let selection = doc.selection(view.id);
5673
5674 let mut ranges: Vec<_> = selection
5675 .slices(text)
5676 .map(|fragment| fragment.chunks().collect())
5677 .collect();
5678
5679 let rotate_by = count.map_or(1, |count| count.get().min(ranges.len()));
5680
5681 let primary_index = match strategy {
5682 ReorderStrategy::RotateForward => {
5683 ranges.rotate_right(rotate_by);
5684 // Like `usize::wrapping_add`, but provide a custom range from `0` to `ranges.len()`
5685 (selection.primary_index() + ranges.len() + rotate_by) % ranges.len()
5686 }
5687 ReorderStrategy::RotateBackward => {
5688 ranges.rotate_left(rotate_by);
5689 // Like `usize::wrapping_sub`, but provide a custom range from `0` to `ranges.len()`
5690 (selection.primary_index() + ranges.len() - rotate_by) % ranges.len()
5691 }
5692 ReorderStrategy::Reverse => {
5693 if rotate_by.is_multiple_of(2) {
5694 // nothing changed, if we reverse something an even
5695 // amount of times, the output will be the same
5696 return;
5697 }
5698 ranges.reverse();
5699 // -1 to turn 1-based len into 0-based index
5700 (ranges.len() - 1) - selection.primary_index()
5701 }
5702 };
5703
5704 let transaction = Transaction::change(
5705 doc.text(),
5706 selection
5707 .ranges()
5708 .iter()
5709 .zip(ranges)
5710 .map(|(range, fragment)| (range.from(), range.to(), Some(fragment))),
5711 );
5712
5713 doc.set_selection(
5714 view.id,
5715 Selection::new(selection.ranges().into(), primary_index),
5716 );
5717 doc.apply(&transaction, view.id);
5718 }
5719
5720 fn rotate_selection_contents_forward(cx: &mut Context) {
5721 reorder_selection_contents(cx, ReorderStrategy::RotateForward)
5722 }
5723 fn rotate_selection_contents_backward(cx: &mut Context) {
5724 reorder_selection_contents(cx, ReorderStrategy::RotateBackward)
5725 }
5726 fn reverse_selection_contents(cx: &mut Context) {
5727 reorder_selection_contents(cx, ReorderStrategy::Reverse)
5728 }
5729
5730 // tree sitter node selection
5731
5732 fn expand_selection(cx: &mut Context) {
5733 let motion = |editor: &mut Editor| {
5734 let (view, doc) = current!(editor);
5735
5736 if let Some(syntax) = doc.syntax() {
5737 let text = doc.text().slice(..);
5738
5739 let current_selection = doc.selection(view.id);
5740 let selection = object::expand_selection(syntax, text, current_selection.clone());
5741
5742 // check if selection is different from the last one
5743 if *current_selection != selection {
5744 // save current selection so it can be restored using shrink_selection
5745 view.object_selections.push(current_selection.clone());
5746
5747 doc.set_selection(view.id, selection);
5748 }
5749 }
5750 };
5751 cx.editor.apply_motion(motion);
5752 }
5753
5754 fn shrink_selection(cx: &mut Context) {
5755 let motion = |editor: &mut Editor| {
5756 let (view, doc) = current!(editor);
5757 let current_selection = doc.selection(view.id);
5758 // try to restore previous selection
5759 if let Some(prev_selection) = view.object_selections.pop() {
5760 if current_selection.contains(&prev_selection) {
5761 doc.set_selection(view.id, prev_selection);
5762 return;
5763 } else {
5764 // clear existing selection as they can't be shrunk to anyway
5765 view.object_selections.clear();
5766 }
5767 }
5768 // if not previous selection, shrink to first child
5769 if let Some(syntax) = doc.syntax() {
5770 let text = doc.text().slice(..);
5771 let selection = object::shrink_selection(syntax, text, current_selection.clone());
5772 doc.set_selection(view.id, selection);
5773 }
5774 };
5775 cx.editor.apply_motion(motion);
5776 }
5777
5778 fn select_sibling_impl<F>(cx: &mut Context, sibling_fn: F)
5779 where
5780 F: Fn(&helix_core::Syntax, RopeSlice, Selection) -> Selection + 'static,
5781 {
5782 let motion = move |editor: &mut Editor| {
5783 let (view, doc) = current!(editor);
5784
5785 if let Some(syntax) = doc.syntax() {
5786 let text = doc.text().slice(..);
5787 let current_selection = doc.selection(view.id);
5788 let selection = sibling_fn(syntax, text, current_selection.clone());
5789 doc.set_selection(view.id, selection);
5790 }
5791 };
5792 cx.editor.apply_motion(motion);
5793 }
5794
5795 fn select_next_sibling(cx: &mut Context) {
5796 select_sibling_impl(cx, object::select_next_sibling)
5797 }
5798
5799 fn select_prev_sibling(cx: &mut Context) {
5800 select_sibling_impl(cx, object::select_prev_sibling)
5801 }
5802
5803 fn move_node_bound_impl(cx: &mut Context, dir: Direction, movement: Movement) {
5804 let motion = move |editor: &mut Editor| {
5805 let (view, doc) = current!(editor);
5806
5807 if let Some(syntax) = doc.syntax() {
5808 let text = doc.text().slice(..);
5809 let current_selection = doc.selection(view.id);
5810
5811 let selection = movement::move_parent_node_end(
5812 syntax,
5813 text,
5814 current_selection.clone(),
5815 dir,
5816 movement,
5817 );
5818
5819 doc.set_selection(view.id, selection);
5820 }
5821 };
5822
5823 cx.editor.apply_motion(motion);
5824 }
5825
5826 pub fn move_parent_node_end(cx: &mut Context) {
5827 move_node_bound_impl(cx, Direction::Forward, Movement::Move)
5828 }
5829
5830 pub fn move_parent_node_start(cx: &mut Context) {
5831 move_node_bound_impl(cx, Direction::Backward, Movement::Move)
5832 }
5833
5834 pub fn extend_parent_node_end(cx: &mut Context) {
5835 move_node_bound_impl(cx, Direction::Forward, Movement::Extend)
5836 }
5837
5838 pub fn extend_parent_node_start(cx: &mut Context) {
5839 move_node_bound_impl(cx, Direction::Backward, Movement::Extend)
5840 }
5841
5842 fn select_all_impl<F>(editor: &mut Editor, select_fn: F)
5843 where
5844 F: Fn(&Syntax, RopeSlice, Selection) -> Selection,
5845 {
5846 let (view, doc) = current!(editor);
5847
5848 if let Some(syntax) = doc.syntax() {
5849 let text = doc.text().slice(..);
5850 let current_selection = doc.selection(view.id);
5851 let selection = select_fn(syntax, text, current_selection.clone());
5852 doc.set_selection(view.id, selection);
5853 }
5854 }
5855
5856 fn select_all_siblings(cx: &mut Context) {
5857 let motion = |editor: &mut Editor| {
5858 select_all_impl(editor, object::select_all_siblings);
5859 };
5860
5861 cx.editor.apply_motion(motion);
5862 }
5863
5864 fn select_all_children(cx: &mut Context) {
5865 let motion = |editor: &mut Editor| {
5866 select_all_impl(editor, object::select_all_children);
5867 };
5868
5869 cx.editor.apply_motion(motion);
5870 }
5871
5872 fn match_brackets(cx: &mut Context) {
5873 let (view, doc) = current!(cx.editor);
5874 let is_select = cx.editor.mode == Mode::Select;
5875 let text = doc.text();
5876 let text_slice = text.slice(..);
5877
5878 let selection = doc.selection(view.id).clone().transform(|range| {
5879 let pos = range.cursor(text_slice);
5880 if let Some(matched_pos) = doc.syntax().map_or_else(
5881 || match_brackets::find_matching_bracket_plaintext(text.slice(..), pos),
5882 |syntax| match_brackets::find_matching_bracket_fuzzy(syntax, text.slice(..), pos),
5883 ) {
5884 range.put_cursor(text_slice, matched_pos, is_select)
5885 } else {
5886 range
5887 }
5888 });
5889
5890 doc.set_selection(view.id, selection);
5891 }
5892
5893 //
5894
5895 fn jump_forward(cx: &mut Context) {
5896 cx.editor.jump_forward(cx.editor.tree.focus, cx.count());
5897 }
5898
5899 fn jump_backward(cx: &mut Context) {
5900 cx.editor.jump_backward(cx.editor.tree.focus, cx.count());
5901 }
5902
5903 fn save_selection(cx: &mut Context) {
5904 let (view, doc) = current!(cx.editor);
5905 push_jump(view, doc);
5906 cx.editor.set_status("Selection saved to jumplist");
5907 }
5908
5909 fn rotate_view(cx: &mut Context) {
5910 cx.editor.focus_next()
5911 }
5912
5913 fn rotate_view_reverse(cx: &mut Context) {
5914 cx.editor.focus_prev()
5915 }
5916
5917 fn jump_view_right(cx: &mut Context) {
5918 cx.editor.focus_direction(tree::Direction::Right)
5919 }
5920
5921 fn jump_view_left(cx: &mut Context) {
5922 cx.editor.focus_direction(tree::Direction::Left)
5923 }
5924
5925 fn jump_view_up(cx: &mut Context) {
5926 cx.editor.focus_direction(tree::Direction::Up)
5927 }
5928
5929 fn jump_view_down(cx: &mut Context) {
5930 cx.editor.focus_direction(tree::Direction::Down)
5931 }
5932
5933 fn swap_view_right(cx: &mut Context) {
5934 cx.editor.swap_split_in_direction(tree::Direction::Right)
5935 }
5936
5937 fn swap_view_left(cx: &mut Context) {
5938 cx.editor.swap_split_in_direction(tree::Direction::Left)
5939 }
5940
5941 fn swap_view_up(cx: &mut Context) {
5942 cx.editor.swap_split_in_direction(tree::Direction::Up)
5943 }
5944
5945 fn swap_view_down(cx: &mut Context) {
5946 cx.editor.swap_split_in_direction(tree::Direction::Down)
5947 }
5948
5949 fn transpose_view(cx: &mut Context) {
5950 cx.editor.transpose_view()
5951 }
5952
5953 /// Open a new split in the given direction specified by the action.
5954 ///
5955 /// Maintain the current view (both the cursor's position and view in document).
5956 fn split(editor: &mut Editor, action: Action) {
5957 let (view, doc) = current!(editor);
5958 let id = doc.id();
5959 let selection = doc.selection(view.id).clone();
5960 let offset = doc.view_offset(view.id);
5961
5962 editor.switch(id, action);
5963
5964 // match the selection in the previous view
5965 let (view, doc) = current!(editor);
5966 doc.set_selection(view.id, selection);
5967 // match the view scroll offset (switch doesn't handle this fully
5968 // since the selection is only matched after the split)
5969 doc.set_view_offset(view.id, offset);
5970 }
5971
5972 fn hsplit(cx: &mut Context) {
5973 split(cx.editor, Action::HorizontalSplit);
5974 }
5975
5976 fn hsplit_new(cx: &mut Context) {
5977 cx.editor.new_file(Action::HorizontalSplit);
5978 }
5979
5980 fn vsplit(cx: &mut Context) {
5981 split(cx.editor, Action::VerticalSplit);
5982 }
5983
5984 fn vsplit_new(cx: &mut Context) {
5985 cx.editor.new_file(Action::VerticalSplit);
5986 }
5987
5988 fn wclose(cx: &mut Context) {
5989 if cx.editor.tree.views().count() == 1 {
5990 if let Err(err) = typed::buffers_remaining_impl(cx.editor) {
5991 cx.editor.set_error(err.to_string());
5992 return;
5993 }
5994 }
5995 let view_id = view!(cx.editor).id;
5996 // close current split
5997 cx.editor.close(view_id);
5998 }
5999
6000 fn wonly(cx: &mut Context) {
6001 let views = cx
6002 .editor
6003 .tree
6004 .views()
6005 .map(|(v, focus)| (v.id, focus))
6006 .collect::<Vec<_>>();
6007 for (view_id, focus) in views {
6008 if !focus {
6009 cx.editor.close(view_id);
6010 }
6011 }
6012 }
6013
6014 fn select_register(cx: &mut Context) {
6015 cx.editor.autoinfo = Some(Info::from_registers(
6016 "Select register",
6017 &cx.editor.registers,
6018 ));
6019 cx.on_next_key(move |cx, event| {
6020 cx.editor.autoinfo = None;
6021 if let Some(ch) = event.char() {
6022 cx.editor.selected_register = Some(ch);
6023 }
6024 })
6025 }
6026
6027 fn insert_register(cx: &mut Context) {
6028 // TODO: count is reset to 1 before next key so we move it into the closure here.
6029 // Would be nice to carry over.
6030 let count = cx.count();
6031 cx.editor.autoinfo = Some(Info::from_registers(
6032 "Insert register",
6033 &cx.editor.registers,
6034 ));
6035 cx.on_next_key(move |cx, event| {
6036 cx.editor.autoinfo = None;
6037 if let Some(ch) = event.char() {
6038 cx.register = Some(ch);
6039 paste(
6040 cx.editor,
6041 cx.register
6042 .unwrap_or(cx.editor.config().default_yank_register),
6043 Paste::Cursor,
6044 count,
6045 );
6046 }
6047 })
6048 }
6049
6050 fn copy_between_registers(cx: &mut Context) {
6051 cx.editor.autoinfo = Some(Info::from_registers(
6052 "Copy from register",
6053 &cx.editor.registers,
6054 ));
6055 cx.on_next_key(move |cx, event| {
6056 cx.editor.autoinfo = None;
6057
6058 let Some(source) = event.char() else {
6059 return;
6060 };
6061
6062 let Some(values) = cx.editor.registers.read(source, cx.editor) else {
6063 cx.editor.set_error(format!("register {source} is empty"));
6064 return;
6065 };
6066 let values: Vec<_> = values.map(|value| value.to_string()).collect();
6067
6068 cx.editor.autoinfo = Some(Info::from_registers(
6069 "Copy into register",
6070 &cx.editor.registers,
6071 ));
6072 cx.on_next_key(move |cx, event| {
6073 cx.editor.autoinfo = None;
6074
6075 let Some(dest) = event.char() else {
6076 return;
6077 };
6078
6079 let n_values = values.len();
6080 match cx.editor.registers.write(dest, values) {
6081 Ok(_) => cx.editor.set_status(format!(
6082 "yanked {n_values} value{} from register {source} to {dest}",
6083 if n_values == 1 { "" } else { "s" }
6084 )),
6085 Err(err) => cx.editor.set_error(err.to_string()),
6086 }
6087 });
6088 });
6089 }
6090
6091 fn align_view_top(cx: &mut Context) {
6092 let (view, doc) = current!(cx.editor);
6093 align_view(doc, view, Align::Top);
6094 }
6095
6096 fn align_view_center(cx: &mut Context) {
6097 let (view, doc) = current!(cx.editor);
6098 align_view(doc, view, Align::Center);
6099 }
6100
6101 fn align_view_bottom(cx: &mut Context) {
6102 let (view, doc) = current!(cx.editor);
6103 align_view(doc, view, Align::Bottom);
6104 }
6105
6106 fn align_view_middle(cx: &mut Context) {
6107 let (view, doc) = current!(cx.editor);
6108 let inner_width = view.inner_width(doc);
6109 let text_fmt = doc.text_format(inner_width, None);
6110 // there is no horizontal position when softwrap is enabled
6111 if text_fmt.soft_wrap {
6112 return;
6113 }
6114 let doc_text = doc.text().slice(..);
6115 let pos = doc.selection(view.id).primary().cursor(doc_text);
6116 let pos = visual_offset_from_block(
6117 doc_text,
6118 doc.view_offset(view.id).anchor,
6119 pos,
6120 &text_fmt,
6121 &view.text_annotations(doc, None),
6122 )
6123 .0;
6124
6125 let mut offset = doc.view_offset(view.id);
6126 offset.horizontal_offset = pos
6127 .col
6128 .saturating_sub((view.inner_area(doc).width as usize) / 2);
6129 doc.set_view_offset(view.id, offset);
6130 }
6131
6132 fn scroll_up(cx: &mut Context) {
6133 scroll(cx, cx.count(), Direction::Backward, false);
6134 }
6135
6136 fn scroll_down(cx: &mut Context) {
6137 scroll(cx, cx.count(), Direction::Forward, false);
6138 }
6139
6140 fn goto_ts_object_impl(cx: &mut Context, object: &'static str, direction: Direction) {
6141 let count = cx.count();
6142 let motion = move |editor: &mut Editor| {
6143 let (view, doc) = current!(editor);
6144 let loader = editor.syn_loader.load();
6145 if let Some(syntax) = doc.syntax() {
6146 let text = doc.text().slice(..);
6147
6148 let selection = doc.selection(view.id).clone().transform(|range| {
6149 let new_range = movement::goto_treesitter_object(
6150 text, range, object, direction, syntax, &loader, count,
6151 );
6152
6153 if editor.mode == Mode::Select {
6154 let head = if new_range.head < range.anchor {
6155 new_range.anchor
6156 } else {
6157 new_range.head
6158 };
6159
6160 Range::new(range.anchor, head)
6161 } else {
6162 new_range.with_direction(direction)
6163 }
6164 });
6165
6166 push_jump(view, doc);
6167 doc.set_selection(view.id, selection);
6168 } else {
6169 editor.set_status("Syntax-tree is not available in current buffer");
6170 }
6171 };
6172 cx.editor.apply_motion(motion);
6173 }
6174
6175 fn goto_next_function(cx: &mut Context) {
6176 goto_ts_object_impl(cx, "function", Direction::Forward)
6177 }
6178
6179 fn goto_prev_function(cx: &mut Context) {
6180 goto_ts_object_impl(cx, "function", Direction::Backward)
6181 }
6182
6183 fn goto_next_class(cx: &mut Context) {
6184 goto_ts_object_impl(cx, "class", Direction::Forward)
6185 }
6186
6187 fn goto_prev_class(cx: &mut Context) {
6188 goto_ts_object_impl(cx, "class", Direction::Backward)
6189 }
6190
6191 fn goto_next_parameter(cx: &mut Context) {
6192 goto_ts_object_impl(cx, "parameter", Direction::Forward)
6193 }
6194
6195 fn goto_prev_parameter(cx: &mut Context) {
6196 goto_ts_object_impl(cx, "parameter", Direction::Backward)
6197 }
6198
6199 fn goto_next_comment(cx: &mut Context) {
6200 goto_ts_object_impl(cx, "comment", Direction::Forward)
6201 }
6202
6203 fn goto_prev_comment(cx: &mut Context) {
6204 goto_ts_object_impl(cx, "comment", Direction::Backward)
6205 }
6206
6207 fn goto_next_test(cx: &mut Context) {
6208 goto_ts_object_impl(cx, "test", Direction::Forward)
6209 }
6210
6211 fn goto_prev_test(cx: &mut Context) {
6212 goto_ts_object_impl(cx, "test", Direction::Backward)
6213 }
6214
6215 fn goto_next_xml_element(cx: &mut Context) {
6216 goto_ts_object_impl(cx, "xml-element", Direction::Forward)
6217 }
6218
6219 fn goto_prev_xml_element(cx: &mut Context) {
6220 goto_ts_object_impl(cx, "xml-element", Direction::Backward)
6221 }
6222
6223 fn goto_next_entry(cx: &mut Context) {
6224 goto_ts_object_impl(cx, "entry", Direction::Forward)
6225 }
6226
6227 fn goto_prev_entry(cx: &mut Context) {
6228 goto_ts_object_impl(cx, "entry", Direction::Backward)
6229 }
6230
6231 fn select_textobject_around(cx: &mut Context) {
6232 select_textobject(cx, textobject::TextObject::Around);
6233 }
6234
6235 fn select_textobject_inner(cx: &mut Context) {
6236 select_textobject(cx, textobject::TextObject::Inside);
6237 }
6238
6239 fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) {
6240 let count = cx.count();
6241
6242 cx.on_next_key(move |cx, event| {
6243 cx.editor.autoinfo = None;
6244 if let Some(ch) = event.char() {
6245 let textobject = move |editor: &mut Editor| {
6246 let (view, doc) = current!(editor);
6247 let loader = editor.syn_loader.load();
6248 let text = doc.text().slice(..);
6249
6250 let textobject_treesitter = |obj_name: &str, range: Range| -> Range {
6251 let Some(syntax) = doc.syntax() else {
6252 return range;
6253 };
6254 textobject::textobject_treesitter(
6255 text, range, objtype, obj_name, syntax, &loader, count,
6256 )
6257 };
6258
6259 if ch == 'g' && doc.diff_handle().is_none() {
6260 editor.set_status("Diff is not available in current buffer");
6261 return;
6262 }
6263
6264 let textobject_change = |range: Range| -> Range {
6265 let diff_handle = doc.diff_handle().unwrap();
6266 let diff = diff_handle.load();
6267 let line = range.cursor_line(text);
6268 let hunk_idx = if let Some(hunk_idx) = diff.hunk_at(line as u32, false) {
6269 hunk_idx
6270 } else {
6271 return range;
6272 };
6273 let hunk = diff.nth_hunk(hunk_idx).after;
6274
6275 let start = text.line_to_char(hunk.start as usize);
6276 let end = text.line_to_char(hunk.end as usize);
6277 Range::new(start, end).with_direction(range.direction())
6278 };
6279
6280 let selection = doc.selection(view.id).clone().transform(|range| {
6281 match ch {
6282 'w' => textobject::textobject_word(text, range, objtype, count, false),
6283 'W' => textobject::textobject_word(text, range, objtype, count, true),
6284 't' => textobject_treesitter("class", range),
6285 'f' => textobject_treesitter("function", range),
6286 'a' => textobject_treesitter("parameter", range),
6287 'c' => textobject_treesitter("comment", range),
6288 'T' => textobject_treesitter("test", range),
6289 'e' => textobject_treesitter("entry", range),
6290 'x' => textobject_treesitter("xml-element", range),
6291 'p' => textobject::textobject_paragraph(text, range, objtype, count),
6292 'm' => textobject::textobject_pair_surround_closest(
6293 doc.syntax(),
6294 text,
6295 range,
6296 objtype,
6297 count,
6298 ),
6299 'g' => textobject_change(range),
6300 // TODO: cancel new ranges if inconsistent surround matches across lines
6301 ch if !ch.is_ascii_alphanumeric() => textobject::textobject_pair_surround(
6302 doc.syntax(),
6303 text,
6304 range,
6305 objtype,
6306 ch,
6307 count,
6308 ),
6309 _ => range,
6310 }
6311 });
6312 doc.set_selection(view.id, selection);
6313 };
6314 cx.editor.apply_motion(textobject);
6315 }
6316 });
6317
6318 let title = match objtype {
6319 textobject::TextObject::Inside => "Match inside",
6320 textobject::TextObject::Around => "Match around",
6321 _ => return,
6322 };
6323 let help_text = [
6324 ("w", "Word"),
6325 ("W", "WORD"),
6326 ("p", "Paragraph"),
6327 ("t", "Type definition (tree-sitter)"),
6328 ("f", "Function (tree-sitter)"),
6329 ("a", "Argument/parameter (tree-sitter)"),
6330 ("c", "Comment (tree-sitter)"),
6331 ("T", "Test (tree-sitter)"),
6332 ("e", "Data structure entry (tree-sitter)"),
6333 ("m", "Closest surrounding pair (tree-sitter)"),
6334 ("g", "Change"),
6335 ("x", "(X)HTML element (tree-sitter)"),
6336 (" ", "... or any character acting as a pair"),
6337 ];
6338
6339 cx.editor.autoinfo = Some(Info::new(title, &help_text));
6340 }
6341
6342 static SURROUND_HELP_TEXT: [(&str, &str); 6] = [
6343 ("m", "Nearest matching pair"),
6344 ("( or )", "Parentheses"),
6345 ("{ or }", "Curly braces"),
6346 ("< or >", "Angled brackets"),
6347 ("[ or ]", "Square brackets"),
6348 (" ", "... or any character"),
6349 ];
6350
6351 fn surround_add(cx: &mut Context) {
6352 cx.on_next_key(move |cx, event| {
6353 cx.editor.autoinfo = None;
6354 let (view, doc) = current!(cx.editor);
6355 // surround_len is the number of new characters being added.
6356 let (open, close, surround_len) = match event.char() {
6357 Some(ch) => {
6358 let (o, c) = match_brackets::get_pair(ch);
6359 let mut open = Tendril::new();
6360 open.push(o);
6361 let mut close = Tendril::new();
6362 close.push(c);
6363 (open, close, 2)
6364 }
6365 None if event.code == KeyCode::Enter => (
6366 doc.line_ending.as_str().into(),
6367 doc.line_ending.as_str().into(),
6368 2 * doc.line_ending.len_chars(),
6369 ),
6370 None => return,
6371 };
6372
6373 let selection = doc.selection(view.id);
6374 let mut changes = Vec::with_capacity(selection.len() * 2);
6375 let mut ranges = SmallVec::with_capacity(selection.len());
6376 let mut offs = 0;
6377
6378 for range in selection.iter() {
6379 changes.push((range.from(), range.from(), Some(open.clone())));
6380 changes.push((range.to(), range.to(), Some(close.clone())));
6381
6382 ranges.push(
6383 Range::new(offs + range.from(), offs + range.to() + surround_len)
6384 .with_direction(range.direction()),
6385 );
6386
6387 offs += surround_len;
6388 }
6389
6390 let transaction = Transaction::change(doc.text(), changes.into_iter())
6391 .with_selection(Selection::new(ranges, selection.primary_index()));
6392 doc.apply(&transaction, view.id);
6393 exit_select_mode(cx);
6394 });
6395
6396 cx.editor.autoinfo = Some(Info::new(
6397 "Surround selections with",
6398 &SURROUND_HELP_TEXT[1..],
6399 ));
6400 }
6401
6402 fn surround_replace(cx: &mut Context) {
6403 let count = cx.count();
6404 cx.on_next_key(move |cx, event| {
6405 cx.editor.autoinfo = None;
6406 let surround_ch = match event.char() {
6407 Some('m') => None, // m selects the closest surround pair
6408 Some(ch) => Some(ch),
6409 None => return,
6410 };
6411 let (view, doc) = current!(cx.editor);
6412 let text = doc.text().slice(..);
6413 let selection = doc.selection(view.id);
6414
6415 let change_pos =
6416 match surround::get_surround_pos(doc.syntax(), text, selection, surround_ch, count) {
6417 Ok(c) => c,
6418 Err(err) => {
6419 cx.editor.set_error(err.to_string());
6420 return;
6421 }
6422 };
6423
6424 let selection = selection.clone();
6425 let ranges: SmallVec<[Range; 1]> = change_pos.iter().map(|&p| Range::point(p)).collect();
6426 doc.set_selection(
6427 view.id,
6428 Selection::new(ranges, selection.primary_index() * 2),
6429 );
6430
6431 cx.on_next_key(move |cx, event| {
6432 cx.editor.autoinfo = None;
6433 let (view, doc) = current!(cx.editor);
6434 let to = match event.char() {
6435 Some(to) => to,
6436 None => return doc.set_selection(view.id, selection),
6437 };
6438 let (open, close) = match_brackets::get_pair(to);
6439
6440 // the changeset has to be sorted to allow nested surrounds
6441 let mut sorted_pos: Vec<(usize, char)> = Vec::new();
6442 for p in change_pos.chunks(2) {
6443 sorted_pos.push((p[0], open));
6444 sorted_pos.push((p[1], close));
6445 }
6446 sorted_pos.sort_unstable();
6447
6448 let transaction = Transaction::change(
6449 doc.text(),
6450 sorted_pos.iter().map(|&pos| {
6451 let mut t = Tendril::new();
6452 t.push(pos.1);
6453 (pos.0, pos.0 + 1, Some(t))
6454 }),
6455 );
6456 doc.set_selection(view.id, selection);
6457 doc.apply(&transaction, view.id);
6458 exit_select_mode(cx);
6459 });
6460
6461 cx.editor.autoinfo = Some(Info::new(
6462 "Replace with a pair of",
6463 &SURROUND_HELP_TEXT[1..],
6464 ));
6465 });
6466
6467 cx.editor.autoinfo = Some(Info::new(
6468 "Replace surrounding pair of",
6469 &SURROUND_HELP_TEXT,
6470 ));
6471 }
6472
6473 fn surround_delete(cx: &mut Context) {
6474 let count = cx.count();
6475 cx.on_next_key(move |cx, event| {
6476 cx.editor.autoinfo = None;
6477 let surround_ch = match event.char() {
6478 Some('m') => None, // m selects the closest surround pair
6479 Some(ch) => Some(ch),
6480 None => return,
6481 };
6482 let (view, doc) = current!(cx.editor);
6483 let text = doc.text().slice(..);
6484 let selection = doc.selection(view.id);
6485
6486 let mut change_pos =
6487 match surround::get_surround_pos(doc.syntax(), text, selection, surround_ch, count) {
6488 Ok(c) => c,
6489 Err(err) => {
6490 cx.editor.set_error(err.to_string());
6491 return;
6492 }
6493 };
6494 change_pos.sort_unstable(); // the changeset has to be sorted to allow nested surrounds
6495 let transaction =
6496 Transaction::change(doc.text(), change_pos.into_iter().map(|p| (p, p + 1, None)));
6497 doc.apply(&transaction, view.id);
6498 exit_select_mode(cx);
6499 });
6500
6501 cx.editor.autoinfo = Some(Info::new("Delete surrounding pair of", &SURROUND_HELP_TEXT));
6502 }
6503
6504 #[derive(Eq, PartialEq)]
6505 enum ShellBehavior {
6506 Replace,
6507 Ignore,
6508 Insert,
6509 Append,
6510 }
6511
6512 fn shell_pipe(cx: &mut Context) {
6513 shell_prompt_for_behavior(cx, "pipe:".into(), ShellBehavior::Replace);
6514 }
6515
6516 fn shell_pipe_to(cx: &mut Context) {
6517 shell_prompt_for_behavior(cx, "pipe-to:".into(), ShellBehavior::Ignore);
6518 }
6519
6520 fn shell_insert_output(cx: &mut Context) {
6521 shell_prompt_for_behavior(cx, "insert-output:".into(), ShellBehavior::Insert);
6522 }
6523
6524 fn shell_append_output(cx: &mut Context) {
6525 shell_prompt_for_behavior(cx, "append-output:".into(), ShellBehavior::Append);
6526 }
6527
6528 fn shell_keep_pipe(cx: &mut Context) {
6529 shell_prompt(cx, "keep-pipe:".into(), |cx, args| {
6530 let shell = &cx.editor.config().shell;
6531 let (view, doc) = current!(cx.editor);
6532 let selection = doc.selection(view.id);
6533
6534 let mut ranges = SmallVec::with_capacity(selection.len());
6535 let old_index = selection.primary_index();
6536 let mut index: Option<usize> = None;
6537 let text = doc.text().slice(..);
6538
6539 for (i, range) in selection.ranges().iter().enumerate() {
6540 let fragment = range.slice(text);
6541 if let Err(err) = shell_impl(shell, args.join(" ").as_str(), Some(fragment.into())) {
6542 log::debug!("Shell command failed: {}", err);
6543 } else {
6544 ranges.push(*range);
6545 if i >= old_index && index.is_none() {
6546 index = Some(ranges.len() - 1);
6547 }
6548 }
6549 }
6550
6551 if ranges.is_empty() {
6552 cx.editor.set_error("No selections remaining");
6553 return;
6554 }
6555
6556 let index = index.unwrap_or_else(|| ranges.len() - 1);
6557 doc.set_selection(view.id, Selection::new(ranges, index));
6558 });
6559 }
6560
6561 fn shell_impl(shell: &[String], cmd: &str, input: Option<Rope>) -> anyhow::Result<Tendril> {
6562 tokio::task::block_in_place(|| helix_lsp::block_on(shell_impl_async(shell, cmd, input)))
6563 }
6564
6565 async fn shell_impl_async(
6566 shell: &[String],
6567 cmd: &str,
6568 input: Option<Rope>,
6569 ) -> anyhow::Result<Tendril> {
6570 use std::process::Stdio;
6571 use tokio::process::Command;
6572 ensure!(!shell.is_empty(), "No shell set");
6573
6574 let mut process = Command::new(&shell[0]);
6575 process
6576 .args(&shell[1..])
6577 .arg(cmd)
6578 .stdout(Stdio::piped())
6579 .stderr(Stdio::piped());
6580
6581 if input.is_some() || cfg!(windows) {
6582 process.stdin(Stdio::piped());
6583 } else {
6584 process.stdin(Stdio::null());
6585 }
6586
6587 let mut process = match process.spawn() {
6588 Ok(process) => process,
6589 Err(e) => {
6590 log::error!("Failed to start shell: {}", e);
6591 return Err(e.into());
6592 }
6593 };
6594 let output = if let Some(mut stdin) = process.stdin.take() {
6595 let input_task = tokio::spawn(async move {
6596 if let Some(input) = input {
6597 helix_view::document::to_writer(&mut stdin, (encoding::UTF_8, false), &input)
6598 .await?;
6599 }
6600 anyhow::Ok(())
6601 });
6602 let (output, _) = tokio::join! {
6603 process.wait_with_output(),
6604 input_task,
6605 };
6606 output?
6607 } else {
6608 // Process has no stdin, so we just take the output
6609 process.wait_with_output().await?
6610 };
6611
6612 let output = if !output.status.success() {
6613 if output.stderr.is_empty() {
6614 match output.status.code() {
6615 Some(exit_code) => bail!("Shell command failed: status {}", exit_code),
6616 None => bail!("Shell command failed"),
6617 }
6618 }
6619 String::from_utf8_lossy(&output.stderr)
6620 // Prioritize `stderr` output over `stdout`
6621 } else if !output.stderr.is_empty() {
6622 let stderr = String::from_utf8_lossy(&output.stderr);
6623 log::debug!("Command printed to stderr: {stderr}");
6624 stderr
6625 } else {
6626 String::from_utf8_lossy(&output.stdout)
6627 };
6628
6629 Ok(Tendril::from(output))
6630 }
6631
6632 fn shell(cx: &mut compositor::Context, cmd: &str, behavior: &ShellBehavior) {
6633 let pipe = match behavior {
6634 ShellBehavior::Replace | ShellBehavior::Ignore => true,
6635 ShellBehavior::Insert | ShellBehavior::Append => false,
6636 };
6637
6638 let config = cx.editor.config();
6639 let shell = &config.shell;
6640 let (view, doc) = current!(cx.editor);
6641 let selection = doc.selection(view.id);
6642
6643 let mut changes = Vec::with_capacity(selection.len());
6644 let mut ranges = SmallVec::with_capacity(selection.len());
6645 let text = doc.text().slice(..);
6646
6647 let mut shell_output: Option<Tendril> = None;
6648 let mut offset = 0isize;
6649 for range in selection.ranges() {
6650 let output = if let Some(output) = shell_output.as_ref() {
6651 output.clone()
6652 } else {
6653 let input = range.slice(text);
6654 match shell_impl(shell, cmd, pipe.then(|| input.into())) {
6655 Ok(mut output) => {
6656 if !input.ends_with("\n") && output.ends_with('\n') {
6657 output.pop();
6658 if output.ends_with('\r') {
6659 output.pop();
6660 }
6661 }
6662
6663 if !pipe {
6664 shell_output = Some(output.clone());
6665 }
6666 output
6667 }
6668 Err(err) => {
6669 cx.editor.set_error(err.to_string());
6670 return;
6671 }
6672 }
6673 };
6674
6675 let output_len = output.chars().count();
6676
6677 let (from, to, deleted_len) = match behavior {
6678 ShellBehavior::Replace => (range.from(), range.to(), range.len()),
6679 ShellBehavior::Insert => (range.from(), range.from(), 0),
6680 ShellBehavior::Append => (range.to(), range.to(), 0),
6681 _ => (range.from(), range.from(), 0),
6682 };
6683
6684 // These `usize`s cannot underflow because selection ranges cannot overlap.
6685 let anchor = to
6686 .checked_add_signed(offset)
6687 .expect("Selection ranges cannot overlap")
6688 .checked_sub(deleted_len)
6689 .expect("Selection ranges cannot overlap");
6690 let new_range = Range::new(anchor, anchor + output_len).with_direction(range.direction());
6691 ranges.push(new_range);
6692 offset = offset
6693 .checked_add_unsigned(output_len)
6694 .expect("Selection ranges cannot overlap")
6695 .checked_sub_unsigned(deleted_len)
6696 .expect("Selection ranges cannot overlap");
6697
6698 changes.push((from, to, Some(output)));
6699 }
6700
6701 if behavior != &ShellBehavior::Ignore {
6702 let transaction = Transaction::change(doc.text(), changes.into_iter())
6703 .with_selection(Selection::new(ranges, selection.primary_index()));
6704 doc.apply(&transaction, view.id);
6705 doc.append_changes_to_history(view);
6706 }
6707
6708 // after replace cursor may be out of bounds, do this to
6709 // make sure cursor is in view and update scroll as well
6710 view.ensure_cursor_in_view(doc, config.scrolloff);
6711 }
6712
6713 fn shell_prompt<F>(cx: &mut Context, prompt: Cow<'static, str>, mut callback_fn: F)
6714 where
6715 F: FnMut(&mut compositor::Context, Args) + 'static,
6716 {
6717 ui::prompt(
6718 cx,
6719 prompt,
6720 Some('|'),
6721 |editor, input| complete_command_args(editor, SHELL_SIGNATURE, &SHELL_COMPLETER, input, 0),
6722 move |cx, input, event| {
6723 if event != PromptEvent::Validate || input.is_empty() {
6724 return;
6725 }
6726 match Args::parse(input, SHELL_SIGNATURE, true, |token| {
6727 expansion::expand(cx.editor, token).map_err(|err| err.into())
6728 }) {
6729 Ok(args) => callback_fn(cx, args),
6730 Err(err) => cx.editor.set_error(err.to_string()),
6731 }
6732 },
6733 );
6734 }
6735
6736 fn shell_prompt_for_behavior(cx: &mut Context, prompt: Cow<'static, str>, behavior: ShellBehavior) {
6737 shell_prompt(cx, prompt, move |cx, args| {
6738 shell(cx, args.join(" ").as_str(), &behavior)
6739 })
6740 }
6741
6742 fn suspend(_cx: &mut Context) {
6743 #[cfg(not(windows))]
6744 {
6745 // SAFETY: These are calls to standard POSIX functions.
6746 // Unsafe is necessary since we are calling outside of Rust.
6747 let is_session_leader = unsafe { libc::getpid() == libc::getsid(0) };
6748
6749 // If helix is the session leader, there is nothing to suspend to, so skip
6750 if is_session_leader {
6751 return;
6752 }
6753 _cx.block_try_flush_writes().ok();
6754 signal_hook::low_level::raise(signal_hook::consts::signal::SIGTSTP).unwrap();
6755 }
6756 }
6757
6758 fn add_newline_above(cx: &mut Context) {
6759 add_newline_impl(cx, Open::Above);
6760 }
6761
6762 fn add_newline_below(cx: &mut Context) {
6763 add_newline_impl(cx, Open::Below)
6764 }
6765
6766 fn add_newline_impl(cx: &mut Context, open: Open) {
6767 let count = cx.count();
6768 let (view, doc) = current!(cx.editor);
6769 let selection = doc.selection(view.id);
6770 let text = doc.text();
6771 let slice = text.slice(..);
6772
6773 let changes = selection.into_iter().map(|range| {
6774 let (start, end) = range.line_range(slice);
6775 let line = match open {
6776 Open::Above => start,
6777 Open::Below => end + 1,
6778 };
6779 let pos = text.line_to_char(line);
6780 (
6781 pos,
6782 pos,
6783 Some(doc.line_ending.as_str().repeat(count).into()),
6784 )
6785 });
6786
6787 let transaction = Transaction::change(text, changes);
6788 doc.apply(&transaction, view.id);
6789 }
6790
6791 enum IncrementDirection {
6792 Increase,
6793 Decrease,
6794 }
6795
6796 /// Increment objects within selections by count.
6797 fn increment(cx: &mut Context) {
6798 increment_impl(cx, IncrementDirection::Increase);
6799 }
6800
6801 /// Decrement objects within selections by count.
6802 fn decrement(cx: &mut Context) {
6803 increment_impl(cx, IncrementDirection::Decrease);
6804 }
6805
6806 /// Increment objects within selections by `amount`.
6807 /// A negative `amount` will decrement objects within selections.
6808 fn increment_impl(cx: &mut Context, increment_direction: IncrementDirection) {
6809 let sign = match increment_direction {
6810 IncrementDirection::Increase => 1,
6811 IncrementDirection::Decrease => -1,
6812 };
6813 let mut amount = sign * cx.count() as i64;
6814 // If the register is `#` then increase or decrease the `amount` by 1 per element
6815 let increase_by = if cx.register == Some('#') { sign } else { 0 };
6816
6817 let (view, doc) = current!(cx.editor);
6818 let selection = doc.selection(view.id);
6819 let text = doc.text().slice(..);
6820
6821 let mut new_selection_ranges = SmallVec::new();
6822 let mut cumulative_length_diff: i128 = 0;
6823 let mut changes = vec![];
6824
6825 for range in selection {
6826 let selected_text: Cow<str> = range.fragment(text);
6827 let new_from = ((range.from() as i128) + cumulative_length_diff) as usize;
6828 let incremented = [increment::integer, increment::date_time]
6829 .iter()
6830 .find_map(|incrementor| incrementor(selected_text.as_ref(), amount));
6831
6832 amount += increase_by;
6833
6834 match incremented {
6835 None => {
6836 let new_range = Range::new(
6837 new_from,
6838 (range.to() as i128 + cumulative_length_diff) as usize,
6839 );
6840 new_selection_ranges.push(new_range);
6841 }
6842 Some(new_text) => {
6843 let new_range = Range::new(new_from, new_from + new_text.len());
6844 cumulative_length_diff += new_text.len() as i128 - selected_text.len() as i128;
6845 new_selection_ranges.push(new_range);
6846 changes.push((range.from(), range.to(), Some(new_text.into())));
6847 }
6848 }
6849 }
6850
6851 if !changes.is_empty() {
6852 let new_selection = Selection::new(new_selection_ranges, selection.primary_index());
6853 let transaction = Transaction::change(doc.text(), changes.into_iter());
6854 let transaction = transaction.with_selection(new_selection);
6855 doc.apply(&transaction, view.id);
6856 exit_select_mode(cx);
6857 }
6858 }
6859
6860 fn goto_next_tabstop(cx: &mut Context) {
6861 goto_next_tabstop_impl(cx, Direction::Forward)
6862 }
6863
6864 fn goto_prev_tabstop(cx: &mut Context) {
6865 goto_next_tabstop_impl(cx, Direction::Backward)
6866 }
6867
6868 fn goto_next_tabstop_impl(cx: &mut Context, direction: Direction) {
6869 let (view, doc) = current!(cx.editor);
6870 let view_id = view.id;
6871 let Some(mut snippet) = doc.active_snippet.take() else {
6872 cx.editor.set_error("no snippet is currently active");
6873 return;
6874 };
6875 let tabstop = match direction {
6876 Direction::Forward => Some(snippet.next_tabstop(doc.selection(view_id))),
6877 Direction::Backward => snippet
6878 .prev_tabstop(doc.selection(view_id))
6879 .map(|selection| (selection, false)),
6880 };
6881 let Some((selection, last_tabstop)) = tabstop else {
6882 return;
6883 };
6884 doc.set_selection(view_id, selection);
6885 if !last_tabstop {
6886 doc.active_snippet = Some(snippet)
6887 }
6888 if cx.editor.mode() == Mode::Insert {
6889 cx.on_next_key_fallback(|cx, key| {
6890 if let Some(c) = key.char() {
6891 let (view, doc) = current!(cx.editor);
6892 if let Some(snippet) = &doc.active_snippet {
6893 doc.apply(&snippet.delete_placeholder(doc.text()), view.id);
6894 }
6895 insert_char(cx, c);
6896 }
6897 })
6898 }
6899 }
6900
6901 fn record_macro(cx: &mut Context) {
6902 if let Some((reg, mut keys)) = cx.editor.macro_recording.take() {
6903 // Remove the keypress which ends the recording
6904 keys.pop();
6905 let s = keys
6906 .into_iter()
6907 .map(|key| {
6908 let s = key.to_string();
6909 if s.chars().count() == 1 {
6910 s
6911 } else {
6912 format!("<{}>", s)
6913 }
6914 })
6915 .collect::<String>();
6916 match cx.editor.registers.write(reg, vec![s]) {
6917 Ok(_) => cx
6918 .editor
6919 .set_status(format!("Recorded to register [{}]", reg)),
6920 Err(err) => cx.editor.set_error(err.to_string()),
6921 }
6922 } else {
6923 let reg = cx.register.take().unwrap_or('@');
6924 cx.editor.macro_recording = Some((reg, Vec::new()));
6925 cx.editor
6926 .set_status(format!("Recording to register [{}]", reg));
6927 }
6928 }
6929
6930 fn replay_macro(cx: &mut Context) {
6931 let reg = cx.register.unwrap_or('@');
6932
6933 if cx.editor.macro_replaying.contains(&reg) {
6934 cx.editor.set_error(format!(
6935 "Cannot replay from register [{}] because already replaying from same register",
6936 reg
6937 ));
6938 return;
6939 }
6940
6941 let keys: Vec<KeyEvent> = if let Some(keys) = cx
6942 .editor
6943 .registers
6944 .read(reg, cx.editor)
6945 .filter(|values| values.len() == 1)
6946 .map(|mut values| values.next().unwrap())
6947 {
6948 match helix_view::input::parse_macro(&keys) {
6949 Ok(keys) => keys,
6950 Err(err) => {
6951 cx.editor.set_error(format!("Invalid macro: {}", err));
6952 return;
6953 }
6954 }
6955 } else {
6956 cx.editor.set_error(format!("Register [{}] empty", reg));
6957 return;
6958 };
6959
6960 // Once the macro has been fully validated, it's marked as being under replay
6961 // to ensure we don't fall into infinite recursion.
6962 cx.editor.macro_replaying.push(reg);
6963
6964 let count = cx.count();
6965 cx.callback.push(Box::new(move |compositor, cx| {
6966 for _ in 0..count {
6967 for &key in keys.iter() {
6968 compositor.handle_event(&compositor::Event::Key(key), cx);
6969 }
6970 }
6971 // The macro under replay is cleared at the end of the callback, not in the
6972 // macro replay context, or it will not correctly protect the user from
6973 // replaying recursively.
6974 cx.editor.macro_replaying.pop();
6975 }));
6976 }
6977
6978 fn goto_word(cx: &mut Context) {
6979 jump_to_word(cx, Movement::Move)
6980 }
6981
6982 fn extend_to_word(cx: &mut Context) {
6983 jump_to_word(cx, Movement::Extend)
6984 }
6985
6986 fn jump_to_label(cx: &mut Context, labels: Vec<Range>, behaviour: Movement) {
6987 let doc = doc!(cx.editor);
6988 let alphabet = &cx.editor.config().jump_label_alphabet;
6989 if labels.is_empty() {
6990 return;
6991 }
6992 let alphabet_char = |i| {
6993 let mut res = Tendril::new();
6994 res.push(alphabet[i]);
6995 res
6996 };
6997
6998 // Add label for each jump candidate to the View as virtual text.
6999 let text = doc.text().slice(..);
7000 let mut overlays: Vec<_> = labels
7001 .iter()
7002 .enumerate()
7003 .flat_map(|(i, range)| {
7004 [
7005 Overlay::new(range.from(), alphabet_char(i / alphabet.len())),
7006 Overlay::new(
7007 graphemes::next_grapheme_boundary(text, range.from()),
7008 alphabet_char(i % alphabet.len()),
7009 ),
7010 ]
7011 })
7012 .collect();
7013 overlays.sort_unstable_by_key(|overlay| overlay.char_idx);
7014 let (view, doc) = current!(cx.editor);
7015 doc.set_jump_labels(view.id, overlays);
7016
7017 // Accept two characters matching a visible label. Jump to the candidate
7018 // for that label if it exists.
7019 let primary_selection = doc.selection(view.id).primary();
7020 let view_id = view.id;
7021 let doc = doc.id();
7022 cx.on_next_key(move |cx, event| {
7023 let alphabet = &cx.editor.config().jump_label_alphabet;
7024 let Some(i) = event
7025 .char()
7026 .filter(|_| event.modifiers.is_empty())
7027 .and_then(|ch| alphabet.iter().position(|&it| it == ch))
7028 else {
7029 doc_mut!(cx.editor, &doc).remove_jump_labels(view_id);
7030 return;
7031 };
7032 let outer = i * alphabet.len();
7033 // Bail if the given character cannot be a jump label.
7034 if outer > labels.len() {
7035 doc_mut!(cx.editor, &doc).remove_jump_labels(view_id);
7036 return;
7037 }
7038 cx.on_next_key(move |cx, event| {
7039 doc_mut!(cx.editor, &doc).remove_jump_labels(view_id);
7040 let alphabet = &cx.editor.config().jump_label_alphabet;
7041 let Some(inner) = event
7042 .char()
7043 .filter(|_| event.modifiers.is_empty())
7044 .and_then(|ch| alphabet.iter().position(|&it| it == ch))
7045 else {
7046 return;
7047 };
7048 if let Some(mut range) = labels.get(outer + inner).copied() {
7049 range = if behaviour == Movement::Extend {
7050 let anchor = if range.anchor < range.head {
7051 let from = primary_selection.from();
7052 if range.anchor < from {
7053 range.anchor
7054 } else {
7055 from
7056 }
7057 } else {
7058 let to = primary_selection.to();
7059 if range.anchor > to {
7060 range.anchor
7061 } else {
7062 to
7063 }
7064 };
7065 Range::new(anchor, range.head)
7066 } else {
7067 range.with_direction(Direction::Forward)
7068 };
7069 let doc = doc_mut!(cx.editor, &doc);
7070 let view = view_mut!(cx.editor, view_id);
7071 push_jump(view, doc);
7072 doc.set_selection(view_id, range.into());
7073 }
7074 });
7075 });
7076 }
7077
7078 fn jump_to_word(cx: &mut Context, behaviour: Movement) {
7079 // Calculate the jump candidates: ranges for any visible words with two or
7080 // more characters.
7081 let alphabet = &cx.editor.config().jump_label_alphabet;
7082 if alphabet.is_empty() {
7083 return;
7084 }
7085
7086 let jump_label_limit = alphabet.len() * alphabet.len();
7087 let mut words = Vec::with_capacity(jump_label_limit);
7088 let (view, doc) = current_ref!(cx.editor);
7089 let text = doc.text().slice(..);
7090
7091 // This is not necessarily exact if there is virtual text like soft wrap.
7092 // It's ok though because the extra jump labels will not be rendered.
7093 let start = text.line_to_char(text.char_to_line(doc.view_offset(view.id).anchor));
7094 let end = text.line_to_char(view.estimate_last_doc_line(doc) + 1);
7095
7096 let primary_selection = doc.selection(view.id).primary();
7097 let cursor = primary_selection.cursor(text);
7098 let mut cursor_fwd = Range::point(cursor);
7099 let mut cursor_rev = Range::point(cursor);
7100 if text.get_char(cursor).is_some_and(|c| !c.is_whitespace()) {
7101 let cursor_word_end = movement::move_next_word_end(text, cursor_fwd, 1);
7102 // single grapheme words need a special case
7103 if cursor_word_end.anchor == cursor {
7104 cursor_fwd = cursor_word_end;
7105 }
7106 let cursor_word_start = movement::move_prev_word_start(text, cursor_rev, 1);
7107 if cursor_word_start.anchor == next_grapheme_boundary(text, cursor) {
7108 cursor_rev = cursor_word_start;
7109 }
7110 }
7111 'outer: loop {
7112 let mut changed = false;
7113 while cursor_fwd.head < end {
7114 cursor_fwd = movement::move_next_word_end(text, cursor_fwd, 1);
7115 // The cursor is on a word that is atleast two graphemes long and
7116 // madeup of word characters. The latter condition is needed because
7117 // move_next_word_end simply treats a sequence of characters from
7118 // the same char class as a word so `=<` would also count as a word.
7119 let add_label = text
7120 .slice(..cursor_fwd.head)
7121 .graphemes_rev()
7122 .take(2)
7123 .take_while(|g| g.chars().all(char_is_word))
7124 .count()
7125 == 2;
7126 if !add_label {
7127 continue;
7128 }
7129 changed = true;
7130 // skip any leading whitespace
7131 cursor_fwd.anchor += text
7132 .chars_at(cursor_fwd.anchor)
7133 .take_while(|&c| !char_is_word(c))
7134 .count();
7135 words.push(cursor_fwd);
7136 if words.len() == jump_label_limit {
7137 break 'outer;
7138 }
7139 break;
7140 }
7141 while cursor_rev.head > start {
7142 cursor_rev = movement::move_prev_word_start(text, cursor_rev, 1);
7143 // The cursor is on a word that is atleast two graphemes long and
7144 // madeup of word characters. The latter condition is needed because
7145 // move_prev_word_start simply treats a sequence of characters from
7146 // the same char class as a word so `=<` would also count as a word.
7147 let add_label = text
7148 .slice(cursor_rev.head..)
7149 .graphemes()
7150 .take(2)
7151 .take_while(|g| g.chars().all(char_is_word))
7152 .count()
7153 == 2;
7154 if !add_label {
7155 continue;
7156 }
7157 changed = true;
7158 cursor_rev.anchor -= text
7159 .chars_at(cursor_rev.anchor)
7160 .reversed()
7161 .take_while(|&c| !char_is_word(c))
7162 .count();
7163 words.push(cursor_rev);
7164 if words.len() == jump_label_limit {
7165 break 'outer;
7166 }
7167 break;
7168 }
7169 if !changed {
7170 break;
7171 }
7172 }
7173 jump_to_label(cx, words, behaviour)
7174 }
7175
7176 fn lsp_or_syntax_symbol_picker(cx: &mut Context) {
7177 let doc = doc!(cx.editor);
7178
7179 if doc
7180 .language_servers_with_feature(LanguageServerFeature::DocumentSymbols)
7181 .next()
7182 .is_some()
7183 {
7184 lsp::symbol_picker(cx);
7185 } else if doc.syntax().is_some() {
7186 syntax_symbol_picker(cx);
7187 } else {
7188 cx.editor
7189 .set_error("No language server supporting document symbols or syntax info available");
7190 }
7191 }
7192
7193 fn lsp_or_syntax_workspace_symbol_picker(cx: &mut Context) {
7194 let doc = doc!(cx.editor);
7195
7196 if doc
7197 .language_servers_with_feature(LanguageServerFeature::WorkspaceSymbols)
7198 .next()
7199 .is_some()
7200 {
7201 lsp::workspace_symbol_picker(cx);
7202 } else {
7203 syntax_workspace_symbol_picker(cx);
7204 }
7205 }