Skip to main content

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        if self.indent_style != style {
737            self.indent_style = style;
738            self.content_cache.clear();
739        }
740    }
741
742    /// Returns the current indentation style.
743    ///
744    /// # Returns
745    ///
746    /// The current [`IndentStyle`] configured for this editor
747    ///
748    /// # Example
749    ///
750    /// ```
751    /// use iced_code_editor::{CodeEditor, IndentStyle};
752    ///
753    /// let editor = CodeEditor::new("fn main() {}", "rs");
754    /// assert_eq!(editor.indent_style(), IndentStyle::Spaces(4));
755    /// ```
756    pub fn indent_style(&self) -> IndentStyle {
757        self.indent_style
758    }
759
760    /// Enables or disables the search/replace functionality.
761    ///
762    /// When disabled, search/replace keyboard shortcuts (Ctrl+F, Ctrl+H, F3)
763    /// will be ignored. If the search dialog is currently open, it will be closed.
764    ///
765    /// # Arguments
766    ///
767    /// * `enabled` - Whether to enable search/replace functionality
768    ///
769    /// # Example
770    ///
771    /// ```
772    /// use iced_code_editor::CodeEditor;
773    ///
774    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
775    /// editor.set_search_replace_enabled(false); // Disable search/replace
776    /// ```
777    pub fn set_search_replace_enabled(&mut self, enabled: bool) {
778        self.search_replace_enabled = enabled;
779        if !enabled && self.search_state.is_open {
780            self.search_state.close();
781        }
782    }
783
784    /// Returns the syntax highlighting language identifier for this editor.
785    ///
786    /// This is the language key passed at construction (e.g., `"lua"`, `"rs"`, `"py"`).
787    ///
788    /// # Examples
789    ///
790    /// ```
791    /// use iced_code_editor::CodeEditor;
792    /// let editor = CodeEditor::new("fn main() {}", "rs");
793    /// assert_eq!(editor.syntax(), "rs");
794    /// ```
795    pub fn syntax(&self) -> &str {
796        &self.syntax
797    }
798
799    /// Returns the display name of the grammar actually used to highlight
800    /// this editor's content.
801    ///
802    /// [`CodeEditor::syntax`] returns the raw identifier the host set; this
803    /// returns what the highlighter resolved it to, so it also reports the
804    /// plain-text fallback when no grammar matches. It is the value to show in
805    /// a status bar: it tells the user which language the editor is really
806    /// coloring with, not which one was requested.
807    ///
808    /// # Returns
809    ///
810    /// The grammar's name (e.g. `"Rust"`, `"Lua"`, `"Plain Text"`).
811    ///
812    /// # Example
813    ///
814    /// ```
815    /// use iced_code_editor::CodeEditor;
816    ///
817    /// let editor = CodeEditor::new("fn main() {}", "rs");
818    /// assert_eq!(editor.syntax_name(), "Rust");
819    ///
820    /// // An identifier no bundled grammar matches degrades to plain text.
821    /// let unknown = CodeEditor::new("...", "no-such-language");
822    /// assert_eq!(unknown.syntax_name(), "Plain Text");
823    /// ```
824    pub fn syntax_name(&self) -> &'static str {
825        let (_, syntax, _) = self.resolve_syntax();
826        syntax.map_or("Plain Text", |syntax| syntax.name.as_str())
827    }
828
829    /// Sets the syntax highlighting language identifier for this editor.
830    ///
831    /// Use this when the content a single editor shows changes language --
832    /// typically after opening or saving a file under a different extension.
833    /// The identifier is the same key [`CodeEditor::new`] takes: a file
834    /// extension (`"rs"`, `"py"`, `"toml"`) or one of the aliases
835    /// `resolve_syntax` normalizes (`"rust"`, `"python"`, `"markdown"`, ...).
836    /// An unknown identifier falls back to plain text rather than losing the
837    /// content.
838    ///
839    /// Changing the identifier drops the cached per-line highlighting, so the
840    /// visible lines are re-tokenized on the next render. Setting the current
841    /// identifier again does nothing.
842    ///
843    /// # Arguments
844    ///
845    /// * `syntax` - Syntax highlighting language identifier (e.g. `"rs"`)
846    ///
847    /// # Example
848    ///
849    /// ```
850    /// use iced_code_editor::CodeEditor;
851    ///
852    /// let mut editor = CodeEditor::new("-- comment", "lua");
853    /// assert_eq!(editor.syntax(), "lua");
854    ///
855    /// editor.set_syntax("rs");
856    /// assert_eq!(editor.syntax(), "rs");
857    /// ```
858    pub fn set_syntax(&mut self, syntax: &str) {
859        if self.syntax == syntax {
860            return;
861        }
862
863        self.syntax.clear();
864        self.syntax.push_str(syntax);
865        // `highlighted_line_cached` rebuilds `HighlightCache` on its own when
866        // the active syntax no longer matches, so only the canvas needs an
867        // explicit redraw here.
868        self.content_cache.clear();
869    }
870
871    /// Sets the wrap column (fixed width wrapping).
872    ///
873    /// When set to `Some(n)`, lines will wrap at column `n`.
874    /// When set to `None`, lines will wrap at the viewport width.
875    /// Zero is normalized to one narrow-character column.
876    ///
877    /// # Arguments
878    ///
879    /// * `column` - The column to wrap at, or None for viewport-based wrapping
880    ///
881    /// # Example
882    ///
883    /// ```
884    /// use iced_code_editor::CodeEditor;
885    ///
886    /// let editor = CodeEditor::new("fn main() {}", "rs")
887    ///     .with_wrap_column(Some(80)); // Wrap at 80 characters
888    /// ```
889    #[must_use]
890    pub fn with_wrap_column(mut self, column: Option<usize>) -> Self {
891        self.set_wrap_column(column);
892        self
893    }
894
895    /// Sets the soft-wrap width in narrow-character columns.
896    ///
897    /// `None` uses the viewport width; `Some(0)` is normalized to `Some(1)`.
898    /// This does not modify document text or enable wrapping. Changing the
899    /// width invalidates text and overlay geometry. While wrapping is enabled,
900    /// horizontal scrolling is reset so the new visual segments stay visible.
901    ///
902    /// # Arguments
903    ///
904    /// * `column` - Wrap width in columns, or `None` for the viewport width
905    ///
906    /// # Example
907    ///
908    /// ```
909    /// use iced_code_editor::CodeEditor;
910    ///
911    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
912    /// editor.set_wrap_column(Some(80));
913    /// assert_eq!(editor.wrap_column(), Some(80));
914    ///
915    /// editor.set_wrap_column(Some(0)); // Normalized to one column
916    /// assert_eq!(editor.wrap_column(), Some(1));
917    ///
918    /// editor.set_wrap_column(None); // Back to viewport-based wrapping
919    /// assert_eq!(editor.wrap_column(), None);
920    /// ```
921    pub fn set_wrap_column(&mut self, column: Option<usize>) {
922        let column = column.map(|value| value.max(1));
923        if self.wrap_column != column {
924            self.wrap_column = column;
925            if self.wrap_enabled {
926                self.horizontal_scroll_offset = 0.0;
927            }
928            self.content_cache.clear();
929            self.overlay_cache.clear();
930        }
931    }
932
933    /// Returns the soft-wrap width in narrow-character columns.
934    ///
935    /// `None` means viewport-based wrapping. The value is retained while
936    /// wrapping is disabled; zero is normalized to one by the setter.
937    ///
938    /// # Returns
939    ///
940    /// The fixed wrap width, or `None` when wrapping follows the viewport
941    ///
942    /// # Example
943    ///
944    /// ```
945    /// use iced_code_editor::CodeEditor;
946    ///
947    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
948    /// assert_eq!(editor.wrap_column(), None); // Viewport width by default
949    ///
950    /// editor.set_wrap_column(Some(100));
951    /// editor.set_wrap_enabled(false);
952    /// assert_eq!(editor.wrap_column(), Some(100)); // Kept while disabled
953    /// ```
954    pub fn wrap_column(&self) -> Option<usize> {
955        self.wrap_column
956    }
957
958    /// Sets whether line numbers are displayed.
959    ///
960    /// When disabled, the gutter is completely removed (0px width),
961    /// providing more space for code display.
962    ///
963    /// # Arguments
964    ///
965    /// * `enabled` - Whether to display line numbers
966    ///
967    /// # Example
968    ///
969    /// ```
970    /// use iced_code_editor::CodeEditor;
971    ///
972    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
973    /// editor.set_line_numbers_enabled(false); // Hide line numbers
974    /// ```
975    pub fn set_line_numbers_enabled(&mut self, enabled: bool) {
976        if self.line_numbers_enabled != enabled {
977            self.line_numbers_enabled = enabled;
978            self.content_cache.clear();
979            self.overlay_cache.clear();
980        }
981    }
982}
983
984#[cfg(test)]
985mod tests {
986    use super::*;
987    use crate::canvas_editor::features::context_menu::ContextMenuItem;
988    use crate::canvas_editor::features::vim;
989
990    #[test]
991    fn test_custom_context_menu_configuration() {
992        let custom_entries = vec![
993            ContextMenuEntry::item("format", "Format document")
994                .with_shortcut("Shift+Alt+F"),
995            ContextMenuEntry::separator(),
996            ContextMenuEntry::Item(
997                ContextMenuItem::new("rename", "Rename symbol")
998                    .with_enabled(false),
999            ),
1000        ];
1001
1002        let editor = CodeEditor::new("", "rs")
1003            .with_custom_context_menu_entries(custom_entries.clone())
1004            .with_default_context_menu_enabled(false);
1005
1006        assert_eq!(editor.custom_context_menu_entries(), custom_entries);
1007        assert!(!editor.default_context_menu_enabled());
1008
1009        let default_editor = CodeEditor::new("", "rs");
1010        assert!(default_editor.custom_context_menu_entries().is_empty());
1011        assert!(default_editor.default_context_menu_enabled());
1012    }
1013
1014    #[test]
1015    fn test_reveal_in_file_manager_configuration() {
1016        let mut editor = CodeEditor::new("", "rs");
1017        assert!(!editor.reveal_in_file_manager_enabled());
1018
1019        editor.set_reveal_in_file_manager_enabled(true);
1020        assert!(editor.reveal_in_file_manager_enabled());
1021
1022        let editor =
1023            CodeEditor::new("", "rs").with_reveal_in_file_manager_enabled(true);
1024        assert!(editor.reveal_in_file_manager_enabled());
1025    }
1026
1027    #[test]
1028    fn test_auto_close_brackets_configuration() {
1029        let mut editor = CodeEditor::new("", "rs");
1030        assert!(editor.auto_close_brackets());
1031
1032        editor.set_auto_close_brackets(false);
1033        assert!(!editor.auto_close_brackets());
1034
1035        editor.set_auto_close_brackets(true);
1036        assert!(editor.auto_close_brackets());
1037    }
1038
1039    #[test]
1040    fn test_bracket_match_highlight_configuration() {
1041        let mut editor = CodeEditor::new("", "rs");
1042        assert!(editor.bracket_match_highlight_enabled());
1043
1044        editor.set_bracket_match_highlight_enabled(false);
1045        assert!(!editor.bracket_match_highlight_enabled());
1046
1047        editor.set_bracket_match_highlight_enabled(true);
1048        assert!(editor.bracket_match_highlight_enabled());
1049    }
1050
1051    #[test]
1052    fn test_bracket_pair_colorization_configuration() {
1053        let mut editor = CodeEditor::new("", "rs");
1054        assert!(editor.bracket_pair_colorization_enabled());
1055
1056        editor.set_bracket_pair_colorization_enabled(false);
1057        assert!(!editor.bracket_pair_colorization_enabled());
1058
1059        editor.set_bracket_pair_colorization_enabled(true);
1060        assert!(editor.bracket_pair_colorization_enabled());
1061    }
1062
1063    #[test]
1064    fn test_show_indent_guides_configuration() {
1065        let mut editor = CodeEditor::new("", "rs");
1066        assert!(editor.show_indent_guides());
1067
1068        editor.set_show_indent_guides(false);
1069        assert!(!editor.show_indent_guides());
1070
1071        editor.set_show_indent_guides(true);
1072        assert!(editor.show_indent_guides());
1073
1074        let editor = CodeEditor::new("", "rs").with_show_indent_guides(false);
1075        assert!(!editor.show_indent_guides());
1076    }
1077
1078    #[test]
1079    fn test_show_color_previews_configuration() {
1080        let mut editor = CodeEditor::new("", "rs");
1081        assert!(editor.show_color_previews());
1082
1083        editor.set_show_color_previews(false);
1084        assert!(!editor.show_color_previews());
1085
1086        editor.set_show_color_previews(true);
1087        assert!(editor.show_color_previews());
1088
1089        let editor = CodeEditor::new("", "rs").with_show_color_previews(false);
1090        assert!(!editor.show_color_previews());
1091    }
1092
1093    #[test]
1094    fn vim_disabled_by_default() {
1095        let editor = CodeEditor::new("unchanged", "rs");
1096
1097        assert!(!editor.vim_enabled());
1098        assert_eq!(editor.vim_mode(), None);
1099        assert_eq!(editor.content(), "unchanged");
1100        assert!(!editor.can_undo());
1101        assert!(!editor.can_redo());
1102    }
1103
1104    #[test]
1105    fn vim_enable_enters_clean_normal_mode() {
1106        let mut editor = CodeEditor::new("unchanged", "rs");
1107        assert_eq!(editor.vim_state.parse_key('9'), None);
1108        assert_eq!(editor.vim_state.parse_key('d'), None);
1109
1110        editor.set_vim_enabled(true);
1111
1112        assert!(editor.vim_enabled());
1113        assert_eq!(editor.vim_mode(), Some(VimMode::Normal));
1114        assert_eq!(
1115            editor.vim_state.parse_key('l'),
1116            Some(vim::VimAction::Motion {
1117                motion: vim::VimMotion::Right,
1118                count: 1,
1119                explicit_count: false,
1120            })
1121        );
1122        assert_eq!(editor.content(), "unchanged");
1123        assert!(!editor.can_undo());
1124        assert!(!editor.can_redo());
1125    }
1126
1127    #[test]
1128    fn vim_disable_clears_pending_state() {
1129        let mut editor =
1130            CodeEditor::new("unchanged", "rs").with_vim_enabled(true);
1131        assert_eq!(editor.vim_state.parse_key('4'), None);
1132        assert_eq!(editor.vim_state.parse_key('d'), None);
1133
1134        editor.set_vim_enabled(false);
1135        assert!(!editor.vim_enabled());
1136        assert_eq!(editor.vim_mode(), None);
1137
1138        editor.set_vim_enabled(true);
1139        assert_eq!(
1140            editor.vim_state.parse_key('w'),
1141            Some(vim::VimAction::Motion {
1142                motion: vim::VimMotion::WordForward,
1143                count: 1,
1144                explicit_count: false,
1145            })
1146        );
1147        assert_eq!(editor.content(), "unchanged");
1148        assert!(!editor.can_undo());
1149        assert!(!editor.can_redo());
1150    }
1151
1152    #[test]
1153    fn vim_reset_clears_pending_state() {
1154        let mut editor = CodeEditor::new("before", "rs").with_vim_enabled(true);
1155        assert_eq!(editor.vim_state.parse_key('3'), None);
1156        assert_eq!(editor.vim_state.parse_key('g'), None);
1157
1158        let _ = editor.reset("after");
1159
1160        assert_eq!(editor.vim_mode(), Some(VimMode::Normal));
1161        assert_eq!(editor.vim_state.parse_key('g'), None);
1162        assert_eq!(
1163            editor.vim_state.parse_key('g'),
1164            Some(vim::VimAction::Motion {
1165                motion: vim::VimMotion::DocumentStart,
1166                count: 1,
1167                explicit_count: false,
1168            })
1169        );
1170        assert_eq!(editor.content(), "after");
1171        assert!(!editor.can_undo());
1172        assert!(!editor.can_redo());
1173    }
1174
1175    #[test]
1176    fn test_syntax_getter() {
1177        let editor = CodeEditor::new("", "lua");
1178        assert_eq!(editor.syntax(), "lua");
1179    }
1180
1181    #[test]
1182    fn test_syntax_name_resolves_grammar_and_fallback() {
1183        assert_eq!(CodeEditor::new("", "rs").syntax_name(), "Rust");
1184        assert_eq!(CodeEditor::new("", "lua").syntax_name(), "Lua");
1185        // Aliases normalized by `resolve_syntax` resolve to the same grammar.
1186        assert_eq!(CodeEditor::new("", "rust").syntax_name(), "Rust");
1187        // Unknown identifiers degrade rather than losing the content.
1188        assert_eq!(
1189            CodeEditor::new("", "no-such-language").syntax_name(),
1190            "Plain Text"
1191        );
1192    }
1193
1194    #[test]
1195    fn test_syntax_name_follows_set_syntax() {
1196        let mut editor = CodeEditor::new("", "lua");
1197        assert_eq!(editor.syntax_name(), "Lua");
1198
1199        editor.set_syntax("py");
1200        assert_eq!(editor.syntax_name(), "Python");
1201    }
1202
1203    #[test]
1204    fn test_set_syntax_updates_identifier() {
1205        let mut editor = CodeEditor::new("-- comment", "lua");
1206
1207        editor.set_syntax("rs");
1208        assert_eq!(editor.syntax(), "rs");
1209
1210        // Setting the same identifier again is a no-op, not an error.
1211        editor.set_syntax("rs");
1212        assert_eq!(editor.syntax(), "rs");
1213    }
1214
1215    /// Color of the first highlighted span of the editor's first line, or
1216    /// `None` when syntect ships no definition for the active syntax.
1217    fn first_span_color(editor: &CodeEditor) -> Option<iced::Color> {
1218        let (syntax_set, syntax, theme) = editor.resolve_syntax();
1219        editor
1220            .highlighted_line_cached(0, syntax?, theme?, syntax_set)
1221            .first()
1222            .map(|(color, _)| *color)
1223    }
1224
1225    #[test]
1226    fn test_set_syntax_rehighlights_with_the_new_language() {
1227        // A Rust doc comment: a comment under `rs`, plain code under `lua`.
1228        let mut editor = CodeEditor::new("/// doc", "lua");
1229
1230        let as_lua = first_span_color(&editor);
1231        assert!(as_lua.is_some(), "syntect ships a Lua definition");
1232
1233        editor.set_syntax("rs");
1234        let as_rust = first_span_color(&editor);
1235        assert!(as_rust.is_some(), "syntect ships a Rust definition");
1236
1237        assert_ne!(
1238            as_lua, as_rust,
1239            "`/// doc` must not keep its Lua colors after switching to Rust"
1240        );
1241    }
1242
1243    #[test]
1244    fn test_set_theme_rehighlights_for_the_new_palette() {
1245        let mut editor = CodeEditor::new("// comment", "rs");
1246
1247        editor.set_theme(crate::theme::from_iced_theme(&iced::Theme::Dark));
1248        let dark = first_span_color(&editor);
1249        assert!(dark.is_some(), "syntect ships a Rust definition");
1250
1251        editor.set_theme(crate::theme::from_iced_theme(&iced::Theme::Light));
1252        let light = first_span_color(&editor);
1253
1254        assert_ne!(
1255            dark, light,
1256            "the cached dark colors must be dropped when the theme turns light"
1257        );
1258    }
1259
1260    #[test]
1261    fn test_folding_enabled_by_default() {
1262        let editor = CodeEditor::new("fn main() {}", "rs");
1263        assert!(editor.folding_enabled());
1264    }
1265}