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