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 continued_line_comment_token<'a>(
3829 doc: &'a Document,
3830 loader: &'a helix_core::syntax::Loader,
3831 text: RopeSlice,
3832 line_num: usize,
3833 byte_pos: usize,
3834 ) -> Option<&'a str> {
3835 if let Some(syntax) = doc.syntax() {
3836 let mut token = None;
3837 for layer in syntax.layers_for_byte_range(byte_pos as u32, byte_pos as u32) {
3838 let config = loader.language(syntax.layer(layer).language).config();
3839 if let Some(tokens) = config.comment_tokens.as_ref() {
3840 token = comment::get_comment_token(text, tokens, line_num).or(token);
3841 }
3842 }
3843 token
3844 } else {
3845 doc.language_config()
3846 .and_then(|config| config.comment_tokens.as_ref())
3847 .and_then(|tokens| comment::get_comment_token(text, tokens, line_num))
3848 }
3849 }
3850
3851 fn open(cx: &mut Context, open: Open, comment_continuation: CommentContinuation) {
3852 let count = cx.count();
3853 enter_insert_mode(cx);
3854 let config = cx.editor.config();
3855 let (view, doc) = current!(cx.editor);
3856 let loader = cx.editor.syn_loader.load();
3857
3858 let text = doc.text().slice(..);
3859 let contents = doc.text();
3860 let selection = doc.selection(view.id);
3861 let mut offs = 0;
3862
3863 let mut ranges = SmallVec::with_capacity(selection.len());
3864
3865 let mut transaction = Transaction::change_by_selection(contents, selection, |range| {
3866 // the line number, where the cursor is currently
3867 let curr_line_num = text.char_to_line(match open {
3868 Open::Below => graphemes::prev_grapheme_boundary(text, range.to()),
3869 Open::Above => range.from(),
3870 });
3871
3872 // the next line number, where the cursor will be, after finishing the transaction
3873 let next_new_line_num = match open {
3874 Open::Below => curr_line_num + 1,
3875 Open::Above => curr_line_num,
3876 };
3877
3878 let above_next_new_line_num = next_new_line_num.saturating_sub(1);
3879
3880 // Continue the comment leader using the comment tokens of the layer at the current line.
3881 let continue_comment_token =
3882 if comment_continuation == CommentContinuation::Enabled && config.continue_comments {
3883 text.line(curr_line_num)
3884 .first_non_whitespace_char()
3885 .map(|c| text.char_to_byte(text.line_to_char(curr_line_num) + c))
3886 .and_then(|byte| {
3887 continued_line_comment_token(doc, &loader, text, curr_line_num, byte)
3888 })
3889 } else {
3890 None
3891 };
3892
3893 // Index to insert newlines after, as well as the char width
3894 // to use to compensate for those inserted newlines.
3895 let (above_next_line_end_index, above_next_line_end_width) = if next_new_line_num == 0 {
3896 (0, 0)
3897 } else {
3898 (
3899 line_end_char_index(&text, above_next_new_line_num),
3900 doc.line_ending.len_chars(),
3901 )
3902 };
3903
3904 let line = text.line(curr_line_num);
3905 let indent = match line.first_non_whitespace_char() {
3906 Some(pos) if continue_comment_token.is_some() => line.slice(..pos).to_string(),
3907 _ => indent::indent_for_newline(
3908 &loader,
3909 doc.syntax(),
3910 &config.indent_heuristic,
3911 &doc.indent_style,
3912 doc.tab_width(),
3913 text,
3914 above_next_new_line_num,
3915 above_next_line_end_index,
3916 curr_line_num,
3917 ),
3918 };
3919
3920 let indent_len = indent.len();
3921 let mut text = String::with_capacity(1 + indent_len);
3922
3923 if open == Open::Above && next_new_line_num == 0 {
3924 text.push_str(&indent);
3925 if let Some(token) = continue_comment_token {
3926 text.push_str(token);
3927 text.push(' ');
3928 }
3929 text.push_str(doc.line_ending.as_str());
3930 } else {
3931 text.push_str(doc.line_ending.as_str());
3932 text.push_str(&indent);
3933
3934 if let Some(token) = continue_comment_token {
3935 text.push_str(token);
3936 text.push(' ');
3937 }
3938 }
3939
3940 let text = text.repeat(count);
3941
3942 // calculate new selection ranges
3943 let pos = offs + above_next_line_end_index + above_next_line_end_width;
3944 let comment_len = continue_comment_token
3945 .map(|token| token.len() + 1) // `+ 1` for the extra space added
3946 .unwrap_or_default();
3947 for i in 0..count {
3948 // pos -> beginning of reference line,
3949 // + (i * (line_ending_len + indent_len + comment_len)) -> beginning of i'th line from pos (possibly including comment token)
3950 // + indent_len + comment_len -> -> indent for i'th line
3951 ranges.push(Range::point(
3952 pos + (i * (doc.line_ending.len_chars() + indent_len + comment_len))
3953 + indent_len
3954 + comment_len,
3955 ));
3956 }
3957
3958 // update the offset for the next range
3959 offs += text.chars().count();
3960
3961 (
3962 above_next_line_end_index,
3963 above_next_line_end_index,
3964 Some(text.into()),
3965 )
3966 });
3967
3968 transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
3969
3970 doc.apply(&transaction, view.id);
3971 }
3972
3973 // o inserts a new line after each line with a selection
3974 fn open_below(cx: &mut Context) {
3975 open(cx, Open::Below, CommentContinuation::Enabled)
3976 }
3977
3978 // O inserts a new line before each line with a selection
3979 fn open_above(cx: &mut Context) {
3980 open(cx, Open::Above, CommentContinuation::Enabled)
3981 }
3982
3983 fn normal_mode(cx: &mut Context) {
3984 cx.editor.enter_normal_mode();
3985 }
3986
3987 // Store a jump on the jumplist.
3988 fn push_jump(view: &mut View, doc: &mut Document) {
3989 doc.append_changes_to_history(view);
3990 let jump = (doc.id(), doc.selection(view.id).clone());
3991 view.push_jump(doc, jump);
3992 }
3993
3994 fn goto_line(cx: &mut Context) {
3995 goto_line_impl(cx, Movement::Move);
3996 }
3997
3998 fn goto_line_impl(cx: &mut Context, movement: Movement) {
3999 if cx.count.is_some() {
4000 let (view, doc) = current!(cx.editor);
4001 push_jump(view, doc);
4002
4003 goto_line_without_jumplist(cx.editor, cx.count, movement);
4004 }
4005 }
4006
4007 fn goto_line_without_jumplist(
4008 editor: &mut Editor,
4009 count: Option<NonZeroUsize>,
4010 movement: Movement,
4011 ) {
4012 if let Some(count) = count {
4013 let (view, doc) = current!(editor);
4014 let text = doc.text().slice(..);
4015 let max_line = if text.line(text.len_lines() - 1).len_chars() == 0 {
4016 // If the last line is blank, don't jump to it.
4017 text.len_lines().saturating_sub(2)
4018 } else {
4019 text.len_lines() - 1
4020 };
4021 let line_idx = std::cmp::min(count.get() - 1, max_line);
4022 let pos = text.line_to_char(line_idx);
4023 let selection = doc
4024 .selection(view.id)
4025 .clone()
4026 .transform(|range| range.put_cursor(text, pos, movement == Movement::Extend));
4027
4028 doc.set_selection(view.id, selection);
4029 }
4030 }
4031
4032 fn goto_last_line(cx: &mut Context) {
4033 goto_last_line_impl(cx, Movement::Move)
4034 }
4035
4036 fn extend_to_last_line(cx: &mut Context) {
4037 goto_last_line_impl(cx, Movement::Extend)
4038 }
4039
4040 fn goto_last_line_impl(cx: &mut Context, movement: Movement) {
4041 let (view, doc) = current!(cx.editor);
4042 let text = doc.text().slice(..);
4043 let line_idx = if text.line(text.len_lines() - 1).len_chars() == 0 {
4044 // If the last line is blank, don't jump to it.
4045 text.len_lines().saturating_sub(2)
4046 } else {
4047 text.len_lines() - 1
4048 };
4049 let pos = text.line_to_char(line_idx);
4050 let selection = doc
4051 .selection(view.id)
4052 .clone()
4053 .transform(|range| 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_column(cx: &mut Context) {
4060 goto_column_impl(cx, Movement::Move);
4061 }
4062
4063 fn extend_to_column(cx: &mut Context) {
4064 goto_column_impl(cx, Movement::Extend);
4065 }
4066
4067 fn goto_column_impl(cx: &mut Context, movement: Movement) {
4068 let count = cx.count();
4069 let (view, doc) = current!(cx.editor);
4070 let text = doc.text().slice(..);
4071 let selection = doc.selection(view.id).clone().transform(|range| {
4072 let line = range.cursor_line(text);
4073 let line_start = text.line_to_char(line);
4074 let line_end = line_end_char_index(&text, line);
4075 let pos = graphemes::nth_next_grapheme_boundary(text, line_start, count - 1).min(line_end);
4076 range.put_cursor(text, pos, movement == Movement::Extend)
4077 });
4078 push_jump(view, doc);
4079 doc.set_selection(view.id, selection);
4080 }
4081
4082 fn goto_last_accessed_file(cx: &mut Context) {
4083 let view = view_mut!(cx.editor);
4084 if let Some(alt) = view.docs_access_history.pop() {
4085 cx.editor.switch(alt, Action::Replace);
4086 } else {
4087 cx.editor.set_error("no last accessed buffer")
4088 }
4089 }
4090
4091 fn goto_last_modification(cx: &mut Context) {
4092 let (view, doc) = current!(cx.editor);
4093 let pos = doc.history.get_mut().last_edit_pos();
4094 let text = doc.text().slice(..);
4095 if let Some(pos) = pos {
4096 let selection = doc
4097 .selection(view.id)
4098 .clone()
4099 .transform(|range| range.put_cursor(text, pos, cx.editor.mode == Mode::Select));
4100 push_jump(view, doc);
4101 doc.set_selection(view.id, selection);
4102 }
4103 }
4104
4105 fn goto_last_modified_file(cx: &mut Context) {
4106 let view = view!(cx.editor);
4107 let alternate_file = view
4108 .last_modified_docs
4109 .into_iter()
4110 .flatten()
4111 .find(|&id| id != view.doc);
4112 if let Some(alt) = alternate_file {
4113 cx.editor.switch(alt, Action::Replace);
4114 } else {
4115 cx.editor.set_error("no last modified buffer")
4116 }
4117 }
4118
4119 fn select_mode(cx: &mut Context) {
4120 let (view, doc) = current!(cx.editor);
4121 let text = doc.text().slice(..);
4122
4123 // Make sure end-of-document selections are also 1-width.
4124 // (With the exception of being in an empty document, of course.)
4125 let selection = doc.selection(view.id).clone().transform(|range| {
4126 if range.is_empty() && range.head == text.len_chars() {
4127 Range::new(
4128 graphemes::prev_grapheme_boundary(text, range.anchor),
4129 range.head,
4130 )
4131 } else {
4132 range
4133 }
4134 });
4135 doc.set_selection(view.id, selection);
4136
4137 cx.editor.mode = Mode::Select;
4138 }
4139
4140 fn exit_select_mode(cx: &mut Context) {
4141 if cx.editor.mode == Mode::Select {
4142 cx.editor.mode = Mode::Normal;
4143 }
4144 }
4145
4146 fn goto_first_diag(cx: &mut Context) {
4147 let (view, doc) = current!(cx.editor);
4148 let selection = match doc.diagnostics().first() {
4149 Some(diag) => Selection::single(diag.range.start, diag.range.end),
4150 None => return,
4151 };
4152 push_jump(view, doc);
4153 doc.set_selection(view.id, selection);
4154 view.diagnostics_handler
4155 .immediately_show_diagnostic(doc, view.id);
4156 }
4157
4158 fn goto_last_diag(cx: &mut Context) {
4159 let (view, doc) = current!(cx.editor);
4160 let selection = match doc.diagnostics().last() {
4161 Some(diag) => Selection::single(diag.range.start, diag.range.end),
4162 None => return,
4163 };
4164 push_jump(view, doc);
4165 doc.set_selection(view.id, selection);
4166 view.diagnostics_handler
4167 .immediately_show_diagnostic(doc, view.id);
4168 }
4169
4170 fn goto_next_diag(cx: &mut Context) {
4171 let motion = move |editor: &mut Editor| {
4172 let (view, doc) = current!(editor);
4173
4174 let cursor_pos = doc
4175 .selection(view.id)
4176 .primary()
4177 .cursor(doc.text().slice(..));
4178
4179 let diag = doc
4180 .diagnostics()
4181 .iter()
4182 .find(|diag| diag.range.start > cursor_pos);
4183
4184 let selection = match diag {
4185 Some(diag) => Selection::single(diag.range.start, diag.range.end),
4186 None => return,
4187 };
4188 push_jump(view, doc);
4189 doc.set_selection(view.id, selection);
4190 view.diagnostics_handler
4191 .immediately_show_diagnostic(doc, view.id);
4192 };
4193
4194 cx.editor.apply_motion(motion);
4195 }
4196
4197 fn goto_prev_diag(cx: &mut Context) {
4198 let motion = move |editor: &mut Editor| {
4199 let (view, doc) = current!(editor);
4200
4201 let cursor_pos = doc
4202 .selection(view.id)
4203 .primary()
4204 .cursor(doc.text().slice(..));
4205
4206 let diag = doc
4207 .diagnostics()
4208 .iter()
4209 .rev()
4210 .find(|diag| diag.range.start < cursor_pos);
4211
4212 let selection = match diag {
4213 // NOTE: the selection is reversed because we're jumping to the
4214 // previous diagnostic.
4215 Some(diag) => Selection::single(diag.range.end, diag.range.start),
4216 None => return,
4217 };
4218 push_jump(view, doc);
4219 doc.set_selection(view.id, selection);
4220 view.diagnostics_handler
4221 .immediately_show_diagnostic(doc, view.id);
4222 };
4223 cx.editor.apply_motion(motion)
4224 }
4225
4226 fn goto_first_change(cx: &mut Context) {
4227 goto_first_change_impl(cx, false);
4228 }
4229
4230 fn goto_last_change(cx: &mut Context) {
4231 goto_first_change_impl(cx, true);
4232 }
4233
4234 fn goto_first_change_impl(cx: &mut Context, reverse: bool) {
4235 let editor = &mut cx.editor;
4236 let (view, doc) = current!(editor);
4237 if let Some(handle) = doc.diff_handle() {
4238 let hunk = {
4239 let diff = handle.load();
4240 let idx = if reverse {
4241 diff.len().saturating_sub(1)
4242 } else {
4243 0
4244 };
4245 diff.nth_hunk(idx)
4246 };
4247 if hunk != Hunk::NONE {
4248 let range = hunk_range(hunk, doc.text().slice(..));
4249 push_jump(view, doc);
4250 doc.set_selection(view.id, Selection::single(range.anchor, range.head));
4251 }
4252 }
4253 }
4254
4255 fn goto_next_change(cx: &mut Context) {
4256 goto_next_change_impl(cx, Direction::Forward)
4257 }
4258
4259 fn goto_prev_change(cx: &mut Context) {
4260 goto_next_change_impl(cx, Direction::Backward)
4261 }
4262
4263 fn goto_next_change_impl(cx: &mut Context, direction: Direction) {
4264 let count = cx.count() as u32 - 1;
4265 let motion = move |editor: &mut Editor| {
4266 let (view, doc) = current!(editor);
4267 let doc_text = doc.text().slice(..);
4268 let diff_handle = if let Some(diff_handle) = doc.diff_handle() {
4269 diff_handle
4270 } else {
4271 editor.set_status("Diff is not available in current buffer");
4272 return;
4273 };
4274
4275 let selection = doc.selection(view.id).clone().transform(|range| {
4276 let cursor_line = range.cursor_line(doc_text) as u32;
4277
4278 let diff = diff_handle.load();
4279 let hunk_idx = match direction {
4280 Direction::Forward => diff
4281 .next_hunk(cursor_line)
4282 .map(|idx| (idx + count).min(diff.len() - 1)),
4283 Direction::Backward => diff
4284 .prev_hunk(cursor_line)
4285 .map(|idx| idx.saturating_sub(count)),
4286 };
4287 let Some(hunk_idx) = hunk_idx else {
4288 return range;
4289 };
4290 let hunk = diff.nth_hunk(hunk_idx);
4291 let new_range = hunk_range(hunk, doc_text);
4292 if editor.mode == Mode::Select {
4293 let head = if new_range.head < range.anchor {
4294 new_range.anchor
4295 } else {
4296 new_range.head
4297 };
4298
4299 Range::new(range.anchor, head)
4300 } else {
4301 new_range.with_direction(direction)
4302 }
4303 });
4304
4305 push_jump(view, doc);
4306 doc.set_selection(view.id, selection)
4307 };
4308 cx.editor.apply_motion(motion);
4309 }
4310
4311 /// Returns the [Range] for a [Hunk] in the given text.
4312 /// Additions and modifications cover the added and modified ranges.
4313 /// Deletions are represented as the point at the start of the deletion hunk.
4314 fn hunk_range(hunk: Hunk, text: RopeSlice) -> Range {
4315 let anchor = text.line_to_char(hunk.after.start as usize);
4316 let head = if hunk.after.is_empty() {
4317 anchor + 1
4318 } else {
4319 text.line_to_char(hunk.after.end as usize)
4320 };
4321
4322 Range::new(anchor, head)
4323 }
4324
4325 pub mod insert {
4326 use crate::{events::PostInsertChar, key};
4327
4328 use super::*;
4329 pub type Hook = fn(&Rope, &Selection, char) -> Option<Transaction>;
4330
4331 /// Exclude the cursor in range.
4332 fn exclude_cursor(text: RopeSlice, range: Range, cursor: Range) -> Range {
4333 if range.to() == cursor.to() && text.len_chars() != cursor.to() {
4334 Range::new(
4335 range.from(),
4336 graphemes::prev_grapheme_boundary(text, cursor.to()),
4337 )
4338 } else {
4339 range
4340 }
4341 }
4342
4343 use helix_core::auto_pairs;
4344 use helix_view::editor::SmartTabConfig;
4345
4346 pub fn insert_char(cx: &mut Context, c: char) {
4347 let (view, doc) = current_ref!(cx.editor);
4348 let text = doc.text();
4349 let selection = doc.selection(view.id);
4350
4351 let loader: &helix_core::syntax::Loader = &cx.editor.syn_loader.load();
4352 let auto_pairs = doc.auto_pairs(cx.editor, loader, view);
4353
4354 let insert_char = |range: Range, ch: char| {
4355 let cursor = range.cursor(text.slice(..));
4356 let t = Tendril::from_iter([ch]);
4357 ((cursor, cursor, Some(t)), None)
4358 };
4359
4360 let transaction = Transaction::change_by_and_with_selection(text, selection, |range| {
4361 auto_pairs
4362 .as_ref()
4363 .and_then(|ap| {
4364 auto_pairs::hook_insert(text, range, c, ap)
4365 .map(|(change, range)| (change, Some(range)))
4366 .or_else(|| Some(insert_char(*range, c)))
4367 })
4368 .unwrap_or_else(|| insert_char(*range, c))
4369 });
4370
4371 let doc = doc_mut!(cx.editor, &doc.id());
4372 doc.apply(&transaction, view.id);
4373
4374 helix_event::dispatch(PostInsertChar { c, cx });
4375 }
4376
4377 pub fn smart_tab(cx: &mut Context) {
4378 let (view, doc) = current_ref!(cx.editor);
4379 let view_id = view.id;
4380
4381 if matches!(
4382 cx.editor.config().smart_tab,
4383 Some(SmartTabConfig { enable: true, .. })
4384 ) {
4385 let cursors_after_whitespace = doc.selection(view_id).ranges().iter().all(|range| {
4386 let cursor = range.cursor(doc.text().slice(..));
4387 let current_line_num = doc.text().char_to_line(cursor);
4388 let current_line_start = doc.text().line_to_char(current_line_num);
4389 let left = doc.text().slice(current_line_start..cursor);
4390 left.chars().all(|c| c.is_whitespace())
4391 });
4392
4393 if !cursors_after_whitespace {
4394 if doc.active_snippet.is_some() {
4395 goto_next_tabstop(cx);
4396 } else {
4397 move_parent_node_end(cx);
4398 }
4399 return;
4400 }
4401 }
4402
4403 insert_tab(cx);
4404 }
4405
4406 pub fn insert_tab(cx: &mut Context) {
4407 insert_tab_impl(cx, 1)
4408 }
4409
4410 fn insert_tab_impl(cx: &mut Context, count: usize) {
4411 let (view, doc) = current!(cx.editor);
4412
4413 let transaction = Transaction::change(
4414 doc.text(),
4415 doc.selection(view.id).ranges().iter().map(|range| {
4416 let cursor = range.cursor(doc.text().slice(..));
4417 let indent = if let IndentStyle::Spaces(indent_width) = doc.indent_style {
4418 let line = range.cursor_line(doc.text().slice(..));
4419 let line_start = doc.text().line_to_char(line);
4420 let offset = (cursor - line_start) % indent_width as usize;
4421
4422 Tendril::from(doc.indent_style.as_str().repeat(count)).split_off(offset)
4423 } else {
4424 Tendril::from(doc.indent_style.as_str().repeat(count))
4425 };
4426
4427 (cursor, cursor, Some(indent))
4428 }),
4429 );
4430 doc.apply(&transaction, view.id);
4431 }
4432
4433 pub fn append_char_interactive(cx: &mut Context) {
4434 // Save the current mode, so we can restore it later.
4435 let mode = cx.editor.mode;
4436 append_mode(cx);
4437 insert_selection_interactive(cx, mode);
4438 }
4439
4440 pub fn insert_char_interactive(cx: &mut Context) {
4441 let mode = cx.editor.mode;
4442 insert_mode(cx);
4443 insert_selection_interactive(cx, mode);
4444 }
4445
4446 fn insert_selection_interactive(cx: &mut Context, old_mode: Mode) {
4447 let count = cx.count();
4448
4449 // need to wait for next key
4450 cx.on_next_key(move |cx, event| {
4451 match event {
4452 KeyEvent {
4453 code: KeyCode::Char(ch),
4454 ..
4455 } => {
4456 for _ in 0..count {
4457 insert::insert_char(cx, ch)
4458 }
4459 }
4460 key!(Enter) => {
4461 if count != 1 {
4462 cx.editor
4463 .set_error("inserting multiple newlines not yet supported");
4464 return;
4465 }
4466 insert_newline(cx)
4467 }
4468 key!(Tab) => insert_tab_impl(cx, count),
4469 _ => (),
4470 };
4471 // Restore the old mode.
4472 cx.editor.mode = old_mode;
4473 });
4474 }
4475
4476 pub fn insert_newline(cx: &mut Context) {
4477 let config = cx.editor.config();
4478 let (view, doc) = current_ref!(cx.editor);
4479 let loader = cx.editor.syn_loader.load();
4480 let text = doc.text().slice(..);
4481 let line_ending = doc.line_ending.as_str();
4482
4483 let contents = doc.text();
4484 let selection = doc.selection(view.id);
4485 let mut ranges = SmallVec::with_capacity(selection.len());
4486
4487 // TODO: this is annoying, but we need to do it to properly calculate pos after edits
4488 let mut global_offs = 0;
4489 let mut new_text = String::new();
4490
4491 let mut last_pos = 0;
4492 let mut transaction = Transaction::change_by_selection(contents, selection, |range| {
4493 // Tracks the number of trailing whitespace characters deleted by this selection.
4494 let mut chars_deleted = 0;
4495 let pos = range.cursor(text);
4496
4497 let prev = if pos == 0 {
4498 ' '
4499 } else {
4500 contents.char(pos - 1)
4501 };
4502 let curr = contents.get_char(pos).unwrap_or(' ');
4503
4504 let current_line = text.char_to_line(pos);
4505 let line_start = text.line_to_char(current_line);
4506
4507 // Continue the comment leader using the comment tokens of the layer at the comment
4508 // leader (i.e. the first non-whitespace char on the line). Looking up at the cursor
4509 // would land inside an injected layer (e.g. `comment`, or markdown in a doc comment)
4510 // and miss the host language's tokens.
4511 let continue_comment_token = if config.continue_comments {
4512 text.line(current_line)
4513 .first_non_whitespace_char()
4514 .map(|c| text.char_to_byte(line_start + c))
4515 .and_then(|byte| {
4516 continued_line_comment_token(doc, &loader, text, current_line, byte)
4517 })
4518 } else {
4519 None
4520 };
4521
4522 let (from, to, local_offs) = if let Some(idx) =
4523 text.slice(line_start..pos).last_non_whitespace_char()
4524 {
4525 let first_trailing_whitespace_char = (line_start + idx + 1).clamp(last_pos, pos);
4526 last_pos = pos;
4527 let line = text.line(current_line);
4528
4529 let indent = match line.first_non_whitespace_char() {
4530 Some(pos) if continue_comment_token.is_some() => line.slice(..pos).to_string(),
4531 _ => indent::indent_for_newline(
4532 &loader,
4533 doc.syntax(),
4534 &config.indent_heuristic,
4535 &doc.indent_style,
4536 doc.tab_width(),
4537 text,
4538 current_line,
4539 pos,
4540 current_line,
4541 ),
4542 };
4543
4544 let loader: &helix_core::syntax::Loader = &cx.editor.syn_loader.load();
4545 // If we are between pairs (such as brackets), we want to
4546 // insert an additional line which is indented one level
4547 // more and place the cursor there
4548 let on_auto_pair = doc
4549 .auto_pairs(cx.editor, loader, view)
4550 .and_then(|pairs| pairs.get(prev))
4551 .is_some_and(|pair| pair.open == prev && pair.close == curr);
4552
4553 let local_offs = if let Some(token) = continue_comment_token {
4554 new_text.reserve_exact(line_ending.len() + indent.len() + token.len() + 1);
4555 new_text.push_str(line_ending);
4556 new_text.push_str(&indent);
4557 new_text.push_str(token);
4558 new_text.push(' ');
4559 new_text.chars().count()
4560 } else if on_auto_pair {
4561 // line where the cursor will be
4562 let inner_indent = indent.clone() + doc.indent_style.as_str();
4563 new_text
4564 .reserve_exact(line_ending.len() * 2 + indent.len() + inner_indent.len());
4565 new_text.push_str(line_ending);
4566 new_text.push_str(&inner_indent);
4567
4568 // line where the matching pair will be
4569 let local_offs = new_text.chars().count();
4570 new_text.push_str(line_ending);
4571 new_text.push_str(&indent);
4572
4573 local_offs
4574 } else {
4575 new_text.reserve_exact(line_ending.len() + indent.len());
4576 new_text.push_str(line_ending);
4577 new_text.push_str(&indent);
4578
4579 new_text.chars().count()
4580 };
4581
4582 // Note that `first_trailing_whitespace_char` is at least `pos` so this unsigned
4583 // subtraction cannot underflow.
4584 chars_deleted = pos - first_trailing_whitespace_char;
4585
4586 (
4587 first_trailing_whitespace_char,
4588 pos,
4589 local_offs as isize - chars_deleted as isize,
4590 )
4591 } else {
4592 // If the current line is all whitespace, insert a line ending at the beginning of
4593 // the current line. This makes the current line empty and the new line contain the
4594 // indentation of the old line.
4595 new_text.push_str(line_ending);
4596
4597 (line_start, line_start, new_text.chars().count() as isize)
4598 };
4599
4600 let new_range = if range.cursor(text) > range.anchor {
4601 // when appending, extend the range by local_offs
4602 Range::new(
4603 (range.anchor as isize + global_offs) as usize,
4604 (range.head as isize + local_offs + global_offs) as usize,
4605 )
4606 } else {
4607 // when inserting, slide the range by local_offs
4608 Range::new(
4609 (range.anchor as isize + local_offs + global_offs) as usize,
4610 (range.head as isize + local_offs + global_offs) as usize,
4611 )
4612 };
4613
4614 // TODO: range replace or extend
4615 // range.replace(|range| range.is_empty(), head); -> fn extend if cond true, new head pos
4616 // can be used with cx.mode to do replace or extend on most changes
4617 ranges.push(new_range);
4618 global_offs += new_text.chars().count() as isize - chars_deleted as isize;
4619 let tendril = Tendril::from(&new_text);
4620 new_text.clear();
4621
4622 (from, to, Some(tendril))
4623 });
4624
4625 transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
4626
4627 let (view, doc) = current!(cx.editor);
4628 doc.apply(&transaction, view.id);
4629 }
4630
4631 fn dedent(doc: &Document, range: &Range) -> Option<Deletion> {
4632 let text = doc.text().slice(..);
4633 let pos = range.cursor(text);
4634 let line_start_pos = text.line_to_char(range.cursor_line(text));
4635
4636 // consider to delete by indent level if all characters before `pos` are indent units.
4637 let fragment = Cow::from(text.slice(line_start_pos..pos));
4638
4639 if fragment.is_empty() || !fragment.chars().all(|ch| ch == ' ' || ch == '\t') {
4640 return None;
4641 }
4642
4643 if text.get_char(pos.saturating_sub(1)) == Some('\t') {
4644 // fast path, delete one char
4645 return Some((graphemes::nth_prev_grapheme_boundary(text, pos, 1), pos));
4646 }
4647
4648 let tab_width = doc.tab_width();
4649 let indent_width = doc.indent_width();
4650
4651 let width: usize = fragment
4652 .chars()
4653 .map(|ch| {
4654 if ch == '\t' {
4655 tab_width
4656 } else {
4657 // it can be none if it still meet control characters other than '\t'
4658 // here just set the width to 1 (or some value better?).
4659 ch.width().unwrap_or(1)
4660 }
4661 })
4662 .sum();
4663
4664 // round down to nearest unit
4665 let mut drop = width % indent_width;
4666
4667 // if it's already at a unit, consume a whole unit
4668 if drop == 0 {
4669 drop = indent_width
4670 };
4671
4672 let mut chars = fragment.chars().rev();
4673 let mut start = pos;
4674
4675 for _ in 0..drop {
4676 // delete up to `drop` spaces
4677 match chars.next() {
4678 Some(' ') => start -= 1,
4679 _ => break,
4680 }
4681 }
4682
4683 Some((start, pos)) // delete!
4684 }
4685
4686 pub fn delete_char_backward(cx: &mut Context) {
4687 let count = cx.count();
4688 let (view, doc) = current_ref!(cx.editor);
4689 let text = doc.text().slice(..);
4690
4691 let loader: &helix_core::syntax::Loader = &cx.editor.syn_loader.load();
4692 let auto_pairs = doc.auto_pairs(cx.editor, loader, view);
4693
4694 let transaction = Transaction::delete_by_and_with_selection(
4695 doc.text(),
4696 doc.selection(view.id),
4697 |range| {
4698 let pos = range.cursor(text);
4699
4700 log::debug!("cursor: {}, len: {}", pos, text.len_chars());
4701
4702 if pos == 0 {
4703 return ((pos, pos), None);
4704 }
4705
4706 dedent(doc, range)
4707 .map(|dedent| (dedent, None))
4708 .or_else(|| {
4709 // [TODO] should this be fixed to get the auto pairs for
4710 // each selection after 46af40017c0704142516b5740cf1a000ba4fd7c1 ?
4711 auto_pairs::hook_delete(doc.text(), range, auto_pairs?)
4712 .map(|(delete, new_range)| (delete, Some(new_range)))
4713 })
4714 .unwrap_or_else(|| {
4715 (
4716 (graphemes::nth_prev_grapheme_boundary(text, pos, count), pos),
4717 None,
4718 )
4719 })
4720 },
4721 );
4722
4723 log::debug!("delete_char_backward transaction: {:?}", transaction);
4724
4725 let doc = doc_mut!(cx.editor, &doc.id());
4726 doc.apply(&transaction, view.id);
4727 }
4728
4729 pub fn delete_char_forward(cx: &mut Context) {
4730 let count = cx.count();
4731 delete_by_selection_insert_mode(
4732 cx,
4733 |text, range| {
4734 let pos = range.cursor(text);
4735 (pos, graphemes::nth_next_grapheme_boundary(text, pos, count))
4736 },
4737 Direction::Forward,
4738 )
4739 }
4740
4741 pub fn delete_word_backward(cx: &mut Context) {
4742 let count = cx.count();
4743 delete_by_selection_insert_mode(
4744 cx,
4745 |text, range| {
4746 let anchor = movement::move_prev_word_start(text, *range, count).from();
4747 let next = Range::new(anchor, range.cursor(text));
4748 let range = exclude_cursor(text, next, *range);
4749 (range.from(), range.to())
4750 },
4751 Direction::Backward,
4752 );
4753 }
4754
4755 pub fn delete_word_forward(cx: &mut Context) {
4756 let count = cx.count();
4757 delete_by_selection_insert_mode(
4758 cx,
4759 |text, range| {
4760 let head = movement::move_next_word_end(text, *range, count).to();
4761 (range.cursor(text), head)
4762 },
4763 Direction::Forward,
4764 );
4765 }
4766 }
4767
4768 // Undo / Redo
4769
4770 fn undo(cx: &mut Context) {
4771 let count = cx.count();
4772 let (view, doc) = current!(cx.editor);
4773 for _ in 0..count {
4774 if !doc.undo(view) {
4775 cx.editor.set_status("Already at oldest change");
4776 break;
4777 }
4778 }
4779 }
4780
4781 fn redo(cx: &mut Context) {
4782 let count = cx.count();
4783 let (view, doc) = current!(cx.editor);
4784 for _ in 0..count {
4785 if !doc.redo(view) {
4786 cx.editor.set_status("Already at newest change");
4787 break;
4788 }
4789 }
4790 }
4791
4792 fn earlier(cx: &mut Context) {
4793 let count = cx.count();
4794 let (view, doc) = current!(cx.editor);
4795 for _ in 0..count {
4796 // rather than doing in batch we do this so get error halfway
4797 if !doc.earlier(view, UndoKind::Steps(1)) {
4798 cx.editor.set_status("Already at oldest change");
4799 break;
4800 }
4801 }
4802 }
4803
4804 fn later(cx: &mut Context) {
4805 let count = cx.count();
4806 let (view, doc) = current!(cx.editor);
4807 for _ in 0..count {
4808 // rather than doing in batch we do this so get error halfway
4809 if !doc.later(view, UndoKind::Steps(1)) {
4810 cx.editor.set_status("Already at newest change");
4811 break;
4812 }
4813 }
4814 }
4815
4816 fn commit_undo_checkpoint(cx: &mut Context) {
4817 let (view, doc) = current!(cx.editor);
4818 doc.append_changes_to_history(view);
4819 }
4820
4821 // Yank / Paste
4822
4823 fn yank(cx: &mut Context) {
4824 yank_impl(
4825 cx.editor,
4826 cx.register
4827 .unwrap_or(cx.editor.config().default_yank_register),
4828 );
4829 exit_select_mode(cx);
4830 }
4831
4832 fn yank_to_clipboard(cx: &mut Context) {
4833 yank_impl(cx.editor, '+');
4834 exit_select_mode(cx);
4835 }
4836
4837 fn yank_to_primary_clipboard(cx: &mut Context) {
4838 yank_impl(cx.editor, '*');
4839 exit_select_mode(cx);
4840 }
4841
4842 fn yank_impl(editor: &mut Editor, register: char) {
4843 let (view, doc) = current!(editor);
4844 let text = doc.text().slice(..);
4845
4846 let values: Vec<String> = doc
4847 .selection(view.id)
4848 .fragments(text)
4849 .map(Cow::into_owned)
4850 .collect();
4851 let selections = values.len();
4852
4853 match editor.registers.write(register, values) {
4854 Ok(_) => editor.set_status(format!(
4855 "yanked {selections} selection{} to register {register}",
4856 if selections == 1 { "" } else { "s" }
4857 )),
4858 Err(err) => editor.set_error(err.to_string()),
4859 }
4860 }
4861
4862 fn yank_joined_impl(editor: &mut Editor, separator: &str, register: char) {
4863 let (view, doc) = current!(editor);
4864 let text = doc.text().slice(..);
4865
4866 let selection = doc.selection(view.id);
4867 let selections = selection.len();
4868 let joined = selection
4869 .fragments(text)
4870 .fold(String::new(), |mut acc, fragment| {
4871 if !acc.is_empty() {
4872 acc.push_str(separator);
4873 }
4874 acc.push_str(&fragment);
4875 acc
4876 });
4877
4878 match editor.registers.write(register, vec![joined]) {
4879 Ok(_) => editor.set_status(format!(
4880 "joined and yanked {selections} selection{} to register {register}",
4881 if selections == 1 { "" } else { "s" }
4882 )),
4883 Err(err) => editor.set_error(err.to_string()),
4884 }
4885 }
4886
4887 fn yank_joined(cx: &mut Context) {
4888 let separator = doc!(cx.editor).line_ending.as_str();
4889 yank_joined_impl(
4890 cx.editor,
4891 separator,
4892 cx.register
4893 .unwrap_or(cx.editor.config().default_yank_register),
4894 );
4895 exit_select_mode(cx);
4896 }
4897
4898 fn yank_joined_to_clipboard(cx: &mut Context) {
4899 let line_ending = doc!(cx.editor).line_ending;
4900 yank_joined_impl(cx.editor, line_ending.as_str(), '+');
4901 exit_select_mode(cx);
4902 }
4903
4904 fn yank_joined_to_primary_clipboard(cx: &mut Context) {
4905 let line_ending = doc!(cx.editor).line_ending;
4906 yank_joined_impl(cx.editor, line_ending.as_str(), '*');
4907 exit_select_mode(cx);
4908 }
4909
4910 pub(crate) fn yank_main_selection_to_register(editor: &mut Editor, register: char) {
4911 let (view, doc) = current!(editor);
4912 let text = doc.text().slice(..);
4913
4914 let selection = doc.selection(view.id).primary().fragment(text).to_string();
4915
4916 match editor.registers.write(register, vec![selection]) {
4917 Ok(_) => editor.set_status(format!("yanked primary selection to register {register}",)),
4918 Err(err) => editor.set_error(err.to_string()),
4919 }
4920 }
4921
4922 fn yank_main_selection_to_clipboard(cx: &mut Context) {
4923 yank_main_selection_to_register(cx.editor, '+');
4924 exit_select_mode(cx);
4925 }
4926
4927 fn yank_main_selection_to_primary_clipboard(cx: &mut Context) {
4928 yank_main_selection_to_register(cx.editor, '*');
4929 exit_select_mode(cx);
4930 }
4931
4932 #[derive(Copy, Clone)]
4933 pub(crate) enum Paste {
4934 Before,
4935 After,
4936 Cursor,
4937 }
4938
4939 static LINE_ENDING_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"\r\n|\r|\n").unwrap());
4940
4941 fn paste_impl(
4942 values: &[String],
4943 doc: &mut Document,
4944 view: &mut View,
4945 action: Paste,
4946 count: usize,
4947 mode: Mode,
4948 ) {
4949 if values.is_empty() {
4950 return;
4951 }
4952
4953 if mode == Mode::Insert {
4954 doc.append_changes_to_history(view);
4955 }
4956
4957 // if any of values ends with a line ending, it's linewise paste
4958 let linewise = values
4959 .iter()
4960 .any(|value| get_line_ending_of_str(value).is_some());
4961
4962 let map_value = |value| {
4963 let value = LINE_ENDING_REGEX.replace_all(value, doc.line_ending.as_str());
4964 let mut out = Tendril::from(value.as_ref());
4965 for _ in 1..count {
4966 out.push_str(&value);
4967 }
4968 out
4969 };
4970
4971 let repeat = std::iter::repeat(
4972 // `values` is asserted to have at least one entry above.
4973 map_value(values.last().unwrap()),
4974 );
4975
4976 let mut values = values.iter().map(|value| map_value(value)).chain(repeat);
4977
4978 let text = doc.text();
4979 let selection = doc.selection(view.id);
4980
4981 let mut offset = 0;
4982 let mut ranges = SmallVec::with_capacity(selection.len());
4983
4984 let mut transaction = Transaction::change_by_selection(text, selection, |range| {
4985 let pos = match (action, linewise) {
4986 // paste linewise before
4987 (Paste::Before, true) => text.line_to_char(text.char_to_line(range.from())),
4988 // paste linewise after
4989 (Paste::After, true) => {
4990 let line = range.line_range(text.slice(..)).1;
4991 text.line_to_char((line + 1).min(text.len_lines()))
4992 }
4993 // paste insert
4994 (Paste::Before, false) => range.from(),
4995 // paste append
4996 (Paste::After, false) => range.to(),
4997 // paste at cursor
4998 (Paste::Cursor, _) => range.cursor(text.slice(..)),
4999 };
5000
5001 let value = values.next();
5002
5003 let value_len = value
5004 .as_ref()
5005 .map(|content| content.chars().count())
5006 .unwrap_or_default();
5007 let anchor = offset + pos;
5008
5009 let new_range = Range::new(anchor, anchor + value_len).with_direction(range.direction());
5010 ranges.push(new_range);
5011 offset += value_len;
5012
5013 (pos, pos, value)
5014 });
5015
5016 if mode == Mode::Normal {
5017 transaction = transaction.with_selection(Selection::new(ranges, selection.primary_index()));
5018 }
5019
5020 doc.apply(&transaction, view.id);
5021 doc.append_changes_to_history(view);
5022 }
5023
5024 pub(crate) fn paste_bracketed_value(cx: &mut Context, contents: String) {
5025 let count = cx.count();
5026 let paste = match cx.editor.mode {
5027 Mode::Insert | Mode::Select => Paste::Cursor,
5028 Mode::Normal => Paste::Before,
5029 };
5030 let (view, doc) = current!(cx.editor);
5031 paste_impl(&[contents], doc, view, paste, count, cx.editor.mode);
5032 exit_select_mode(cx);
5033 }
5034
5035 fn paste_clipboard_after(cx: &mut Context) {
5036 paste(cx.editor, '+', Paste::After, cx.count());
5037 exit_select_mode(cx);
5038 }
5039
5040 fn paste_clipboard_before(cx: &mut Context) {
5041 paste(cx.editor, '+', Paste::Before, cx.count());
5042 exit_select_mode(cx);
5043 }
5044
5045 fn paste_primary_clipboard_after(cx: &mut Context) {
5046 paste(cx.editor, '*', Paste::After, cx.count());
5047 exit_select_mode(cx);
5048 }
5049
5050 fn paste_primary_clipboard_before(cx: &mut Context) {
5051 paste(cx.editor, '*', Paste::Before, cx.count());
5052 exit_select_mode(cx);
5053 }
5054
5055 fn replace_with_yanked(cx: &mut Context) {
5056 replace_selections_with_register(
5057 cx.editor,
5058 cx.register
5059 .unwrap_or(cx.editor.config().default_yank_register),
5060 cx.count(),
5061 );
5062 exit_select_mode(cx);
5063 }
5064
5065 pub(crate) fn replace_selections_with_register(editor: &mut Editor, register: char, count: usize) {
5066 let Some(values) = editor
5067 .registers
5068 .read(register, editor)
5069 .filter(|values| values.len() > 0)
5070 else {
5071 return;
5072 };
5073 let scrolloff = editor.config().scrolloff;
5074 let (view, doc) = current_ref!(editor);
5075
5076 let map_value = |value: &Cow<str>| {
5077 let value = LINE_ENDING_REGEX.replace_all(value, doc.line_ending.as_str());
5078 let mut out = Tendril::from(value.as_ref());
5079 for _ in 1..count {
5080 out.push_str(&value);
5081 }
5082 out
5083 };
5084 let mut values_rev = values.rev().peekable();
5085 // `values` is asserted to have at least one entry above.
5086 let last = values_rev.peek().unwrap();
5087 let repeat = std::iter::repeat(map_value(last));
5088 let mut values = values_rev
5089 .rev()
5090 .map(|value| map_value(&value))
5091 .chain(repeat);
5092 let selection = doc.selection(view.id);
5093 let transaction = Transaction::change_by_selection(doc.text(), selection, |range| {
5094 if !range.is_empty() {
5095 (range.from(), range.to(), Some(values.next().unwrap()))
5096 } else {
5097 (range.from(), range.to(), None)
5098 }
5099 });
5100 drop(values);
5101
5102 let (view, doc) = current!(editor);
5103 doc.apply(&transaction, view.id);
5104 doc.append_changes_to_history(view);
5105 view.ensure_cursor_in_view(doc, scrolloff);
5106 }
5107
5108 fn replace_selections_with_clipboard(cx: &mut Context) {
5109 replace_selections_with_register(cx.editor, '+', cx.count());
5110 exit_select_mode(cx);
5111 }
5112
5113 fn replace_selections_with_primary_clipboard(cx: &mut Context) {
5114 replace_selections_with_register(cx.editor, '*', cx.count());
5115 exit_select_mode(cx);
5116 }
5117
5118 pub(crate) fn paste(editor: &mut Editor, register: char, pos: Paste, count: usize) {
5119 let Some(values) = editor.registers.read(register, editor) else {
5120 return;
5121 };
5122 let values: Vec<_> = values.map(|value| value.to_string()).collect();
5123
5124 let (view, doc) = current!(editor);
5125 paste_impl(&values, doc, view, pos, count, editor.mode);
5126 }
5127
5128 fn paste_after(cx: &mut Context) {
5129 paste(
5130 cx.editor,
5131 cx.register
5132 .unwrap_or(cx.editor.config().default_yank_register),
5133 Paste::After,
5134 cx.count(),
5135 );
5136 exit_select_mode(cx);
5137 }
5138
5139 fn paste_before(cx: &mut Context) {
5140 paste(
5141 cx.editor,
5142 cx.register
5143 .unwrap_or(cx.editor.config().default_yank_register),
5144 Paste::Before,
5145 cx.count(),
5146 );
5147 exit_select_mode(cx);
5148 }
5149
5150 fn get_lines(doc: &Document, view_id: ViewId) -> Vec<usize> {
5151 let mut lines = Vec::new();
5152
5153 // Get all line numbers
5154 for range in doc.selection(view_id) {
5155 let (start, end) = range.line_range(doc.text().slice(..));
5156
5157 for line in start..=end {
5158 lines.push(line)
5159 }
5160 }
5161 lines.sort_unstable(); // sorting by usize so _unstable is preferred
5162 lines.dedup();
5163 lines
5164 }
5165
5166 fn indent(cx: &mut Context) {
5167 let count = cx.count();
5168 let (view, doc) = current!(cx.editor);
5169 let lines = get_lines(doc, view.id);
5170
5171 // Indent by one level
5172 let indent = Tendril::from(doc.indent_style.as_str().repeat(count));
5173
5174 let transaction = Transaction::change(
5175 doc.text(),
5176 lines.into_iter().filter_map(|line| {
5177 let is_blank = doc.text().line(line).chunks().all(|s| s.trim().is_empty());
5178 if is_blank {
5179 return None;
5180 }
5181 let pos = doc.text().line_to_char(line);
5182
5183 let indent = if let IndentStyle::Spaces(indent_width) = doc.indent_style {
5184 let line = doc.text().line(line);
5185 let offset = line.first_non_whitespace_char().unwrap_or(0) % indent_width as usize;
5186 indent.clone().split_off(offset)
5187 } else {
5188 indent.clone()
5189 };
5190
5191 Some((pos, pos, Some(indent)))
5192 }),
5193 );
5194 doc.apply(&transaction, view.id);
5195 exit_select_mode(cx);
5196 }
5197
5198 fn unindent(cx: &mut Context) {
5199 let count = cx.count();
5200 let (view, doc) = current!(cx.editor);
5201 let lines = get_lines(doc, view.id);
5202 let mut changes = Vec::with_capacity(lines.len());
5203 let tab_width = doc.tab_width();
5204 let indent_width = count * doc.indent_width();
5205
5206 for line_idx in lines {
5207 let line = doc.text().line(line_idx);
5208 let mut width = 0;
5209 let mut pos = 0;
5210
5211 for ch in line.chars() {
5212 match ch {
5213 ' ' => width += 1,
5214 '\t' => width = (width / tab_width + 1) * tab_width,
5215 _ => break,
5216 }
5217
5218 pos += 1;
5219
5220 if width >= indent_width {
5221 break;
5222 }
5223 }
5224
5225 // now delete from start to first non-blank
5226 if pos > 0 {
5227 let start = doc.text().line_to_char(line_idx);
5228 changes.push((start, start + pos, None))
5229 }
5230 }
5231
5232 let transaction = Transaction::change(doc.text(), changes.into_iter());
5233
5234 doc.apply(&transaction, view.id);
5235 exit_select_mode(cx);
5236 }
5237
5238 fn format_selections(cx: &mut Context) {
5239 use helix_lsp::{lsp, util::range_to_lsp_range};
5240
5241 let (view, doc) = current!(cx.editor);
5242 let view_id = view.id;
5243
5244 // via lsp if available
5245 // TODO: else via tree-sitter indentation calculations
5246
5247 if doc.selection(view_id).len() != 1 {
5248 cx.editor
5249 .set_error("format_selections only supports a single selection for now");
5250 return;
5251 }
5252
5253 // TODO extra LanguageServerFeature::FormatSelections?
5254 // maybe such that LanguageServerFeature::Format contains it as well
5255 let Some(language_server) = doc
5256 .language_servers_with_feature(LanguageServerFeature::Format)
5257 .find(|ls| {
5258 matches!(
5259 ls.capabilities().document_range_formatting_provider,
5260 Some(lsp::OneOf::Left(true) | lsp::OneOf::Right(_))
5261 )
5262 })
5263 else {
5264 cx.editor
5265 .set_error("No configured language server supports range formatting");
5266 return;
5267 };
5268
5269 let offset_encoding = language_server.offset_encoding();
5270 let ranges: Vec<lsp::Range> = doc
5271 .selection(view_id)
5272 .iter()
5273 .map(|range| range_to_lsp_range(doc.text(), *range, offset_encoding))
5274 .collect();
5275
5276 // TODO: handle fails
5277 // TODO: concurrent map over all ranges
5278
5279 let range = ranges[0];
5280
5281 let future = language_server
5282 .text_document_range_formatting(
5283 doc.identifier(),
5284 range,
5285 lsp::FormattingOptions {
5286 tab_size: doc.tab_width() as u32,
5287 insert_spaces: matches!(doc.indent_style, IndentStyle::Spaces(_)),
5288 ..Default::default()
5289 },
5290 None,
5291 )
5292 .unwrap();
5293
5294 let text = doc.text().clone();
5295 let doc_id = doc.id();
5296 let doc_version = doc.version();
5297
5298 tokio::spawn(async move {
5299 match future.await {
5300 Ok(Some(res)) => {
5301 let transaction =
5302 helix_lsp::util::generate_transaction_from_edits(&text, res, offset_encoding);
5303 job::dispatch(move |editor, _compositor| {
5304 let Some(doc) = editor.document_mut(doc_id) else {
5305 return;
5306 };
5307 // Updating a desynced document causes problems with applying the transaction
5308 if doc.version() != doc_version {
5309 return;
5310 }
5311 doc.apply(&transaction, view_id);
5312 })
5313 .await
5314 }
5315 Err(err) => log::error!("format sections failed: {err}"),
5316 Ok(None) => (),
5317 }
5318 });
5319 }
5320
5321 fn join_selections_impl(cx: &mut Context, select_space: bool) {
5322 use movement::skip_while;
5323 let loader = cx.editor.syn_loader.load();
5324 let (view, doc) = current!(cx.editor);
5325 let text = doc.text();
5326 let slice = text.slice(..);
5327
5328 let mut changes = Vec::new();
5329
5330 for selection in doc.selection(view.id) {
5331 let (start, mut end) = selection.line_range(slice);
5332 if start == end {
5333 end = (end + 1).min(text.len_lines() - 1);
5334 }
5335 let lines = start..end;
5336
5337 changes.reserve(lines.len());
5338
5339 // Strip the comment leader of joined lines using the comment tokens of the layer at this selection.
5340 let byte = slice.char_to_byte(slice.line_to_char(start));
5341 let comment_tokens = doc
5342 .language_config_at(&loader, byte)
5343 .and_then(|config| config.comment_tokens.as_deref())
5344 .unwrap_or(&[]);
5345 // Sort by length to handle Rust's /// vs //
5346 let mut comment_tokens: Vec<&str> = comment_tokens.iter().map(|x| x.as_str()).collect();
5347 comment_tokens.sort_unstable_by_key(|x| std::cmp::Reverse(x.len()));
5348
5349 let first_line_idx = slice.line_to_char(start);
5350 let first_line_idx = skip_while(slice, first_line_idx, |ch| matches!(ch, ' ' | '\t'))
5351 .unwrap_or(first_line_idx);
5352 let first_line = slice.slice(first_line_idx..);
5353 let mut current_comment_token = comment_tokens
5354 .iter()
5355 .find(|token| first_line.starts_with(token));
5356
5357 for line in lines {
5358 let start = line_end_char_index(&slice, line);
5359 let mut end = text.line_to_char(line + 1);
5360 end = skip_while(slice, end, |ch| matches!(ch, ' ' | '\t')).unwrap_or(end);
5361 let slice_from_end = slice.slice(end..);
5362 if let Some(token) = comment_tokens
5363 .iter()
5364 .find(|token| slice_from_end.starts_with(token))
5365 {
5366 if Some(token) == current_comment_token {
5367 end += token.chars().count();
5368 end = skip_while(slice, end, |ch| matches!(ch, ' ' | '\t')).unwrap_or(end);
5369 } else {
5370 // update current token, but don't delete this one.
5371 current_comment_token = Some(token);
5372 }
5373 }
5374
5375 let separator = if end == line_end_char_index(&slice, line + 1) {
5376 // the joining line contains only space-characters => don't include a whitespace when joining
5377 None
5378 } else {
5379 Some(Tendril::from(" "))
5380 };
5381 changes.push((start, end, separator));
5382 }
5383 }
5384
5385 // nothing to do, bail out early to avoid crashes later
5386 if changes.is_empty() {
5387 return;
5388 }
5389
5390 changes.sort_unstable_by_key(|(from, _to, _text)| *from);
5391 changes.dedup();
5392
5393 // select inserted spaces
5394 let transaction = if select_space {
5395 let mut offset: usize = 0;
5396 let ranges: SmallVec<_> = changes
5397 .iter()
5398 .filter_map(|change| {
5399 if change.2.is_some() {
5400 let range = Range::point(change.0 - offset);
5401 offset += change.1 - change.0 - 1; // -1 adjusts for the replacement of the range by a space
5402 Some(range)
5403 } else {
5404 offset += change.1 - change.0;
5405 None
5406 }
5407 })
5408 .collect();
5409 let t = Transaction::change(text, changes.into_iter());
5410 if ranges.is_empty() {
5411 t
5412 } else {
5413 let selection = Selection::new(ranges, 0);
5414 t.with_selection(selection)
5415 }
5416 } else {
5417 Transaction::change(text, changes.into_iter())
5418 };
5419
5420 doc.apply(&transaction, view.id);
5421 }
5422
5423 fn keep_or_remove_selections_impl(cx: &mut Context, remove: bool) {
5424 // keep or remove selections matching regex
5425 let reg = cx.register.unwrap_or('/');
5426 ui::regex_prompt(
5427 cx,
5428 if remove { "remove:" } else { "keep:" }.into(),
5429 Some(reg),
5430 ui::completers::none,
5431 move |cx, regex, event| {
5432 let (view, doc) = current!(cx.editor);
5433 if !matches!(event, PromptEvent::Update | PromptEvent::Validate) {
5434 return;
5435 }
5436 let text = doc.text().slice(..);
5437
5438 if let Some(selection) =
5439 selection::keep_or_remove_matches(text, doc.selection(view.id), &regex, remove)
5440 {
5441 doc.set_selection(view.id, selection);
5442 } else if event == PromptEvent::Validate {
5443 cx.editor.set_error("no selections remaining");
5444 }
5445 },
5446 )
5447 }
5448
5449 fn join_selections(cx: &mut Context) {
5450 join_selections_impl(cx, false)
5451 }
5452
5453 fn join_selections_space(cx: &mut Context) {
5454 join_selections_impl(cx, true)
5455 }
5456
5457 fn keep_selections(cx: &mut Context) {
5458 keep_or_remove_selections_impl(cx, false)
5459 }
5460
5461 fn remove_selections(cx: &mut Context) {
5462 keep_or_remove_selections_impl(cx, true)
5463 }
5464
5465 fn keep_primary_selection(cx: &mut Context) {
5466 let (view, doc) = current!(cx.editor);
5467 // TODO: handle count
5468
5469 let range = doc.selection(view.id).primary();
5470 doc.set_selection(view.id, Selection::single(range.anchor, range.head));
5471 }
5472
5473 fn remove_primary_selection(cx: &mut Context) {
5474 let (view, doc) = current!(cx.editor);
5475 // TODO: handle count
5476
5477 let selection = doc.selection(view.id);
5478 if selection.len() == 1 {
5479 cx.editor.set_error("no selections remaining");
5480 return;
5481 }
5482 let index = selection.primary_index();
5483 let selection = selection.clone().remove(index);
5484
5485 doc.set_selection(view.id, selection);
5486 }
5487
5488 pub fn completion(cx: &mut Context) {
5489 let (view, doc) = current!(cx.editor);
5490 let range = doc.selection(view.id).primary();
5491 let text = doc.text().slice(..);
5492 let cursor = range.cursor(text);
5493
5494 cx.editor
5495 .handlers
5496 .trigger_completions(cursor, doc.id(), view.id);
5497 }
5498
5499 // comments
5500 type CommentTransactionFn = fn(
5501 line_token: Option<&str>,
5502 block_tokens: Option<&[BlockCommentToken]>,
5503 doc: &Rope,
5504 selection: &Selection,
5505 ) -> Transaction;
5506
5507 fn toggle_comments_impl(cx: &mut Context, comment_transaction: CommentTransactionFn) {
5508 let loader: &helix_core::syntax::Loader = &cx.editor.syn_loader.load();
5509 let (view, doc) = current!(cx.editor);
5510 let cursor = doc
5511 .selection(view.id)
5512 .primary()
5513 .cursor(doc.text().slice(..));
5514 let byte_pos = doc.text().char_to_byte(cursor);
5515 // Resolve the comment tokens from the enclosing injection layer that owns the comment,
5516 // not the innermost layer at the cursor. Prefer the innermost layer that defines
5517 // *line* comment tokens, falling back to the innermost layer with block tokens.
5518 let mut line_layer = None;
5519 let mut block_layer = None;
5520 if let Some(syntax) = doc.syntax() {
5521 for layer in syntax.layers_for_byte_range(byte_pos as u32, byte_pos as u32) {
5522 let language = syntax.layer(layer).language;
5523 let config = loader.language(language).config();
5524 if config.comment_tokens.is_some() {
5525 line_layer = Some(language);
5526 }
5527 if config.block_comment_tokens.is_some() {
5528 block_layer = Some(language);
5529 }
5530 }
5531 }
5532 let lang_config = line_layer
5533 .or(block_layer)
5534 .map(|language| &**loader.language(language).config())
5535 .or_else(|| doc.language_config());
5536
5537 // Pick the token the cursor's line is already commented with (longest match, so `///` wins over `//`).
5538 // If the line isn't commented yet, fall back to the primary token for adding a comment.
5539 let cursor_line = doc.text().char_to_line(cursor);
5540 let line_token: Option<&str> = lang_config
5541 .and_then(|lc| lc.comment_tokens.as_ref())
5542 .and_then(|tokens| {
5543 comment::get_comment_token(doc.text().slice(..), tokens, cursor_line)
5544 .or_else(|| tokens.first().map(|token| token.as_str()))
5545 });
5546 let block_tokens: Option<&[BlockCommentToken]> = lang_config
5547 .and_then(|lc| lc.block_comment_tokens.as_ref())
5548 .map(|tc| &tc[..]);
5549
5550 let transaction =
5551 comment_transaction(line_token, block_tokens, doc.text(), doc.selection(view.id));
5552
5553 doc.apply(&transaction, view.id);
5554 exit_select_mode(cx);
5555 }
5556
5557 /// commenting behavior:
5558 /// 1. only line comment tokens -> line comment
5559 /// 2. each line block commented -> uncomment all lines
5560 /// 3. whole selection block commented -> uncomment selection
5561 /// 4. all lines not commented and block tokens -> comment uncommented lines
5562 /// 5. no comment tokens and not block commented -> line comment
5563 fn toggle_comments(cx: &mut Context) {
5564 toggle_comments_impl(cx, |line_token, block_tokens, doc, selection| {
5565 let text = doc.slice(..);
5566
5567 // only have line comment tokens
5568 if line_token.is_some() && block_tokens.is_none() {
5569 return comment::toggle_line_comments(doc, selection, line_token);
5570 }
5571
5572 let split_lines = comment::split_lines_of_selection(text, selection);
5573
5574 let default_block_tokens = &[BlockCommentToken::default()];
5575 let block_comment_tokens = block_tokens.unwrap_or(default_block_tokens);
5576
5577 let (line_commented, line_comment_changes) =
5578 comment::find_block_comments(block_comment_tokens, text, &split_lines);
5579
5580 // block commented by line would also be block commented so check this first
5581 if line_commented {
5582 return comment::create_block_comment_transaction(
5583 doc,
5584 &split_lines,
5585 line_commented,
5586 line_comment_changes,
5587 )
5588 .0;
5589 }
5590
5591 let (block_commented, comment_changes) =
5592 comment::find_block_comments(block_comment_tokens, text, selection);
5593
5594 // check if selection has block comments
5595 if block_commented {
5596 return comment::create_block_comment_transaction(
5597 doc,
5598 selection,
5599 block_commented,
5600 comment_changes,
5601 )
5602 .0;
5603 }
5604
5605 // not commented and only have block comment tokens
5606 if line_token.is_none() && block_tokens.is_some() {
5607 return comment::create_block_comment_transaction(
5608 doc,
5609 &split_lines,
5610 line_commented,
5611 line_comment_changes,
5612 )
5613 .0;
5614 }
5615
5616 // not block commented at all and don't have any tokens
5617 comment::toggle_line_comments(doc, selection, line_token)
5618 })
5619 }
5620
5621 fn toggle_line_comments(cx: &mut Context) {
5622 toggle_comments_impl(cx, |line_token, block_tokens, doc, selection| {
5623 if line_token.is_none() && block_tokens.is_some() {
5624 let default_block_tokens = &[BlockCommentToken::default()];
5625 let block_comment_tokens = block_tokens.unwrap_or(default_block_tokens);
5626 comment::toggle_block_comments(
5627 doc,
5628 &comment::split_lines_of_selection(doc.slice(..), selection),
5629 block_comment_tokens,
5630 )
5631 } else {
5632 comment::toggle_line_comments(doc, selection, line_token)
5633 }
5634 });
5635 }
5636
5637 fn toggle_block_comments(cx: &mut Context) {
5638 toggle_comments_impl(cx, |line_token, block_tokens, doc, selection| {
5639 if line_token.is_some() && block_tokens.is_none() {
5640 comment::toggle_line_comments(doc, selection, line_token)
5641 } else {
5642 let default_block_tokens = &[BlockCommentToken::default()];
5643 let block_comment_tokens = block_tokens.unwrap_or(default_block_tokens);
5644 comment::toggle_block_comments(doc, selection, block_comment_tokens)
5645 }
5646 });
5647 }
5648
5649 fn rotate_selections(cx: &mut Context, direction: Direction) {
5650 let count = cx.count();
5651 let (view, doc) = current!(cx.editor);
5652 let mut selection = doc.selection(view.id).clone();
5653 let index = selection.primary_index();
5654 let len = selection.len();
5655 selection.set_primary_index(match direction {
5656 Direction::Forward => (index + count) % len,
5657 Direction::Backward => (index + (len.saturating_sub(count) % len)) % len,
5658 });
5659 doc.set_selection(view.id, selection);
5660 }
5661 fn rotate_selections_forward(cx: &mut Context) {
5662 rotate_selections(cx, Direction::Forward)
5663 }
5664 fn rotate_selections_backward(cx: &mut Context) {
5665 rotate_selections(cx, Direction::Backward)
5666 }
5667
5668 fn rotate_selections_first(cx: &mut Context) {
5669 let (view, doc) = current!(cx.editor);
5670 let mut selection = doc.selection(view.id).clone();
5671 selection.set_primary_index(0);
5672 doc.set_selection(view.id, selection);
5673 }
5674
5675 fn rotate_selections_last(cx: &mut Context) {
5676 let (view, doc) = current!(cx.editor);
5677 let mut selection = doc.selection(view.id).clone();
5678 let len = selection.len();
5679 selection.set_primary_index(len - 1);
5680 doc.set_selection(view.id, selection);
5681 }
5682
5683 #[derive(Debug)]
5684 enum ReorderStrategy {
5685 RotateForward,
5686 RotateBackward,
5687 Reverse,
5688 }
5689
5690 fn reorder_selection_contents(cx: &mut Context, strategy: ReorderStrategy) {
5691 let count = cx.count;
5692 let (view, doc) = current!(cx.editor);
5693 let text = doc.text().slice(..);
5694
5695 let selection = doc.selection(view.id);
5696
5697 let mut ranges: Vec<_> = selection
5698 .slices(text)
5699 .map(|fragment| fragment.chunks().collect())
5700 .collect();
5701
5702 let rotate_by = count.map_or(1, |count| count.get().min(ranges.len()));
5703
5704 let primary_index = match strategy {
5705 ReorderStrategy::RotateForward => {
5706 ranges.rotate_right(rotate_by);
5707 // Like `usize::wrapping_add`, but provide a custom range from `0` to `ranges.len()`
5708 (selection.primary_index() + ranges.len() + rotate_by) % ranges.len()
5709 }
5710 ReorderStrategy::RotateBackward => {
5711 ranges.rotate_left(rotate_by);
5712 // Like `usize::wrapping_sub`, but provide a custom range from `0` to `ranges.len()`
5713 (selection.primary_index() + ranges.len() - rotate_by) % ranges.len()
5714 }
5715 ReorderStrategy::Reverse => {
5716 if rotate_by.is_multiple_of(2) {
5717 // nothing changed, if we reverse something an even
5718 // amount of times, the output will be the same
5719 return;
5720 }
5721 ranges.reverse();
5722 // -1 to turn 1-based len into 0-based index
5723 (ranges.len() - 1) - selection.primary_index()
5724 }
5725 };
5726
5727 let transaction = Transaction::change(
5728 doc.text(),
5729 selection
5730 .ranges()
5731 .iter()
5732 .zip(ranges)
5733 .map(|(range, fragment)| (range.from(), range.to(), Some(fragment))),
5734 );
5735
5736 doc.set_selection(
5737 view.id,
5738 Selection::new(selection.ranges().into(), primary_index),
5739 );
5740 doc.apply(&transaction, view.id);
5741 }
5742
5743 fn rotate_selection_contents_forward(cx: &mut Context) {
5744 reorder_selection_contents(cx, ReorderStrategy::RotateForward)
5745 }
5746 fn rotate_selection_contents_backward(cx: &mut Context) {
5747 reorder_selection_contents(cx, ReorderStrategy::RotateBackward)
5748 }
5749 fn reverse_selection_contents(cx: &mut Context) {
5750 reorder_selection_contents(cx, ReorderStrategy::Reverse)
5751 }
5752
5753 // tree sitter node selection
5754
5755 fn expand_selection(cx: &mut Context) {
5756 let motion = |editor: &mut Editor| {
5757 let (view, doc) = current!(editor);
5758
5759 if let Some(syntax) = doc.syntax() {
5760 let text = doc.text().slice(..);
5761
5762 let current_selection = doc.selection(view.id);
5763 let selection = object::expand_selection(syntax, text, current_selection.clone());
5764
5765 // check if selection is different from the last one
5766 if *current_selection != selection {
5767 // save current selection so it can be restored using shrink_selection
5768 view.object_selections.push(current_selection.clone());
5769
5770 doc.set_selection(view.id, selection);
5771 }
5772 }
5773 };
5774 cx.editor.apply_motion(motion);
5775 }
5776
5777 fn shrink_selection(cx: &mut Context) {
5778 let motion = |editor: &mut Editor| {
5779 let (view, doc) = current!(editor);
5780 let current_selection = doc.selection(view.id);
5781 // try to restore previous selection
5782 if let Some(prev_selection) = view.object_selections.pop() {
5783 if current_selection.contains(&prev_selection) {
5784 doc.set_selection(view.id, prev_selection);
5785 return;
5786 } else {
5787 // clear existing selection as they can't be shrunk to anyway
5788 view.object_selections.clear();
5789 }
5790 }
5791 // if not previous selection, shrink to first child
5792 if let Some(syntax) = doc.syntax() {
5793 let text = doc.text().slice(..);
5794 let selection = object::shrink_selection(syntax, text, current_selection.clone());
5795 doc.set_selection(view.id, selection);
5796 }
5797 };
5798 cx.editor.apply_motion(motion);
5799 }
5800
5801 fn select_sibling_impl<F>(cx: &mut Context, sibling_fn: F)
5802 where
5803 F: Fn(&helix_core::Syntax, RopeSlice, Selection) -> Selection + 'static,
5804 {
5805 let motion = move |editor: &mut Editor| {
5806 let (view, doc) = current!(editor);
5807
5808 if let Some(syntax) = doc.syntax() {
5809 let text = doc.text().slice(..);
5810 let current_selection = doc.selection(view.id);
5811 let selection = sibling_fn(syntax, text, current_selection.clone());
5812 doc.set_selection(view.id, selection);
5813 }
5814 };
5815 cx.editor.apply_motion(motion);
5816 }
5817
5818 fn select_next_sibling(cx: &mut Context) {
5819 select_sibling_impl(cx, object::select_next_sibling)
5820 }
5821
5822 fn select_prev_sibling(cx: &mut Context) {
5823 select_sibling_impl(cx, object::select_prev_sibling)
5824 }
5825
5826 fn move_node_bound_impl(cx: &mut Context, dir: Direction, movement: Movement) {
5827 let motion = move |editor: &mut Editor| {
5828 let (view, doc) = current!(editor);
5829
5830 if let Some(syntax) = doc.syntax() {
5831 let text = doc.text().slice(..);
5832 let current_selection = doc.selection(view.id);
5833
5834 let selection = movement::move_parent_node_end(
5835 syntax,
5836 text,
5837 current_selection.clone(),
5838 dir,
5839 movement,
5840 );
5841
5842 doc.set_selection(view.id, selection);
5843 }
5844 };
5845
5846 cx.editor.apply_motion(motion);
5847 }
5848
5849 pub fn move_parent_node_end(cx: &mut Context) {
5850 move_node_bound_impl(cx, Direction::Forward, Movement::Move)
5851 }
5852
5853 pub fn move_parent_node_start(cx: &mut Context) {
5854 move_node_bound_impl(cx, Direction::Backward, Movement::Move)
5855 }
5856
5857 pub fn extend_parent_node_end(cx: &mut Context) {
5858 move_node_bound_impl(cx, Direction::Forward, Movement::Extend)
5859 }
5860
5861 pub fn extend_parent_node_start(cx: &mut Context) {
5862 move_node_bound_impl(cx, Direction::Backward, Movement::Extend)
5863 }
5864
5865 fn select_all_impl<F>(editor: &mut Editor, select_fn: F)
5866 where
5867 F: Fn(&Syntax, RopeSlice, Selection) -> Selection,
5868 {
5869 let (view, doc) = current!(editor);
5870
5871 if let Some(syntax) = doc.syntax() {
5872 let text = doc.text().slice(..);
5873 let current_selection = doc.selection(view.id);
5874 let selection = select_fn(syntax, text, current_selection.clone());
5875 doc.set_selection(view.id, selection);
5876 }
5877 }
5878
5879 fn select_all_siblings(cx: &mut Context) {
5880 let motion = |editor: &mut Editor| {
5881 select_all_impl(editor, object::select_all_siblings);
5882 };
5883
5884 cx.editor.apply_motion(motion);
5885 }
5886
5887 fn select_all_children(cx: &mut Context) {
5888 let motion = |editor: &mut Editor| {
5889 select_all_impl(editor, object::select_all_children);
5890 };
5891
5892 cx.editor.apply_motion(motion);
5893 }
5894
5895 fn match_brackets(cx: &mut Context) {
5896 let (view, doc) = current!(cx.editor);
5897 let is_select = cx.editor.mode == Mode::Select;
5898 let text = doc.text();
5899 let text_slice = text.slice(..);
5900
5901 let selection = doc.selection(view.id).clone().transform(|range| {
5902 let pos = range.cursor(text_slice);
5903 if let Some(matched_pos) = doc.syntax().map_or_else(
5904 || match_brackets::find_matching_bracket_plaintext(text.slice(..), pos),
5905 |syntax| match_brackets::find_matching_bracket_fuzzy(syntax, text.slice(..), pos),
5906 ) {
5907 range.put_cursor(text_slice, matched_pos, is_select)
5908 } else {
5909 range
5910 }
5911 });
5912
5913 doc.set_selection(view.id, selection);
5914 }
5915
5916 //
5917
5918 fn jump_forward(cx: &mut Context) {
5919 cx.editor.jump_forward(cx.editor.tree.focus, cx.count());
5920 }
5921
5922 fn jump_backward(cx: &mut Context) {
5923 cx.editor.jump_backward(cx.editor.tree.focus, cx.count());
5924 }
5925
5926 fn save_selection(cx: &mut Context) {
5927 let (view, doc) = current!(cx.editor);
5928 push_jump(view, doc);
5929 cx.editor.set_status("Selection saved to jumplist");
5930 }
5931
5932 fn rotate_view(cx: &mut Context) {
5933 cx.editor.focus_next()
5934 }
5935
5936 fn rotate_view_reverse(cx: &mut Context) {
5937 cx.editor.focus_prev()
5938 }
5939
5940 fn jump_view_right(cx: &mut Context) {
5941 cx.editor.focus_direction(tree::Direction::Right)
5942 }
5943
5944 fn jump_view_left(cx: &mut Context) {
5945 cx.editor.focus_direction(tree::Direction::Left)
5946 }
5947
5948 fn jump_view_up(cx: &mut Context) {
5949 cx.editor.focus_direction(tree::Direction::Up)
5950 }
5951
5952 fn jump_view_down(cx: &mut Context) {
5953 cx.editor.focus_direction(tree::Direction::Down)
5954 }
5955
5956 fn swap_view_right(cx: &mut Context) {
5957 cx.editor.swap_split_in_direction(tree::Direction::Right)
5958 }
5959
5960 fn swap_view_left(cx: &mut Context) {
5961 cx.editor.swap_split_in_direction(tree::Direction::Left)
5962 }
5963
5964 fn swap_view_up(cx: &mut Context) {
5965 cx.editor.swap_split_in_direction(tree::Direction::Up)
5966 }
5967
5968 fn swap_view_down(cx: &mut Context) {
5969 cx.editor.swap_split_in_direction(tree::Direction::Down)
5970 }
5971
5972 fn transpose_view(cx: &mut Context) {
5973 cx.editor.transpose_view()
5974 }
5975
5976 /// Open a new split in the given direction specified by the action.
5977 ///
5978 /// Maintain the current view (both the cursor's position and view in document).
5979 fn split(editor: &mut Editor, action: Action) {
5980 let (view, doc) = current!(editor);
5981 let id = doc.id();
5982 let selection = doc.selection(view.id).clone();
5983 let offset = doc.view_offset(view.id);
5984
5985 editor.switch(id, action);
5986
5987 // match the selection in the previous view
5988 let (view, doc) = current!(editor);
5989 doc.set_selection(view.id, selection);
5990 // match the view scroll offset (switch doesn't handle this fully
5991 // since the selection is only matched after the split)
5992 doc.set_view_offset(view.id, offset);
5993 }
5994
5995 fn hsplit(cx: &mut Context) {
5996 split(cx.editor, Action::HorizontalSplit);
5997 }
5998
5999 fn hsplit_new(cx: &mut Context) {
6000 cx.editor.new_file(Action::HorizontalSplit);
6001 }
6002
6003 fn vsplit(cx: &mut Context) {
6004 split(cx.editor, Action::VerticalSplit);
6005 }
6006
6007 fn vsplit_new(cx: &mut Context) {
6008 cx.editor.new_file(Action::VerticalSplit);
6009 }
6010
6011 fn wclose(cx: &mut Context) {
6012 if cx.editor.tree.views().count() == 1 {
6013 if let Err(err) = typed::buffers_remaining_impl(cx.editor) {
6014 cx.editor.set_error(err.to_string());
6015 return;
6016 }
6017 }
6018 let view_id = view!(cx.editor).id;
6019 // close current split
6020 cx.editor.close(view_id);
6021 }
6022
6023 fn wonly(cx: &mut Context) {
6024 let views = cx
6025 .editor
6026 .tree
6027 .views()
6028 .map(|(v, focus)| (v.id, focus))
6029 .collect::<Vec<_>>();
6030 for (view_id, focus) in views {
6031 if !focus {
6032 cx.editor.close(view_id);
6033 }
6034 }
6035 }
6036
6037 fn select_register(cx: &mut Context) {
6038 cx.editor.autoinfo = Some(Info::from_registers(
6039 "Select register",
6040 &cx.editor.registers,
6041 ));
6042 cx.on_next_key(move |cx, event| {
6043 cx.editor.autoinfo = None;
6044 if let Some(ch) = event.char() {
6045 cx.editor.selected_register = Some(ch);
6046 }
6047 })
6048 }
6049
6050 fn insert_register(cx: &mut Context) {
6051 // TODO: count is reset to 1 before next key so we move it into the closure here.
6052 // Would be nice to carry over.
6053 let count = cx.count();
6054 cx.editor.autoinfo = Some(Info::from_registers(
6055 "Insert register",
6056 &cx.editor.registers,
6057 ));
6058 cx.on_next_key(move |cx, event| {
6059 cx.editor.autoinfo = None;
6060 if let Some(ch) = event.char() {
6061 cx.register = Some(ch);
6062 paste(
6063 cx.editor,
6064 cx.register
6065 .unwrap_or(cx.editor.config().default_yank_register),
6066 Paste::Cursor,
6067 count,
6068 );
6069 }
6070 })
6071 }
6072
6073 fn copy_between_registers(cx: &mut Context) {
6074 cx.editor.autoinfo = Some(Info::from_registers(
6075 "Copy from register",
6076 &cx.editor.registers,
6077 ));
6078 cx.on_next_key(move |cx, event| {
6079 cx.editor.autoinfo = None;
6080
6081 let Some(source) = event.char() else {
6082 return;
6083 };
6084
6085 let Some(values) = cx.editor.registers.read(source, cx.editor) else {
6086 cx.editor.set_error(format!("register {source} is empty"));
6087 return;
6088 };
6089 let values: Vec<_> = values.map(|value| value.to_string()).collect();
6090
6091 cx.editor.autoinfo = Some(Info::from_registers(
6092 "Copy into register",
6093 &cx.editor.registers,
6094 ));
6095 cx.on_next_key(move |cx, event| {
6096 cx.editor.autoinfo = None;
6097
6098 let Some(dest) = event.char() else {
6099 return;
6100 };
6101
6102 let n_values = values.len();
6103 match cx.editor.registers.write(dest, values) {
6104 Ok(_) => cx.editor.set_status(format!(
6105 "yanked {n_values} value{} from register {source} to {dest}",
6106 if n_values == 1 { "" } else { "s" }
6107 )),
6108 Err(err) => cx.editor.set_error(err.to_string()),
6109 }
6110 });
6111 });
6112 }
6113
6114 fn align_view_top(cx: &mut Context) {
6115 let (view, doc) = current!(cx.editor);
6116 align_view(doc, view, Align::Top);
6117 }
6118
6119 fn align_view_center(cx: &mut Context) {
6120 let (view, doc) = current!(cx.editor);
6121 align_view(doc, view, Align::Center);
6122 }
6123
6124 fn align_view_bottom(cx: &mut Context) {
6125 let (view, doc) = current!(cx.editor);
6126 align_view(doc, view, Align::Bottom);
6127 }
6128
6129 fn align_view_middle(cx: &mut Context) {
6130 let (view, doc) = current!(cx.editor);
6131 let inner_width = view.inner_width(doc);
6132 let text_fmt = doc.text_format(inner_width, None);
6133 // there is no horizontal position when softwrap is enabled
6134 if text_fmt.soft_wrap {
6135 return;
6136 }
6137 let doc_text = doc.text().slice(..);
6138 let pos = doc.selection(view.id).primary().cursor(doc_text);
6139 let pos = visual_offset_from_block(
6140 doc_text,
6141 doc.view_offset(view.id).anchor,
6142 pos,
6143 &text_fmt,
6144 &view.text_annotations(doc, None),
6145 )
6146 .0;
6147
6148 let mut offset = doc.view_offset(view.id);
6149 offset.horizontal_offset = pos
6150 .col
6151 .saturating_sub((view.inner_area(doc).width as usize) / 2);
6152 doc.set_view_offset(view.id, offset);
6153 }
6154
6155 fn scroll_up(cx: &mut Context) {
6156 scroll(cx, cx.count(), Direction::Backward, false);
6157 }
6158
6159 fn scroll_down(cx: &mut Context) {
6160 scroll(cx, cx.count(), Direction::Forward, false);
6161 }
6162
6163 fn goto_ts_object_impl(cx: &mut Context, object: &'static str, direction: Direction) {
6164 let count = cx.count();
6165 let motion = move |editor: &mut Editor| {
6166 let (view, doc) = current!(editor);
6167 let loader = editor.syn_loader.load();
6168 if let Some(syntax) = doc.syntax() {
6169 let text = doc.text().slice(..);
6170
6171 let selection = doc.selection(view.id).clone().transform(|range| {
6172 let new_range = movement::goto_treesitter_object(
6173 text, range, object, direction, syntax, &loader, count,
6174 );
6175
6176 if editor.mode == Mode::Select {
6177 let head = if new_range.head < range.anchor {
6178 new_range.anchor
6179 } else {
6180 new_range.head
6181 };
6182
6183 Range::new(range.anchor, head)
6184 } else {
6185 new_range.with_direction(direction)
6186 }
6187 });
6188
6189 push_jump(view, doc);
6190 doc.set_selection(view.id, selection);
6191 } else {
6192 editor.set_status("Syntax-tree is not available in current buffer");
6193 }
6194 };
6195 cx.editor.apply_motion(motion);
6196 }
6197
6198 fn goto_next_function(cx: &mut Context) {
6199 goto_ts_object_impl(cx, "function", Direction::Forward)
6200 }
6201
6202 fn goto_prev_function(cx: &mut Context) {
6203 goto_ts_object_impl(cx, "function", Direction::Backward)
6204 }
6205
6206 fn goto_next_class(cx: &mut Context) {
6207 goto_ts_object_impl(cx, "class", Direction::Forward)
6208 }
6209
6210 fn goto_prev_class(cx: &mut Context) {
6211 goto_ts_object_impl(cx, "class", Direction::Backward)
6212 }
6213
6214 fn goto_next_parameter(cx: &mut Context) {
6215 goto_ts_object_impl(cx, "parameter", Direction::Forward)
6216 }
6217
6218 fn goto_prev_parameter(cx: &mut Context) {
6219 goto_ts_object_impl(cx, "parameter", Direction::Backward)
6220 }
6221
6222 fn goto_next_comment(cx: &mut Context) {
6223 goto_ts_object_impl(cx, "comment", Direction::Forward)
6224 }
6225
6226 fn goto_prev_comment(cx: &mut Context) {
6227 goto_ts_object_impl(cx, "comment", Direction::Backward)
6228 }
6229
6230 fn goto_next_test(cx: &mut Context) {
6231 goto_ts_object_impl(cx, "test", Direction::Forward)
6232 }
6233
6234 fn goto_prev_test(cx: &mut Context) {
6235 goto_ts_object_impl(cx, "test", Direction::Backward)
6236 }
6237
6238 fn goto_next_xml_element(cx: &mut Context) {
6239 goto_ts_object_impl(cx, "xml-element", Direction::Forward)
6240 }
6241
6242 fn goto_prev_xml_element(cx: &mut Context) {
6243 goto_ts_object_impl(cx, "xml-element", Direction::Backward)
6244 }
6245
6246 fn goto_next_entry(cx: &mut Context) {
6247 goto_ts_object_impl(cx, "entry", Direction::Forward)
6248 }
6249
6250 fn goto_prev_entry(cx: &mut Context) {
6251 goto_ts_object_impl(cx, "entry", Direction::Backward)
6252 }
6253
6254 fn select_textobject_around(cx: &mut Context) {
6255 select_textobject(cx, textobject::TextObject::Around);
6256 }
6257
6258 fn select_textobject_inner(cx: &mut Context) {
6259 select_textobject(cx, textobject::TextObject::Inside);
6260 }
6261
6262 fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) {
6263 let count = cx.count();
6264
6265 cx.on_next_key(move |cx, event| {
6266 cx.editor.autoinfo = None;
6267 if let Some(ch) = event.char() {
6268 let textobject = move |editor: &mut Editor| {
6269 let (view, doc) = current!(editor);
6270 let loader = editor.syn_loader.load();
6271 let text = doc.text().slice(..);
6272
6273 let textobject_treesitter = |obj_name: &str, range: Range| -> Range {
6274 let Some(syntax) = doc.syntax() else {
6275 return range;
6276 };
6277 textobject::textobject_treesitter(
6278 text, range, objtype, obj_name, syntax, &loader, count,
6279 )
6280 };
6281
6282 if ch == 'g' && doc.diff_handle().is_none() {
6283 editor.set_status("Diff is not available in current buffer");
6284 return;
6285 }
6286
6287 let textobject_change = |range: Range| -> Range {
6288 let diff_handle = doc.diff_handle().unwrap();
6289 let diff = diff_handle.load();
6290 let line = range.cursor_line(text);
6291 let hunk_idx = if let Some(hunk_idx) = diff.hunk_at(line as u32, false) {
6292 hunk_idx
6293 } else {
6294 return range;
6295 };
6296 let hunk = diff.nth_hunk(hunk_idx).after;
6297
6298 let start = text.line_to_char(hunk.start as usize);
6299 let end = text.line_to_char(hunk.end as usize);
6300 Range::new(start, end).with_direction(range.direction())
6301 };
6302
6303 let selection = doc.selection(view.id).clone().transform(|range| {
6304 match ch {
6305 'w' => textobject::textobject_word(text, range, objtype, count, false),
6306 'W' => textobject::textobject_word(text, range, objtype, count, true),
6307 't' => textobject_treesitter("class", range),
6308 'f' => textobject_treesitter("function", range),
6309 'a' => textobject_treesitter("parameter", range),
6310 'c' => textobject_treesitter("comment", range),
6311 'T' => textobject_treesitter("test", range),
6312 'e' => textobject_treesitter("entry", range),
6313 'x' => textobject_treesitter("xml-element", range),
6314 'p' => textobject::textobject_paragraph(text, range, objtype, count),
6315 'm' => textobject::textobject_pair_surround_closest(
6316 doc.syntax(),
6317 text,
6318 range,
6319 objtype,
6320 count,
6321 ),
6322 'g' => textobject_change(range),
6323 // TODO: cancel new ranges if inconsistent surround matches across lines
6324 ch if !ch.is_ascii_alphanumeric() => textobject::textobject_pair_surround(
6325 doc.syntax(),
6326 text,
6327 range,
6328 objtype,
6329 ch,
6330 count,
6331 ),
6332 _ => range,
6333 }
6334 });
6335 doc.set_selection(view.id, selection);
6336 };
6337 cx.editor.apply_motion(textobject);
6338 }
6339 });
6340
6341 let title = match objtype {
6342 textobject::TextObject::Inside => "Match inside",
6343 textobject::TextObject::Around => "Match around",
6344 _ => return,
6345 };
6346 let help_text = [
6347 ("w", "Word"),
6348 ("W", "WORD"),
6349 ("p", "Paragraph"),
6350 ("t", "Type definition (tree-sitter)"),
6351 ("f", "Function (tree-sitter)"),
6352 ("a", "Argument/parameter (tree-sitter)"),
6353 ("c", "Comment (tree-sitter)"),
6354 ("T", "Test (tree-sitter)"),
6355 ("e", "Data structure entry (tree-sitter)"),
6356 ("m", "Closest surrounding pair (tree-sitter)"),
6357 ("g", "Change"),
6358 ("x", "(X)HTML element (tree-sitter)"),
6359 (" ", "... or any character acting as a pair"),
6360 ];
6361
6362 cx.editor.autoinfo = Some(Info::new(title, &help_text));
6363 }
6364
6365 static SURROUND_HELP_TEXT: [(&str, &str); 6] = [
6366 ("m", "Nearest matching pair"),
6367 ("( or )", "Parentheses"),
6368 ("{ or }", "Curly braces"),
6369 ("< or >", "Angled brackets"),
6370 ("[ or ]", "Square brackets"),
6371 (" ", "... or any character"),
6372 ];
6373
6374 fn surround_add(cx: &mut Context) {
6375 cx.on_next_key(move |cx, event| {
6376 cx.editor.autoinfo = None;
6377 let (view, doc) = current!(cx.editor);
6378 // surround_len is the number of new characters being added.
6379 let (open, close, surround_len) = match event.char() {
6380 Some(ch) => {
6381 let (o, c) = match_brackets::get_pair(ch);
6382 let mut open = Tendril::new();
6383 open.push(o);
6384 let mut close = Tendril::new();
6385 close.push(c);
6386 (open, close, 2)
6387 }
6388 None if event.code == KeyCode::Enter => (
6389 doc.line_ending.as_str().into(),
6390 doc.line_ending.as_str().into(),
6391 2 * doc.line_ending.len_chars(),
6392 ),
6393 None => return,
6394 };
6395
6396 let selection = doc.selection(view.id);
6397 let mut changes = Vec::with_capacity(selection.len() * 2);
6398 let mut ranges = SmallVec::with_capacity(selection.len());
6399 let mut offs = 0;
6400
6401 for range in selection.iter() {
6402 changes.push((range.from(), range.from(), Some(open.clone())));
6403 changes.push((range.to(), range.to(), Some(close.clone())));
6404
6405 ranges.push(
6406 Range::new(offs + range.from(), offs + range.to() + surround_len)
6407 .with_direction(range.direction()),
6408 );
6409
6410 offs += surround_len;
6411 }
6412
6413 let transaction = Transaction::change(doc.text(), changes.into_iter())
6414 .with_selection(Selection::new(ranges, selection.primary_index()));
6415 doc.apply(&transaction, view.id);
6416 exit_select_mode(cx);
6417 });
6418
6419 cx.editor.autoinfo = Some(Info::new(
6420 "Surround selections with",
6421 &SURROUND_HELP_TEXT[1..],
6422 ));
6423 }
6424
6425 fn surround_replace(cx: &mut Context) {
6426 let count = cx.count();
6427 cx.on_next_key(move |cx, event| {
6428 cx.editor.autoinfo = None;
6429 let surround_ch = match event.char() {
6430 Some('m') => None, // m selects the closest surround pair
6431 Some(ch) => Some(ch),
6432 None => return,
6433 };
6434 let (view, doc) = current!(cx.editor);
6435 let text = doc.text().slice(..);
6436 let selection = doc.selection(view.id);
6437
6438 let change_pos =
6439 match surround::get_surround_pos(doc.syntax(), text, selection, surround_ch, count) {
6440 Ok(c) => c,
6441 Err(err) => {
6442 cx.editor.set_error(err.to_string());
6443 return;
6444 }
6445 };
6446
6447 let selection = selection.clone();
6448 let ranges: SmallVec<[Range; 1]> = change_pos.iter().map(|&p| Range::point(p)).collect();
6449 doc.set_selection(
6450 view.id,
6451 Selection::new(ranges, selection.primary_index() * 2),
6452 );
6453
6454 cx.on_next_key(move |cx, event| {
6455 cx.editor.autoinfo = None;
6456 let (view, doc) = current!(cx.editor);
6457 let to = match event.char() {
6458 Some(to) => to,
6459 None => return doc.set_selection(view.id, selection),
6460 };
6461 let (open, close) = match_brackets::get_pair(to);
6462
6463 // the changeset has to be sorted to allow nested surrounds
6464 let mut sorted_pos: Vec<(usize, char)> = Vec::new();
6465 for p in change_pos.chunks(2) {
6466 sorted_pos.push((p[0], open));
6467 sorted_pos.push((p[1], close));
6468 }
6469 sorted_pos.sort_unstable();
6470
6471 let transaction = Transaction::change(
6472 doc.text(),
6473 sorted_pos.iter().map(|&pos| {
6474 let mut t = Tendril::new();
6475 t.push(pos.1);
6476 (pos.0, pos.0 + 1, Some(t))
6477 }),
6478 );
6479 doc.set_selection(view.id, selection);
6480 doc.apply(&transaction, view.id);
6481 exit_select_mode(cx);
6482 });
6483
6484 cx.editor.autoinfo = Some(Info::new(
6485 "Replace with a pair of",
6486 &SURROUND_HELP_TEXT[1..],
6487 ));
6488 });
6489
6490 cx.editor.autoinfo = Some(Info::new(
6491 "Replace surrounding pair of",
6492 &SURROUND_HELP_TEXT,
6493 ));
6494 }
6495
6496 fn surround_delete(cx: &mut Context) {
6497 let count = cx.count();
6498 cx.on_next_key(move |cx, event| {
6499 cx.editor.autoinfo = None;
6500 let surround_ch = match event.char() {
6501 Some('m') => None, // m selects the closest surround pair
6502 Some(ch) => Some(ch),
6503 None => return,
6504 };
6505 let (view, doc) = current!(cx.editor);
6506 let text = doc.text().slice(..);
6507 let selection = doc.selection(view.id);
6508
6509 let mut change_pos =
6510 match surround::get_surround_pos(doc.syntax(), text, selection, surround_ch, count) {
6511 Ok(c) => c,
6512 Err(err) => {
6513 cx.editor.set_error(err.to_string());
6514 return;
6515 }
6516 };
6517 change_pos.sort_unstable(); // the changeset has to be sorted to allow nested surrounds
6518 let transaction =
6519 Transaction::change(doc.text(), change_pos.into_iter().map(|p| (p, p + 1, None)));
6520 doc.apply(&transaction, view.id);
6521 exit_select_mode(cx);
6522 });
6523
6524 cx.editor.autoinfo = Some(Info::new("Delete surrounding pair of", &SURROUND_HELP_TEXT));
6525 }
6526
6527 #[derive(Eq, PartialEq)]
6528 enum ShellBehavior {
6529 Replace,
6530 Ignore,
6531 Insert,
6532 Append,
6533 }
6534
6535 fn shell_pipe(cx: &mut Context) {
6536 shell_prompt_for_behavior(cx, "pipe:".into(), ShellBehavior::Replace);
6537 }
6538
6539 fn shell_pipe_to(cx: &mut Context) {
6540 shell_prompt_for_behavior(cx, "pipe-to:".into(), ShellBehavior::Ignore);
6541 }
6542
6543 fn shell_insert_output(cx: &mut Context) {
6544 shell_prompt_for_behavior(cx, "insert-output:".into(), ShellBehavior::Insert);
6545 }
6546
6547 fn shell_append_output(cx: &mut Context) {
6548 shell_prompt_for_behavior(cx, "append-output:".into(), ShellBehavior::Append);
6549 }
6550
6551 fn shell_keep_pipe(cx: &mut Context) {
6552 shell_prompt(cx, "keep-pipe:".into(), |cx, args| {
6553 let shell = &cx.editor.config().shell;
6554 let (view, doc) = current!(cx.editor);
6555 let selection = doc.selection(view.id);
6556
6557 let mut ranges = SmallVec::with_capacity(selection.len());
6558 let old_index = selection.primary_index();
6559 let mut index: Option<usize> = None;
6560 let text = doc.text().slice(..);
6561
6562 for (i, range) in selection.ranges().iter().enumerate() {
6563 let fragment = range.slice(text);
6564 if let Err(err) = shell_impl(shell, args.join(" ").as_str(), Some(fragment.into())) {
6565 log::debug!("Shell command failed: {}", err);
6566 } else {
6567 ranges.push(*range);
6568 if i >= old_index && index.is_none() {
6569 index = Some(ranges.len() - 1);
6570 }
6571 }
6572 }
6573
6574 if ranges.is_empty() {
6575 cx.editor.set_error("No selections remaining");
6576 return;
6577 }
6578
6579 let index = index.unwrap_or_else(|| ranges.len() - 1);
6580 doc.set_selection(view.id, Selection::new(ranges, index));
6581 });
6582 }
6583
6584 fn shell_impl(shell: &[String], cmd: &str, input: Option<Rope>) -> anyhow::Result<Tendril> {
6585 tokio::task::block_in_place(|| helix_lsp::block_on(shell_impl_async(shell, cmd, input)))
6586 }
6587
6588 async fn shell_impl_async(
6589 shell: &[String],
6590 cmd: &str,
6591 input: Option<Rope>,
6592 ) -> anyhow::Result<Tendril> {
6593 use std::process::Stdio;
6594 use tokio::process::Command;
6595 ensure!(!shell.is_empty(), "No shell set");
6596
6597 let mut process = Command::new(&shell[0]);
6598 process
6599 .args(&shell[1..])
6600 .arg(cmd)
6601 .stdout(Stdio::piped())
6602 .stderr(Stdio::piped());
6603
6604 if input.is_some() || cfg!(windows) {
6605 process.stdin(Stdio::piped());
6606 } else {
6607 process.stdin(Stdio::null());
6608 }
6609
6610 let mut process = match process.spawn() {
6611 Ok(process) => process,
6612 Err(e) => {
6613 log::error!("Failed to start shell: {}", e);
6614 return Err(e.into());
6615 }
6616 };
6617 let output = if let Some(mut stdin) = process.stdin.take() {
6618 let input_task = tokio::spawn(async move {
6619 if let Some(input) = input {
6620 helix_view::document::to_writer(&mut stdin, (encoding::UTF_8, false), &input)
6621 .await?;
6622 }
6623 anyhow::Ok(())
6624 });
6625 let (output, _) = tokio::join! {
6626 process.wait_with_output(),
6627 input_task,
6628 };
6629 output?
6630 } else {
6631 // Process has no stdin, so we just take the output
6632 process.wait_with_output().await?
6633 };
6634
6635 let output = if !output.status.success() {
6636 if output.stderr.is_empty() {
6637 match output.status.code() {
6638 Some(exit_code) => bail!("Shell command failed: status {}", exit_code),
6639 None => bail!("Shell command failed"),
6640 }
6641 }
6642 String::from_utf8_lossy(&output.stderr)
6643 // Prioritize `stderr` output over `stdout`
6644 } else if !output.stderr.is_empty() {
6645 let stderr = String::from_utf8_lossy(&output.stderr);
6646 log::debug!("Command printed to stderr: {stderr}");
6647 stderr
6648 } else {
6649 String::from_utf8_lossy(&output.stdout)
6650 };
6651
6652 Ok(Tendril::from(output))
6653 }
6654
6655 fn shell(cx: &mut compositor::Context, cmd: &str, behavior: &ShellBehavior) {
6656 let pipe = match behavior {
6657 ShellBehavior::Replace | ShellBehavior::Ignore => true,
6658 ShellBehavior::Insert | ShellBehavior::Append => false,
6659 };
6660
6661 let config = cx.editor.config();
6662 let shell = &config.shell;
6663 let (view, doc) = current!(cx.editor);
6664 let selection = doc.selection(view.id);
6665
6666 let mut changes = Vec::with_capacity(selection.len());
6667 let mut ranges = SmallVec::with_capacity(selection.len());
6668 let text = doc.text().slice(..);
6669
6670 let mut shell_output: Option<Tendril> = None;
6671 let mut offset = 0isize;
6672 for range in selection.ranges() {
6673 let output = if let Some(output) = shell_output.as_ref() {
6674 output.clone()
6675 } else {
6676 let input = range.slice(text);
6677 match shell_impl(shell, cmd, pipe.then(|| input.into())) {
6678 Ok(mut output) => {
6679 if !input.ends_with("\n") && output.ends_with('\n') {
6680 output.pop();
6681 if output.ends_with('\r') {
6682 output.pop();
6683 }
6684 }
6685
6686 if !pipe {
6687 shell_output = Some(output.clone());
6688 }
6689 output
6690 }
6691 Err(err) => {
6692 cx.editor.set_error(err.to_string());
6693 return;
6694 }
6695 }
6696 };
6697
6698 let output_len = output.chars().count();
6699
6700 let (from, to, deleted_len) = match behavior {
6701 ShellBehavior::Replace => (range.from(), range.to(), range.len()),
6702 ShellBehavior::Insert => (range.from(), range.from(), 0),
6703 ShellBehavior::Append => (range.to(), range.to(), 0),
6704 _ => (range.from(), range.from(), 0),
6705 };
6706
6707 // These `usize`s cannot underflow because selection ranges cannot overlap.
6708 let anchor = to
6709 .checked_add_signed(offset)
6710 .expect("Selection ranges cannot overlap")
6711 .checked_sub(deleted_len)
6712 .expect("Selection ranges cannot overlap");
6713 let new_range = Range::new(anchor, anchor + output_len).with_direction(range.direction());
6714 ranges.push(new_range);
6715 offset = offset
6716 .checked_add_unsigned(output_len)
6717 .expect("Selection ranges cannot overlap")
6718 .checked_sub_unsigned(deleted_len)
6719 .expect("Selection ranges cannot overlap");
6720
6721 changes.push((from, to, Some(output)));
6722 }
6723
6724 if behavior != &ShellBehavior::Ignore {
6725 let transaction = Transaction::change(doc.text(), changes.into_iter())
6726 .with_selection(Selection::new(ranges, selection.primary_index()));
6727 doc.apply(&transaction, view.id);
6728 doc.append_changes_to_history(view);
6729 }
6730
6731 // after replace cursor may be out of bounds, do this to
6732 // make sure cursor is in view and update scroll as well
6733 view.ensure_cursor_in_view(doc, config.scrolloff);
6734 }
6735
6736 fn shell_prompt<F>(cx: &mut Context, prompt: Cow<'static, str>, mut callback_fn: F)
6737 where
6738 F: FnMut(&mut compositor::Context, Args) + 'static,
6739 {
6740 ui::prompt(
6741 cx,
6742 prompt,
6743 Some('|'),
6744 |editor, input| complete_command_args(editor, SHELL_SIGNATURE, &SHELL_COMPLETER, input, 0),
6745 move |cx, input, event| {
6746 if event != PromptEvent::Validate || input.is_empty() {
6747 return;
6748 }
6749 match Args::parse(input, SHELL_SIGNATURE, true, |token| {
6750 expansion::expand(cx.editor, token).map_err(|err| err.into())
6751 }) {
6752 Ok(args) => callback_fn(cx, args),
6753 Err(err) => cx.editor.set_error(err.to_string()),
6754 }
6755 },
6756 );
6757 }
6758
6759 fn shell_prompt_for_behavior(cx: &mut Context, prompt: Cow<'static, str>, behavior: ShellBehavior) {
6760 shell_prompt(cx, prompt, move |cx, args| {
6761 shell(cx, args.join(" ").as_str(), &behavior)
6762 })
6763 }
6764
6765 fn suspend(_cx: &mut Context) {
6766 #[cfg(not(windows))]
6767 {
6768 // SAFETY: These are calls to standard POSIX functions.
6769 // Unsafe is necessary since we are calling outside of Rust.
6770 let is_session_leader = unsafe { libc::getpid() == libc::getsid(0) };
6771
6772 // If helix is the session leader, there is nothing to suspend to, so skip
6773 if is_session_leader {
6774 return;
6775 }
6776 _cx.block_try_flush_writes().ok();
6777 signal_hook::low_level::raise(signal_hook::consts::signal::SIGTSTP).unwrap();
6778 }
6779 }
6780
6781 fn add_newline_above(cx: &mut Context) {
6782 add_newline_impl(cx, Open::Above);
6783 }
6784
6785 fn add_newline_below(cx: &mut Context) {
6786 add_newline_impl(cx, Open::Below)
6787 }
6788
6789 fn add_newline_impl(cx: &mut Context, open: Open) {
6790 let count = cx.count();
6791 let (view, doc) = current!(cx.editor);
6792 let selection = doc.selection(view.id);
6793 let text = doc.text();
6794 let slice = text.slice(..);
6795
6796 let changes = selection.into_iter().map(|range| {
6797 let (start, end) = range.line_range(slice);
6798 let line = match open {
6799 Open::Above => start,
6800 Open::Below => end + 1,
6801 };
6802 let pos = text.line_to_char(line);
6803 (
6804 pos,
6805 pos,
6806 Some(doc.line_ending.as_str().repeat(count).into()),
6807 )
6808 });
6809
6810 let transaction = Transaction::change(text, changes);
6811 doc.apply(&transaction, view.id);
6812 }
6813
6814 enum IncrementDirection {
6815 Increase,
6816 Decrease,
6817 }
6818
6819 /// Increment objects within selections by count.
6820 fn increment(cx: &mut Context) {
6821 increment_impl(cx, IncrementDirection::Increase);
6822 }
6823
6824 /// Decrement objects within selections by count.
6825 fn decrement(cx: &mut Context) {
6826 increment_impl(cx, IncrementDirection::Decrease);
6827 }
6828
6829 /// Increment objects within selections by `amount`.
6830 /// A negative `amount` will decrement objects within selections.
6831 fn increment_impl(cx: &mut Context, increment_direction: IncrementDirection) {
6832 let sign = match increment_direction {
6833 IncrementDirection::Increase => 1,
6834 IncrementDirection::Decrease => -1,
6835 };
6836 let mut amount = sign * cx.count() as i64;
6837 // If the register is `#` then increase or decrease the `amount` by 1 per element
6838 let increase_by = if cx.register == Some('#') { sign } else { 0 };
6839
6840 let (view, doc) = current!(cx.editor);
6841 let selection = doc.selection(view.id);
6842 let text = doc.text().slice(..);
6843
6844 let mut new_selection_ranges = SmallVec::new();
6845 let mut cumulative_length_diff: i128 = 0;
6846 let mut changes = vec![];
6847
6848 for range in selection {
6849 let selected_text: Cow<str> = range.fragment(text);
6850 let new_from = ((range.from() as i128) + cumulative_length_diff) as usize;
6851 let incremented = [increment::integer, increment::date_time]
6852 .iter()
6853 .find_map(|incrementor| incrementor(selected_text.as_ref(), amount));
6854
6855 amount += increase_by;
6856
6857 match incremented {
6858 None => {
6859 let new_range = Range::new(
6860 new_from,
6861 (range.to() as i128 + cumulative_length_diff) as usize,
6862 );
6863 new_selection_ranges.push(new_range);
6864 }
6865 Some(new_text) => {
6866 let new_range = Range::new(new_from, new_from + new_text.len());
6867 cumulative_length_diff += new_text.len() as i128 - selected_text.len() as i128;
6868 new_selection_ranges.push(new_range);
6869 changes.push((range.from(), range.to(), Some(new_text.into())));
6870 }
6871 }
6872 }
6873
6874 if !changes.is_empty() {
6875 let new_selection = Selection::new(new_selection_ranges, selection.primary_index());
6876 let transaction = Transaction::change(doc.text(), changes.into_iter());
6877 let transaction = transaction.with_selection(new_selection);
6878 doc.apply(&transaction, view.id);
6879 exit_select_mode(cx);
6880 }
6881 }
6882
6883 fn goto_next_tabstop(cx: &mut Context) {
6884 goto_next_tabstop_impl(cx, Direction::Forward)
6885 }
6886
6887 fn goto_prev_tabstop(cx: &mut Context) {
6888 goto_next_tabstop_impl(cx, Direction::Backward)
6889 }
6890
6891 fn goto_next_tabstop_impl(cx: &mut Context, direction: Direction) {
6892 let (view, doc) = current!(cx.editor);
6893 let view_id = view.id;
6894 let Some(mut snippet) = doc.active_snippet.take() else {
6895 cx.editor.set_error("no snippet is currently active");
6896 return;
6897 };
6898 let tabstop = match direction {
6899 Direction::Forward => Some(snippet.next_tabstop(doc.selection(view_id))),
6900 Direction::Backward => snippet
6901 .prev_tabstop(doc.selection(view_id))
6902 .map(|selection| (selection, false)),
6903 };
6904 let Some((selection, last_tabstop)) = tabstop else {
6905 return;
6906 };
6907 doc.set_selection(view_id, selection);
6908 if !last_tabstop {
6909 doc.active_snippet = Some(snippet)
6910 }
6911 if cx.editor.mode() == Mode::Insert {
6912 cx.on_next_key_fallback(|cx, key| {
6913 if let Some(c) = key.char() {
6914 let (view, doc) = current!(cx.editor);
6915 if let Some(snippet) = &doc.active_snippet {
6916 doc.apply(&snippet.delete_placeholder(doc.text()), view.id);
6917 }
6918 insert_char(cx, c);
6919 }
6920 })
6921 }
6922 }
6923
6924 fn record_macro(cx: &mut Context) {
6925 if let Some((reg, mut keys)) = cx.editor.macro_recording.take() {
6926 // Remove the keypress which ends the recording
6927 keys.pop();
6928 let s = keys
6929 .into_iter()
6930 .map(|key| {
6931 let s = key.to_string();
6932 if s.chars().count() == 1 {
6933 s
6934 } else {
6935 format!("<{}>", s)
6936 }
6937 })
6938 .collect::<String>();
6939 match cx.editor.registers.write(reg, vec![s]) {
6940 Ok(_) => cx
6941 .editor
6942 .set_status(format!("Recorded to register [{}]", reg)),
6943 Err(err) => cx.editor.set_error(err.to_string()),
6944 }
6945 } else {
6946 let reg = cx.register.take().unwrap_or('@');
6947 cx.editor.macro_recording = Some((reg, Vec::new()));
6948 cx.editor
6949 .set_status(format!("Recording to register [{}]", reg));
6950 }
6951 }
6952
6953 fn replay_macro(cx: &mut Context) {
6954 let reg = cx.register.unwrap_or('@');
6955
6956 if cx.editor.macro_replaying.contains(&reg) {
6957 cx.editor.set_error(format!(
6958 "Cannot replay from register [{}] because already replaying from same register",
6959 reg
6960 ));
6961 return;
6962 }
6963
6964 let keys: Vec<KeyEvent> = if let Some(keys) = cx
6965 .editor
6966 .registers
6967 .read(reg, cx.editor)
6968 .filter(|values| values.len() == 1)
6969 .map(|mut values| values.next().unwrap())
6970 {
6971 match helix_view::input::parse_macro(&keys) {
6972 Ok(keys) => keys,
6973 Err(err) => {
6974 cx.editor.set_error(format!("Invalid macro: {}", err));
6975 return;
6976 }
6977 }
6978 } else {
6979 cx.editor.set_error(format!("Register [{}] empty", reg));
6980 return;
6981 };
6982
6983 // Once the macro has been fully validated, it's marked as being under replay
6984 // to ensure we don't fall into infinite recursion.
6985 cx.editor.macro_replaying.push(reg);
6986
6987 let count = cx.count();
6988 cx.callback.push(Box::new(move |compositor, cx| {
6989 for _ in 0..count {
6990 for &key in keys.iter() {
6991 compositor.handle_event(&compositor::Event::Key(key), cx);
6992 }
6993 }
6994 // The macro under replay is cleared at the end of the callback, not in the
6995 // macro replay context, or it will not correctly protect the user from
6996 // replaying recursively.
6997 cx.editor.macro_replaying.pop();
6998 }));
6999 }
7000
7001 fn goto_word(cx: &mut Context) {
7002 jump_to_word(cx, Movement::Move)
7003 }
7004
7005 fn extend_to_word(cx: &mut Context) {
7006 jump_to_word(cx, Movement::Extend)
7007 }
7008
7009 fn jump_to_label(cx: &mut Context, labels: Vec<Range>, behaviour: Movement) {
7010 let doc = doc!(cx.editor);
7011 let alphabet = &cx.editor.config().jump_label_alphabet;
7012 if labels.is_empty() {
7013 return;
7014 }
7015 let alphabet_char = |i| {
7016 let mut res = Tendril::new();
7017 res.push(alphabet[i]);
7018 res
7019 };
7020
7021 // Add label for each jump candidate to the View as virtual text.
7022 let text = doc.text().slice(..);
7023 let mut overlays: Vec<_> = labels
7024 .iter()
7025 .enumerate()
7026 .flat_map(|(i, range)| {
7027 [
7028 Overlay::new(range.from(), alphabet_char(i / alphabet.len())),
7029 Overlay::new(
7030 graphemes::next_grapheme_boundary(text, range.from()),
7031 alphabet_char(i % alphabet.len()),
7032 ),
7033 ]
7034 })
7035 .collect();
7036 overlays.sort_unstable_by_key(|overlay| overlay.char_idx);
7037 let (view, doc) = current!(cx.editor);
7038 doc.set_jump_labels(view.id, overlays);
7039
7040 // Accept two characters matching a visible label. Jump to the candidate
7041 // for that label if it exists.
7042 let primary_selection = doc.selection(view.id).primary();
7043 let view_id = view.id;
7044 let doc = doc.id();
7045 cx.on_next_key(move |cx, event| {
7046 let alphabet = &cx.editor.config().jump_label_alphabet;
7047 let Some(i) = event
7048 .char()
7049 .filter(|_| event.modifiers.is_empty())
7050 .and_then(|ch| alphabet.iter().position(|&it| it == ch))
7051 else {
7052 doc_mut!(cx.editor, &doc).remove_jump_labels(view_id);
7053 return;
7054 };
7055 let outer = i * alphabet.len();
7056 // Bail if the given character cannot be a jump label.
7057 if outer > labels.len() {
7058 doc_mut!(cx.editor, &doc).remove_jump_labels(view_id);
7059 return;
7060 }
7061 cx.on_next_key(move |cx, event| {
7062 doc_mut!(cx.editor, &doc).remove_jump_labels(view_id);
7063 let alphabet = &cx.editor.config().jump_label_alphabet;
7064 let Some(inner) = event
7065 .char()
7066 .filter(|_| event.modifiers.is_empty())
7067 .and_then(|ch| alphabet.iter().position(|&it| it == ch))
7068 else {
7069 return;
7070 };
7071 if let Some(mut range) = labels.get(outer + inner).copied() {
7072 range = if behaviour == Movement::Extend {
7073 let anchor = if range.anchor < range.head {
7074 let from = primary_selection.from();
7075 if range.anchor < from {
7076 range.anchor
7077 } else {
7078 from
7079 }
7080 } else {
7081 let to = primary_selection.to();
7082 if range.anchor > to {
7083 range.anchor
7084 } else {
7085 to
7086 }
7087 };
7088 Range::new(anchor, range.head)
7089 } else {
7090 range.with_direction(Direction::Forward)
7091 };
7092 let doc = doc_mut!(cx.editor, &doc);
7093 let view = view_mut!(cx.editor, view_id);
7094 push_jump(view, doc);
7095 doc.set_selection(view_id, range.into());
7096 }
7097 });
7098 });
7099 }
7100
7101 fn jump_to_word(cx: &mut Context, behaviour: Movement) {
7102 // Calculate the jump candidates: ranges for any visible words with two or
7103 // more characters.
7104 let alphabet = &cx.editor.config().jump_label_alphabet;
7105 if alphabet.is_empty() {
7106 return;
7107 }
7108
7109 let jump_label_limit = alphabet.len() * alphabet.len();
7110 let mut words = Vec::with_capacity(jump_label_limit);
7111 let (view, doc) = current_ref!(cx.editor);
7112 let text = doc.text().slice(..);
7113
7114 // This is not necessarily exact if there is virtual text like soft wrap.
7115 // It's ok though because the extra jump labels will not be rendered.
7116 let start = text.line_to_char(text.char_to_line(doc.view_offset(view.id).anchor));
7117 let end = text.line_to_char(view.estimate_last_doc_line(doc) + 1);
7118
7119 let primary_selection = doc.selection(view.id).primary();
7120 let cursor = primary_selection.cursor(text);
7121 let mut cursor_fwd = Range::point(cursor);
7122 let mut cursor_rev = Range::point(cursor);
7123 if text.get_char(cursor).is_some_and(|c| !c.is_whitespace()) {
7124 let cursor_word_end = movement::move_next_word_end(text, cursor_fwd, 1);
7125 // single grapheme words need a special case
7126 if cursor_word_end.anchor == cursor {
7127 cursor_fwd = cursor_word_end;
7128 }
7129 let cursor_word_start = movement::move_prev_word_start(text, cursor_rev, 1);
7130 if cursor_word_start.anchor == next_grapheme_boundary(text, cursor) {
7131 cursor_rev = cursor_word_start;
7132 }
7133 }
7134 'outer: loop {
7135 let mut changed = false;
7136 while cursor_fwd.head < end {
7137 cursor_fwd = movement::move_next_word_end(text, cursor_fwd, 1);
7138 // The cursor is on a word that is atleast two graphemes long and
7139 // madeup of word characters. The latter condition is needed because
7140 // move_next_word_end simply treats a sequence of characters from
7141 // the same char class as a word so `=<` would also count as a word.
7142 let add_label = text
7143 .slice(..cursor_fwd.head)
7144 .graphemes_rev()
7145 .take(2)
7146 .take_while(|g| g.chars().all(char_is_word))
7147 .count()
7148 == 2;
7149 if !add_label {
7150 continue;
7151 }
7152 changed = true;
7153 // skip any leading whitespace
7154 cursor_fwd.anchor += text
7155 .chars_at(cursor_fwd.anchor)
7156 .take_while(|&c| !char_is_word(c))
7157 .count();
7158 words.push(cursor_fwd);
7159 if words.len() == jump_label_limit {
7160 break 'outer;
7161 }
7162 break;
7163 }
7164 while cursor_rev.head > start {
7165 cursor_rev = movement::move_prev_word_start(text, cursor_rev, 1);
7166 // The cursor is on a word that is atleast two graphemes long and
7167 // madeup of word characters. The latter condition is needed because
7168 // move_prev_word_start simply treats a sequence of characters from
7169 // the same char class as a word so `=<` would also count as a word.
7170 let add_label = text
7171 .slice(cursor_rev.head..)
7172 .graphemes()
7173 .take(2)
7174 .take_while(|g| g.chars().all(char_is_word))
7175 .count()
7176 == 2;
7177 if !add_label {
7178 continue;
7179 }
7180 changed = true;
7181 cursor_rev.anchor -= text
7182 .chars_at(cursor_rev.anchor)
7183 .reversed()
7184 .take_while(|&c| !char_is_word(c))
7185 .count();
7186 words.push(cursor_rev);
7187 if words.len() == jump_label_limit {
7188 break 'outer;
7189 }
7190 break;
7191 }
7192 if !changed {
7193 break;
7194 }
7195 }
7196 jump_to_label(cx, words, behaviour)
7197 }
7198
7199 fn lsp_or_syntax_symbol_picker(cx: &mut Context) {
7200 let doc = doc!(cx.editor);
7201
7202 if doc
7203 .language_servers_with_feature(LanguageServerFeature::DocumentSymbols)
7204 .next()
7205 .is_some()
7206 {
7207 lsp::symbol_picker(cx);
7208 } else if doc.syntax().is_some() {
7209 syntax_symbol_picker(cx);
7210 } else {
7211 cx.editor
7212 .set_error("No language server supporting document symbols or syntax info available");
7213 }
7214 }
7215
7216 fn lsp_or_syntax_workspace_symbol_picker(cx: &mut Context) {
7217 let doc = doc!(cx.editor);
7218
7219 if doc
7220 .language_servers_with_feature(LanguageServerFeature::WorkspaceSymbols)
7221 .next()
7222 .is_some()
7223 {
7224 lsp::workspace_symbol_picker(cx);
7225 } else {
7226 syntax_workspace_symbol_picker(cx);
7227 }
7228 }