Debian Codegraph @

helix-term/src/commands/typed.rs

raw symbols SCIP
1 use std::fmt::Write;
2 use std::io::BufReader;
3 use std::ops::{self, Deref};
4
5 use crate::job::Job;
6
7 use super::*;
8
9 use helix_core::command_line::{Args, Flag, Signature, Token, TokenKind};
10 use helix_core::fuzzy::fuzzy_match;
11 use helix_core::indent::MAX_INDENT;
12 use helix_core::line_ending;
13 use helix_stdx::path::home_dir;
14 use helix_view::document::{read_to_string, DEFAULT_LANGUAGE_NAME};
15 use helix_view::editor::{CloseError, ConfigEvent};
16 use helix_view::expansion;
17 use serde_json::Value;
18 use ui::completers::{self, Completer};
19
20 #[derive(Clone)]
21 pub struct TypableCommand {
22 pub name: &'static str,
23 pub aliases: &'static [&'static str],
24 pub doc: &'static str,
25 // params, flags, helper, completer
26 pub fun: fn(&mut compositor::Context, Args, PromptEvent) -> anyhow::Result<()>,
27 /// What completion methods, if any, does this command have?
28 pub completer: CommandCompleter,
29 pub signature: Signature,
30 }
31
32 #[derive(Clone)]
33 pub struct CommandCompleter {
34 // Arguments with specific completion methods based on their position.
35 positional_args: &'static [Completer],
36
37 // All remaining arguments will use this completion method, if set.
38 var_args: Completer,
39 }
40
41 impl CommandCompleter {
42 const fn none() -> Self {
43 Self {
44 positional_args: &[],
45 var_args: completers::none,
46 }
47 }
48
49 const fn positional(completers: &'static [Completer]) -> Self {
50 Self {
51 positional_args: completers,
52 var_args: completers::none,
53 }
54 }
55
56 const fn all(completer: Completer) -> Self {
57 Self {
58 positional_args: &[],
59 var_args: completer,
60 }
61 }
62
63 fn for_argument_number(&self, n: usize) -> &Completer {
64 match self.positional_args.get(n) {
65 Some(completer) => completer,
66 _ => &self.var_args,
67 }
68 }
69 }
70
71 fn exit(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
72 if event != PromptEvent::Validate {
73 return Ok(());
74 }
75
76 if doc!(cx.editor).is_modified() {
77 write_impl(
78 cx,
79 args.first(),
80 WriteOptions {
81 force: false,
82 auto_format: !args.has_flag(WRITE_NO_FORMAT_FLAG.name),
83 code_actions: !args.has_flag(WRITE_NO_CODE_ACTIONS_FLAG.name),
84 },
85 )?;
86 }
87 cx.block_try_flush_writes()?;
88 quit(cx, Args::default(), event)
89 }
90
91 fn force_exit(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
92 if event != PromptEvent::Validate {
93 return Ok(());
94 }
95
96 if doc!(cx.editor).is_modified() {
97 write_impl(
98 cx,
99 args.first(),
100 WriteOptions {
101 force: true,
102 auto_format: !args.has_flag(WRITE_NO_FORMAT_FLAG.name),
103 code_actions: !args.has_flag(WRITE_NO_CODE_ACTIONS_FLAG.name),
104 },
105 )?;
106 }
107 cx.block_try_flush_writes()?;
108 quit(cx, Args::default(), event)
109 }
110
111 fn quit(cx: &mut compositor::Context, _args: Args, event: PromptEvent) -> anyhow::Result<()> {
112 log::debug!("quitting...");
113
114 if event != PromptEvent::Validate {
115 return Ok(());
116 }
117
118 // last view and we have unsaved changes
119 if cx.editor.tree.views().count() == 1 {
120 buffers_remaining_impl(cx.editor)?
121 }
122
123 cx.block_try_flush_writes()?;
124 cx.editor.close(view!(cx.editor).id);
125
126 Ok(())
127 }
128
129 fn force_quit(cx: &mut compositor::Context, _args: Args, event: PromptEvent) -> anyhow::Result<()> {
130 if event != PromptEvent::Validate {
131 return Ok(());
132 }
133
134 cx.block_try_flush_writes()?;
135 cx.editor.close(view!(cx.editor).id);
136
137 Ok(())
138 }
139
140 fn open(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
141 if event != PromptEvent::Validate {
142 return Ok(());
143 }
144
145 open_impl(cx, args, Action::Replace)
146 }
147
148 fn open_impl(cx: &mut compositor::Context, args: Args, action: Action) -> anyhow::Result<()> {
149 for arg in args {
150 let (path, pos) = crate::args::parse_file(&arg);
151 let path = helix_stdx::path::expand_tilde(path);
152 // If the path is a directory, open a file picker on that directory and update the status
153 // message
154 if let Ok(true) = std::fs::canonicalize(&path).map(|p| p.is_dir()) {
155 let callback = async move {
156 let call: job::Callback = job::Callback::EditorCompositor(Box::new(
157 move |editor: &mut Editor, compositor: &mut Compositor| {
158 let picker =
159 ui::file_picker(editor, path.into_owned()).with_default_action(action);
160 compositor.push(Box::new(overlaid(picker)));
161 },
162 ));
163 Ok(call)
164 };
165 cx.jobs.callback(callback);
166 } else {
167 // Otherwise, just open the file
168 let _ = cx.editor.open(&path, action)?;
169 let (view, doc) = current!(cx.editor);
170 let pos = Selection::point(pos_at_coords(doc.text().slice(..), pos, true));
171 doc.set_selection(view.id, pos);
172 // does not affect opening a buffer without pos
173 align_view(doc, view, Align::Center);
174 }
175 }
176 Ok(())
177 }
178
179 fn buffer_close_by_ids_impl(
180 cx: &mut compositor::Context,
181 doc_ids: &[DocumentId],
182 force: bool,
183 ) -> anyhow::Result<()> {
184 cx.block_try_flush_writes()?;
185
186 let (modified_ids, modified_names): (Vec<_>, Vec<_>) = doc_ids
187 .iter()
188 .filter_map(|&doc_id| {
189 if let Err(CloseError::BufferModified(name)) = cx.editor.close_document(doc_id, force) {
190 Some((doc_id, name))
191 } else {
192 None
193 }
194 })
195 .unzip();
196
197 if let Some(first) = modified_ids.first() {
198 let current = doc!(cx.editor);
199 // If the current document is unmodified, and there are modified
200 // documents, switch focus to the first modified doc.
201 if !modified_ids.contains(&current.id()) {
202 cx.editor.switch(*first, Action::Replace);
203 }
204 bail!(
205 "{} unsaved buffer{} remaining: {:?}",
206 modified_names.len(),
207 if modified_names.len() == 1 { "" } else { "s" },
208 modified_names,
209 );
210 }
211
212 Ok(())
213 }
214
215 fn buffer_gather_paths_impl(editor: &mut Editor, args: Args) -> Vec<DocumentId> {
216 // No arguments implies current document
217 if args.is_empty() {
218 let doc_id = view!(editor).doc;
219 return vec![doc_id];
220 }
221
222 let mut nonexistent_buffers = vec![];
223 let mut document_ids = vec![];
224 for arg in args {
225 let doc_id = editor.documents().find_map(|doc| {
226 let arg_path = Some(Path::new(arg.as_ref()));
227 if doc.path() == arg_path || doc.relative_path() == arg_path {
228 Some(doc.id())
229 } else {
230 None
231 }
232 });
233
234 match doc_id {
235 Some(doc_id) => document_ids.push(doc_id),
236 None => nonexistent_buffers.push(format!("'{}'", arg)),
237 }
238 }
239
240 if !nonexistent_buffers.is_empty() {
241 editor.set_error(format!(
242 "cannot close non-existent buffers: {}",
243 nonexistent_buffers.join(", ")
244 ));
245 }
246
247 document_ids
248 }
249
250 fn buffer_close(
251 cx: &mut compositor::Context,
252 args: Args,
253 event: PromptEvent,
254 ) -> anyhow::Result<()> {
255 if event != PromptEvent::Validate {
256 return Ok(());
257 }
258
259 let document_ids = buffer_gather_paths_impl(cx.editor, args);
260 buffer_close_by_ids_impl(cx, &document_ids, false)
261 }
262
263 fn force_buffer_close(
264 cx: &mut compositor::Context,
265 args: Args,
266 event: PromptEvent,
267 ) -> anyhow::Result<()> {
268 if event != PromptEvent::Validate {
269 return Ok(());
270 }
271
272 let document_ids = buffer_gather_paths_impl(cx.editor, args);
273 buffer_close_by_ids_impl(cx, &document_ids, true)
274 }
275
276 fn buffer_gather_others_impl(editor: &mut Editor, skip_visible: bool) -> Vec<DocumentId> {
277 if skip_visible {
278 let visible_document_ids = editor
279 .tree
280 .views()
281 .map(|view| &view.0.doc)
282 .collect::<HashSet<_>>();
283 editor
284 .documents()
285 .map(|doc| doc.id())
286 .filter(|doc_id| !visible_document_ids.contains(doc_id))
287 .collect()
288 } else {
289 let current_document = &doc!(editor).id();
290 editor
291 .documents()
292 .map(|doc| doc.id())
293 .filter(|doc_id| doc_id != current_document)
294 .collect()
295 }
296 }
297
298 fn buffer_close_others(
299 cx: &mut compositor::Context,
300 args: Args,
301 event: PromptEvent,
302 ) -> anyhow::Result<()> {
303 if event != PromptEvent::Validate {
304 return Ok(());
305 }
306
307 let document_ids = buffer_gather_others_impl(cx.editor, args.has_flag("skip-visible"));
308 buffer_close_by_ids_impl(cx, &document_ids, false)
309 }
310
311 fn force_buffer_close_others(
312 cx: &mut compositor::Context,
313 args: Args,
314 event: PromptEvent,
315 ) -> anyhow::Result<()> {
316 if event != PromptEvent::Validate {
317 return Ok(());
318 }
319
320 let document_ids = buffer_gather_others_impl(cx.editor, args.has_flag("skip-visible"));
321 buffer_close_by_ids_impl(cx, &document_ids, true)
322 }
323
324 fn buffer_gather_all_impl(editor: &mut Editor) -> Vec<DocumentId> {
325 editor.documents().map(|doc| doc.id()).collect()
326 }
327
328 fn buffer_close_all(
329 cx: &mut compositor::Context,
330 _args: Args,
331 event: PromptEvent,
332 ) -> anyhow::Result<()> {
333 if event != PromptEvent::Validate {
334 return Ok(());
335 }
336
337 let document_ids = buffer_gather_all_impl(cx.editor);
338 buffer_close_by_ids_impl(cx, &document_ids, false)
339 }
340
341 fn force_buffer_close_all(
342 cx: &mut compositor::Context,
343 _args: Args,
344 event: PromptEvent,
345 ) -> anyhow::Result<()> {
346 if event != PromptEvent::Validate {
347 return Ok(());
348 }
349
350 let document_ids = buffer_gather_all_impl(cx.editor);
351 buffer_close_by_ids_impl(cx, &document_ids, true)
352 }
353
354 fn buffer_next(
355 cx: &mut compositor::Context,
356 _args: Args,
357 event: PromptEvent,
358 ) -> anyhow::Result<()> {
359 if event != PromptEvent::Validate {
360 return Ok(());
361 }
362
363 goto_buffer(cx.editor, Direction::Forward, 1);
364 Ok(())
365 }
366
367 fn buffer_previous(
368 cx: &mut compositor::Context,
369 _args: Args,
370 event: PromptEvent,
371 ) -> anyhow::Result<()> {
372 if event != PromptEvent::Validate {
373 return Ok(());
374 }
375
376 goto_buffer(cx.editor, Direction::Backward, 1);
377 Ok(())
378 }
379
380 fn write_impl(
381 cx: &mut compositor::Context,
382 path: Option<&str>,
383 options: WriteOptions,
384 ) -> anyhow::Result<()> {
385 let config = cx.editor.config();
386 let (view, doc) = current!(cx.editor);
387 let doc_id = doc.id();
388 let view_id = view.id;
389
390 if doc.trim_trailing_whitespace() {
391 trim_trailing_whitespace(doc, view_id);
392 }
393 if config.trim_final_newlines {
394 trim_final_newlines(doc, view_id);
395 }
396 if doc.insert_final_newline() {
397 insert_final_newline(doc, view_id);
398 }
399
400 // Save an undo checkpoint for any outstanding changes.
401 doc.append_changes_to_history(view);
402
403 let auto_format = config.auto_format && options.auto_format;
404 let force = options.force;
405 let path: Option<PathBuf> = path.map(Into::into);
406
407 // Does the document configure any code actions to run on save?
408 let run_code_actions = options.code_actions
409 && doc!(cx.editor, &doc_id)
410 .language_config()
411 .and_then(|c| c.code_actions_on_save.as_deref())
412 .is_some_and(|kinds| !kinds.is_empty());
413
414 // The tail of the on-save chain: re-build the auto-format job against the
415 // latest document (so it formats after any code-action edits), or save
416 // directly when there's no formatter. Deferred via `Followup`, and always
417 // saves, so code-actions-on-save works even with auto-format off. Only
418 // built when there is pre-save work. A plain `:w` saves synchronously below.
419 let tail = (auto_format || run_code_actions).then(|| {
420 let path = path.clone();
421 let callback = Callback::Followup(Box::new(move |editor| {
422 let doc = doc!(editor, &doc_id);
423 let fmt_job = auto_format
424 .then(|| doc.auto_format(editor))
425 .flatten()
426 .map(|fmt| {
427 let call = make_format_callback(
428 doc_id,
429 doc.version(),
430 view_id,
431 fmt,
432 Some((path.clone(), force)),
433 );
434 Job::with_callback(call).wait_before_exiting()
435 });
436 if fmt_job.is_none() {
437 if let Err(err) = editor.save(doc_id, path, force) {
438 editor.set_error(format!("Error saving: {}", err));
439 }
440 }
441 fmt_job
442 }));
443 Job::with_callback(async { Ok(callback) }).wait_before_exiting()
444 });
445
446 let job = if run_code_actions {
447 code_actions_on_save(cx, doc_id, tail)
448 } else {
449 tail
450 };
451
452 if let Some(job) = job {
453 cx.jobs.add(job);
454 } else {
455 cx.editor.save(doc_id, path, force)?;
456 }
457
458 Ok(())
459 }
460
461 /// Trim all whitespace preceding line-endings in a document.
462 fn trim_trailing_whitespace(doc: &mut Document, view_id: ViewId) {
463 let text = doc.text();
464 let mut pos = 0;
465 let transaction = Transaction::delete(
466 text,
467 text.lines().filter_map(|line| {
468 let line_end_len_chars = line_ending::get_line_ending(&line)
469 .map(|le| le.len_chars())
470 .unwrap_or_default();
471 // Char after the last non-whitespace character or the beginning of the line if the
472 // line is all whitespace:
473 let first_trailing_whitespace =
474 pos + line.last_non_whitespace_char().map_or(0, |idx| idx + 1);
475 pos += line.len_chars();
476 // Char before the line ending character(s), or the final char in the text if there
477 // is no line-ending on this line:
478 let line_end = pos - line_end_len_chars;
479 if first_trailing_whitespace != line_end {
480 Some((first_trailing_whitespace, line_end))
481 } else {
482 None
483 }
484 }),
485 );
486 doc.apply(&transaction, view_id);
487 }
488
489 /// Trim any extra line-endings after the final line-ending.
490 fn trim_final_newlines(doc: &mut Document, view_id: ViewId) {
491 let rope = doc.text();
492 let mut text = rope.slice(..);
493 let mut total_char_len = 0;
494 let mut final_char_len = 0;
495 while let Some(line_ending) = line_ending::get_line_ending(&text) {
496 total_char_len += line_ending.len_chars();
497 final_char_len = line_ending.len_chars();
498 text = text.slice(..text.len_chars() - line_ending.len_chars());
499 }
500 let chars_to_delete = total_char_len - final_char_len;
501 if chars_to_delete != 0 {
502 let transaction = Transaction::delete(
503 rope,
504 [(rope.len_chars() - chars_to_delete, rope.len_chars())].into_iter(),
505 );
506 doc.apply(&transaction, view_id);
507 }
508 }
509
510 /// Ensure that the document is terminated with a line ending.
511 fn insert_final_newline(doc: &mut Document, view_id: ViewId) {
512 let text = doc.text();
513 if text.len_chars() > 0 && line_ending::get_line_ending(&text.slice(..)).is_none() {
514 let eof = Selection::point(text.len_chars());
515 let insert = Transaction::insert(text, &eof, doc.line_ending.as_str().into());
516 doc.apply(&insert, view_id);
517 }
518 }
519
520 #[derive(Debug, Clone, Copy)]
521 pub struct WriteOptions {
522 pub force: bool,
523 pub auto_format: bool,
524 pub code_actions: bool,
525 }
526
527 fn write(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
528 if event != PromptEvent::Validate {
529 return Ok(());
530 }
531
532 write_impl(
533 cx,
534 args.first(),
535 WriteOptions {
536 force: false,
537 auto_format: !args.has_flag(WRITE_NO_FORMAT_FLAG.name),
538 code_actions: !args.has_flag(WRITE_NO_CODE_ACTIONS_FLAG.name),
539 },
540 )
541 }
542
543 fn force_write(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
544 if event != PromptEvent::Validate {
545 return Ok(());
546 }
547
548 write_impl(
549 cx,
550 args.first(),
551 WriteOptions {
552 force: true,
553 auto_format: !args.has_flag(WRITE_NO_FORMAT_FLAG.name),
554 code_actions: !args.has_flag(WRITE_NO_CODE_ACTIONS_FLAG.name),
555 },
556 )
557 }
558
559 fn write_buffer_close(
560 cx: &mut compositor::Context,
561 args: Args,
562 event: PromptEvent,
563 ) -> anyhow::Result<()> {
564 if event != PromptEvent::Validate {
565 return Ok(());
566 }
567
568 write_impl(
569 cx,
570 args.first(),
571 WriteOptions {
572 force: false,
573 auto_format: !args.has_flag(WRITE_NO_FORMAT_FLAG.name),
574 code_actions: !args.has_flag(WRITE_NO_CODE_ACTIONS_FLAG.name),
575 },
576 )?;
577
578 let document_ids = buffer_gather_paths_impl(cx.editor, args);
579 buffer_close_by_ids_impl(cx, &document_ids, false)
580 }
581
582 fn force_write_buffer_close(
583 cx: &mut compositor::Context,
584 args: Args,
585 event: PromptEvent,
586 ) -> anyhow::Result<()> {
587 if event != PromptEvent::Validate {
588 return Ok(());
589 }
590
591 write_impl(
592 cx,
593 args.first(),
594 WriteOptions {
595 force: true,
596 auto_format: !args.has_flag(WRITE_NO_FORMAT_FLAG.name),
597 code_actions: !args.has_flag(WRITE_NO_CODE_ACTIONS_FLAG.name),
598 },
599 )?;
600
601 let document_ids = buffer_gather_paths_impl(cx.editor, args);
602 buffer_close_by_ids_impl(cx, &document_ids, false)
603 }
604
605 fn new_file(cx: &mut compositor::Context, _args: Args, event: PromptEvent) -> anyhow::Result<()> {
606 if event != PromptEvent::Validate {
607 return Ok(());
608 }
609
610 cx.editor.new_file(Action::Replace);
611
612 Ok(())
613 }
614
615 fn format(cx: &mut compositor::Context, _args: Args, event: PromptEvent) -> anyhow::Result<()> {
616 if event != PromptEvent::Validate {
617 return Ok(());
618 }
619
620 let (view, doc) = current_ref!(cx.editor);
621 let format = doc.format(cx.editor).context(
622 "A formatter isn't available, and no language server provides formatting capabilities",
623 )?;
624 let callback = make_format_callback(doc.id(), doc.version(), view.id, format, None);
625 cx.jobs.callback(callback);
626
627 Ok(())
628 }
629
630 fn set_indent_style(
631 cx: &mut compositor::Context,
632 args: Args,
633 event: PromptEvent,
634 ) -> anyhow::Result<()> {
635 if event != PromptEvent::Validate {
636 return Ok(());
637 }
638
639 use IndentStyle::*;
640
641 // If no argument, report current indent style.
642 if args.is_empty() {
643 let style = doc!(cx.editor).indent_style;
644 cx.editor.set_status(match style {
645 Tabs => "tabs".to_owned(),
646 Spaces(1) => "1 space".to_owned(),
647 Spaces(n) => format!("{} spaces", n),
648 });
649 return Ok(());
650 }
651
652 // Attempt to parse argument as an indent style.
653 let style = match args.first() {
654 Some(arg) if "tabs".starts_with(&arg.to_lowercase()) => Some(Tabs),
655 Some("0") => Some(Tabs),
656 Some(arg) => arg
657 .parse::<u8>()
658 .ok()
659 .filter(|n| (1..=MAX_INDENT).contains(n))
660 .map(Spaces),
661 _ => None,
662 };
663
664 let style = style.context("invalid indent style")?;
665 let doc = doc_mut!(cx.editor);
666 doc.indent_style = style;
667
668 Ok(())
669 }
670
671 /// Sets or reports the current document's line ending setting.
672 fn set_line_ending(
673 cx: &mut compositor::Context,
674 args: Args,
675 event: PromptEvent,
676 ) -> anyhow::Result<()> {
677 if event != PromptEvent::Validate {
678 return Ok(());
679 }
680
681 use LineEnding::*;
682
683 // If no argument, report current line ending setting.
684 if args.is_empty() {
685 let line_ending = doc!(cx.editor).line_ending;
686 cx.editor.set_status(match line_ending {
687 Crlf => "crlf",
688 LF => "line feed",
689 #[cfg(feature = "unicode-lines")]
690 FF => "form feed",
691 #[cfg(feature = "unicode-lines")]
692 CR => "carriage return",
693 #[cfg(feature = "unicode-lines")]
694 Nel => "next line",
695
696 // These should never be a document's default line ending.
697 #[cfg(feature = "unicode-lines")]
698 VT | LS | PS => "error",
699 });
700
701 return Ok(());
702 }
703
704 let arg = args
705 .first()
706 .context("argument missing")?
707 .to_ascii_lowercase();
708
709 // Attempt to parse argument as a line ending.
710 let line_ending = match arg {
711 arg if arg.starts_with("crlf") => Crlf,
712 arg if arg.starts_with("lf") => LF,
713 #[cfg(feature = "unicode-lines")]
714 arg if arg.starts_with("cr") => CR,
715 #[cfg(feature = "unicode-lines")]
716 arg if arg.starts_with("ff") => FF,
717 #[cfg(feature = "unicode-lines")]
718 arg if arg.starts_with("nel") => Nel,
719 _ => bail!("invalid line ending"),
720 };
721 let (view, doc) = current!(cx.editor);
722 doc.line_ending = line_ending;
723
724 let mut pos = 0;
725 let transaction = Transaction::change(
726 doc.text(),
727 doc.text().lines().filter_map(|line| {
728 pos += line.len_chars();
729 match helix_core::line_ending::get_line_ending(&line) {
730 Some(ending) if ending != line_ending => {
731 let start = pos - ending.len_chars();
732 let end = pos;
733 Some((start, end, Some(line_ending.as_str().into())))
734 }
735 _ => None,
736 }
737 }),
738 );
739 doc.apply(&transaction, view.id);
740 doc.append_changes_to_history(view);
741
742 Ok(())
743 }
744 fn earlier(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
745 if event != PromptEvent::Validate {
746 return Ok(());
747 }
748
749 let uk = args.join(" ").parse::<UndoKind>().map_err(|s| anyhow!(s))?;
750
751 let (view, doc) = current!(cx.editor);
752 let success = doc.earlier(view, uk);
753 if !success {
754 cx.editor.set_status("Already at oldest change");
755 }
756
757 Ok(())
758 }
759
760 fn later(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
761 if event != PromptEvent::Validate {
762 return Ok(());
763 }
764
765 let uk = args.join(" ").parse::<UndoKind>().map_err(|s| anyhow!(s))?;
766 let (view, doc) = current!(cx.editor);
767 let success = doc.later(view, uk);
768 if !success {
769 cx.editor.set_status("Already at newest change");
770 }
771
772 Ok(())
773 }
774
775 fn write_quit(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
776 if event != PromptEvent::Validate {
777 return Ok(());
778 }
779
780 write_impl(
781 cx,
782 args.first(),
783 WriteOptions {
784 force: false,
785 auto_format: !args.has_flag(WRITE_NO_FORMAT_FLAG.name),
786 code_actions: !args.has_flag(WRITE_NO_CODE_ACTIONS_FLAG.name),
787 },
788 )?;
789 cx.block_try_flush_writes()?;
790 quit(cx, Args::default(), event)
791 }
792
793 fn force_write_quit(
794 cx: &mut compositor::Context,
795 args: Args,
796 event: PromptEvent,
797 ) -> anyhow::Result<()> {
798 if event != PromptEvent::Validate {
799 return Ok(());
800 }
801
802 write_impl(
803 cx,
804 args.first(),
805 WriteOptions {
806 force: true,
807 auto_format: !args.has_flag(WRITE_NO_FORMAT_FLAG.name),
808 code_actions: !args.has_flag(WRITE_NO_CODE_ACTIONS_FLAG.name),
809 },
810 )?;
811 cx.block_try_flush_writes()?;
812 force_quit(cx, Args::default(), event)
813 }
814
815 /// Results in an error if there are modified buffers remaining and sets editor
816 /// error, otherwise returns `Ok(())`. If the current document is unmodified,
817 /// and there are modified documents, switches focus to one of them.
818 pub(super) fn buffers_remaining_impl(editor: &mut Editor) -> anyhow::Result<()> {
819 let modified_ids: Vec<_> = editor
820 .documents()
821 .filter(|doc| doc.is_modified())
822 .map(|doc| doc.id())
823 .collect();
824
825 if let Some(first) = modified_ids.first() {
826 let current = doc!(editor);
827 // If the current document is unmodified, and there are modified
828 // documents, switch focus to the first modified doc.
829 if !modified_ids.contains(&current.id()) {
830 editor.switch(*first, Action::Replace);
831 }
832
833 let modified_names: Vec<_> = modified_ids
834 .iter()
835 .map(|doc_id| doc!(editor, doc_id).display_name())
836 .collect();
837
838 bail!(
839 "{} unsaved buffer{} remaining: {:?}",
840 modified_names.len(),
841 if modified_names.len() == 1 { "" } else { "s" },
842 modified_names,
843 );
844 }
845 Ok(())
846 }
847
848 #[derive(Debug, Clone, Copy)]
849 pub struct WriteAllOptions {
850 pub force: bool,
851 pub write_scratch: bool,
852 pub auto_format: bool,
853 pub code_actions: bool,
854 }
855
856 pub fn write_all_impl(
857 cx: &mut compositor::Context,
858 options: WriteAllOptions,
859 ) -> anyhow::Result<()> {
860 let mut errors: Vec<&'static str> = Vec::new();
861 let config = cx.editor.config();
862 let saves: Vec<_> = cx
863 .editor
864 .documents
865 .keys()
866 .cloned()
867 .collect::<Vec<_>>()
868 .into_iter()
869 .filter_map(|id| {
870 let doc = doc!(cx.editor, &id);
871 if !doc.is_modified() {
872 return None;
873 }
874 if doc.path().is_none() {
875 if options.write_scratch {
876 errors.push("cannot write a buffer without a filename");
877 }
878 return None;
879 }
880
881 // Look for a view to apply the formatting change to.
882 let target_view = cx.editor.get_synced_view_id(doc.id());
883 Some((id, target_view))
884 })
885 .collect();
886
887 for (doc_id, target_view) in saves {
888 let doc = doc_mut!(cx.editor, &doc_id);
889 let view = view_mut!(cx.editor, target_view);
890
891 if doc.trim_trailing_whitespace() {
892 trim_trailing_whitespace(doc, target_view);
893 }
894 if config.trim_final_newlines {
895 trim_final_newlines(doc, target_view);
896 }
897 if doc.insert_final_newline() {
898 insert_final_newline(doc, target_view);
899 }
900
901 // Save an undo checkpoint for any outstanding changes.
902 doc.append_changes_to_history(view);
903
904 let auto_format = config.auto_format && options.auto_format;
905 let force = options.force;
906
907 let run_code_actions = options.code_actions
908 && doc!(cx.editor, &doc_id)
909 .language_config()
910 .and_then(|c| c.code_actions_on_save.as_deref())
911 .is_some_and(|kinds| !kinds.is_empty());
912
913 // See `write_impl`: deferred format-or-save tail that always saves, only
914 // built when there is pre-save work; otherwise a synchronous save below.
915 let tail = (auto_format || run_code_actions).then(|| {
916 let callback: job::Callback = Callback::Followup(Box::new(move |editor| {
917 let doc = doc!(editor, &doc_id);
918 let fmt_job = auto_format
919 .then(|| doc.auto_format(editor))
920 .flatten()
921 .map(|fmt| {
922 let call = make_format_callback(
923 doc_id,
924 doc.version(),
925 target_view,
926 fmt,
927 Some((None, force)),
928 );
929 Job::with_callback(call).wait_before_exiting()
930 });
931 if fmt_job.is_none() {
932 if let Err(err) = editor.save::<PathBuf>(doc_id, None, force) {
933 editor.set_error(format!("Error saving: {}", err));
934 }
935 }
936 fmt_job
937 }));
938 Job::with_callback(async { Ok(callback) }).wait_before_exiting()
939 });
940
941 let job = if run_code_actions {
942 code_actions_on_save(cx, doc_id, tail)
943 } else {
944 tail
945 };
946
947 if let Some(job) = job {
948 cx.jobs.add(job);
949 } else {
950 cx.editor.save::<PathBuf>(doc_id, None, force)?;
951 }
952 }
953
954 if !errors.is_empty() && !options.force {
955 bail!("{:?}", errors);
956 }
957
958 Ok(())
959 }
960
961 fn write_all(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
962 if event != PromptEvent::Validate {
963 return Ok(());
964 }
965
966 write_all_impl(
967 cx,
968 WriteAllOptions {
969 force: false,
970 write_scratch: true,
971 auto_format: !args.has_flag(WRITE_NO_FORMAT_FLAG.name),
972 code_actions: !args.has_flag(WRITE_NO_CODE_ACTIONS_FLAG.name),
973 },
974 )
975 }
976
977 fn force_write_all(
978 cx: &mut compositor::Context,
979 args: Args,
980 event: PromptEvent,
981 ) -> anyhow::Result<()> {
982 if event != PromptEvent::Validate {
983 return Ok(());
984 }
985
986 write_all_impl(
987 cx,
988 WriteAllOptions {
989 force: true,
990 write_scratch: true,
991 auto_format: !args.has_flag(WRITE_NO_FORMAT_FLAG.name),
992 code_actions: !args.has_flag(WRITE_NO_CODE_ACTIONS_FLAG.name),
993 },
994 )
995 }
996
997 fn write_all_quit(
998 cx: &mut compositor::Context,
999 args: Args,
1000 event: PromptEvent,
1001 ) -> anyhow::Result<()> {
1002 if event != PromptEvent::Validate {
1003 return Ok(());
1004 }
1005 write_all_impl(
1006 cx,
1007 WriteAllOptions {
1008 force: false,
1009 write_scratch: true,
1010 auto_format: !args.has_flag(WRITE_NO_FORMAT_FLAG.name),
1011 code_actions: !args.has_flag(WRITE_NO_CODE_ACTIONS_FLAG.name),
1012 },
1013 )?;
1014 quit_all_impl(cx, false)
1015 }
1016
1017 fn force_write_all_quit(
1018 cx: &mut compositor::Context,
1019 args: Args,
1020 event: PromptEvent,
1021 ) -> anyhow::Result<()> {
1022 if event != PromptEvent::Validate {
1023 return Ok(());
1024 }
1025 let _ = write_all_impl(
1026 cx,
1027 WriteAllOptions {
1028 force: true,
1029 write_scratch: true,
1030 auto_format: !args.has_flag(WRITE_NO_FORMAT_FLAG.name),
1031 code_actions: !args.has_flag(WRITE_NO_CODE_ACTIONS_FLAG.name),
1032 },
1033 );
1034 quit_all_impl(cx, true)
1035 }
1036
1037 fn quit_all_impl(cx: &mut compositor::Context, force: bool) -> anyhow::Result<()> {
1038 cx.block_try_flush_writes()?;
1039 if !force {
1040 buffers_remaining_impl(cx.editor)?;
1041 }
1042
1043 // close all views
1044 let views: Vec<_> = cx.editor.tree.views().map(|(view, _)| view.id).collect();
1045 for view_id in views {
1046 cx.editor.close(view_id);
1047 }
1048
1049 Ok(())
1050 }
1051
1052 fn quit_all(cx: &mut compositor::Context, _args: Args, event: PromptEvent) -> anyhow::Result<()> {
1053 if event != PromptEvent::Validate {
1054 return Ok(());
1055 }
1056
1057 quit_all_impl(cx, false)
1058 }
1059
1060 fn force_quit_all(
1061 cx: &mut compositor::Context,
1062 _args: Args,
1063 event: PromptEvent,
1064 ) -> anyhow::Result<()> {
1065 if event != PromptEvent::Validate {
1066 return Ok(());
1067 }
1068
1069 quit_all_impl(cx, true)
1070 }
1071
1072 fn cquit(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
1073 if event != PromptEvent::Validate {
1074 return Ok(());
1075 }
1076
1077 let exit_code = args
1078 .first()
1079 .and_then(|code| code.parse::<i32>().ok())
1080 .unwrap_or(1);
1081
1082 cx.editor.exit_code = exit_code;
1083 quit_all_impl(cx, false)
1084 }
1085
1086 fn force_cquit(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
1087 if event != PromptEvent::Validate {
1088 return Ok(());
1089 }
1090
1091 let exit_code = args
1092 .first()
1093 .and_then(|code| code.parse::<i32>().ok())
1094 .unwrap_or(1);
1095 cx.editor.exit_code = exit_code;
1096
1097 quit_all_impl(cx, true)
1098 }
1099
1100 fn theme(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
1101 let true_color = cx.editor.config.load().true_color || crate::true_color();
1102 match event {
1103 PromptEvent::Abort => {
1104 cx.editor.unset_theme_preview()?;
1105 }
1106 PromptEvent::Update => {
1107 if args.is_empty() {
1108 // Ensures that a preview theme gets cleaned up if the user backspaces until the prompt is empty.
1109 cx.editor.unset_theme_preview()?;
1110 } else if let Some(theme_name) = args.first() {
1111 if let Ok(theme) = cx.editor.theme_loader.load(theme_name) {
1112 if !(true_color || theme.is_16_color()) {
1113 bail!("Unsupported theme: theme requires true color support");
1114 }
1115 cx.editor.set_theme_preview(theme)?;
1116 };
1117 };
1118 }
1119 PromptEvent::Validate => {
1120 if let Some(theme_name) = args.first() {
1121 let theme = cx
1122 .editor
1123 .theme_loader
1124 .load(theme_name)
1125 .map_err(|err| anyhow::anyhow!("Could not load theme: {}", err))?;
1126 if !(true_color || theme.is_16_color()) {
1127 bail!("Unsupported theme: theme requires true color support");
1128 }
1129 cx.editor.set_theme(theme)?;
1130 } else {
1131 let name = cx.editor.theme.name().to_string();
1132
1133 cx.editor.set_status(name);
1134 }
1135 }
1136 };
1137
1138 Ok(())
1139 }
1140
1141 fn yank_main_selection_to_clipboard(
1142 cx: &mut compositor::Context,
1143 _args: Args,
1144 event: PromptEvent,
1145 ) -> anyhow::Result<()> {
1146 if event != PromptEvent::Validate {
1147 return Ok(());
1148 }
1149
1150 yank_main_selection_to_register(cx.editor, '+');
1151 Ok(())
1152 }
1153
1154 fn yank_joined(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
1155 if event != PromptEvent::Validate {
1156 return Ok(());
1157 }
1158
1159 let doc = doc!(cx.editor);
1160 let default_sep = Cow::Borrowed(doc.line_ending.as_str());
1161 let separator = args.first().unwrap_or(&default_sep);
1162 let register = cx
1163 .editor
1164 .selected_register
1165 .unwrap_or(cx.editor.config().default_yank_register);
1166 yank_joined_impl(cx.editor, separator, register);
1167 Ok(())
1168 }
1169
1170 fn yank_joined_to_clipboard(
1171 cx: &mut compositor::Context,
1172 args: Args,
1173 event: PromptEvent,
1174 ) -> anyhow::Result<()> {
1175 if event != PromptEvent::Validate {
1176 return Ok(());
1177 }
1178
1179 let doc = doc!(cx.editor);
1180 let default_sep = Cow::Borrowed(doc.line_ending.as_str());
1181 let separator = args.first().unwrap_or(&default_sep);
1182 yank_joined_impl(cx.editor, separator, '+');
1183 Ok(())
1184 }
1185
1186 fn yank_main_selection_to_primary_clipboard(
1187 cx: &mut compositor::Context,
1188 _args: Args,
1189 event: PromptEvent,
1190 ) -> anyhow::Result<()> {
1191 if event != PromptEvent::Validate {
1192 return Ok(());
1193 }
1194
1195 yank_main_selection_to_register(cx.editor, '*');
1196 Ok(())
1197 }
1198
1199 fn yank_joined_to_primary_clipboard(
1200 cx: &mut compositor::Context,
1201 args: Args,
1202 event: PromptEvent,
1203 ) -> anyhow::Result<()> {
1204 if event != PromptEvent::Validate {
1205 return Ok(());
1206 }
1207
1208 let doc = doc!(cx.editor);
1209 let default_sep = Cow::Borrowed(doc.line_ending.as_str());
1210 let separator = args.first().unwrap_or(&default_sep);
1211 yank_joined_impl(cx.editor, separator, '*');
1212 Ok(())
1213 }
1214
1215 fn paste_clipboard_after(
1216 cx: &mut compositor::Context,
1217 _args: Args,
1218 event: PromptEvent,
1219 ) -> anyhow::Result<()> {
1220 if event != PromptEvent::Validate {
1221 return Ok(());
1222 }
1223
1224 paste(cx.editor, '+', Paste::After, 1);
1225 Ok(())
1226 }
1227
1228 fn paste_clipboard_before(
1229 cx: &mut compositor::Context,
1230 _args: Args,
1231 event: PromptEvent,
1232 ) -> anyhow::Result<()> {
1233 if event != PromptEvent::Validate {
1234 return Ok(());
1235 }
1236
1237 paste(cx.editor, '+', Paste::Before, 1);
1238 Ok(())
1239 }
1240
1241 fn paste_primary_clipboard_after(
1242 cx: &mut compositor::Context,
1243 _args: Args,
1244 event: PromptEvent,
1245 ) -> anyhow::Result<()> {
1246 if event != PromptEvent::Validate {
1247 return Ok(());
1248 }
1249
1250 paste(cx.editor, '*', Paste::After, 1);
1251 Ok(())
1252 }
1253
1254 fn paste_primary_clipboard_before(
1255 cx: &mut compositor::Context,
1256 _args: Args,
1257 event: PromptEvent,
1258 ) -> anyhow::Result<()> {
1259 if event != PromptEvent::Validate {
1260 return Ok(());
1261 }
1262
1263 paste(cx.editor, '*', Paste::Before, 1);
1264 Ok(())
1265 }
1266
1267 fn replace_selections_with_clipboard(
1268 cx: &mut compositor::Context,
1269 _args: Args,
1270 event: PromptEvent,
1271 ) -> anyhow::Result<()> {
1272 if event != PromptEvent::Validate {
1273 return Ok(());
1274 }
1275
1276 replace_selections_with_register(cx.editor, '+', 1);
1277 Ok(())
1278 }
1279
1280 fn replace_selections_with_primary_clipboard(
1281 cx: &mut compositor::Context,
1282 _args: Args,
1283 event: PromptEvent,
1284 ) -> anyhow::Result<()> {
1285 if event != PromptEvent::Validate {
1286 return Ok(());
1287 }
1288
1289 replace_selections_with_register(cx.editor, '*', 1);
1290 Ok(())
1291 }
1292
1293 fn show_clipboard_provider(
1294 cx: &mut compositor::Context,
1295 _args: Args,
1296 event: PromptEvent,
1297 ) -> anyhow::Result<()> {
1298 if event != PromptEvent::Validate {
1299 return Ok(());
1300 }
1301
1302 cx.editor
1303 .set_status(cx.editor.registers.clipboard_provider_name());
1304 Ok(())
1305 }
1306
1307 /// Helper function to parse the first argument as a directory
1308 #[inline]
1309 fn parse_first_arg_as_dir(args: &Args, last_cwd: Option<PathBuf>) -> anyhow::Result<PathBuf> {
1310 match args.first().map(AsRef::as_ref) {
1311 Some("-") => last_cwd.ok_or_else(|| anyhow!("No previous working directory")),
1312 Some(path) => Ok(helix_stdx::path::expand_tilde(Path::new(path)).into_owned()),
1313 None => Ok(home_dir()?),
1314 }
1315 }
1316
1317 /// Helper function to apply a directory change for an already-parsed Path ref
1318 #[inline]
1319 fn apply_directory_change(cx: &mut compositor::Context, dir: &Path) -> anyhow::Result<()> {
1320 cx.editor.set_cwd(dir).map_err(|err| {
1321 anyhow!(
1322 "Could not change working directory to '{}': {err}",
1323 dir.display()
1324 )
1325 })?;
1326
1327 cx.editor.set_status(format!(
1328 "Current working directory is now {}",
1329 helix_stdx::env::current_working_dir().display()
1330 ));
1331
1332 Ok(())
1333 }
1334
1335 fn change_current_directory(
1336 cx: &mut compositor::Context,
1337 args: Args,
1338 event: PromptEvent,
1339 ) -> anyhow::Result<()> {
1340 if event != PromptEvent::Validate {
1341 return Ok(());
1342 }
1343
1344 let dir = parse_first_arg_as_dir(&args, cx.editor.get_last_cwd().map(|p| p.to_path_buf()))?;
1345
1346 apply_directory_change(cx, &dir)
1347 }
1348
1349 fn show_directory_stack(
1350 cx: &mut compositor::Context,
1351 _args: Args,
1352 event: PromptEvent,
1353 ) -> anyhow::Result<()> {
1354 if event != PromptEvent::Validate {
1355 return Ok(());
1356 }
1357
1358 let serialized_stack = cx
1359 .editor
1360 .dir_stack
1361 .iter()
1362 .map(|p| p.display().to_string())
1363 .collect::<Vec<_>>()
1364 .join(" ");
1365
1366 if !serialized_stack.is_empty() {
1367 cx.editor.set_status(serialized_stack);
1368 } else {
1369 cx.editor.set_error("Stack is empty");
1370 }
1371
1372 Ok(())
1373 }
1374
1375 fn push_directory(
1376 cx: &mut compositor::Context,
1377 args: Args,
1378 event: PromptEvent,
1379 ) -> anyhow::Result<()> {
1380 if event != PromptEvent::Validate {
1381 return Ok(());
1382 }
1383
1384 // avoid an unbounded directory stack and reallocs for perf
1385 if cx.editor.dir_stack.len() == cx.editor.dir_stack.capacity() {
1386 cx.editor.dir_stack.pop_back();
1387 }
1388
1389 cx.editor
1390 .dir_stack
1391 .push_front(helix_stdx::env::current_working_dir());
1392
1393 change_current_directory(cx, args, event)
1394 }
1395
1396 fn pop_directory(
1397 cx: &mut compositor::Context,
1398 _args: Args,
1399 event: PromptEvent,
1400 ) -> anyhow::Result<()> {
1401 if event != PromptEvent::Validate {
1402 return Ok(());
1403 }
1404
1405 if let Some(dir) = cx.editor.dir_stack.pop_front() {
1406 apply_directory_change(cx, &dir)?;
1407 } else {
1408 cx.editor.set_error("Stack is empty");
1409 }
1410
1411 Ok(())
1412 }
1413
1414 fn show_current_directory(
1415 cx: &mut compositor::Context,
1416 _args: Args,
1417 event: PromptEvent,
1418 ) -> anyhow::Result<()> {
1419 if event != PromptEvent::Validate {
1420 return Ok(());
1421 }
1422
1423 let cwd = helix_stdx::env::current_working_dir();
1424 let message = format!("Current working directory is {}", cwd.display());
1425
1426 if cwd.exists() {
1427 cx.editor.set_status(message);
1428 } else {
1429 cx.editor.set_error(format!("{} (deleted)", message));
1430 }
1431 Ok(())
1432 }
1433
1434 /// Sets the [`Document`]'s encoding..
1435 fn set_encoding(
1436 cx: &mut compositor::Context,
1437 args: Args,
1438 event: PromptEvent,
1439 ) -> anyhow::Result<()> {
1440 if event != PromptEvent::Validate {
1441 return Ok(());
1442 }
1443
1444 let doc = doc_mut!(cx.editor);
1445 if let Some(label) = args.first() {
1446 doc.set_encoding(label)
1447 } else {
1448 let encoding = doc.encoding().name().to_owned();
1449 cx.editor.set_status(encoding);
1450 Ok(())
1451 }
1452 }
1453
1454 /// Shows info about the character under the primary cursor.
1455 fn get_character_info(
1456 cx: &mut compositor::Context,
1457 _args: Args,
1458 event: PromptEvent,
1459 ) -> anyhow::Result<()> {
1460 if event != PromptEvent::Validate {
1461 return Ok(());
1462 }
1463
1464 let (view, doc) = current_ref!(cx.editor);
1465 let text = doc.text().slice(..);
1466
1467 let grapheme_start = doc.selection(view.id).primary().cursor(text);
1468 let grapheme_end = graphemes::next_grapheme_boundary(text, grapheme_start);
1469
1470 if grapheme_start == grapheme_end {
1471 return Ok(());
1472 }
1473
1474 let grapheme = text.slice(grapheme_start..grapheme_end).to_string();
1475 let encoding = doc.encoding();
1476
1477 let printable = grapheme.chars().fold(String::new(), |mut s, c| {
1478 match c {
1479 '\0' => s.push_str("\\0"),
1480 '\t' => s.push_str("\\t"),
1481 '\n' => s.push_str("\\n"),
1482 '\r' => s.push_str("\\r"),
1483 _ => s.push(c),
1484 }
1485
1486 s
1487 });
1488
1489 // Convert to Unicode codepoints if in UTF-8
1490 let unicode = if encoding == encoding::UTF_8 {
1491 let mut unicode = " (".to_owned();
1492
1493 for (i, char) in grapheme.chars().enumerate() {
1494 if i != 0 {
1495 unicode.push(' ');
1496 }
1497
1498 unicode.push_str("U+");
1499
1500 let codepoint: u32 = if char.is_ascii() {
1501 char.into()
1502 } else {
1503 // Not ascii means it will be multi-byte, so strip out the extra
1504 // bits that encode the length & mark continuation bytes
1505
1506 let s = String::from(char);
1507 let bytes = s.as_bytes();
1508
1509 // First byte starts with 2-4 ones then a zero, so strip those off
1510 let first = bytes[0];
1511 let codepoint = first & (0xFF >> (first.leading_ones() + 1));
1512 let mut codepoint = u32::from(codepoint);
1513
1514 // Following bytes start with 10
1515 for byte in bytes.iter().skip(1) {
1516 codepoint <<= 6;
1517 codepoint += u32::from(*byte) & 0x3F;
1518 }
1519
1520 codepoint
1521 };
1522
1523 write!(unicode, "{codepoint:0>4x}").unwrap();
1524 }
1525
1526 unicode.push(')');
1527 unicode
1528 } else {
1529 String::new()
1530 };
1531
1532 // Give the decimal value for ascii characters
1533 let dec = if encoding.is_ascii_compatible() && grapheme.len() == 1 {
1534 format!(" Dec {}", grapheme.as_bytes()[0])
1535 } else {
1536 String::new()
1537 };
1538
1539 let hex = {
1540 let mut encoder = encoding.new_encoder();
1541 let max_encoded_len = encoder
1542 .max_buffer_length_from_utf8_without_replacement(grapheme.len())
1543 .unwrap();
1544 let mut bytes = Vec::with_capacity(max_encoded_len);
1545 let mut current_byte = 0;
1546 let mut hex = String::new();
1547
1548 for (i, char) in grapheme.chars().enumerate() {
1549 if i != 0 {
1550 hex.push_str(" +");
1551 }
1552
1553 let (result, _input_bytes_read) = encoder.encode_from_utf8_to_vec_without_replacement(
1554 &char.to_string(),
1555 &mut bytes,
1556 true,
1557 );
1558
1559 if let encoding::EncoderResult::Unmappable(char) = result {
1560 bail!("{char:?} cannot be mapped to {}", encoding.name());
1561 }
1562
1563 for byte in &bytes[current_byte..] {
1564 write!(hex, " {byte:0>2x}").unwrap();
1565 }
1566
1567 current_byte = bytes.len();
1568 }
1569
1570 hex
1571 };
1572
1573 cx.editor
1574 .set_status(format!("\"{printable}\"{unicode}{dec} Hex{hex}"));
1575
1576 Ok(())
1577 }
1578
1579 /// Reload the [`Document`] from its source file.
1580 fn reload(cx: &mut compositor::Context, _args: Args, event: PromptEvent) -> anyhow::Result<()> {
1581 if event != PromptEvent::Validate {
1582 return Ok(());
1583 }
1584
1585 let scrolloff = cx.editor.config().scrolloff;
1586 let trust_full = doc_trust_full(cx.editor);
1587 let (view, doc) = current!(cx.editor);
1588 doc.reload(view, &cx.editor.diff_providers, trust_full)
1589 .map(|_| {
1590 view.ensure_cursor_in_view(doc, scrolloff);
1591 })?;
1592 if let Some(path) = doc.path().map(ToOwned::to_owned) {
1593 cx.editor
1594 .language_servers
1595 .file_event_handler
1596 .file_changed(path);
1597 }
1598 Ok(())
1599 }
1600
1601 fn reload_all(cx: &mut compositor::Context, _args: Args, event: PromptEvent) -> anyhow::Result<()> {
1602 if event != PromptEvent::Validate {
1603 return Ok(());
1604 }
1605
1606 let scrolloff = cx.editor.config().scrolloff;
1607 let view_id = view!(cx.editor).id;
1608
1609 let docs_view_ids: Vec<(DocumentId, Vec<ViewId>)> = cx
1610 .editor
1611 .documents_mut()
1612 .map(|doc| {
1613 let mut view_ids: Vec<_> = doc.selections().keys().cloned().collect();
1614
1615 if view_ids.is_empty() {
1616 doc.ensure_view_init(view_id);
1617 view_ids.push(view_id);
1618 };
1619
1620 (doc.id(), view_ids)
1621 })
1622 .collect();
1623
1624 for (doc_id, view_ids) in docs_view_ids {
1625 let doc = doc_mut!(cx.editor, &doc_id);
1626
1627 // Every doc is guaranteed to have at least 1 view at this point.
1628 let view = view_mut!(cx.editor, view_ids[0]);
1629
1630 // Ensure that the view is synced with the document's history.
1631 view.sync_changes(doc);
1632
1633 // Per-document trust: each doc's workspace may differ.
1634 let trust_full = cx
1635 .editor
1636 .workspace_trust
1637 .query(
1638 doc.workspace_root(),
1639 helix_loader::workspace_trust::TrustQuery::Git,
1640 )
1641 .is_trusted();
1642 if let Err(error) = doc.reload(view, &cx.editor.diff_providers, trust_full) {
1643 cx.editor.set_error(format!("{}", error));
1644 continue;
1645 }
1646
1647 if let Some(path) = doc.path().map(ToOwned::to_owned) {
1648 cx.editor
1649 .language_servers
1650 .file_event_handler
1651 .file_changed(path);
1652 }
1653
1654 for view_id in view_ids {
1655 let view = view_mut!(cx.editor, view_id);
1656 if view.doc.eq(&doc_id) {
1657 // Reloading commits the diff against disk through the first view
1658 // only (above). Any other view onto this document is left
1659 // pointing at the pre-reload revision, so sync it now; otherwise
1660 // its jumplist entries keep referencing the old (e.g. larger)
1661 // text and a later commit panics when mapping them through a
1662 // changeset whose pre-image no longer contains them.
1663 view.sync_changes(doc);
1664 view.ensure_cursor_in_view(doc, scrolloff);
1665 }
1666 }
1667 }
1668
1669 Ok(())
1670 }
1671
1672 /// Update the [`Document`] if it has been modified.
1673 fn update(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
1674 if event != PromptEvent::Validate {
1675 return Ok(());
1676 }
1677
1678 let (_view, doc) = current!(cx.editor);
1679 if doc.is_modified() {
1680 write_impl(
1681 cx,
1682 None,
1683 WriteOptions {
1684 force: false,
1685 auto_format: !args.has_flag(WRITE_NO_FORMAT_FLAG.name),
1686 code_actions: !args.has_flag(WRITE_NO_CODE_ACTIONS_FLAG.name),
1687 },
1688 )
1689 } else {
1690 Ok(())
1691 }
1692 }
1693
1694 fn lsp_workspace_command(
1695 cx: &mut compositor::Context,
1696 args: Args,
1697 event: PromptEvent,
1698 ) -> anyhow::Result<()> {
1699 if event != PromptEvent::Validate {
1700 return Ok(());
1701 }
1702
1703 let doc = doc!(cx.editor);
1704 let ls_id_commands = doc
1705 .language_servers_with_feature(LanguageServerFeature::WorkspaceCommand)
1706 .flat_map(|ls| {
1707 ls.capabilities()
1708 .execute_command_provider
1709 .iter()
1710 .flat_map(|options| options.commands.iter())
1711 .map(|command| (ls.id(), command))
1712 });
1713
1714 if args.is_empty() {
1715 let commands = ls_id_commands
1716 .map(|(ls_id, command)| {
1717 (
1718 ls_id,
1719 helix_lsp::lsp::Command {
1720 title: command.clone(),
1721 command: command.clone(),
1722 arguments: None,
1723 },
1724 )
1725 })
1726 .collect::<Vec<_>>();
1727 let callback = async move {
1728 let call: job::Callback = Callback::EditorCompositor(Box::new(
1729 move |_editor: &mut Editor, compositor: &mut Compositor| {
1730 let columns = [ui::PickerColumn::new(
1731 "title",
1732 |(_ls_id, command): &(_, helix_lsp::lsp::Command), _| {
1733 command.title.as_str().into()
1734 },
1735 )];
1736 let picker = ui::Picker::new(
1737 columns,
1738 0,
1739 commands,
1740 (),
1741 move |cx, (ls_id, command), _action| {
1742 cx.editor.execute_lsp_command(command.clone(), *ls_id);
1743 },
1744 );
1745 compositor.push(Box::new(overlaid(picker)))
1746 },
1747 ));
1748 Ok(call)
1749 };
1750 cx.jobs.callback(callback);
1751 } else {
1752 let command = args[0].to_string();
1753 let matches: Vec<_> = ls_id_commands
1754 .filter(|(_ls_id, c)| *c == &command)
1755 .collect();
1756
1757 match matches.as_slice() {
1758 [(ls_id, _command)] => {
1759 let arguments = args
1760 .get(1)
1761 .map(|rest| {
1762 serde_json::Deserializer::from_str(rest)
1763 .into_iter()
1764 .collect::<Result<Vec<Value>, _>>()
1765 .map_err(|err| anyhow!("failed to parse arguments: {err}"))
1766 })
1767 .transpose()?
1768 .filter(|args| !args.is_empty());
1769
1770 cx.editor.execute_lsp_command(
1771 helix_lsp::lsp::Command {
1772 title: command.clone(),
1773 arguments,
1774 command,
1775 },
1776 *ls_id,
1777 );
1778 }
1779 [] => {
1780 cx.editor.set_status(format!(
1781 "`{command}` is not supported for any language server"
1782 ));
1783 }
1784 _ => {
1785 cx.editor.set_status(format!(
1786 "`{command}` supported by multiple language servers"
1787 ));
1788 }
1789 }
1790 }
1791 Ok(())
1792 }
1793
1794 fn lsp_restart(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
1795 if event != PromptEvent::Validate {
1796 return Ok(());
1797 }
1798
1799 let editor_config = cx.editor.config.load();
1800 let doc = doc!(cx.editor);
1801 let config = doc
1802 .language_config()
1803 .context("LSP not defined for the current document")?;
1804
1805 let language_servers: Vec<_> = config
1806 .language_servers
1807 .iter()
1808 .map(|ls| ls.name.as_str())
1809 .collect();
1810 let language_servers = if args.is_empty() {
1811 language_servers
1812 } else {
1813 let (valid, invalid): (Vec<_>, Vec<_>) = args
1814 .iter()
1815 .map(|arg| arg.as_ref())
1816 .partition(|name| language_servers.contains(name));
1817 if !invalid.is_empty() {
1818 let s = if invalid.len() == 1 { "" } else { "s" };
1819 bail!("Unknown language server{s}: {}", invalid.join(", "));
1820 }
1821 valid
1822 };
1823
1824 let mut errors = Vec::new();
1825 for server in language_servers.iter() {
1826 match cx
1827 .editor
1828 .language_servers
1829 .restart_server(
1830 server,
1831 config,
1832 doc.path(),
1833 &editor_config.workspace_lsp_roots,
1834 editor_config.lsp.snippets,
1835 )
1836 .transpose()
1837 {
1838 // Ignore the executable-not-found error unless the server was explicitly requested
1839 // in the arguments.
1840 Err(helix_lsp::Error::ExecutableNotFound(_))
1841 if !args.iter().any(|arg| arg == server) => {}
1842 Err(err) => errors.push(err.to_string()),
1843 _ => (),
1844 }
1845 }
1846
1847 // This collect is needed because refresh_language_server would need to re-borrow editor.
1848 let document_ids_to_refresh: Vec<DocumentId> = cx
1849 .editor
1850 .documents()
1851 .filter_map(|doc| match doc.language_config() {
1852 Some(config)
1853 if config.language_servers.iter().any(|ls| {
1854 language_servers
1855 .iter()
1856 .any(|restarted_ls| restarted_ls == &ls.name)
1857 }) =>
1858 {
1859 Some(doc.id())
1860 }
1861 _ => None,
1862 })
1863 .collect();
1864
1865 for document_id in document_ids_to_refresh {
1866 cx.editor.refresh_language_servers(document_id);
1867 }
1868
1869 if errors.is_empty() {
1870 Ok(())
1871 } else {
1872 Err(anyhow::anyhow!(
1873 "Error restarting language servers: {}",
1874 errors.join(", ")
1875 ))
1876 }
1877 }
1878
1879 fn lsp_stop(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
1880 if event != PromptEvent::Validate {
1881 return Ok(());
1882 }
1883 let doc = doc!(cx.editor);
1884
1885 let language_servers: Vec<_> = doc
1886 .language_servers()
1887 .map(|ls| ls.name().to_string())
1888 .collect();
1889 let language_servers = if args.is_empty() {
1890 language_servers
1891 } else {
1892 let (valid, invalid): (Vec<_>, Vec<_>) = args
1893 .iter()
1894 .map(|arg| arg.to_string())
1895 .partition(|name| language_servers.contains(name));
1896 if !invalid.is_empty() {
1897 let s = if invalid.len() == 1 { "" } else { "s" };
1898 bail!("Unknown language server{s}: {}", invalid.join(", "));
1899 }
1900 valid
1901 };
1902
1903 for ls_name in &language_servers {
1904 cx.editor.language_servers.stop(ls_name);
1905
1906 for doc in cx.editor.documents_mut() {
1907 if let Some(client) = doc.remove_language_server_by_name(ls_name) {
1908 doc.clear_diagnostics_for_language_server(client.id());
1909 doc.reset_all_inlay_hints();
1910 doc.inlay_hints_oudated = true;
1911 }
1912 }
1913 }
1914
1915 Ok(())
1916 }
1917
1918 fn tree_sitter_scopes(
1919 cx: &mut compositor::Context,
1920 _args: Args,
1921 event: PromptEvent,
1922 ) -> anyhow::Result<()> {
1923 if event != PromptEvent::Validate {
1924 return Ok(());
1925 }
1926
1927 let (view, doc) = current!(cx.editor);
1928 let text = doc.text().slice(..);
1929
1930 let pos = doc.selection(view.id).primary().cursor(text);
1931 let scopes = indent::get_scopes(doc.syntax(), text, pos);
1932
1933 let contents = format!("```json\n{:?}\n````", scopes);
1934
1935 let callback = async move {
1936 let call: job::Callback = Callback::EditorCompositor(Box::new(
1937 move |editor: &mut Editor, compositor: &mut Compositor| {
1938 let contents = ui::Markdown::new(contents, editor.syn_loader.clone());
1939 let popup = Popup::new("hover", contents).auto_close(true);
1940 compositor.replace_or_push("hover", popup);
1941 },
1942 ));
1943 Ok(call)
1944 };
1945
1946 cx.jobs.callback(callback);
1947
1948 Ok(())
1949 }
1950
1951 fn tree_sitter_highlight_name(
1952 cx: &mut compositor::Context,
1953 _args: Args,
1954 event: PromptEvent,
1955 ) -> anyhow::Result<()> {
1956 if event != PromptEvent::Validate {
1957 return Ok(());
1958 }
1959
1960 let (view, doc) = current_ref!(cx.editor);
1961 let Some(syntax) = doc.syntax() else {
1962 return Ok(());
1963 };
1964 let text = doc.text().slice(..);
1965 let cursor = doc.selection(view.id).primary().cursor(text);
1966 let byte = text.char_to_byte(cursor) as u32;
1967 // Query the same range as the one used in syntax highlighting.
1968 let range = {
1969 // Calculate viewport byte ranges:
1970 let row = text.char_to_line(doc.view_offset(view.id).anchor.min(text.len_chars()));
1971 // Saturating subs to make it inclusive zero indexing.
1972 let last_line = text.len_lines().saturating_sub(1);
1973 let height = view.inner_area(doc).height;
1974 let last_visible_line = (row + height as usize).saturating_sub(1).min(last_line);
1975 let start = text.line_to_byte(row.min(last_line)) as u32;
1976 let end = text.line_to_byte(last_visible_line + 1) as u32;
1977
1978 start..end
1979 };
1980
1981 let loader = cx.editor.syn_loader.load();
1982 let mut highlighter = syntax.highlighter(text, &loader, range);
1983 let mut highlights = Vec::new();
1984
1985 while highlighter.next_event_offset() <= byte {
1986 let (event, new_highlights) = highlighter.advance();
1987 if event == helix_core::syntax::HighlightEvent::Refresh {
1988 highlights.clear();
1989 }
1990 highlights.extend(new_highlights);
1991 }
1992
1993 let content = highlights
1994 .into_iter()
1995 .fold(String::new(), |mut acc, highlight| {
1996 if !acc.is_empty() {
1997 acc.push_str(", ");
1998 }
1999 acc.push_str(cx.editor.theme.scope(highlight));
2000 acc
2001 });
2002
2003 let callback = async move {
2004 let call: job::Callback = Callback::EditorCompositor(Box::new(
2005 move |editor: &mut Editor, compositor: &mut Compositor| {
2006 let content = ui::Markdown::new(content, editor.syn_loader.clone());
2007 let popup = Popup::new("hover", content).auto_close(true);
2008 compositor.replace_or_push("hover", popup);
2009 },
2010 ));
2011 Ok(call)
2012 };
2013
2014 cx.jobs.callback(callback);
2015
2016 Ok(())
2017 }
2018
2019 fn tree_sitter_layers(
2020 cx: &mut compositor::Context,
2021 _args: Args,
2022 event: PromptEvent,
2023 ) -> anyhow::Result<()> {
2024 if event != PromptEvent::Validate {
2025 return Ok(());
2026 }
2027
2028 let (view, doc) = current_ref!(cx.editor);
2029 let Some(syntax) = doc.syntax() else {
2030 bail!("Syntax information is not available");
2031 };
2032
2033 let loader: &helix_core::syntax::Loader = &cx.editor.syn_loader.load();
2034 let text = doc.text().slice(..);
2035 let cursor = doc.selection(view.id).primary().cursor(text);
2036 let byte = text.char_to_byte(cursor) as u32;
2037 let languages =
2038 syntax
2039 .layers_for_byte_range(byte, byte)
2040 .fold(String::new(), |mut acc, layer| {
2041 if !acc.is_empty() {
2042 acc.push_str(", ");
2043 }
2044 acc.push_str(
2045 &loader
2046 .language(syntax.layer(layer).language)
2047 .config()
2048 .language_id,
2049 );
2050 acc
2051 });
2052
2053 let callback = async move {
2054 let call: job::Callback = Callback::EditorCompositor(Box::new(
2055 move |editor: &mut Editor, compositor: &mut Compositor| {
2056 let content = ui::Markdown::new(languages, editor.syn_loader.clone());
2057 let popup = Popup::new("hover", content).auto_close(true);
2058 compositor.replace_or_push("hover", popup);
2059 },
2060 ));
2061 Ok(call)
2062 };
2063
2064 cx.jobs.callback(callback);
2065
2066 Ok(())
2067 }
2068
2069 fn vsplit(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2070 if event != PromptEvent::Validate {
2071 return Ok(());
2072 }
2073
2074 if args.is_empty() {
2075 split(cx.editor, Action::VerticalSplit);
2076 } else {
2077 open_impl(cx, args, Action::VerticalSplit)?;
2078 }
2079
2080 Ok(())
2081 }
2082
2083 fn hsplit(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2084 if event != PromptEvent::Validate {
2085 return Ok(());
2086 }
2087
2088 if args.is_empty() {
2089 split(cx.editor, Action::HorizontalSplit);
2090 } else {
2091 open_impl(cx, args, Action::HorizontalSplit)?;
2092 }
2093
2094 Ok(())
2095 }
2096
2097 fn vsplit_new(cx: &mut compositor::Context, _args: Args, event: PromptEvent) -> anyhow::Result<()> {
2098 if event != PromptEvent::Validate {
2099 return Ok(());
2100 }
2101
2102 cx.editor.new_file(Action::VerticalSplit);
2103
2104 Ok(())
2105 }
2106
2107 fn hsplit_new(cx: &mut compositor::Context, _args: Args, event: PromptEvent) -> anyhow::Result<()> {
2108 if event != PromptEvent::Validate {
2109 return Ok(());
2110 }
2111
2112 cx.editor.new_file(Action::HorizontalSplit);
2113
2114 Ok(())
2115 }
2116
2117 fn debug_eval(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2118 if event != PromptEvent::Validate {
2119 return Ok(());
2120 }
2121
2122 if let Some(debugger) = cx.editor.debug_adapters.get_active_client() {
2123 let (frame, thread_id) = match (debugger.active_frame, debugger.thread_id) {
2124 (Some(frame), Some(thread_id)) => (frame, thread_id),
2125 _ => {
2126 bail!("Cannot find current stack frame to access variables")
2127 }
2128 };
2129
2130 // TODO: support no frame_id
2131
2132 let frame_id = debugger.stack_frames[&thread_id][frame].id;
2133 let response = helix_lsp::block_on(debugger.eval(args.join(" "), Some(frame_id)))?;
2134 cx.editor.set_status(response.result);
2135 }
2136 Ok(())
2137 }
2138
2139 fn debug_start(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2140 if event != PromptEvent::Validate {
2141 return Ok(());
2142 }
2143
2144 let mut args: Vec<_> = args.into_iter().collect();
2145 let name = match args.len() {
2146 0 => None,
2147 _ => Some(args.remove(0)),
2148 };
2149 dap_start_impl(cx, name.as_deref(), None, Some(args))
2150 }
2151
2152 fn debug_remote(
2153 cx: &mut compositor::Context,
2154 args: Args,
2155 event: PromptEvent,
2156 ) -> anyhow::Result<()> {
2157 if event != PromptEvent::Validate {
2158 return Ok(());
2159 }
2160
2161 let mut args: Vec<_> = args.into_iter().collect();
2162 let address = match args.len() {
2163 0 => None,
2164 _ => Some(args.remove(0).parse()?),
2165 };
2166 let name = match args.len() {
2167 0 => None,
2168 _ => Some(args.remove(0)),
2169 };
2170 dap_start_impl(cx, name.as_deref(), address, Some(args))
2171 }
2172
2173 fn tutor(cx: &mut compositor::Context, _args: Args, event: PromptEvent) -> anyhow::Result<()> {
2174 if event != PromptEvent::Validate {
2175 return Ok(());
2176 }
2177
2178 let path = helix_loader::runtime_file(Path::new("tutor"));
2179 cx.editor.open(&path, Action::Replace)?;
2180 // Unset path to prevent accidentally saving to the original tutor file.
2181 doc_mut!(cx.editor).set_path(None);
2182 Ok(())
2183 }
2184
2185 fn abort_goto_line_number_preview(cx: &mut compositor::Context) {
2186 if let Some(last_selection) = cx.editor.last_selection.take() {
2187 let scrolloff = cx.editor.config().scrolloff;
2188
2189 let (view, doc) = current!(cx.editor);
2190 doc.set_selection(view.id, last_selection);
2191 view.ensure_cursor_in_view(doc, scrolloff);
2192 }
2193 }
2194
2195 fn update_goto_line_number_preview(cx: &mut compositor::Context, args: Args) -> anyhow::Result<()> {
2196 cx.editor.last_selection.get_or_insert_with(|| {
2197 let (view, doc) = current!(cx.editor);
2198 doc.selection(view.id).clone()
2199 });
2200
2201 let scrolloff = cx.editor.config().scrolloff;
2202 let line = args[0].parse::<usize>()?;
2203 goto_line_without_jumplist(
2204 cx.editor,
2205 NonZeroUsize::new(line),
2206 if cx.editor.mode == Mode::Select {
2207 Movement::Extend
2208 } else {
2209 Movement::Move
2210 },
2211 );
2212
2213 let (view, doc) = current!(cx.editor);
2214 view.ensure_cursor_in_view(doc, scrolloff);
2215
2216 Ok(())
2217 }
2218
2219 pub(super) fn goto_line_number(
2220 cx: &mut compositor::Context,
2221 args: Args,
2222 event: PromptEvent,
2223 ) -> anyhow::Result<()> {
2224 match event {
2225 PromptEvent::Abort => abort_goto_line_number_preview(cx),
2226 PromptEvent::Validate => {
2227 // If we are invoked directly via a keybinding, Validate is
2228 // sent without any prior Update events. Ensure the cursor
2229 // is moved to the appropriate location.
2230 update_goto_line_number_preview(cx, args)?;
2231
2232 let last_selection = cx
2233 .editor
2234 .last_selection
2235 .take()
2236 .expect("update_goto_line_number_preview should always set last_selection");
2237
2238 let (view, doc) = current!(cx.editor);
2239 view.push_jump(doc, (doc.id(), last_selection));
2240 }
2241
2242 // When a user hits backspace and there are no numbers left,
2243 // we can bring them back to their original selection. If they
2244 // begin typing numbers again, we'll start a new preview session.
2245 PromptEvent::Update if args.is_empty() => abort_goto_line_number_preview(cx),
2246 PromptEvent::Update => update_goto_line_number_preview(cx, args)?,
2247 }
2248
2249 Ok(())
2250 }
2251
2252 // Fetch the current value of a config option and output as status.
2253 fn get_option(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2254 if event != PromptEvent::Validate {
2255 return Ok(());
2256 }
2257
2258 let key = &args[0].to_lowercase();
2259 let key_error = || anyhow::anyhow!("Unknown key `{}`", key);
2260
2261 let config = serde_json::json!(cx.editor.config().deref());
2262 let pointer = format!("/{}", key.replace('.', "/"));
2263 let value = config.pointer(&pointer).ok_or_else(key_error)?;
2264
2265 cx.editor.set_status(value.to_string());
2266 Ok(())
2267 }
2268
2269 /// Change config at runtime. Access nested values by dot syntax, for
2270 /// example to disable smart case search, use `:set search.smart-case false`.
2271 fn set_option(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2272 if event != PromptEvent::Validate {
2273 return Ok(());
2274 }
2275
2276 let (key, arg) = (&args[0].to_lowercase(), args[1].trim());
2277
2278 let key_error = || anyhow::anyhow!("Unknown key `{}`", key);
2279 let field_error = |_| anyhow::anyhow!("Could not parse field `{}`", arg);
2280
2281 let mut config = serde_json::json!(&cx.editor.config().deref());
2282 let pointer = format!("/{}", key.replace('.', "/"));
2283 let value = config.pointer_mut(&pointer).ok_or_else(key_error)?;
2284
2285 *value = if value.is_string() {
2286 // JSON strings require quotes, so we can't .parse() directly
2287 Value::String(arg.to_string())
2288 } else {
2289 arg.parse().map_err(field_error)?
2290 };
2291 let config = serde_json::from_value(config).map_err(field_error)?;
2292
2293 cx.editor
2294 .config_events
2295 .0
2296 .send(ConfigEvent::Update(config))?;
2297 Ok(())
2298 }
2299
2300 /// Toggle boolean config option at runtime. Access nested values by dot
2301 /// syntax, for example to toggle smart case search, use `:toggle search.smart-
2302 /// case`.
2303 fn toggle_option(
2304 cx: &mut compositor::Context,
2305 args: Args,
2306 event: PromptEvent,
2307 ) -> anyhow::Result<()> {
2308 if event != PromptEvent::Validate {
2309 return Ok(());
2310 }
2311
2312 let key = &args[0].to_lowercase();
2313
2314 let key_error = || anyhow::anyhow!("Unknown key `{}`", key);
2315
2316 let mut config = serde_json::json!(&cx.editor.config().deref());
2317 let pointer = format!("/{}", key.replace('.', "/"));
2318 let value = config.pointer_mut(&pointer).ok_or_else(key_error)?;
2319
2320 *value = match value {
2321 Value::Bool(ref value) => {
2322 ensure!(
2323 args.len() == 1,
2324 "Bad arguments. For boolean configurations use: `:toggle {key}`"
2325 );
2326 Value::Bool(!value)
2327 }
2328 Value::String(ref value) => {
2329 ensure!(
2330 args.len() == 2,
2331 "Bad arguments. For string configurations use: `:toggle {key} val1 val2 ...`",
2332 );
2333 // For string values, parse the input according to normal command line rules.
2334 let values: Vec<_> = command_line::Tokenizer::new(&args[1], true)
2335 .map(|res| res.map(|token| token.content))
2336 .collect::<Result<_, _>>()
2337 .map_err(|err| anyhow!("failed to parse values: {err}"))?;
2338
2339 Value::String(
2340 values
2341 .iter()
2342 .skip_while(|e| *e != value)
2343 .nth(1)
2344 .map(AsRef::as_ref)
2345 .unwrap_or_else(|| &values[0])
2346 .to_string(),
2347 )
2348 }
2349 Value::Null => bail!("Configuration {key} cannot be toggled"),
2350 Value::Number(_) | Value::Array(_) | Value::Object(_) => {
2351 ensure!(
2352 args.len() == 2,
2353 "Bad arguments. For {kind} configurations use: `:toggle {key} val1 val2 ...`",
2354 kind = match value {
2355 Value::Number(_) => "number",
2356 Value::Array(_) => "array",
2357 Value::Object(_) => "object",
2358 _ => unreachable!(),
2359 }
2360 );
2361 // For numbers, arrays and objects, parse each argument with
2362 // `serde_json::StreamDeserializer`.
2363 let values: Vec<Value> = serde_json::Deserializer::from_str(&args[1])
2364 .into_iter()
2365 .collect::<Result<_, _>>()
2366 .map_err(|err| anyhow!("failed to parse value: {err}"))?;
2367
2368 if let Some(wrongly_typed_value) = values
2369 .iter()
2370 .find(|v| std::mem::discriminant(*v) != std::mem::discriminant(&*value))
2371 {
2372 bail!("value '{wrongly_typed_value}' has a different type than '{value}'");
2373 }
2374
2375 values
2376 .iter()
2377 .skip_while(|e| *e != value)
2378 .nth(1)
2379 .unwrap_or(&values[0])
2380 .clone()
2381 }
2382 };
2383
2384 let status = format!("'{key}' is now set to {value}");
2385 let config = serde_json::from_value(config)
2386 .map_err(|err| anyhow::anyhow!("Failed to parse config: {err}"))?;
2387
2388 cx.editor
2389 .config_events
2390 .0
2391 .send(ConfigEvent::Update(config))?;
2392 cx.editor.set_status(status);
2393 Ok(())
2394 }
2395
2396 /// Change the language of the current buffer at runtime.
2397 fn language(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2398 if event != PromptEvent::Validate {
2399 return Ok(());
2400 }
2401
2402 if args.is_empty() {
2403 let doc = doc!(cx.editor);
2404 let language = &doc.language_name().unwrap_or(DEFAULT_LANGUAGE_NAME);
2405 cx.editor.set_status(language.to_string());
2406 return Ok(());
2407 }
2408
2409 let doc = doc_mut!(cx.editor);
2410
2411 let loader = cx.editor.syn_loader.load();
2412 if &args[0] == DEFAULT_LANGUAGE_NAME {
2413 doc.set_language(None, &loader)
2414 } else {
2415 doc.set_language_by_language_id(&args[0], &loader)?;
2416 }
2417 doc.detect_indent_and_line_ending();
2418
2419 let id = doc.id();
2420 cx.editor.refresh_language_servers(id);
2421 let doc = doc_mut!(cx.editor);
2422 let diagnostics =
2423 Editor::doc_diagnostics(&cx.editor.language_servers, &cx.editor.diagnostics, doc);
2424 doc.replace_diagnostics(diagnostics, &[], None);
2425 Ok(())
2426 }
2427
2428 fn sort(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2429 if event != PromptEvent::Validate {
2430 return Ok(());
2431 }
2432
2433 let scrolloff = cx.editor.config().scrolloff;
2434 let (view, doc) = current!(cx.editor);
2435 let text = doc.text().slice(..);
2436
2437 let selection = doc.selection(view.id);
2438
2439 if selection.len() == 1 {
2440 bail!("Sorting requires multiple selections. Hint: split selection first");
2441 }
2442
2443 let mut fragments: Vec<_> = selection
2444 .slices(text)
2445 .map(|fragment| fragment.chunks().collect())
2446 .collect();
2447
2448 fragments.sort_by(
2449 match (args.has_flag("insensitive"), args.has_flag("reverse")) {
2450 (true, true) => |a: &Tendril, b: &Tendril| b.to_lowercase().cmp(&a.to_lowercase()),
2451 (true, false) => |a: &Tendril, b: &Tendril| a.to_lowercase().cmp(&b.to_lowercase()),
2452 (false, true) => |a: &Tendril, b: &Tendril| b.cmp(a),
2453 (false, false) => |a: &Tendril, b: &Tendril| a.cmp(b),
2454 },
2455 );
2456
2457 let transaction = Transaction::change(
2458 doc.text(),
2459 selection
2460 .into_iter()
2461 .zip(fragments)
2462 .map(|(s, fragment)| (s.from(), s.to(), Some(fragment))),
2463 );
2464
2465 doc.apply(&transaction, view.id);
2466 doc.append_changes_to_history(view);
2467 view.ensure_cursor_in_view(doc, scrolloff);
2468
2469 Ok(())
2470 }
2471
2472 fn reflow(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2473 if event != PromptEvent::Validate {
2474 return Ok(());
2475 }
2476
2477 let scrolloff = cx.editor.config().scrolloff;
2478 let (view, doc) = current!(cx.editor);
2479
2480 // Find the text_width by checking the following sources in order:
2481 // - The passed argument in `args`
2482 // - The configured text-width for this language in languages.toml
2483 // - The configured text-width in the config.toml
2484 let text_width: usize = args
2485 .first()
2486 .map(|num| num.parse::<usize>())
2487 .transpose()?
2488 .unwrap_or_else(|| doc.text_width());
2489
2490 let rope = doc.text();
2491
2492 let selection = doc.selection(view.id);
2493 let transaction = Transaction::change_by_selection(rope, selection, |range| {
2494 let fragment = range.fragment(rope.slice(..));
2495 let reflowed_text = helix_core::wrap::reflow_hard_wrap(&fragment, text_width);
2496
2497 (range.from(), range.to(), Some(reflowed_text))
2498 });
2499
2500 doc.apply(&transaction, view.id);
2501 doc.append_changes_to_history(view);
2502 view.ensure_cursor_in_view(doc, scrolloff);
2503
2504 Ok(())
2505 }
2506
2507 fn tree_sitter_subtree(
2508 cx: &mut compositor::Context,
2509 _args: Args,
2510 event: PromptEvent,
2511 ) -> anyhow::Result<()> {
2512 if event != PromptEvent::Validate {
2513 return Ok(());
2514 }
2515
2516 let (view, doc) = current!(cx.editor);
2517
2518 if let Some(syntax) = doc.syntax() {
2519 let primary_selection = doc.selection(view.id).primary();
2520 let text = doc.text();
2521 let from = text.char_to_byte(primary_selection.from()) as u32;
2522 let to = text.char_to_byte(primary_selection.to()) as u32;
2523 if let Some(selected_node) = syntax.descendant_for_byte_range(from, to) {
2524 let mut contents = String::from("```tsq\n");
2525 helix_core::syntax::pretty_print_tree(&mut contents, selected_node)?;
2526 contents.push_str("\n```");
2527
2528 let callback = async move {
2529 let call: job::Callback = Callback::EditorCompositor(Box::new(
2530 move |editor: &mut Editor, compositor: &mut Compositor| {
2531 let contents = ui::Markdown::new(contents, editor.syn_loader.clone());
2532 let popup = Popup::new("hover", contents).auto_close(true);
2533 compositor.replace_or_push("hover", popup);
2534 },
2535 ));
2536 Ok(call)
2537 };
2538
2539 cx.jobs.callback(callback);
2540 }
2541 }
2542
2543 Ok(())
2544 }
2545
2546 fn open_config(
2547 cx: &mut compositor::Context,
2548 _args: Args,
2549 event: PromptEvent,
2550 ) -> anyhow::Result<()> {
2551 if event != PromptEvent::Validate {
2552 return Ok(());
2553 }
2554
2555 cx.editor
2556 .open(&helix_loader::config_file(), Action::Replace)?;
2557 Ok(())
2558 }
2559
2560 fn open_workspace_config(
2561 cx: &mut compositor::Context,
2562 _args: Args,
2563 event: PromptEvent,
2564 ) -> anyhow::Result<()> {
2565 if event != PromptEvent::Validate {
2566 return Ok(());
2567 }
2568
2569 cx.editor
2570 .open(&helix_loader::workspace_config_file(), Action::Replace)?;
2571 Ok(())
2572 }
2573
2574 fn open_log(cx: &mut compositor::Context, _args: Args, event: PromptEvent) -> anyhow::Result<()> {
2575 if event != PromptEvent::Validate {
2576 return Ok(());
2577 }
2578
2579 cx.editor.open(&helix_loader::log_file(), Action::Replace)?;
2580 Ok(())
2581 }
2582
2583 fn refresh_config(
2584 cx: &mut compositor::Context,
2585 _args: Args,
2586 event: PromptEvent,
2587 ) -> anyhow::Result<()> {
2588 if event != PromptEvent::Validate {
2589 return Ok(());
2590 }
2591
2592 cx.editor.config_events.0.send(ConfigEvent::Refresh)?;
2593 Ok(())
2594 }
2595
2596 fn append_output(
2597 cx: &mut compositor::Context,
2598 args: Args,
2599 event: PromptEvent,
2600 ) -> anyhow::Result<()> {
2601 if event != PromptEvent::Validate {
2602 return Ok(());
2603 }
2604
2605 shell(cx, &args.join(" "), &ShellBehavior::Append);
2606 Ok(())
2607 }
2608
2609 fn insert_output(
2610 cx: &mut compositor::Context,
2611 args: Args,
2612 event: PromptEvent,
2613 ) -> anyhow::Result<()> {
2614 if event != PromptEvent::Validate {
2615 return Ok(());
2616 }
2617
2618 shell(cx, &args.join(" "), &ShellBehavior::Insert);
2619 Ok(())
2620 }
2621
2622 fn pipe_to(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2623 pipe_impl(cx, args, event, &ShellBehavior::Ignore)
2624 }
2625
2626 fn pipe(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2627 pipe_impl(cx, args, event, &ShellBehavior::Replace)
2628 }
2629
2630 fn pipe_impl(
2631 cx: &mut compositor::Context,
2632 args: Args,
2633 event: PromptEvent,
2634 behavior: &ShellBehavior,
2635 ) -> anyhow::Result<()> {
2636 if event != PromptEvent::Validate {
2637 return Ok(());
2638 }
2639
2640 shell(cx, &args.join(" "), behavior);
2641 Ok(())
2642 }
2643
2644 fn run_shell_command(
2645 cx: &mut compositor::Context,
2646 args: Args,
2647 event: PromptEvent,
2648 ) -> anyhow::Result<()> {
2649 if event != PromptEvent::Validate {
2650 return Ok(());
2651 }
2652
2653 let shell = cx.editor.config().shell.clone();
2654 let args = args.join(" ");
2655
2656 let callback = async move {
2657 let output = shell_impl_async(&shell, &args, None).await?;
2658 let call: job::Callback = Callback::EditorCompositor(Box::new(
2659 move |editor: &mut Editor, compositor: &mut Compositor| {
2660 if !output.trim().is_empty() {
2661 let contents = ui::Markdown::new(
2662 format!("```sh\n{}\n```", output.trim_end()),
2663 editor.syn_loader.clone(),
2664 );
2665 let popup = Popup::new("shell", contents).position(Some(
2666 helix_core::Position::new(editor.cursor().0.unwrap_or_default().row, 2),
2667 ));
2668 compositor.replace_or_push("shell", popup);
2669 }
2670 editor.set_status("Command run");
2671 },
2672 ));
2673 Ok(call)
2674 };
2675 cx.jobs.callback(callback);
2676
2677 Ok(())
2678 }
2679
2680 fn reset_diff_change(
2681 cx: &mut compositor::Context,
2682 _args: Args,
2683 event: PromptEvent,
2684 ) -> anyhow::Result<()> {
2685 if event != PromptEvent::Validate {
2686 return Ok(());
2687 }
2688
2689 let editor = &mut cx.editor;
2690 let scrolloff = editor.config().scrolloff;
2691
2692 let (view, doc) = current!(editor);
2693 let Some(handle) = doc.diff_handle() else {
2694 bail!("Diff is not available in the current buffer")
2695 };
2696
2697 let diff = handle.load();
2698 let doc_text = doc.text().slice(..);
2699 let diff_base = diff.diff_base();
2700 let mut changes = 0;
2701
2702 let transaction = Transaction::change(
2703 doc.text(),
2704 diff.hunks_intersecting_line_ranges(doc.selection(view.id).line_ranges(doc_text))
2705 .map(|hunk| {
2706 changes += 1;
2707 let start = diff_base.line_to_char(hunk.before.start as usize);
2708 let end = diff_base.line_to_char(hunk.before.end as usize);
2709 let text: Tendril = diff_base.slice(start..end).chunks().collect();
2710 (
2711 doc_text.line_to_char(hunk.after.start as usize),
2712 doc_text.line_to_char(hunk.after.end as usize),
2713 (!text.is_empty()).then_some(text),
2714 )
2715 }),
2716 );
2717 if changes == 0 {
2718 bail!("There are no changes under any selection");
2719 }
2720
2721 drop(diff); // make borrow check happy
2722 doc.apply(&transaction, view.id);
2723 doc.append_changes_to_history(view);
2724 view.ensure_cursor_in_view(doc, scrolloff);
2725 cx.editor.set_status(format!(
2726 "Reset {changes} change{}",
2727 if changes == 1 { "" } else { "s" }
2728 ));
2729 Ok(())
2730 }
2731
2732 fn clear_register(
2733 cx: &mut compositor::Context,
2734 args: Args,
2735 event: PromptEvent,
2736 ) -> anyhow::Result<()> {
2737 if event != PromptEvent::Validate {
2738 return Ok(());
2739 }
2740
2741 if args.is_empty() {
2742 cx.editor.registers.clear();
2743 cx.editor.set_status("All registers cleared");
2744 return Ok(());
2745 }
2746
2747 ensure!(
2748 args[0].chars().count() == 1,
2749 format!("Invalid register {}", &args[0])
2750 );
2751 let register = args[0].chars().next().unwrap_or_default();
2752 if cx.editor.registers.remove(register) {
2753 cx.editor
2754 .set_status(format!("Register {} cleared", register));
2755 } else {
2756 cx.editor
2757 .set_error(format!("Register {} not found", register));
2758 }
2759 Ok(())
2760 }
2761
2762 fn set_register(
2763 cx: &mut compositor::Context,
2764 args: Args,
2765 event: PromptEvent,
2766 ) -> anyhow::Result<()> {
2767 if event != PromptEvent::Validate {
2768 return Ok(());
2769 }
2770
2771 ensure!(
2772 args[0].chars().count() == 1,
2773 format!("Invalid register {}", &args[0])
2774 );
2775
2776 let register = args[0].chars().next().unwrap_or_default();
2777 cx.editor.registers.write(register, vec![args[1].into()])
2778 }
2779
2780 fn redraw(cx: &mut compositor::Context, _args: Args, event: PromptEvent) -> anyhow::Result<()> {
2781 if event != PromptEvent::Validate {
2782 return Ok(());
2783 }
2784
2785 let callback = Box::pin(async move {
2786 let call: job::Callback =
2787 job::Callback::EditorCompositor(Box::new(|_editor, compositor| {
2788 compositor.need_full_redraw();
2789 }));
2790
2791 Ok(call)
2792 });
2793
2794 cx.jobs.callback(callback);
2795
2796 Ok(())
2797 }
2798
2799 #[derive(Debug, Clone, Copy)]
2800 pub struct MoveBufferOptions {
2801 pub force: bool,
2802 }
2803
2804 fn move_buffer(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2805 if event != PromptEvent::Validate {
2806 return Ok(());
2807 }
2808
2809 let new_path: PathBuf = args.first().unwrap().into();
2810 move_buffer_impl(cx, new_path, MoveBufferOptions { force: false })
2811 }
2812
2813 fn force_move_buffer(
2814 cx: &mut compositor::Context,
2815 args: Args,
2816 event: PromptEvent,
2817 ) -> anyhow::Result<()> {
2818 if event != PromptEvent::Validate {
2819 return Ok(());
2820 }
2821
2822 let new_path: PathBuf = args.first().unwrap().into();
2823 move_buffer_impl(cx, new_path, MoveBufferOptions { force: true })
2824 }
2825
2826 fn move_buffer_impl(
2827 cx: &mut compositor::Context,
2828 new_path: PathBuf,
2829 options: MoveBufferOptions,
2830 ) -> anyhow::Result<()> {
2831 let doc = doc!(cx.editor);
2832 let old_path = doc
2833 .path()
2834 .map(ToOwned::to_owned)
2835 .context("Scratch buffer cannot be moved. Use :write instead")?;
2836
2837 // if new_path is a directory, append the original file name
2838 // to move the file into that directory.
2839 let new_path = old_path
2840 .file_name()
2841 .filter(|_| new_path.is_dir())
2842 .map(|old_file_name| new_path.join(old_file_name))
2843 .unwrap_or(new_path);
2844
2845 if old_path.exists() {
2846 if let Some(parent) = new_path.parent() {
2847 if !parent.exists() {
2848 if options.force {
2849 std::fs::DirBuilder::new().recursive(true).create(parent)?;
2850 } else {
2851 bail!(
2852 "can't move file, parent directory does not exist (use :mv! to create it)"
2853 )
2854 }
2855 }
2856 }
2857 }
2858
2859 if let Err(err) = cx.editor.move_path(&old_path, new_path.as_ref()) {
2860 bail!("Could not move file: {err}");
2861 }
2862 Ok(())
2863 }
2864
2865 fn yank_diagnostic(
2866 cx: &mut compositor::Context,
2867 args: Args,
2868 event: PromptEvent,
2869 ) -> anyhow::Result<()> {
2870 if event != PromptEvent::Validate {
2871 return Ok(());
2872 }
2873
2874 let reg = match args.first() {
2875 Some(s) => {
2876 ensure!(s.chars().count() == 1, format!("Invalid register {s}"));
2877 s.chars().next().unwrap()
2878 }
2879 None => '+',
2880 };
2881
2882 let (view, doc) = current_ref!(cx.editor);
2883 let primary = doc.selection(view.id).primary();
2884
2885 // Look only for diagnostics that intersect with the primary selection
2886 let diag: Vec<_> = doc
2887 .diagnostics()
2888 .iter()
2889 .filter(|d| primary.overlaps(&helix_core::Range::new(d.range.start, d.range.end)))
2890 .map(|d| d.message.clone())
2891 .collect();
2892 let n = diag.len();
2893 if n == 0 {
2894 bail!("No diagnostics under primary selection");
2895 }
2896
2897 cx.editor.registers.write(reg, diag)?;
2898 cx.editor.set_status(format!(
2899 "Yanked {n} diagnostic{} to register {reg}",
2900 if n == 1 { "" } else { "s" }
2901 ));
2902 Ok(())
2903 }
2904
2905 fn read(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2906 if event != PromptEvent::Validate {
2907 return Ok(());
2908 }
2909
2910 let scrolloff = cx.editor.config().scrolloff;
2911 let (view, doc) = current!(cx.editor);
2912
2913 let filename = args.first().unwrap();
2914 let path = helix_stdx::path::expand_tilde(PathBuf::from(filename.to_string()));
2915
2916 ensure!(
2917 path.exists() && path.is_file(),
2918 "path is not a file: {:?}",
2919 path
2920 );
2921
2922 let file = std::fs::File::open(path).map_err(|err| anyhow!("error opening file: {}", err))?;
2923 let mut reader = BufReader::new(file);
2924 let (contents, _, _) = read_to_string(&mut reader, Some(doc.encoding()))
2925 .map_err(|err| anyhow!("error reading file: {}", err))?;
2926 let contents = Tendril::from(contents);
2927 let selection = doc.selection(view.id);
2928 let transaction = Transaction::insert(doc.text(), selection, contents);
2929 doc.apply(&transaction, view.id);
2930 doc.append_changes_to_history(view);
2931 view.ensure_cursor_in_view(doc, scrolloff);
2932
2933 Ok(())
2934 }
2935
2936 fn echo(cx: &mut compositor::Context, args: Args, event: PromptEvent) -> anyhow::Result<()> {
2937 if event != PromptEvent::Validate {
2938 return Ok(());
2939 }
2940
2941 let output = args.into_iter().fold(String::new(), |mut acc, arg| {
2942 if !acc.is_empty() {
2943 acc.push(' ');
2944 }
2945 acc.push_str(&arg);
2946 acc
2947 });
2948 cx.editor.set_status(output);
2949
2950 Ok(())
2951 }
2952
2953 fn noop(_cx: &mut compositor::Context, _args: Args, _event: PromptEvent) -> anyhow::Result<()> {
2954 Ok(())
2955 }
2956
2957 /// This command accepts a single boolean --skip-visible flag and no positionals.
2958 const BUFFER_CLOSE_OTHERS_SIGNATURE: Signature = Signature {
2959 positionals: (0, Some(0)),
2960 flags: &[Flag {
2961 name: "skip-visible",
2962 alias: Some('s'),
2963 doc: "don't close buffers that are visible",
2964 ..Flag::DEFAULT
2965 }],
2966 ..Signature::DEFAULT
2967 };
2968
2969 // TODO: SHELL_SIGNATURE should specify var args for arguments, so that just completers::filename can be used,
2970 // but Signature does not yet allow for var args.
2971
2972 /// This command handles all of its input as-is with no quoting or flags.
2973 pub const SHELL_SIGNATURE: Signature = Signature {
2974 positionals: (1, Some(2)),
2975 raw_after: Some(1),
2976 ..Signature::DEFAULT
2977 };
2978
2979 pub const SHELL_COMPLETER: CommandCompleter = CommandCompleter::positional(&[
2980 // Command name
2981 completers::program,
2982 // Shell argument(s)
2983 completers::repeating_filenames,
2984 ]);
2985
2986 const WRITE_NO_FORMAT_FLAG: Flag = Flag {
2987 name: "no-format",
2988 doc: "skip auto-formatting",
2989 ..Flag::DEFAULT
2990 };
2991
2992 const WRITE_NO_CODE_ACTIONS_FLAG: Flag = Flag {
2993 name: "no-code-actions",
2994 doc: "skip code actions on save",
2995 ..Flag::DEFAULT
2996 };
2997
2998 pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[
2999 TypableCommand {
3000 name: "exit",
3001 aliases: &["x", "xit"],
3002 doc: "Write changes to disk if the buffer is modified and then quit. Accepts an optional path (:exit some/path.txt).",
3003 fun: exit,
3004 completer: CommandCompleter::positional(&[completers::filename]),
3005 signature: Signature {
3006 positionals: (0, Some(1)),
3007 flags: &[WRITE_NO_FORMAT_FLAG, WRITE_NO_CODE_ACTIONS_FLAG],
3008 ..Signature::DEFAULT
3009 },
3010 },
3011 TypableCommand {
3012 name: "exit!",
3013 aliases: &["x!", "xit!"],
3014 doc: "Force write changes to disk, creating necessary subdirectories, if the buffer is modified and then quit. Accepts an optional path (:exit! some/path.txt).",
3015 fun: force_exit,
3016 completer: CommandCompleter::positional(&[completers::filename]),
3017 signature: Signature {
3018 positionals: (0, Some(1)),
3019 flags: &[WRITE_NO_FORMAT_FLAG, WRITE_NO_CODE_ACTIONS_FLAG],
3020 ..Signature::DEFAULT
3021 },
3022 },
3023 TypableCommand {
3024 name: "quit",
3025 aliases: &["q"],
3026 doc: "Close the current view.",
3027 fun: quit,
3028 completer: CommandCompleter::none(),
3029 signature: Signature {
3030 positionals: (0, Some(0)),
3031 ..Signature::DEFAULT
3032 },
3033 },
3034 TypableCommand {
3035 name: "quit!",
3036 aliases: &["q!"],
3037 doc: "Force close the current view, ignoring unsaved changes.",
3038 fun: force_quit,
3039 completer: CommandCompleter::none(),
3040 signature: Signature {
3041 positionals: (0, Some(0)),
3042 ..Signature::DEFAULT
3043 },
3044 },
3045 TypableCommand {
3046 name: "open",
3047 aliases: &["o", "edit", "e"],
3048 doc: "Open a file from disk into the current view.",
3049 fun: open,
3050 completer: CommandCompleter::all(completers::filename),
3051 signature: Signature {
3052 positionals: (1, None),
3053 ..Signature::DEFAULT
3054 },
3055 },
3056 TypableCommand {
3057 name: "buffer-close",
3058 aliases: &["bc", "bclose"],
3059 doc: "Close the current buffer.",
3060 fun: buffer_close,
3061 completer: CommandCompleter::all(completers::buffer),
3062 signature: Signature {
3063 positionals: (0, None),
3064 ..Signature::DEFAULT
3065 },
3066 },
3067 TypableCommand {
3068 name: "buffer-close!",
3069 aliases: &["bc!", "bclose!"],
3070 doc: "Close the current buffer forcefully, ignoring unsaved changes.",
3071 fun: force_buffer_close,
3072 completer: CommandCompleter::all(completers::buffer),
3073 signature: Signature {
3074 positionals: (0, None),
3075 ..Signature::DEFAULT
3076 },
3077 },
3078 TypableCommand {
3079 name: "buffer-close-others",
3080 aliases: &["bco", "bcloseother"],
3081 doc: "Close all buffers but the currently focused one.",
3082 fun: buffer_close_others,
3083 completer: CommandCompleter::none(),
3084 signature: BUFFER_CLOSE_OTHERS_SIGNATURE,
3085 },
3086 TypableCommand {
3087 name: "buffer-close-others!",
3088 aliases: &["bco!", "bcloseother!"],
3089 doc: "Force close all buffers but the currently focused one.",
3090 fun: force_buffer_close_others,
3091 completer: CommandCompleter::none(),
3092 signature: BUFFER_CLOSE_OTHERS_SIGNATURE,
3093 },
3094 TypableCommand {
3095 name: "buffer-close-all",
3096 aliases: &["bca", "bcloseall"],
3097 doc: "Close all buffers without quitting.",
3098 fun: buffer_close_all,
3099 completer: CommandCompleter::none(),
3100 signature: Signature {
3101 positionals: (0, Some(0)),
3102 ..Signature::DEFAULT
3103 },
3104 },
3105 TypableCommand {
3106 name: "buffer-close-all!",
3107 aliases: &["bca!", "bcloseall!"],
3108 doc: "Force close all buffers ignoring unsaved changes without quitting.",
3109 fun: force_buffer_close_all,
3110 completer: CommandCompleter::none(),
3111 signature: Signature {
3112 positionals: (0, Some(0)),
3113 ..Signature::DEFAULT
3114 },
3115 },
3116 TypableCommand {
3117 name: "buffer-next",
3118 aliases: &["bn", "bnext"],
3119 doc: "Goto next buffer.",
3120 fun: buffer_next,
3121 completer: CommandCompleter::none(),
3122 signature: Signature {
3123 positionals: (0, Some(0)),
3124 ..Signature::DEFAULT
3125 },
3126 },
3127 TypableCommand {
3128 name: "buffer-previous",
3129 aliases: &["bp", "bprev"],
3130 doc: "Goto previous buffer.",
3131 fun: buffer_previous,
3132 completer: CommandCompleter::none(),
3133 signature: Signature {
3134 positionals: (0, Some(0)),
3135 ..Signature::DEFAULT
3136 },
3137 },
3138 TypableCommand {
3139 name: "write",
3140 aliases: &["w"],
3141 doc: "Write changes to disk. Accepts an optional path (:write some/path.txt)",
3142 fun: write,
3143 completer: CommandCompleter::positional(&[completers::filename]),
3144 signature: Signature {
3145 positionals: (0, Some(1)),
3146 flags: &[WRITE_NO_FORMAT_FLAG, WRITE_NO_CODE_ACTIONS_FLAG],
3147 ..Signature::DEFAULT
3148 },
3149 },
3150 TypableCommand {
3151 name: "write!",
3152 aliases: &["w!"],
3153 doc: "Force write changes to disk creating necessary subdirectories. Accepts an optional path (:write! some/path.txt)",
3154 fun: force_write,
3155 completer: CommandCompleter::positional(&[completers::filename]),
3156 signature: Signature {
3157 positionals: (0, Some(1)),
3158 flags: &[WRITE_NO_FORMAT_FLAG,WRITE_NO_CODE_ACTIONS_FLAG],
3159 ..Signature::DEFAULT
3160 },
3161 },
3162 TypableCommand {
3163 name: "write-buffer-close",
3164 aliases: &["wbc"],
3165 doc: "Write changes to disk and closes the buffer. Accepts an optional path (:write-buffer-close some/path.txt)",
3166 fun: write_buffer_close,
3167 completer: CommandCompleter::positional(&[completers::filename]),
3168 signature: Signature {
3169 positionals: (0, Some(1)),
3170 flags: &[WRITE_NO_FORMAT_FLAG,WRITE_NO_CODE_ACTIONS_FLAG],
3171 ..Signature::DEFAULT
3172 },
3173 },
3174 TypableCommand {
3175 name: "write-buffer-close!",
3176 aliases: &["wbc!"],
3177 doc: "Force write changes to disk creating necessary subdirectories and closes the buffer. Accepts an optional path (:write-buffer-close! some/path.txt)",
3178 fun: force_write_buffer_close,
3179 completer: CommandCompleter::positional(&[completers::filename]),
3180 signature: Signature {
3181 positionals: (0, Some(1)),
3182 flags: &[WRITE_NO_FORMAT_FLAG,WRITE_NO_CODE_ACTIONS_FLAG],
3183 ..Signature::DEFAULT
3184 },
3185 },
3186 TypableCommand {
3187 name: "new",
3188 aliases: &["n"],
3189 doc: "Create a new scratch buffer.",
3190 fun: new_file,
3191 completer: CommandCompleter::none(),
3192 signature: Signature {
3193 positionals: (0, Some(0)),
3194 ..Signature::DEFAULT
3195 },
3196 },
3197 TypableCommand {
3198 name: "format",
3199 aliases: &["fmt"],
3200 doc: "Format the file using an external formatter or language server.",
3201 fun: format,
3202 completer: CommandCompleter::none(),
3203 signature: Signature {
3204 positionals: (0, Some(0)),
3205 ..Signature::DEFAULT
3206 },
3207 },
3208 TypableCommand {
3209 name: "indent-style",
3210 aliases: &[],
3211 doc: "Set the indentation style for editing. ('t' for tabs or 1-16 for number of spaces.)",
3212 fun: set_indent_style,
3213 completer: CommandCompleter::none(),
3214 signature: Signature {
3215 positionals: (0, Some(1)),
3216 ..Signature::DEFAULT
3217 },
3218 },
3219 TypableCommand {
3220 name: "line-ending",
3221 aliases: &[],
3222 #[cfg(not(feature = "unicode-lines"))]
3223 doc: "Set the document's default line ending. Options: crlf, lf.",
3224 #[cfg(feature = "unicode-lines")]
3225 doc: "Set the document's default line ending. Options: crlf, lf, cr, ff, nel.",
3226 fun: set_line_ending,
3227 completer: CommandCompleter::none(),
3228 signature: Signature {
3229 positionals: (0, Some(1)),
3230 ..Signature::DEFAULT
3231 },
3232 },
3233 TypableCommand {
3234 name: "earlier",
3235 aliases: &["ear"],
3236 doc: "Jump back to an earlier point in edit history. Accepts a number of steps or a time span.",
3237 fun: earlier,
3238 completer: CommandCompleter::none(),
3239 signature: Signature {
3240 positionals: (0, Some(1)),
3241 ..Signature::DEFAULT
3242 },
3243 },
3244 TypableCommand {
3245 name: "later",
3246 aliases: &["lat"],
3247 doc: "Jump to a later point in edit history. Accepts a number of steps or a time span.",
3248 fun: later,
3249 completer: CommandCompleter::none(),
3250 signature: Signature {
3251 positionals: (0, Some(1)),
3252 ..Signature::DEFAULT
3253 },
3254 },
3255 TypableCommand {
3256 name: "write-quit",
3257 aliases: &["wq"],
3258 doc: "Write changes to disk and close the current view. Accepts an optional path (:wq some/path.txt)",
3259 fun: write_quit,
3260 completer: CommandCompleter::positional(&[completers::filename]),
3261 signature: Signature {
3262 positionals: (0, Some(1)),
3263 flags: &[WRITE_NO_FORMAT_FLAG, WRITE_NO_CODE_ACTIONS_FLAG],
3264 ..Signature::DEFAULT
3265 },
3266 },
3267 TypableCommand {
3268 name: "write-quit!",
3269 aliases: &["wq!"],
3270 doc: "Write changes to disk and close the current view forcefully. Accepts an optional path (:wq! some/path.txt)",
3271 fun: force_write_quit,
3272 completer: CommandCompleter::positional(&[completers::filename]),
3273 signature: Signature {
3274 positionals: (0, Some(1)),
3275 flags: &[WRITE_NO_FORMAT_FLAG, WRITE_NO_CODE_ACTIONS_FLAG],
3276 ..Signature::DEFAULT
3277 },
3278 },
3279 TypableCommand {
3280 name: "write-all",
3281 aliases: &["wa"],
3282 doc: "Write changes from all buffers to disk.",
3283 fun: write_all,
3284 completer: CommandCompleter::none(),
3285 signature: Signature {
3286 positionals: (0, Some(0)),
3287 flags: &[WRITE_NO_FORMAT_FLAG, WRITE_NO_CODE_ACTIONS_FLAG],
3288 ..Signature::DEFAULT
3289 },
3290 },
3291 TypableCommand {
3292 name: "write-all!",
3293 aliases: &["wa!"],
3294 doc: "Forcefully write changes from all buffers to disk creating necessary subdirectories.",
3295 fun: force_write_all,
3296 completer: CommandCompleter::none(),
3297 signature: Signature {
3298 positionals: (0, Some(0)),
3299 flags: &[WRITE_NO_FORMAT_FLAG, WRITE_NO_CODE_ACTIONS_FLAG],
3300 ..Signature::DEFAULT
3301 },
3302 },
3303 TypableCommand {
3304 name: "write-quit-all",
3305 aliases: &["wqa", "xa"],
3306 doc: "Write changes from all buffers to disk and close all views.",
3307 fun: write_all_quit,
3308 completer: CommandCompleter::none(),
3309 signature: Signature {
3310 positionals: (0, Some(0)),
3311 flags: &[WRITE_NO_FORMAT_FLAG, WRITE_NO_CODE_ACTIONS_FLAG],
3312 ..Signature::DEFAULT
3313 },
3314 },
3315 TypableCommand {
3316 name: "write-quit-all!",
3317 aliases: &["wqa!", "xa!"],
3318 doc: "Forcefully write changes from all buffers to disk, creating necessary subdirectories, and close all views (ignoring unsaved changes).",
3319 fun: force_write_all_quit,
3320 completer: CommandCompleter::none(),
3321 signature: Signature {
3322 positionals: (0, Some(0)),
3323 flags: &[WRITE_NO_FORMAT_FLAG, WRITE_NO_CODE_ACTIONS_FLAG],
3324 ..Signature::DEFAULT
3325 },
3326 },
3327 TypableCommand {
3328 name: "quit-all",
3329 aliases: &["qa"],
3330 doc: "Close all views.",
3331 fun: quit_all,
3332 completer: CommandCompleter::none(),
3333 signature: Signature {
3334 positionals: (0, Some(0)),
3335 ..Signature::DEFAULT
3336 },
3337 },
3338 TypableCommand {
3339 name: "quit-all!",
3340 aliases: &["qa!"],
3341 doc: "Force close all views ignoring unsaved changes.",
3342 fun: force_quit_all,
3343 completer: CommandCompleter::none(),
3344 signature: Signature {
3345 positionals: (0, Some(0)),
3346 ..Signature::DEFAULT
3347 },
3348 },
3349 TypableCommand {
3350 name: "cquit",
3351 aliases: &["cq"],
3352 doc: "Quit with exit code (default 1). Accepts an optional integer exit code (:cq 2).",
3353 fun: cquit,
3354 completer: CommandCompleter::none(),
3355 signature: Signature {
3356 positionals: (0, Some(1)),
3357 ..Signature::DEFAULT
3358 },
3359 },
3360 TypableCommand {
3361 name: "cquit!",
3362 aliases: &["cq!"],
3363 doc: "Force quit with exit code (default 1) ignoring unsaved changes. Accepts an optional integer exit code (:cq! 2).",
3364 fun: force_cquit,
3365 completer: CommandCompleter::none(),
3366 signature: Signature {
3367 positionals: (0, Some(1)),
3368 ..Signature::DEFAULT
3369 },
3370 },
3371 TypableCommand {
3372 name: "theme",
3373 aliases: &[],
3374 doc: "Change the editor theme (show current theme if no name specified).",
3375 fun: theme,
3376 completer: CommandCompleter::positional(&[completers::theme]),
3377 signature: Signature {
3378 positionals: (0, Some(1)),
3379 ..Signature::DEFAULT
3380 },
3381 },
3382 TypableCommand {
3383 name: "yank-join",
3384 aliases: &[],
3385 doc: "Yank joined selections. A separator can be provided as first argument. Default value is newline.",
3386 fun: yank_joined,
3387 completer: CommandCompleter::none(),
3388 signature: Signature {
3389 positionals: (0, Some(1)),
3390 ..Signature::DEFAULT
3391 },
3392 },
3393 TypableCommand {
3394 name: "clipboard-yank",
3395 aliases: &[],
3396 doc: "Yank main selection into system clipboard.",
3397 fun: yank_main_selection_to_clipboard,
3398 completer: CommandCompleter::none(),
3399 signature: Signature {
3400 positionals: (0, Some(0)),
3401 ..Signature::DEFAULT
3402 },
3403 },
3404 TypableCommand {
3405 name: "clipboard-yank-join",
3406 aliases: &[],
3407 doc: "Yank joined selections into system clipboard. A separator can be provided as first argument. Default value is newline.", // FIXME: current UI can't display long doc.
3408 fun: yank_joined_to_clipboard,
3409 completer: CommandCompleter::none(),
3410 signature: Signature {
3411 positionals: (0, Some(1)),
3412 ..Signature::DEFAULT
3413 },
3414 },
3415 TypableCommand {
3416 name: "primary-clipboard-yank",
3417 aliases: &[],
3418 doc: "Yank main selection into system primary clipboard.",
3419 fun: yank_main_selection_to_primary_clipboard,
3420 completer: CommandCompleter::none(),
3421 signature: Signature {
3422 positionals: (0, Some(0)),
3423 ..Signature::DEFAULT
3424 },
3425 },
3426 TypableCommand {
3427 name: "primary-clipboard-yank-join",
3428 aliases: &[],
3429 doc: "Yank joined selections into system primary clipboard. A separator can be provided as first argument. Default value is newline.", // FIXME: current UI can't display long doc.
3430 fun: yank_joined_to_primary_clipboard,
3431 completer: CommandCompleter::none(),
3432 signature: Signature {
3433 positionals: (0, Some(1)),
3434 ..Signature::DEFAULT
3435 },
3436 },
3437 TypableCommand {
3438 name: "clipboard-paste-after",
3439 aliases: &[],
3440 doc: "Paste system clipboard after selections.",
3441 fun: paste_clipboard_after,
3442 completer: CommandCompleter::none(),
3443 signature: Signature {
3444 positionals: (0, Some(0)),
3445 ..Signature::DEFAULT
3446 },
3447 },
3448 TypableCommand {
3449 name: "clipboard-paste-before",
3450 aliases: &[],
3451 doc: "Paste system clipboard before selections.",
3452 fun: paste_clipboard_before,
3453 completer: CommandCompleter::none(),
3454 signature: Signature {
3455 positionals: (0, Some(0)),
3456 ..Signature::DEFAULT
3457 },
3458 },
3459 TypableCommand {
3460 name: "clipboard-paste-replace",
3461 aliases: &[],
3462 doc: "Replace selections with content of system clipboard.",
3463 fun: replace_selections_with_clipboard,
3464 completer: CommandCompleter::none(),
3465 signature: Signature {
3466 positionals: (0, Some(0)),
3467 ..Signature::DEFAULT
3468 },
3469 },
3470 TypableCommand {
3471 name: "primary-clipboard-paste-after",
3472 aliases: &[],
3473 doc: "Paste primary clipboard after selections.",
3474 fun: paste_primary_clipboard_after,
3475 completer: CommandCompleter::none(),
3476 signature: Signature {
3477 positionals: (0, Some(0)),
3478 ..Signature::DEFAULT
3479 },
3480 },
3481 TypableCommand {
3482 name: "primary-clipboard-paste-before",
3483 aliases: &[],
3484 doc: "Paste primary clipboard before selections.",
3485 fun: paste_primary_clipboard_before,
3486 completer: CommandCompleter::none(),
3487 signature: Signature {
3488 positionals: (0, Some(0)),
3489 ..Signature::DEFAULT
3490 },
3491 },
3492 TypableCommand {
3493 name: "primary-clipboard-paste-replace",
3494 aliases: &[],
3495 doc: "Replace selections with content of system primary clipboard.",
3496 fun: replace_selections_with_primary_clipboard,
3497 completer: CommandCompleter::none(),
3498 signature: Signature {
3499 positionals: (0, Some(0)),
3500 ..Signature::DEFAULT
3501 },
3502 },
3503 TypableCommand {
3504 name: "show-clipboard-provider",
3505 aliases: &[],
3506 doc: "Show clipboard provider name in status bar.",
3507 fun: show_clipboard_provider,
3508 completer: CommandCompleter::none(),
3509 signature: Signature {
3510 positionals: (0, Some(0)),
3511 ..Signature::DEFAULT
3512 },
3513 },
3514 TypableCommand {
3515 name: "change-current-directory",
3516 aliases: &["cd"],
3517 doc: "Change the current working directory.",
3518 fun: change_current_directory,
3519 completer: CommandCompleter::positional(&[completers::directory]),
3520 signature: Signature {
3521 positionals: (1, Some(1)),
3522 ..Signature::DEFAULT
3523 },
3524 },
3525 TypableCommand {
3526 name: "show-directory-stack",
3527 aliases: &[],
3528 doc: "Show the directory stack as a <space> delimited string.",
3529 fun: show_directory_stack,
3530 completer: CommandCompleter::none(),
3531 signature: Signature {
3532 positionals: (0, Some(0)),
3533 ..Signature::DEFAULT
3534 },
3535 },
3536 TypableCommand {
3537 name: "push-directory",
3538 aliases: &["pushd"],
3539 doc: "Save and then change the current directory.",
3540 fun: push_directory,
3541 completer: CommandCompleter::positional(&[completers::directory]),
3542 signature: Signature {
3543 positionals: (1, Some(1)),
3544 ..Signature::DEFAULT
3545 },
3546 },
3547 TypableCommand {
3548 name: "pop-directory",
3549 aliases: &["popd"],
3550 doc: "Remove the top entry from the directory stack, and cd to the new top directory..",
3551 fun: pop_directory,
3552 completer: CommandCompleter::none(),
3553 signature: Signature {
3554 positionals: (0, Some(0)),
3555 ..Signature::DEFAULT
3556 },
3557 },
3558 TypableCommand {
3559 name: "show-directory",
3560 aliases: &["pwd"],
3561 doc: "Show the current working directory.",
3562 fun: show_current_directory,
3563 completer: CommandCompleter::none(),
3564 signature: Signature {
3565 positionals: (0, Some(0)),
3566 ..Signature::DEFAULT
3567 },
3568 },
3569 TypableCommand {
3570 name: "encoding",
3571 aliases: &[],
3572 doc: "Set encoding. Based on `https://encoding.spec.whatwg.org`.",
3573 fun: set_encoding,
3574 completer: CommandCompleter::none(),
3575 signature: Signature {
3576 positionals: (0, Some(1)),
3577 ..Signature::DEFAULT
3578 },
3579 },
3580 TypableCommand {
3581 name: "character-info",
3582 aliases: &["char"],
3583 doc: "Get info about the character under the primary cursor.",
3584 fun: get_character_info,
3585 completer: CommandCompleter::none(),
3586 signature: Signature {
3587 positionals: (0, Some(0)),
3588 ..Signature::DEFAULT
3589 },
3590 },
3591 TypableCommand {
3592 name: "reload",
3593 aliases: &["rl"],
3594 doc: "Discard changes and reload from the source file.",
3595 fun: reload,
3596 completer: CommandCompleter::none(),
3597 signature: Signature {
3598 positionals: (0, Some(0)),
3599 ..Signature::DEFAULT
3600 },
3601 },
3602 TypableCommand {
3603 name: "reload-all",
3604 aliases: &["rla"],
3605 doc: "Discard changes and reload all documents from the source files.",
3606 fun: reload_all,
3607 completer: CommandCompleter::none(),
3608 signature: Signature {
3609 positionals: (0, Some(0)),
3610 ..Signature::DEFAULT
3611 },
3612 },
3613 TypableCommand {
3614 name: "update",
3615 aliases: &["u"],
3616 doc: "Write changes only if the file has been modified.",
3617 fun: update,
3618 completer: CommandCompleter::none(),
3619 signature: Signature {
3620 positionals: (0, Some(0)),
3621 flags: &[WRITE_NO_FORMAT_FLAG],
3622 ..Signature::DEFAULT
3623 },
3624 },
3625 TypableCommand {
3626 name: "lsp-workspace-command",
3627 aliases: &[],
3628 doc: "Open workspace command picker",
3629 fun: lsp_workspace_command,
3630 completer: CommandCompleter::positional(&[completers::lsp_workspace_command]),
3631 signature: Signature {
3632 positionals: (0, None),
3633 raw_after: Some(1),
3634 ..Signature::DEFAULT
3635 },
3636 },
3637 TypableCommand {
3638 name: "lsp-restart",
3639 aliases: &[],
3640 doc: "Restarts the given language servers, or all language servers that are used by the current file if no arguments are supplied",
3641 fun: lsp_restart,
3642 completer: CommandCompleter::all(completers::configured_language_servers),
3643 signature: Signature {
3644 positionals: (0, None),
3645 ..Signature::DEFAULT
3646 },
3647 },
3648 TypableCommand {
3649 name: "lsp-stop",
3650 aliases: &[],
3651 doc: "Stops the given language servers, or all language servers that are used by the current file if no arguments are supplied",
3652 fun: lsp_stop,
3653 completer: CommandCompleter::all(completers::active_language_servers),
3654 signature: Signature {
3655 positionals: (0, None),
3656 ..Signature::DEFAULT
3657 },
3658 },
3659 TypableCommand {
3660 name: "tree-sitter-scopes",
3661 aliases: &[],
3662 doc: "Display tree sitter scopes, primarily for theming and development.",
3663 fun: tree_sitter_scopes,
3664 completer: CommandCompleter::none(),
3665 signature: Signature {
3666 positionals: (0, Some(0)),
3667 ..Signature::DEFAULT
3668 },
3669 },
3670 TypableCommand {
3671 name: "tree-sitter-highlight-name",
3672 aliases: &[],
3673 doc: "Display name of tree-sitter highlight scope under the cursor.",
3674 fun: tree_sitter_highlight_name,
3675 completer: CommandCompleter::none(),
3676 signature: Signature {
3677 positionals: (0, Some(0)),
3678 ..Signature::DEFAULT
3679 },
3680 },
3681 TypableCommand {
3682 name: "tree-sitter-layers",
3683 aliases: &[],
3684 doc: "Display language names of tree-sitter injection layers under the cursor.",
3685 fun: tree_sitter_layers,
3686 completer: CommandCompleter::none(),
3687 signature: Signature {
3688 positionals: (0, Some(0)),
3689 ..Signature::DEFAULT
3690 },
3691 },
3692 TypableCommand {
3693 name: "debug-start",
3694 aliases: &["dbg"],
3695 doc: "Start a debug session from a given template with given parameters.",
3696 fun: debug_start,
3697 completer: CommandCompleter::none(),
3698 signature: Signature {
3699 positionals: (0, None),
3700 ..Signature::DEFAULT
3701 },
3702 },
3703 TypableCommand {
3704 name: "debug-remote",
3705 aliases: &["dbg-tcp"],
3706 doc: "Connect to a debug adapter by TCP address and start a debugging session from a given template with given parameters.",
3707 fun: debug_remote,
3708 completer: CommandCompleter::none(),
3709 signature: Signature {
3710 positionals: (0, None),
3711 ..Signature::DEFAULT
3712 },
3713 },
3714 TypableCommand {
3715 name: "debug-eval",
3716 aliases: &[],
3717 doc: "Evaluate expression in current debug context.",
3718 fun: debug_eval,
3719 completer: CommandCompleter::none(),
3720 signature: Signature {
3721 positionals: (1, Some(1)),
3722 ..Signature::DEFAULT
3723 },
3724 },
3725 TypableCommand {
3726 name: "vsplit",
3727 aliases: &["vs"],
3728 doc: "Open the file in a vertical split.",
3729 fun: vsplit,
3730 completer: CommandCompleter::all(completers::filename),
3731 signature: Signature {
3732 positionals: (0, None),
3733 ..Signature::DEFAULT
3734 },
3735 },
3736 TypableCommand {
3737 name: "vsplit-new",
3738 aliases: &["vnew"],
3739 doc: "Open a scratch buffer in a vertical split.",
3740 fun: vsplit_new,
3741 completer: CommandCompleter::none(),
3742 signature: Signature {
3743 positionals: (0, Some(0)),
3744 ..Signature::DEFAULT
3745 },
3746 },
3747 TypableCommand {
3748 name: "hsplit",
3749 aliases: &["hs", "sp"],
3750 doc: "Open the file in a horizontal split.",
3751 fun: hsplit,
3752 completer: CommandCompleter::all(completers::filename),
3753 signature: Signature {
3754 positionals: (0, None),
3755 ..Signature::DEFAULT
3756 },
3757 },
3758 TypableCommand {
3759 name: "hsplit-new",
3760 aliases: &["hnew"],
3761 doc: "Open a scratch buffer in a horizontal split.",
3762 fun: hsplit_new,
3763 completer: CommandCompleter::none(),
3764 signature: Signature {
3765 positionals: (0, Some(0)),
3766 ..Signature::DEFAULT
3767 },
3768 },
3769 TypableCommand {
3770 name: "tutor",
3771 aliases: &[],
3772 doc: "Open the tutorial.",
3773 fun: tutor,
3774 completer: CommandCompleter::none(),
3775 signature: Signature {
3776 positionals: (0, Some(0)),
3777 ..Signature::DEFAULT
3778 },
3779 },
3780 TypableCommand {
3781 name: "goto",
3782 aliases: &["g"],
3783 doc: "Goto line number.",
3784 fun: goto_line_number,
3785 completer: CommandCompleter::none(),
3786 signature: Signature {
3787 positionals: (1, Some(1)),
3788 ..Signature::DEFAULT
3789 },
3790 },
3791 TypableCommand {
3792 name: "set-language",
3793 aliases: &["lang"],
3794 doc: "Set the language of current buffer (show current language if no value specified).",
3795 fun: language,
3796 completer: CommandCompleter::positional(&[completers::language]),
3797 signature: Signature {
3798 positionals: (0, Some(1)),
3799 ..Signature::DEFAULT
3800 },
3801 },
3802 TypableCommand {
3803 name: "set-option",
3804 aliases: &["set"],
3805 doc: "Set a config option at runtime.\nFor example to disable smart case search, use `:set search.smart-case false`.",
3806 fun: set_option,
3807 // TODO: Add support for completion of the options value(s), when appropriate.
3808 completer: CommandCompleter::positional(&[completers::setting]),
3809 signature: Signature {
3810 positionals: (2, Some(2)),
3811 raw_after: Some(1),
3812 ..Signature::DEFAULT
3813 },
3814 },
3815 TypableCommand {
3816 name: "toggle-option",
3817 aliases: &["toggle"],
3818 doc: "Toggle a config option at runtime.\nFor example to toggle smart case search, use `:toggle search.smart-case`.",
3819 fun: toggle_option,
3820 completer: CommandCompleter::positional(&[completers::setting]),
3821 signature: Signature {
3822 positionals: (1, None),
3823 raw_after: Some(1),
3824 ..Signature::DEFAULT
3825 },
3826 },
3827 TypableCommand {
3828 name: "get-option",
3829 aliases: &["get"],
3830 doc: "Get the current value of a config option.",
3831 fun: get_option,
3832 completer: CommandCompleter::positional(&[completers::setting]),
3833 signature: Signature {
3834 positionals: (1, Some(1)),
3835 ..Signature::DEFAULT
3836 },
3837 },
3838 TypableCommand {
3839 name: "sort",
3840 aliases: &[],
3841 doc: "Sort ranges in selection.",
3842 fun: sort,
3843 completer: CommandCompleter::none(),
3844 signature: Signature {
3845 positionals: (0, Some(0)),
3846 flags: &[
3847 Flag {
3848 name: "insensitive",
3849 alias: Some('i'),
3850 doc: "sort the ranges case-insensitively",
3851 ..Flag::DEFAULT
3852 },
3853 Flag {
3854 name: "reverse",
3855 alias: Some('r'),
3856 doc: "sort ranges in reverse order",
3857 ..Flag::DEFAULT
3858 },
3859 ],
3860 ..Signature::DEFAULT
3861 },
3862 },
3863 TypableCommand {
3864 name: "reflow",
3865 aliases: &[],
3866 doc: "Hard-wrap the current selection of lines to a given width.",
3867 fun: reflow,
3868 completer: CommandCompleter::none(),
3869 signature: Signature {
3870 positionals: (0, Some(1)),
3871 ..Signature::DEFAULT
3872 },
3873 },
3874 TypableCommand {
3875 name: "tree-sitter-subtree",
3876 aliases: &["ts-subtree"],
3877 doc: "Display the smallest tree-sitter subtree that spans the primary selection, primarily for debugging queries.",
3878 fun: tree_sitter_subtree,
3879 completer: CommandCompleter::none(),
3880 signature: Signature {
3881 positionals: (0, Some(0)),
3882 ..Signature::DEFAULT
3883 },
3884 },
3885 TypableCommand {
3886 name: "config-reload",
3887 aliases: &[],
3888 doc: "Refresh user config.",
3889 fun: refresh_config,
3890 completer: CommandCompleter::none(),
3891 signature: Signature {
3892 positionals: (0, Some(0)),
3893 ..Signature::DEFAULT
3894 },
3895 },
3896 TypableCommand {
3897 name: "config-open",
3898 aliases: &[],
3899 doc: "Open the user config.toml file.",
3900 fun: open_config,
3901 completer: CommandCompleter::none(),
3902 signature: Signature {
3903 positionals: (0, Some(0)),
3904 ..Signature::DEFAULT
3905 },
3906 },
3907 TypableCommand {
3908 name: "config-open-workspace",
3909 aliases: &[],
3910 doc: "Open the workspace config.toml file.",
3911 fun: open_workspace_config,
3912 completer: CommandCompleter::none(),
3913 signature: Signature {
3914 positionals: (0, Some(0)),
3915 ..Signature::DEFAULT
3916 },
3917 },
3918 TypableCommand {
3919 name: "log-open",
3920 aliases: &[],
3921 doc: "Open the helix log file.",
3922 fun: open_log,
3923 completer: CommandCompleter::none(),
3924 signature: Signature {
3925 positionals: (0, Some(0)),
3926 ..Signature::DEFAULT
3927 },
3928 },
3929 TypableCommand {
3930 name: "insert-output",
3931 aliases: &[],
3932 doc: "Run shell command, inserting output before each selection.",
3933 fun: insert_output,
3934 completer: SHELL_COMPLETER,
3935 signature: SHELL_SIGNATURE,
3936 },
3937 TypableCommand {
3938 name: "append-output",
3939 aliases: &[],
3940 doc: "Run shell command, appending output after each selection.",
3941 fun: append_output,
3942 completer: SHELL_COMPLETER,
3943 signature: SHELL_SIGNATURE,
3944 },
3945 TypableCommand {
3946 name: "pipe",
3947 aliases: &["|"],
3948 doc: "Pipe each selection to the shell command.",
3949 fun: pipe,
3950 completer: SHELL_COMPLETER,
3951 signature: SHELL_SIGNATURE,
3952 },
3953 TypableCommand {
3954 name: "pipe-to",
3955 aliases: &[],
3956 doc: "Pipe each selection to the shell command, ignoring output.",
3957 fun: pipe_to,
3958 completer: SHELL_COMPLETER,
3959 signature: SHELL_SIGNATURE,
3960 },
3961 TypableCommand {
3962 name: "run-shell-command",
3963 aliases: &["sh", "!"],
3964 doc: "Run a shell command",
3965 fun: run_shell_command,
3966 completer: SHELL_COMPLETER,
3967 signature: SHELL_SIGNATURE,
3968 },
3969 TypableCommand {
3970 name: "reset-diff-change",
3971 aliases: &["diffget", "diffg"],
3972 doc: "Reset the diff change at the cursor position.",
3973 fun: reset_diff_change,
3974 completer: CommandCompleter::none(),
3975 signature: Signature {
3976 positionals: (0, Some(0)),
3977 ..Signature::DEFAULT
3978 },
3979 },
3980 TypableCommand {
3981 name: "clear-register",
3982 aliases: &[],
3983 doc: "Clear given register. If no argument is provided, clear all registers.",
3984 fun: clear_register,
3985 completer: CommandCompleter::all(completers::register),
3986 signature: Signature {
3987 positionals: (0, Some(1)),
3988 ..Signature::DEFAULT
3989 },
3990 },
3991 TypableCommand {
3992 name: "set-register",
3993 aliases: &[],
3994 doc: "Set contents of the given register.",
3995 fun: set_register,
3996 completer: CommandCompleter::positional(&[completers::register, completers::none]),
3997 signature: Signature {
3998 positionals: (2, Some(2)),
3999 raw_after: Some(1),
4000 ..Signature::DEFAULT
4001 },
4002 },
4003 TypableCommand {
4004 name: "redraw",
4005 aliases: &[],
4006 doc: "Clear and re-render the whole UI",
4007 fun: redraw,
4008 completer: CommandCompleter::none(),
4009 signature: Signature {
4010 positionals: (0, Some(0)),
4011 ..Signature::DEFAULT
4012 },
4013 },
4014 TypableCommand {
4015 name: "move",
4016 aliases: &["mv"],
4017 doc: "Move the current buffer and its corresponding file to a different path",
4018 fun: move_buffer,
4019 completer: CommandCompleter::positional(&[completers::filename]),
4020 signature: Signature {
4021 positionals: (1, Some(1)),
4022 ..Signature::DEFAULT
4023 },
4024 },
4025 TypableCommand {
4026 name: "move!",
4027 aliases: &["mv!"],
4028 doc: "Move the current buffer and its corresponding file to a different path creating necessary subdirectories",
4029 fun: force_move_buffer,
4030 completer: CommandCompleter::positional(&[completers::filename]),
4031 signature: Signature {
4032 positionals: (1, Some(1)),
4033 ..Signature::DEFAULT
4034 },
4035 },
4036 TypableCommand {
4037 name: "yank-diagnostic",
4038 aliases: &[],
4039 doc: "Yank diagnostic(s) under primary cursor to register, or clipboard by default",
4040 fun: yank_diagnostic,
4041 completer: CommandCompleter::all(completers::register),
4042 signature: Signature {
4043 positionals: (0, Some(1)),
4044 ..Signature::DEFAULT
4045 },
4046 },
4047 TypableCommand {
4048 name: "read",
4049 aliases: &["r"],
4050 doc: "Load a file into buffer",
4051 fun: read,
4052 completer: CommandCompleter::positional(&[completers::filename]),
4053 signature: Signature {
4054 positionals: (1, Some(1)),
4055 ..Signature::DEFAULT
4056 },
4057 },
4058 TypableCommand {
4059 name: "echo",
4060 aliases: &[],
4061 doc: "Prints the given arguments to the statusline.",
4062 fun: echo,
4063 completer: CommandCompleter::none(),
4064 signature: Signature {
4065 positionals: (1, None),
4066 ..Signature::DEFAULT
4067 },
4068 },
4069 TypableCommand {
4070 name: "noop",
4071 aliases: &[],
4072 doc: "Does nothing.",
4073 fun: noop,
4074 completer: CommandCompleter::none(),
4075 signature: Signature {
4076 positionals: (0, None),
4077 ..Signature::DEFAULT
4078 },
4079 },
4080 TypableCommand {
4081 name: "workspace-trust",
4082 aliases: &[],
4083 doc: "Allow language servers and local config for the current workspace.",
4084 fun: trust_workspace,
4085 completer: CommandCompleter::none(),
4086 signature: Signature { positionals: (0, None), ..Signature::DEFAULT },
4087 },
4088 TypableCommand {
4089 name: "workspace-untrust",
4090 aliases: &[],
4091 doc: "Revoke the current workspace's trust grant or exclusion.",
4092 fun: untrust_workspace,
4093 completer: CommandCompleter::none(),
4094 signature: Signature { positionals: (0, None), ..Signature::DEFAULT },
4095 },
4096 TypableCommand {
4097 name: "workspace-exclude",
4098 aliases: &[],
4099 doc: "Mark the current workspace as never-prompt. Never prompts for trust again.",
4100 fun: exclude_workspace,
4101 completer: CommandCompleter::none(),
4102 signature: Signature { positionals: (0, None), ..Signature::DEFAULT },
4103 }
4104 ];
4105
4106 pub static TYPABLE_COMMAND_MAP: Lazy<HashMap<&'static str, &'static TypableCommand>> =
4107 Lazy::new(|| {
4108 TYPABLE_COMMAND_LIST
4109 .iter()
4110 .flat_map(|cmd| {
4111 std::iter::once((cmd.name, cmd))
4112 .chain(cmd.aliases.iter().map(move |&alias| (alias, cmd)))
4113 })
4114 .collect()
4115 });
4116
4117 fn execute_command_line(
4118 cx: &mut compositor::Context,
4119 input: &str,
4120 event: PromptEvent,
4121 ) -> anyhow::Result<()> {
4122 let (command, rest, _) = command_line::split(input);
4123 if command.is_empty() {
4124 return Ok(());
4125 }
4126
4127 // If command is numeric, interpret as line number and go there.
4128 if command.parse::<usize>().is_ok() && rest.trim().is_empty() {
4129 let cmd = TYPABLE_COMMAND_MAP.get("goto").unwrap();
4130 return execute_command(cx, cmd, command, event);
4131 }
4132
4133 match typed::TYPABLE_COMMAND_MAP.get(command) {
4134 Some(cmd) => execute_command(cx, cmd, rest, event),
4135 None if event == PromptEvent::Validate => Err(anyhow!("no such command: '{command}'")),
4136 None => Ok(()),
4137 }
4138 }
4139
4140 pub(super) fn execute_command(
4141 cx: &mut compositor::Context,
4142 cmd: &TypableCommand,
4143 args: &str,
4144 event: PromptEvent,
4145 ) -> anyhow::Result<()> {
4146 let args = if event == PromptEvent::Validate {
4147 Args::parse(args, cmd.signature, true, |token| {
4148 expansion::expand(cx.editor, token).map_err(|err| err.into())
4149 })
4150 .map_err(|err| anyhow!("'{}': {err}", cmd.name))?
4151 } else {
4152 Args::parse(args, cmd.signature, false, |token| Ok(token.content))
4153 .expect("arg parsing cannot fail when validation is turned off")
4154 };
4155
4156 (cmd.fun)(cx, args, event).map_err(|err| anyhow!("'{}': {err}", cmd.name))
4157 }
4158
4159 #[allow(clippy::unnecessary_unwrap)]
4160 pub(super) fn command_mode(cx: &mut Context) {
4161 let mut prompt = Prompt::new(
4162 ":".into(),
4163 Some(':'),
4164 complete_command_line,
4165 move |cx: &mut compositor::Context, input: &str, event: PromptEvent| {
4166 if let Err(err) = execute_command_line(cx, input, event) {
4167 cx.editor.set_error(err.to_string());
4168 }
4169 },
4170 );
4171 prompt.doc_fn = Box::new(command_line_doc);
4172
4173 // Calculate initial completion
4174 prompt.recalculate_completion(cx.editor);
4175 cx.push_layer(Box::new(prompt));
4176 }
4177
4178 fn command_line_doc(input: &str) -> Option<Cow<'_, str>> {
4179 let (command, _, _) = command_line::split(input);
4180 let command = TYPABLE_COMMAND_MAP.get(command)?;
4181
4182 if command.aliases.is_empty() && command.signature.flags.is_empty() {
4183 return Some(Cow::Borrowed(command.doc));
4184 }
4185
4186 let mut doc = command.doc.to_string();
4187
4188 if !command.aliases.is_empty() {
4189 write!(doc, "\nAliases: {}", command.aliases.join(", ")).unwrap();
4190 }
4191
4192 if !command.signature.flags.is_empty() {
4193 const ARG_PLACEHOLDER: &str = " <arg>";
4194
4195 fn flag_len(flag: &Flag) -> usize {
4196 let name_len = flag.name.len();
4197 let alias_len = if let Some(alias) = flag.alias {
4198 "/-".len() + alias.len_utf8()
4199 } else {
4200 0
4201 };
4202 let arg_len = if flag.completions.is_some() {
4203 ARG_PLACEHOLDER.len()
4204 } else {
4205 0
4206 };
4207 name_len + alias_len + arg_len
4208 }
4209
4210 doc.push_str("\nFlags:");
4211
4212 let max_flag_len = command.signature.flags.iter().map(flag_len).max().unwrap();
4213
4214 for flag in command.signature.flags {
4215 let mut buf = [0u8; 4];
4216 let this_flag_len = flag_len(flag);
4217 write!(
4218 doc,
4219 "\n --{flag_text}{spacer:spacing$} {doc}",
4220 doc = flag.doc,
4221 // `fmt::Arguments` does not respect width controls so we must place the spacers
4222 // explicitly:
4223 spacer = "",
4224 spacing = max_flag_len - this_flag_len,
4225 flag_text = format_args!(
4226 "{}{}{}{}",
4227 flag.name,
4228 // Ideally this would be written as a `format_args!` too but the borrow
4229 // checker is not yet smart enough.
4230 if flag.alias.is_some() { "/-" } else { "" },
4231 if let Some(alias) = flag.alias {
4232 alias.encode_utf8(&mut buf)
4233 } else {
4234 ""
4235 },
4236 if flag.completions.is_some() {
4237 ARG_PLACEHOLDER
4238 } else {
4239 ""
4240 }
4241 ),
4242 )
4243 .unwrap();
4244 }
4245 }
4246
4247 Some(Cow::Owned(doc))
4248 }
4249
4250 fn complete_command_line(editor: &Editor, input: &str) -> Vec<ui::prompt::Completion> {
4251 let (command, rest, complete_command) = command_line::split(input);
4252
4253 if complete_command {
4254 fuzzy_match(
4255 input,
4256 TYPABLE_COMMAND_LIST.iter().map(|command| command.name),
4257 false,
4258 )
4259 .into_iter()
4260 .map(|(name, _)| (0.., name.into()))
4261 .collect()
4262 } else {
4263 TYPABLE_COMMAND_MAP
4264 .get(command)
4265 .map_or_else(Vec::new, |cmd| {
4266 let args_offset = command.len() + 1;
4267 complete_command_args(editor, cmd.signature, &cmd.completer, rest, args_offset)
4268 })
4269 }
4270 }
4271
4272 pub fn complete_command_args(
4273 editor: &Editor,
4274 signature: Signature,
4275 completer: &CommandCompleter,
4276 input: &str,
4277 offset: usize,
4278 ) -> Vec<ui::prompt::Completion> {
4279 use command_line::{CompletionState, ExpansionKind, Tokenizer};
4280
4281 // TODO: completion should depend on the location of the cursor instead of the end of the
4282 // string. This refactor is left for the future but the below completion code should respect
4283 // the cursor position if it becomes a parameter.
4284 let cursor = input.len();
4285 let prefix = &input[..cursor];
4286 let mut tokenizer = Tokenizer::new(prefix, false);
4287 let mut args = Args::new(signature, false);
4288 let mut final_token = None;
4289 let mut is_last_token = true;
4290
4291 while let Some(token) = args
4292 .read_token(&mut tokenizer)
4293 .expect("arg parsing cannot fail when validation is turned off")
4294 {
4295 final_token = Some(token.clone());
4296 args.push(token.content)
4297 .expect("arg parsing cannot fail when validation is turned off");
4298 if tokenizer.pos() >= cursor {
4299 is_last_token = false;
4300 }
4301 }
4302
4303 // Use a fake final token when the input is not terminated with a token. This simulates an
4304 // empty argument, causing completion on an empty value whenever you type space/tab. For
4305 // example if you say `":open README.md "` (with that trailing space) you should see the
4306 // files in the current dir - completing `""` rather than completions for `"README.md"` or
4307 // `"README.md "`.
4308 let token = if is_last_token {
4309 let token = Token::empty_at(prefix.len());
4310 args.push(token.content.clone()).unwrap();
4311 token
4312 } else {
4313 final_token.unwrap()
4314 };
4315
4316 // Don't complete on closed tokens, for example after writing a closing double quote.
4317 if token.is_terminated {
4318 return Vec::new();
4319 }
4320
4321 match token.kind {
4322 TokenKind::Unquoted | TokenKind::Quoted(_) => {
4323 match args.completion_state() {
4324 CompletionState::Positional => {
4325 // If the completion state is positional there must be at least one positional
4326 // in `args`.
4327 let n = args
4328 .len()
4329 .checked_sub(1)
4330 .expect("completion state to be positional");
4331 let completer = completer.for_argument_number(n);
4332
4333 completer(editor, &token.content)
4334 .into_iter()
4335 .map(|(range, span)| quote_completion(&token, range, span, offset))
4336 .collect()
4337 }
4338 CompletionState::Flag(_) => fuzzy_match(
4339 token.content.trim_start_matches('-'),
4340 signature.flags.iter().map(|flag| flag.name),
4341 false,
4342 )
4343 .into_iter()
4344 .map(|(name, _)| ((offset + token.content_start).., format!("--{name}").into()))
4345 .collect(),
4346 CompletionState::FlagArgument(flag) => fuzzy_match(
4347 &token.content,
4348 flag.completions
4349 .expect("flags in FlagArgument always have completions"),
4350 false,
4351 )
4352 .into_iter()
4353 .map(|(value, _)| ((offset + token.content_start).., (*value).into()))
4354 .collect(),
4355 }
4356 }
4357 TokenKind::Expand | TokenKind::Expansion(ExpansionKind::Shell) => {
4358 // See the comment about the checked sub expect above.
4359 let arg_completer = matches!(args.completion_state(), CompletionState::Positional)
4360 .then(|| {
4361 let n = args
4362 .len()
4363 .checked_sub(1)
4364 .expect("completion state to be positional");
4365 completer.for_argument_number(n)
4366 });
4367 complete_expand(editor, &token, arg_completer, offset + token.content_start)
4368 }
4369 TokenKind::Expansion(ExpansionKind::Variable) => {
4370 complete_variable_expansion(&token.content, offset + token.content_start)
4371 }
4372 TokenKind::Expansion(ExpansionKind::Unicode) => Vec::new(),
4373 TokenKind::Expansion(ExpansionKind::Register) => {
4374 complete_register_expansion(editor, &token.content, offset + token.content_start)
4375 }
4376 TokenKind::ExpansionKind => {
4377 complete_expansion_kind(&token.content, offset + token.content_start)
4378 }
4379 }
4380 }
4381
4382 /// Replace the content and optionally update the range of a positional's completion to account
4383 /// for quoting.
4384 ///
4385 /// This is used to handle completions of file or directory names for example. When completing a
4386 /// file with a space, tab or percent character in the name, the space should be escaped by
4387 /// quoting the entire token. If the token being completed is already quoted, any quotes within
4388 /// the completion text should be escaped by doubling them.
4389 fn quote_completion<'a>(
4390 token: &Token,
4391 range: ops::RangeFrom<usize>,
4392 mut span: Span<'a>,
4393 offset: usize,
4394 ) -> (ops::RangeFrom<usize>, Span<'a>) {
4395 fn replace<'a>(text: Cow<'a, str>, from: char, to: &str) -> Cow<'a, str> {
4396 if text.contains(from) {
4397 Cow::Owned(text.replace(from, to))
4398 } else {
4399 text
4400 }
4401 }
4402
4403 match token.kind {
4404 TokenKind::Unquoted if span.content.contains([' ', '\t', '%']) => {
4405 span.content = Cow::Owned(format!(
4406 "'{}{}'",
4407 // Escape any inner single quotes by doubling them.
4408 replace(token.content[..range.start].into(), '\'', "''"),
4409 replace(span.content, '\'', "''")
4410 ));
4411 // Ignore `range.start` here since we're replacing the entire token. We used
4412 // `range.start` above to emulate the replacement that using `range.start` would have
4413 // done.
4414 ((offset + token.content_start).., span)
4415 }
4416 TokenKind::Quoted(quote) => {
4417 span.content = replace(span.content, quote.char(), quote.escape());
4418 ((range.start + offset + token.content_start).., span)
4419 }
4420 TokenKind::Expand => {
4421 // NOTE: `token.content_start` is already accounted for in `offset` for `Expand`
4422 // tokens.
4423 span.content = replace(span.content, '"', "\"\"");
4424 ((range.start + offset).., span)
4425 }
4426 _ => ((range.start + offset + token.content_start).., span),
4427 }
4428 }
4429
4430 fn complete_expand(
4431 editor: &Editor,
4432 token: &Token,
4433 completer: Option<&Completer>,
4434 offset: usize,
4435 ) -> Vec<ui::prompt::Completion> {
4436 use command_line::{ExpansionKind, Tokenizer};
4437
4438 let mut start = 0;
4439
4440 // If the expand token contains expansions, complete those.
4441 while let Some(idx) = token.content[start..].find('%') {
4442 let idx = start + idx;
4443 if token.content.as_bytes().get(idx + '%'.len_utf8()).copied() == Some(b'%') {
4444 // Two percents together are skipped.
4445 start = idx + ('%'.len_utf8() * 2);
4446 } else {
4447 let mut tokenizer = Tokenizer::new(&token.content[idx..], false);
4448 let token = tokenizer
4449 .parse_percent_token()
4450 .map(|token| token.expect("arg parser cannot fail when validation is disabled"));
4451 start = idx + tokenizer.pos();
4452
4453 // Like closing quote characters in `complete_command_args` above, don't provide
4454 // completions if the token is already terminated. This also skips expansions
4455 // which have already been fully written, for example
4456 // `"%{cursor_line}:%{cursor_col` should complete `cursor_column` instead of
4457 // `cursor_line`.
4458 let Some(token) = token.filter(|t| !t.is_terminated) else {
4459 continue;
4460 };
4461
4462 let local_offset = offset + idx + token.content_start;
4463 match token.kind {
4464 TokenKind::Expansion(ExpansionKind::Variable) => {
4465 return complete_variable_expansion(&token.content, local_offset);
4466 }
4467 TokenKind::Expansion(ExpansionKind::Shell) => {
4468 return complete_expand(editor, &token, None, local_offset);
4469 }
4470 TokenKind::ExpansionKind => {
4471 return complete_expansion_kind(&token.content, local_offset);
4472 }
4473 _ => continue,
4474 }
4475 }
4476 }
4477
4478 match completer {
4479 // If no expansions were found and an argument is being completed,
4480 Some(completer) if start == 0 => completer(editor, &token.content)
4481 .into_iter()
4482 .map(|(range, span)| quote_completion(token, range, span, offset))
4483 .collect(),
4484 _ => Vec::new(),
4485 }
4486 }
4487
4488 fn complete_variable_expansion(content: &str, offset: usize) -> Vec<ui::prompt::Completion> {
4489 use expansion::Variable;
4490
4491 fuzzy_match(
4492 content,
4493 Variable::VARIANTS.iter().map(Variable::as_str),
4494 false,
4495 )
4496 .into_iter()
4497 .map(|(name, _)| (offset.., (*name).into()))
4498 .collect()
4499 }
4500
4501 fn complete_register_expansion(
4502 editor: &Editor,
4503 content: &str,
4504 offset: usize,
4505 ) -> Vec<ui::prompt::Completion> {
4506 let register_names: Vec<String> = editor
4507 .registers
4508 .iter_preview()
4509 .map(|(ch, _)| ch.to_string())
4510 .collect();
4511 fuzzy_match(content, register_names, false)
4512 .into_iter()
4513 .map(|(name, _)| (offset.., name.to_string().into()))
4514 .collect()
4515 }
4516
4517 fn complete_expansion_kind(content: &str, offset: usize) -> Vec<ui::prompt::Completion> {
4518 use command_line::ExpansionKind;
4519
4520 fuzzy_match(
4521 content,
4522 // Skip `ExpansionKind::Variable` since its kind string is empty.
4523 ExpansionKind::VARIANTS
4524 .iter()
4525 .skip(1)
4526 .map(ExpansionKind::as_str),
4527 false,
4528 )
4529 .into_iter()
4530 .map(|(name, _)| (offset.., (*name).into()))
4531 .collect()
4532 }
4533
4534 fn current_workspace(cx: &compositor::Context) -> std::path::PathBuf {
4535 let (_, doc) = current_ref!(cx.editor);
4536 doc.workspace_root().to_path_buf()
4537 }
4538
4539 /// Whether the currently focused document's workspace is trusted for git operations (gix
4540 /// `Trust::Full`).
4541 fn doc_trust_full(editor: &helix_view::Editor) -> bool {
4542 let (_, doc) = current_ref!(editor);
4543 editor
4544 .workspace_trust
4545 .query(
4546 doc.workspace_root(),
4547 helix_loader::workspace_trust::TrustQuery::Git,
4548 )
4549 .is_trusted()
4550 }
4551
4552 fn trust_workspace(
4553 cx: &mut compositor::Context,
4554 args: Args<'_>,
4555 event: PromptEvent,
4556 ) -> anyhow::Result<()> {
4557 if event != PromptEvent::Validate {
4558 return Ok(());
4559 }
4560
4561 let workspace = current_workspace(cx);
4562 cx.editor.workspace_trust.trust(&workspace);
4563
4564 cx.editor.config_events.0.send(ConfigEvent::Refresh)?;
4565 // Restart any LSPs that didn't start because trust was missing.
4566 lsp_restart(cx, args, event)
4567 }
4568
4569 fn untrust_workspace(
4570 cx: &mut compositor::Context,
4571 _args: Args<'_>,
4572 event: PromptEvent,
4573 ) -> anyhow::Result<()> {
4574 if event != PromptEvent::Validate {
4575 return Ok(());
4576 }
4577
4578 let workspace = current_workspace(cx);
4579 cx.editor.workspace_trust.untrust(&workspace);
4580 // Drop any workspace overrides that were merged into the live editor config while trust was
4581 // granted. Running LSPs are not stopped here (use `:lsp-stop` for that); this only handles
4582 // in-memory config.
4583 cx.editor.config_events.0.send(ConfigEvent::Refresh)?;
4584 Ok(())
4585 }
4586
4587 fn exclude_workspace(
4588 cx: &mut compositor::Context,
4589 _args: Args<'_>,
4590 event: PromptEvent,
4591 ) -> anyhow::Result<()> {
4592 if event != PromptEvent::Validate {
4593 return Ok(());
4594 }
4595
4596 let workspace = current_workspace(cx);
4597 cx.editor.workspace_trust.exclude(&workspace);
4598 cx.editor.config_events.0.send(ConfigEvent::Refresh)?;
4599 Ok(())
4600 }