iced_code_editor/canvas_editor/config.rs
1//! Builder-style configuration: context menu, theme/language, Vim toggle,
2//! wrap/whitespace/bracket/folding-enabled flags, auto-indent, auto-close
3//! brackets, indent style, search/replace enablement, and line numbers.
4
5use crate::canvas_editor::features::context_menu::{
6 ContextMenuEntry, ContextMenuItem,
7};
8use crate::canvas_editor::features::vim::VimMode;
9use crate::canvas_editor::{CodeEditor, IndentStyle};
10use crate::theme::Style;
11
12impl CodeEditor {
13 /// Replaces the custom context-menu entries.
14 ///
15 /// Custom entries are shown in addition to the built-in editing actions;
16 /// see [`Self::set_default_context_menu_enabled`] to hide those.
17 ///
18 /// # Arguments
19 ///
20 /// * `entries` - The entries to display, in order
21 ///
22 /// # Example
23 ///
24 /// ```
25 /// use iced_code_editor::{CodeEditor, ContextMenuEntry};
26 ///
27 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
28 /// editor.set_custom_context_menu_entries(vec![
29 /// ContextMenuEntry::item("format", "Format Document")
30 /// .with_shortcut("Ctrl+Shift+F"),
31 /// ContextMenuEntry::separator(),
32 /// ContextMenuEntry::item("rename", "Rename Symbol").with_enabled(false),
33 /// ]);
34 /// assert_eq!(editor.custom_context_menu_entries().len(), 3);
35 /// ```
36 pub fn set_custom_context_menu_entries(
37 &mut self,
38 entries: Vec<ContextMenuEntry>,
39 ) {
40 self.custom_context_menu_entries = entries;
41 }
42
43 /// Replaces the custom context-menu entries using the builder pattern.
44 ///
45 /// # Arguments
46 ///
47 /// * `entries` - The entries to display, in order
48 ///
49 /// # Returns
50 ///
51 /// Self for method chaining
52 ///
53 /// # Example
54 ///
55 /// ```
56 /// use iced_code_editor::{CodeEditor, ContextMenuEntry};
57 ///
58 /// let editor = CodeEditor::new("fn main() {}", "rs")
59 /// .with_custom_context_menu_entries(vec![
60 /// ContextMenuEntry::item("format", "Format Document"),
61 /// ]);
62 /// assert_eq!(editor.custom_context_menu_entries().len(), 1);
63 /// ```
64 #[must_use]
65 pub fn with_custom_context_menu_entries(
66 mut self,
67 entries: Vec<ContextMenuEntry>,
68 ) -> Self {
69 self.set_custom_context_menu_entries(entries);
70 self
71 }
72
73 /// Returns the custom context-menu entries in display order.
74 ///
75 /// # Returns
76 ///
77 /// The entries previously set, or an empty slice if none were set
78 ///
79 /// # Example
80 ///
81 /// ```
82 /// use iced_code_editor::CodeEditor;
83 ///
84 /// let editor = CodeEditor::new("fn main() {}", "rs");
85 /// assert!(editor.custom_context_menu_entries().is_empty());
86 /// ```
87 pub fn custom_context_menu_entries(&self) -> &[ContextMenuEntry] {
88 &self.custom_context_menu_entries
89 }
90
91 /// Sets whether the built-in editing actions appear in the context menu.
92 ///
93 /// The built-in actions are undo/redo, cut/copy/paste, and select all.
94 /// Disabling them leaves only the custom entries, which is how a host
95 /// application replaces the menu wholesale rather than extending it.
96 ///
97 /// # Arguments
98 ///
99 /// * `enabled` - Whether to show the built-in actions
100 ///
101 /// # Example
102 ///
103 /// ```
104 /// use iced_code_editor::CodeEditor;
105 ///
106 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
107 /// editor.set_default_context_menu_enabled(false);
108 /// assert!(!editor.default_context_menu_enabled());
109 /// ```
110 pub fn set_default_context_menu_enabled(&mut self, enabled: bool) {
111 self.default_context_menu_enabled = enabled;
112 }
113
114 /// Replaces the custom command-palette entries.
115 ///
116 /// Custom commands are listed before the built-in editor commands; see
117 /// [`Self::set_default_command_palette_enabled`] to hide those. Running
118 /// one emits [`Message::CommandPaletteAction`] carrying the entry's `id`,
119 /// which the host application handles — the editor never acts on it.
120 ///
121 /// Entries created with `with_enabled(false)` are left out of the list
122 /// entirely rather than dimmed: the palette is a search result list, so
123 /// every row it offers should be runnable.
124 ///
125 /// # Arguments
126 ///
127 /// * `entries` - The commands to list, in order
128 ///
129 /// # Example
130 ///
131 /// ```
132 /// use iced_code_editor::{CodeEditor, ContextMenuItem};
133 ///
134 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
135 /// editor.set_custom_command_palette_entries(vec![
136 /// ContextMenuItem::new("app.open_file", "Open File")
137 /// .with_shortcut("Ctrl+O"),
138 /// ContextMenuItem::new("app.new_tab", "New Tab"),
139 /// ]);
140 /// assert_eq!(editor.custom_command_palette_entries().len(), 2);
141 /// ```
142 ///
143 /// [`Message::CommandPaletteAction`]: crate::Message::CommandPaletteAction
144 pub fn set_custom_command_palette_entries(
145 &mut self,
146 entries: Vec<ContextMenuItem>,
147 ) {
148 self.custom_command_palette_entries = entries;
149 }
150
151 /// Replaces the custom command-palette entries using the builder pattern.
152 ///
153 /// # Arguments
154 ///
155 /// * `entries` - The commands to list, in order
156 ///
157 /// # Returns
158 ///
159 /// Self for method chaining
160 ///
161 /// # Example
162 ///
163 /// ```
164 /// use iced_code_editor::{CodeEditor, ContextMenuItem};
165 ///
166 /// let editor = CodeEditor::new("fn main() {}", "rs")
167 /// .with_custom_command_palette_entries(vec![
168 /// ContextMenuItem::new("app.open_file", "Open File"),
169 /// ]);
170 /// assert_eq!(editor.custom_command_palette_entries().len(), 1);
171 /// ```
172 #[must_use]
173 pub fn with_custom_command_palette_entries(
174 mut self,
175 entries: Vec<ContextMenuItem>,
176 ) -> Self {
177 self.set_custom_command_palette_entries(entries);
178 self
179 }
180
181 /// Returns the custom command-palette entries in display order.
182 ///
183 /// # Returns
184 ///
185 /// The entries previously set, or an empty slice if none were set
186 ///
187 /// # Example
188 ///
189 /// ```
190 /// use iced_code_editor::CodeEditor;
191 ///
192 /// let editor = CodeEditor::new("fn main() {}", "rs");
193 /// assert!(editor.custom_command_palette_entries().is_empty());
194 /// ```
195 pub fn custom_command_palette_entries(&self) -> &[ContextMenuItem] {
196 &self.custom_command_palette_entries
197 }
198
199 /// Sets whether the built-in editor commands are listed in the palette.
200 ///
201 /// Disabling them leaves only the custom entries, which is how a host
202 /// application takes the palette over rather than extending it.
203 ///
204 /// # Arguments
205 ///
206 /// * `enabled` - Whether to list the built-in commands
207 ///
208 /// # Example
209 ///
210 /// ```
211 /// use iced_code_editor::CodeEditor;
212 ///
213 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
214 /// editor.set_default_command_palette_enabled(false);
215 /// assert!(!editor.default_command_palette_enabled());
216 /// ```
217 pub fn set_default_command_palette_enabled(&mut self, enabled: bool) {
218 self.default_command_palette_enabled = enabled;
219 }
220
221 /// Sets built-in command visibility using the builder pattern.
222 ///
223 /// # Arguments
224 ///
225 /// * `enabled` - Whether to list the built-in commands
226 ///
227 /// # Returns
228 ///
229 /// Self for method chaining
230 ///
231 /// # Example
232 ///
233 /// ```
234 /// use iced_code_editor::CodeEditor;
235 ///
236 /// let editor = CodeEditor::new("fn main() {}", "rs")
237 /// .with_default_command_palette_enabled(false);
238 /// assert!(!editor.default_command_palette_enabled());
239 /// ```
240 #[must_use]
241 pub fn with_default_command_palette_enabled(
242 mut self,
243 enabled: bool,
244 ) -> Self {
245 self.set_default_command_palette_enabled(enabled);
246 self
247 }
248
249 /// Sets whether the command palette can be opened.
250 ///
251 /// Turning it off makes `Ctrl/Cmd+Shift+P` and
252 /// [`CodeEditor::open_command_palette`] no-ops, freeing the shortcut for
253 /// a host application that provides its own palette.
254 ///
255 /// # Arguments
256 ///
257 /// * `enabled` - Whether the palette can be opened
258 ///
259 /// # Example
260 ///
261 /// ```
262 /// use iced_code_editor::CodeEditor;
263 ///
264 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
265 /// editor.set_command_palette_enabled(false);
266 /// assert!(!editor.command_palette_enabled());
267 /// ```
268 pub fn set_command_palette_enabled(&mut self, enabled: bool) {
269 self.command_palette_enabled = enabled;
270 if !enabled {
271 self.command_palette_state.close();
272 }
273 }
274
275 /// Sets whether the built-in reveal-in-file-manager action is shown.
276 ///
277 /// The action is only useful when the host application knows the file path
278 /// backing the editor, so it is off by default and the host opts in.
279 ///
280 /// # Arguments
281 ///
282 /// * `enabled` - Whether to show the reveal action
283 ///
284 /// # Example
285 ///
286 /// ```
287 /// use iced_code_editor::CodeEditor;
288 ///
289 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
290 /// editor.set_reveal_in_file_manager_enabled(true);
291 /// assert!(editor.reveal_in_file_manager_enabled());
292 /// ```
293 pub fn set_reveal_in_file_manager_enabled(&mut self, enabled: bool) {
294 self.reveal_in_file_manager_enabled = enabled;
295 }
296
297 /// Sets reveal-in-file-manager visibility using the builder pattern.
298 ///
299 /// # Arguments
300 ///
301 /// * `enabled` - Whether to show the reveal action
302 ///
303 /// # Returns
304 ///
305 /// Self for method chaining
306 ///
307 /// # Example
308 ///
309 /// ```
310 /// use iced_code_editor::CodeEditor;
311 ///
312 /// let editor = CodeEditor::new("fn main() {}", "rs")
313 /// .with_reveal_in_file_manager_enabled(true);
314 /// assert!(editor.reveal_in_file_manager_enabled());
315 /// ```
316 #[must_use]
317 pub fn with_reveal_in_file_manager_enabled(
318 mut self,
319 enabled: bool,
320 ) -> Self {
321 self.set_reveal_in_file_manager_enabled(enabled);
322 self
323 }
324
325 /// Enables or disables Vim behavior for this editor instance.
326 ///
327 /// Changing this setting enters a clean Normal mode without modifying the
328 /// buffer or command history. Any secondary cursors are collapsed onto the
329 /// primary one, since Vim owns its own selection model.
330 ///
331 /// # Arguments
332 ///
333 /// * `enabled` - Whether to enable Vim behavior
334 ///
335 /// # Example
336 ///
337 /// ```
338 /// use iced_code_editor::{CodeEditor, VimMode};
339 ///
340 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
341 /// editor.set_vim_enabled(true);
342 ///
343 /// // Vim always starts in Normal mode.
344 /// assert_eq!(editor.vim_mode(), Some(VimMode::Normal));
345 /// ```
346 pub fn set_vim_enabled(&mut self, enabled: bool) {
347 if self.is_grouping {
348 self.history.end_group();
349 self.is_grouping = false;
350 }
351 self.vim_enabled = enabled;
352 self.vim_state.enter_clean_normal_mode();
353 self.cursors.remove_all_but_primary();
354 let position = if enabled {
355 self.vim_normal_position(self.cursors.primary_position())
356 } else {
357 self.cursors.primary_position()
358 };
359 self.cursors.set_single(position);
360 self.is_dragging = false;
361 self.overlay_cache.clear();
362 }
363
364 /// Returns the active Vim mode, or `None` when Vim behavior is disabled.
365 ///
366 /// Use this to drive a mode indicator in the host application's status bar.
367 ///
368 /// # Returns
369 ///
370 /// `Some(mode)` when Vim is enabled, `None` otherwise
371 ///
372 /// # Example
373 ///
374 /// ```
375 /// use iced_code_editor::{CodeEditor, VimMode};
376 ///
377 /// let editor = CodeEditor::new("fn main() {}", "rs");
378 /// // `None` rather than a default mode, so a status bar can tell
379 /// // "Vim is off" apart from "Vim is in Normal mode".
380 /// assert_eq!(editor.vim_mode(), None);
381 ///
382 /// let editor = editor.with_vim_enabled(true);
383 /// assert_eq!(editor.vim_mode(), Some(VimMode::Normal));
384 /// ```
385 pub fn vim_mode(&self) -> Option<VimMode> {
386 self.vim_enabled.then(|| self.vim_state.mode())
387 }
388
389 /// Sets the theme style for the editor.
390 ///
391 /// # Arguments
392 ///
393 /// * `style` - The style to apply to the editor
394 ///
395 /// # Example
396 ///
397 /// ```
398 /// use iced_code_editor::{CodeEditor, theme};
399 ///
400 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
401 /// editor.set_theme(theme::from_iced_theme(&iced::Theme::TokyoNightStorm));
402 /// ```
403 pub fn set_theme(&mut self, style: Style) {
404 self.style = style;
405 // The highlight cache stores resolved colors, not scopes, and the
406 // syntect palette is picked from the style's background lightness
407 // (see `CodeEditor::resolve_syntax`). A theme change can therefore
408 // flip light/dark and invalidate every cached span.
409 self.invalidate_highlight_from(0);
410 self.content_cache.clear();
411 self.overlay_cache.clear();
412 }
413
414 /// Sets the language for UI translations.
415 ///
416 /// This changes the language used for all UI text elements in the editor,
417 /// including search dialog tooltips, placeholders, and labels.
418 ///
419 /// # Arguments
420 ///
421 /// * `language` - The language to use for UI text
422 ///
423 /// # Example
424 ///
425 /// ```
426 /// use iced_code_editor::{CodeEditor, Language};
427 ///
428 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
429 /// editor.set_language(Language::French);
430 /// ```
431 pub fn set_language(&mut self, language: crate::i18n::Language) {
432 self.translations.set_language(language);
433 self.overlay_cache.clear();
434 }
435
436 /// Returns the current UI language.
437 ///
438 /// # Returns
439 ///
440 /// The currently active language for UI text
441 ///
442 /// # Example
443 ///
444 /// ```
445 /// use iced_code_editor::{CodeEditor, Language};
446 ///
447 /// let editor = CodeEditor::new("fn main() {}", "rs");
448 /// let current_lang = editor.language();
449 /// ```
450 pub fn language(&self) -> crate::i18n::Language {
451 self.translations.language()
452 }
453
454 /// Sets whether line wrapping is enabled.
455 ///
456 /// When enabled, long lines will wrap at the viewport width or at a
457 /// configured column width.
458 ///
459 /// # Arguments
460 ///
461 /// * `enabled` - Whether to enable line wrapping
462 ///
463 /// # Example
464 ///
465 /// ```
466 /// use iced_code_editor::CodeEditor;
467 ///
468 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
469 /// editor.set_wrap_enabled(false); // Disable wrapping
470 /// ```
471 pub fn set_wrap_enabled(&mut self, enabled: bool) {
472 if self.wrap_enabled != enabled {
473 self.wrap_enabled = enabled;
474 if enabled {
475 self.horizontal_scroll_offset = 0.0;
476 }
477 self.content_cache.clear();
478 self.overlay_cache.clear();
479 }
480 }
481
482 /// Enables or disables visible whitespace rendering.
483 ///
484 /// When enabled, space characters are rendered as `·` and tab characters
485 /// as `→`, both drawn in a dimmed color to remain non-intrusive. Toggling
486 /// this setting clears the content cache to trigger an immediate redraw.
487 ///
488 /// # Arguments
489 ///
490 /// * `enabled` - Whether to show whitespace characters
491 ///
492 /// # Example
493 ///
494 /// ```
495 /// use iced_code_editor::CodeEditor;
496 ///
497 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
498 /// editor.set_show_whitespace(true);
499 /// ```
500 pub fn set_show_whitespace(&mut self, enabled: bool) {
501 if self.show_whitespace != enabled {
502 self.show_whitespace = enabled;
503 self.content_cache.clear();
504 }
505 }
506
507 /// Enables or disables indentation guides.
508 ///
509 /// Indentation guides are faint vertical lines drawn at every indentation
510 /// level, making the nesting of a block visible at a glance. Their spacing
511 /// follows [`CodeEditor::indent_style`]. Toggling this setting clears the
512 /// content cache to trigger an immediate redraw.
513 ///
514 /// # Arguments
515 ///
516 /// * `enabled` - Whether to draw indentation guides
517 ///
518 /// # Example
519 ///
520 /// ```
521 /// use iced_code_editor::CodeEditor;
522 ///
523 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
524 /// editor.set_show_indent_guides(false);
525 /// ```
526 pub fn set_show_indent_guides(&mut self, enabled: bool) {
527 if self.show_indent_guides != enabled {
528 self.show_indent_guides = enabled;
529 self.content_cache.clear();
530 }
531 }
532
533 /// Enables or disables inline color previews.
534 ///
535 /// An inline color preview is a small square drawn just after a color
536 /// literal — `#1e1e2e`, `0xFF6B6B`, `rgb(58, 123, 213)` — filled with the
537 /// color the literal denotes, so a palette can be read without decoding
538 /// hexadecimal by eye. Toggling this setting clears the content cache to
539 /// trigger an immediate redraw.
540 ///
541 /// # Arguments
542 ///
543 /// * `enabled` - Whether to draw color-preview swatches
544 ///
545 /// # Example
546 ///
547 /// ```
548 /// use iced_code_editor::CodeEditor;
549 ///
550 /// let mut editor = CodeEditor::new("body { color: #f0c; }", "css");
551 /// editor.set_show_color_previews(false);
552 /// ```
553 pub fn set_show_color_previews(&mut self, enabled: bool) {
554 if self.show_color_previews != enabled {
555 self.show_color_previews = enabled;
556 self.content_cache.clear();
557 }
558 }
559
560 /// Enables or disables sticky scroll.
561 ///
562 /// Sticky scroll pins the header lines of the blocks enclosing the topmost
563 /// visible line to the top of the viewport, so the structural context stays
564 /// readable while scrolling deep inside a long block. Clicking a pinned
565 /// header scrolls back to it. Enclosing blocks are detected from
566 /// indentation, exactly like code folding, so the feature is
567 /// language-agnostic but follows the file's indentation rather than its
568 /// syntax tree.
569 ///
570 /// Independent of [`CodeEditor::set_folding_enabled`], despite sharing that
571 /// detection: turning code folding off removes the fold chevrons and leaves
572 /// the pinned headers alone.
573 ///
574 /// # Arguments
575 ///
576 /// * `enabled` - Whether to pin enclosing block headers above the viewport
577 ///
578 /// # Example
579 ///
580 /// ```
581 /// use iced_code_editor::CodeEditor;
582 ///
583 /// let mut editor = CodeEditor::new("fn main() {\n let x = 1;\n}", "rs");
584 /// editor.set_sticky_scroll_enabled(false);
585 /// ```
586 pub fn set_sticky_scroll_enabled(&mut self, enabled: bool) {
587 self.sticky_scroll_enabled = enabled;
588 }
589
590 /// Enables or disables the matching-bracket/quote-pair highlight overlay.
591 ///
592 /// When enabled, placing the cursor next to a bracket (`(`, `)`, `[`,
593 /// `]`, `{`, `}`) or a quote (`"`, `'`) highlights it and its matching
594 /// pair. When disabled, no matching scan or highlight is performed.
595 ///
596 /// # Arguments
597 ///
598 /// * `enabled` - Whether to enable the bracket/quote-matching highlight
599 ///
600 /// # Example
601 ///
602 /// ```
603 /// use iced_code_editor::CodeEditor;
604 ///
605 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
606 /// editor.set_bracket_match_highlight_enabled(false); // Disable
607 /// ```
608 pub fn set_bracket_match_highlight_enabled(&mut self, enabled: bool) {
609 if self.bracket_match_highlight_enabled != enabled {
610 self.bracket_match_highlight_enabled = enabled;
611 self.overlay_cache.clear();
612 }
613 }
614
615 /// Enables or disables bracket-pair colorization (rainbow brackets).
616 ///
617 /// When enabled, each `( ) [ ] { }` is colored by its nesting depth, so a
618 /// matching pair always shares the same color, cycling through a fixed
619 /// palette as depth increases. When disabled, brackets render with their
620 /// normal syntax-highlight color.
621 ///
622 /// # Arguments
623 ///
624 /// * `enabled` - Whether to enable bracket-pair colorization
625 ///
626 /// # Example
627 ///
628 /// ```
629 /// use iced_code_editor::CodeEditor;
630 ///
631 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
632 /// editor.set_bracket_pair_colorization_enabled(false); // Disable
633 /// ```
634 pub fn set_bracket_pair_colorization_enabled(&mut self, enabled: bool) {
635 if self.bracket_pair_colorization_enabled != enabled {
636 self.bracket_pair_colorization_enabled = enabled;
637 self.content_cache.clear();
638 }
639 }
640
641 /// Enables or disables code folding (collapse/expand blocks).
642 ///
643 /// When disabled, no fold chevrons are drawn and all lines are shown
644 /// regardless of the collapsed state (which is preserved, so re-enabling
645 /// restores the previously collapsed blocks).
646 ///
647 /// # Arguments
648 ///
649 /// * `enabled` - Whether to enable code folding
650 ///
651 /// # Example
652 ///
653 /// ```
654 /// use iced_code_editor::CodeEditor;
655 ///
656 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
657 /// editor.set_folding_enabled(true);
658 /// ```
659 pub fn set_folding_enabled(&mut self, enabled: bool) {
660 if self.folding_enabled != enabled {
661 self.folding_enabled = enabled;
662 self.bump_fold_revision();
663 }
664 }
665
666 /// Enables or disables automatic indentation on Enter.
667 ///
668 /// When enabled, pressing Enter copies the leading whitespace of the
669 /// current line to the new line. When disabled, the cursor is placed
670 /// at column 0 on the new line.
671 ///
672 /// # Arguments
673 ///
674 /// * `enabled` - `true` to enable auto-indentation, `false` to disable
675 ///
676 /// # Example
677 ///
678 /// ```
679 /// use iced_code_editor::CodeEditor;
680 ///
681 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
682 /// editor.set_auto_indent_enabled(false);
683 /// assert!(!editor.auto_indent_enabled());
684 /// ```
685 pub fn set_auto_indent_enabled(&mut self, enabled: bool) {
686 self.auto_indent_enabled = enabled;
687 }
688
689 /// Enables or disables auto-closing of brackets and quotes.
690 ///
691 /// When enabled, typing an opening bracket/quote (`(`, `[`, `{`, `"`,
692 /// `'`) auto-inserts its matching closing character with the cursor
693 /// placed between them, typing the closing character right before an
694 /// already-inserted match moves the cursor past it instead of
695 /// duplicating it, and typing an opening bracket/quote while text is
696 /// selected wraps the selection in the pair instead of replacing it.
697 ///
698 /// # Arguments
699 ///
700 /// * `enabled` - `true` to enable auto-closing, `false` to disable
701 ///
702 /// # Example
703 ///
704 /// ```
705 /// use iced_code_editor::CodeEditor;
706 ///
707 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
708 /// editor.set_auto_close_brackets(false); // Disable auto-closing
709 /// ```
710 pub fn set_auto_close_brackets(&mut self, enabled: bool) {
711 self.auto_close_brackets = enabled;
712 }
713
714 /// Sets the indentation style used when pressing the Tab key.
715 ///
716 /// # Arguments
717 ///
718 /// * `style` - The indentation style (`IndentStyle::Spaces(n)` or `IndentStyle::Tab`)
719 ///
720 /// # Example
721 ///
722 /// ```
723 /// use iced_code_editor::{CodeEditor, IndentStyle};
724 ///
725 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
726 ///
727 /// // Indent with a real tab character instead of the default 4 spaces.
728 /// editor.set_indent_style(IndentStyle::Tab);
729 /// assert_eq!(editor.indent_style(), IndentStyle::Tab);
730 ///
731 /// // Or pick a different space width.
732 /// editor.set_indent_style(IndentStyle::Spaces(2));
733 /// assert_eq!(editor.indent_style(), IndentStyle::Spaces(2));
734 /// ```
735 pub fn set_indent_style(&mut self, style: IndentStyle) {
736 self.indent_style = style;
737 }
738
739 /// Returns the current indentation style.
740 ///
741 /// # Returns
742 ///
743 /// The current [`IndentStyle`] configured for this editor
744 ///
745 /// # Example
746 ///
747 /// ```
748 /// use iced_code_editor::{CodeEditor, IndentStyle};
749 ///
750 /// let editor = CodeEditor::new("fn main() {}", "rs");
751 /// assert_eq!(editor.indent_style(), IndentStyle::Spaces(4));
752 /// ```
753 pub fn indent_style(&self) -> IndentStyle {
754 self.indent_style
755 }
756
757 /// Enables or disables the search/replace functionality.
758 ///
759 /// When disabled, search/replace keyboard shortcuts (Ctrl+F, Ctrl+H, F3)
760 /// will be ignored. If the search dialog is currently open, it will be closed.
761 ///
762 /// # Arguments
763 ///
764 /// * `enabled` - Whether to enable search/replace functionality
765 ///
766 /// # Example
767 ///
768 /// ```
769 /// use iced_code_editor::CodeEditor;
770 ///
771 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
772 /// editor.set_search_replace_enabled(false); // Disable search/replace
773 /// ```
774 pub fn set_search_replace_enabled(&mut self, enabled: bool) {
775 self.search_replace_enabled = enabled;
776 if !enabled && self.search_state.is_open {
777 self.search_state.close();
778 }
779 }
780
781 /// Returns the syntax highlighting language identifier for this editor.
782 ///
783 /// This is the language key passed at construction (e.g., `"lua"`, `"rs"`, `"py"`).
784 ///
785 /// # Examples
786 ///
787 /// ```
788 /// use iced_code_editor::CodeEditor;
789 /// let editor = CodeEditor::new("fn main() {}", "rs");
790 /// assert_eq!(editor.syntax(), "rs");
791 /// ```
792 pub fn syntax(&self) -> &str {
793 &self.syntax
794 }
795
796 /// Returns the display name of the grammar actually used to highlight
797 /// this editor's content.
798 ///
799 /// [`CodeEditor::syntax`] returns the raw identifier the host set; this
800 /// returns what the highlighter resolved it to, so it also reports the
801 /// plain-text fallback when no grammar matches. It is the value to show in
802 /// a status bar: it tells the user which language the editor is really
803 /// coloring with, not which one was requested.
804 ///
805 /// # Returns
806 ///
807 /// The grammar's name (e.g. `"Rust"`, `"Lua"`, `"Plain Text"`).
808 ///
809 /// # Example
810 ///
811 /// ```
812 /// use iced_code_editor::CodeEditor;
813 ///
814 /// let editor = CodeEditor::new("fn main() {}", "rs");
815 /// assert_eq!(editor.syntax_name(), "Rust");
816 ///
817 /// // An identifier no bundled grammar matches degrades to plain text.
818 /// let unknown = CodeEditor::new("...", "no-such-language");
819 /// assert_eq!(unknown.syntax_name(), "Plain Text");
820 /// ```
821 pub fn syntax_name(&self) -> &'static str {
822 let (_, syntax, _) = self.resolve_syntax();
823 syntax.map_or("Plain Text", |syntax| syntax.name.as_str())
824 }
825
826 /// Sets the syntax highlighting language identifier for this editor.
827 ///
828 /// Use this when the content a single editor shows changes language --
829 /// typically after opening or saving a file under a different extension.
830 /// The identifier is the same key [`CodeEditor::new`] takes: a file
831 /// extension (`"rs"`, `"py"`, `"toml"`) or one of the aliases
832 /// `resolve_syntax` normalizes (`"rust"`, `"python"`, `"markdown"`, ...).
833 /// An unknown identifier falls back to plain text rather than losing the
834 /// content.
835 ///
836 /// Changing the identifier drops the cached per-line highlighting, so the
837 /// visible lines are re-tokenized on the next render. Setting the current
838 /// identifier again does nothing.
839 ///
840 /// # Arguments
841 ///
842 /// * `syntax` - Syntax highlighting language identifier (e.g. `"rs"`)
843 ///
844 /// # Example
845 ///
846 /// ```
847 /// use iced_code_editor::CodeEditor;
848 ///
849 /// let mut editor = CodeEditor::new("-- comment", "lua");
850 /// assert_eq!(editor.syntax(), "lua");
851 ///
852 /// editor.set_syntax("rs");
853 /// assert_eq!(editor.syntax(), "rs");
854 /// ```
855 pub fn set_syntax(&mut self, syntax: &str) {
856 if self.syntax == syntax {
857 return;
858 }
859
860 self.syntax.clear();
861 self.syntax.push_str(syntax);
862 // `highlighted_line_cached` rebuilds `HighlightCache` on its own when
863 // the active syntax no longer matches, so only the canvas needs an
864 // explicit redraw here.
865 self.content_cache.clear();
866 }
867
868 /// Sets the wrap column (fixed width wrapping).
869 ///
870 /// When set to `Some(n)`, lines will wrap at column `n`.
871 /// When set to `None`, lines will wrap at the viewport width.
872 ///
873 /// # Arguments
874 ///
875 /// * `column` - The column to wrap at, or None for viewport-based wrapping
876 ///
877 /// # Example
878 ///
879 /// ```
880 /// use iced_code_editor::CodeEditor;
881 ///
882 /// let editor = CodeEditor::new("fn main() {}", "rs")
883 /// .with_wrap_column(Some(80)); // Wrap at 80 characters
884 /// ```
885 #[must_use]
886 pub fn with_wrap_column(mut self, column: Option<usize>) -> Self {
887 self.wrap_column = column;
888 self
889 }
890
891 /// Sets whether line numbers are displayed.
892 ///
893 /// When disabled, the gutter is completely removed (0px width),
894 /// providing more space for code display.
895 ///
896 /// # Arguments
897 ///
898 /// * `enabled` - Whether to display line numbers
899 ///
900 /// # Example
901 ///
902 /// ```
903 /// use iced_code_editor::CodeEditor;
904 ///
905 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
906 /// editor.set_line_numbers_enabled(false); // Hide line numbers
907 /// ```
908 pub fn set_line_numbers_enabled(&mut self, enabled: bool) {
909 if self.line_numbers_enabled != enabled {
910 self.line_numbers_enabled = enabled;
911 self.content_cache.clear();
912 self.overlay_cache.clear();
913 }
914 }
915}
916
917#[cfg(test)]
918mod tests {
919 use super::*;
920 use crate::canvas_editor::features::context_menu::ContextMenuItem;
921 use crate::canvas_editor::features::vim;
922
923 #[test]
924 fn test_custom_context_menu_configuration() {
925 let custom_entries = vec![
926 ContextMenuEntry::item("format", "Format document")
927 .with_shortcut("Shift+Alt+F"),
928 ContextMenuEntry::separator(),
929 ContextMenuEntry::Item(
930 ContextMenuItem::new("rename", "Rename symbol")
931 .with_enabled(false),
932 ),
933 ];
934
935 let editor = CodeEditor::new("", "rs")
936 .with_custom_context_menu_entries(custom_entries.clone())
937 .with_default_context_menu_enabled(false);
938
939 assert_eq!(editor.custom_context_menu_entries(), custom_entries);
940 assert!(!editor.default_context_menu_enabled());
941
942 let default_editor = CodeEditor::new("", "rs");
943 assert!(default_editor.custom_context_menu_entries().is_empty());
944 assert!(default_editor.default_context_menu_enabled());
945 }
946
947 #[test]
948 fn test_reveal_in_file_manager_configuration() {
949 let mut editor = CodeEditor::new("", "rs");
950 assert!(!editor.reveal_in_file_manager_enabled());
951
952 editor.set_reveal_in_file_manager_enabled(true);
953 assert!(editor.reveal_in_file_manager_enabled());
954
955 let editor =
956 CodeEditor::new("", "rs").with_reveal_in_file_manager_enabled(true);
957 assert!(editor.reveal_in_file_manager_enabled());
958 }
959
960 #[test]
961 fn test_auto_close_brackets_configuration() {
962 let mut editor = CodeEditor::new("", "rs");
963 assert!(editor.auto_close_brackets());
964
965 editor.set_auto_close_brackets(false);
966 assert!(!editor.auto_close_brackets());
967
968 editor.set_auto_close_brackets(true);
969 assert!(editor.auto_close_brackets());
970 }
971
972 #[test]
973 fn test_bracket_match_highlight_configuration() {
974 let mut editor = CodeEditor::new("", "rs");
975 assert!(editor.bracket_match_highlight_enabled());
976
977 editor.set_bracket_match_highlight_enabled(false);
978 assert!(!editor.bracket_match_highlight_enabled());
979
980 editor.set_bracket_match_highlight_enabled(true);
981 assert!(editor.bracket_match_highlight_enabled());
982 }
983
984 #[test]
985 fn test_bracket_pair_colorization_configuration() {
986 let mut editor = CodeEditor::new("", "rs");
987 assert!(editor.bracket_pair_colorization_enabled());
988
989 editor.set_bracket_pair_colorization_enabled(false);
990 assert!(!editor.bracket_pair_colorization_enabled());
991
992 editor.set_bracket_pair_colorization_enabled(true);
993 assert!(editor.bracket_pair_colorization_enabled());
994 }
995
996 #[test]
997 fn test_show_indent_guides_configuration() {
998 let mut editor = CodeEditor::new("", "rs");
999 assert!(editor.show_indent_guides());
1000
1001 editor.set_show_indent_guides(false);
1002 assert!(!editor.show_indent_guides());
1003
1004 editor.set_show_indent_guides(true);
1005 assert!(editor.show_indent_guides());
1006
1007 let editor = CodeEditor::new("", "rs").with_show_indent_guides(false);
1008 assert!(!editor.show_indent_guides());
1009 }
1010
1011 #[test]
1012 fn test_show_color_previews_configuration() {
1013 let mut editor = CodeEditor::new("", "rs");
1014 assert!(editor.show_color_previews());
1015
1016 editor.set_show_color_previews(false);
1017 assert!(!editor.show_color_previews());
1018
1019 editor.set_show_color_previews(true);
1020 assert!(editor.show_color_previews());
1021
1022 let editor = CodeEditor::new("", "rs").with_show_color_previews(false);
1023 assert!(!editor.show_color_previews());
1024 }
1025
1026 #[test]
1027 fn vim_disabled_by_default() {
1028 let editor = CodeEditor::new("unchanged", "rs");
1029
1030 assert!(!editor.vim_enabled());
1031 assert_eq!(editor.vim_mode(), None);
1032 assert_eq!(editor.content(), "unchanged");
1033 assert!(!editor.can_undo());
1034 assert!(!editor.can_redo());
1035 }
1036
1037 #[test]
1038 fn vim_enable_enters_clean_normal_mode() {
1039 let mut editor = CodeEditor::new("unchanged", "rs");
1040 assert_eq!(editor.vim_state.parse_key('9'), None);
1041 assert_eq!(editor.vim_state.parse_key('d'), None);
1042
1043 editor.set_vim_enabled(true);
1044
1045 assert!(editor.vim_enabled());
1046 assert_eq!(editor.vim_mode(), Some(VimMode::Normal));
1047 assert_eq!(
1048 editor.vim_state.parse_key('l'),
1049 Some(vim::VimAction::Motion {
1050 motion: vim::VimMotion::Right,
1051 count: 1,
1052 explicit_count: false,
1053 })
1054 );
1055 assert_eq!(editor.content(), "unchanged");
1056 assert!(!editor.can_undo());
1057 assert!(!editor.can_redo());
1058 }
1059
1060 #[test]
1061 fn vim_disable_clears_pending_state() {
1062 let mut editor =
1063 CodeEditor::new("unchanged", "rs").with_vim_enabled(true);
1064 assert_eq!(editor.vim_state.parse_key('4'), None);
1065 assert_eq!(editor.vim_state.parse_key('d'), None);
1066
1067 editor.set_vim_enabled(false);
1068 assert!(!editor.vim_enabled());
1069 assert_eq!(editor.vim_mode(), None);
1070
1071 editor.set_vim_enabled(true);
1072 assert_eq!(
1073 editor.vim_state.parse_key('w'),
1074 Some(vim::VimAction::Motion {
1075 motion: vim::VimMotion::WordForward,
1076 count: 1,
1077 explicit_count: false,
1078 })
1079 );
1080 assert_eq!(editor.content(), "unchanged");
1081 assert!(!editor.can_undo());
1082 assert!(!editor.can_redo());
1083 }
1084
1085 #[test]
1086 fn vim_reset_clears_pending_state() {
1087 let mut editor = CodeEditor::new("before", "rs").with_vim_enabled(true);
1088 assert_eq!(editor.vim_state.parse_key('3'), None);
1089 assert_eq!(editor.vim_state.parse_key('g'), None);
1090
1091 let _ = editor.reset("after");
1092
1093 assert_eq!(editor.vim_mode(), Some(VimMode::Normal));
1094 assert_eq!(editor.vim_state.parse_key('g'), None);
1095 assert_eq!(
1096 editor.vim_state.parse_key('g'),
1097 Some(vim::VimAction::Motion {
1098 motion: vim::VimMotion::DocumentStart,
1099 count: 1,
1100 explicit_count: false,
1101 })
1102 );
1103 assert_eq!(editor.content(), "after");
1104 assert!(!editor.can_undo());
1105 assert!(!editor.can_redo());
1106 }
1107
1108 #[test]
1109 fn test_syntax_getter() {
1110 let editor = CodeEditor::new("", "lua");
1111 assert_eq!(editor.syntax(), "lua");
1112 }
1113
1114 #[test]
1115 fn test_syntax_name_resolves_grammar_and_fallback() {
1116 assert_eq!(CodeEditor::new("", "rs").syntax_name(), "Rust");
1117 assert_eq!(CodeEditor::new("", "lua").syntax_name(), "Lua");
1118 // Aliases normalized by `resolve_syntax` resolve to the same grammar.
1119 assert_eq!(CodeEditor::new("", "rust").syntax_name(), "Rust");
1120 // Unknown identifiers degrade rather than losing the content.
1121 assert_eq!(
1122 CodeEditor::new("", "no-such-language").syntax_name(),
1123 "Plain Text"
1124 );
1125 }
1126
1127 #[test]
1128 fn test_syntax_name_follows_set_syntax() {
1129 let mut editor = CodeEditor::new("", "lua");
1130 assert_eq!(editor.syntax_name(), "Lua");
1131
1132 editor.set_syntax("py");
1133 assert_eq!(editor.syntax_name(), "Python");
1134 }
1135
1136 #[test]
1137 fn test_set_syntax_updates_identifier() {
1138 let mut editor = CodeEditor::new("-- comment", "lua");
1139
1140 editor.set_syntax("rs");
1141 assert_eq!(editor.syntax(), "rs");
1142
1143 // Setting the same identifier again is a no-op, not an error.
1144 editor.set_syntax("rs");
1145 assert_eq!(editor.syntax(), "rs");
1146 }
1147
1148 /// Color of the first highlighted span of the editor's first line, or
1149 /// `None` when syntect ships no definition for the active syntax.
1150 fn first_span_color(editor: &CodeEditor) -> Option<iced::Color> {
1151 let (syntax_set, syntax, theme) = editor.resolve_syntax();
1152 editor
1153 .highlighted_line_cached(0, syntax?, theme?, syntax_set)
1154 .first()
1155 .map(|(color, _)| *color)
1156 }
1157
1158 #[test]
1159 fn test_set_syntax_rehighlights_with_the_new_language() {
1160 // A Rust doc comment: a comment under `rs`, plain code under `lua`.
1161 let mut editor = CodeEditor::new("/// doc", "lua");
1162
1163 let as_lua = first_span_color(&editor);
1164 assert!(as_lua.is_some(), "syntect ships a Lua definition");
1165
1166 editor.set_syntax("rs");
1167 let as_rust = first_span_color(&editor);
1168 assert!(as_rust.is_some(), "syntect ships a Rust definition");
1169
1170 assert_ne!(
1171 as_lua, as_rust,
1172 "`/// doc` must not keep its Lua colors after switching to Rust"
1173 );
1174 }
1175
1176 #[test]
1177 fn test_set_theme_rehighlights_for_the_new_palette() {
1178 let mut editor = CodeEditor::new("// comment", "rs");
1179
1180 editor.set_theme(crate::theme::from_iced_theme(&iced::Theme::Dark));
1181 let dark = first_span_color(&editor);
1182 assert!(dark.is_some(), "syntect ships a Rust definition");
1183
1184 editor.set_theme(crate::theme::from_iced_theme(&iced::Theme::Light));
1185 let light = first_span_color(&editor);
1186
1187 assert_ne!(
1188 dark, light,
1189 "the cached dark colors must be dropped when the theme turns light"
1190 );
1191 }
1192
1193 #[test]
1194 fn test_folding_enabled_by_default() {
1195 let editor = CodeEditor::new("fn main() {}", "rs");
1196 assert!(editor.folding_enabled());
1197 }
1198}