Skip to main content

iced_code_editor/canvas_editor/
mod.rs

1//! Canvas-based text editor widget for maximum performance.
2//!
3//! This module provides a custom Canvas widget that handles all text rendering
4//! and input directly, bypassing Iced's higher-level widgets for optimal speed.
5
6use iced::widget::operation::{RelativeOffset, snap_to};
7use iced::widget::{Id, canvas};
8use std::cell::{Cell, RefCell};
9use std::collections::HashSet;
10use std::ops::Range;
11use std::rc::Rc;
12use std::sync::atomic::{AtomicU64, Ordering};
13#[cfg(not(target_arch = "wasm32"))]
14use std::time::Instant;
15
16use crate::buffer::TextBuffer;
17use crate::i18n::Translations;
18use crate::theme::Style;
19use caches::{
20    BracketDepthCache, HighlightCache, MaxContentWidthCache, VisualLinesCache,
21};
22use editing::cursor_set;
23pub use editing::history::CommandHistory;
24use features::{folding, goto_line, search, vim};
25use metrics::{
26    CACHE_WINDOW_MARGIN_MULTIPLIER, CHAR_WIDTH, CURSOR_BLINK_INTERVAL,
27    FONT_SIZE, GUTTER_WIDTH, HIGHLIGHT_LINES_PER_FRAME, LINE_HEIGHT, TAB_WIDTH,
28    compare_floats, measure_char_width, measure_text_width,
29};
30
31#[cfg(target_arch = "wasm32")]
32use web_time::Instant;
33
34/// Global counter for generating unique editor IDs (starts at 1)
35static EDITOR_ID_COUNTER: AtomicU64 = AtomicU64::new(1);
36
37/// ID of the currently focused editor (0 = no editor focused)
38static FOCUSED_EDITOR_ID: AtomicU64 = AtomicU64::new(0);
39
40// Re-export submodules
41#[cfg(feature = "bench")]
42#[doc(hidden)]
43pub mod bench_support;
44mod caches;
45mod config;
46mod editing;
47pub(crate) mod features;
48mod focus;
49mod input;
50pub mod lsp;
51mod metrics;
52mod render;
53
54pub use features::context_menu::{ContextMenuEntry, ContextMenuItem};
55pub use features::vim::VimMode;
56#[derive(Debug, Clone)]
57pub(crate) struct ImePreedit {
58    pub(crate) content: String,
59    pub(crate) selection: Option<Range<usize>>,
60}
61
62/// Conservative logical-line range captured immediately before an edit.
63///
64/// It lets LSP synchronization send one incremental range replacement without
65/// serializing and diffing the entire document after every keystroke.
66pub(crate) struct LspEditSnapshot {
67    pub(crate) start_line: usize,
68    pub(crate) old_end_exclusive: usize,
69    pub(crate) old_line_count: usize,
70    pub(crate) old_end: lsp::LspPosition,
71}
72
73/// Canvas-based high-performance text editor.
74pub struct CodeEditor {
75    /// Unique ID for this editor instance (for focus management)
76    pub(crate) editor_id: u64,
77    /// Text buffer
78    pub(crate) buffer: TextBuffer,
79    /// All cursor positions (multi-cursor support).
80    pub(crate) cursors: cursor_set::CursorSet,
81    /// Horizontal scroll offset in pixels, only used when wrap_enabled = false
82    pub(crate) horizontal_scroll_offset: f32,
83    /// Editor theme style
84    pub(crate) style: Style,
85    /// Syntax highlighting language
86    pub(crate) syntax: String,
87    /// Last cursor blink time
88    pub(crate) last_blink: Instant,
89    /// Cursor visible state
90    pub(crate) cursor_visible: bool,
91    /// Mouse is currently dragging for selection
92    pub(crate) is_dragging: bool,
93    /// Cached geometry for the "content" layer.
94    ///
95    /// This layer includes expensive-to-build, mostly static visuals such as:
96    /// - syntax-highlighted text glyphs
97    /// - line numbers / gutter text
98    ///
99    /// It is intentionally kept stable across selection/cursor movement so
100    /// that mouse-drag selection feels smooth.
101    pub(crate) content_cache: canvas::Cache,
102    /// Cached geometry for the "overlay" layer.
103    ///
104    /// This layer includes visuals that change frequently without modifying the
105    /// underlying buffer, such as:
106    /// - cursor and current-line highlight
107    /// - selection highlight
108    /// - search match highlights
109    /// - IME preedit decorations
110    ///
111    /// Keeping overlays in a separate cache avoids invalidating the content
112    /// layer on every cursor blink or selection drag.
113    pub(crate) overlay_cache: canvas::Cache,
114    /// Scrollable ID for programmatic scrolling
115    pub(crate) scrollable_id: Id,
116    /// ID for the horizontal scrollable widget (only used when wrap_enabled = false)
117    pub(crate) horizontal_scrollable_id: Id,
118    /// Incremental per-line width index for the horizontal scrollbar.
119    pub(crate) max_content_width_cache: RefCell<Option<MaxContentWidthCache>>,
120    /// Current viewport scroll position (Y offset)
121    pub(crate) viewport_scroll: f32,
122    /// Viewport height (visible area)
123    pub(crate) viewport_height: f32,
124    /// Viewport width (visible area)
125    pub(crate) viewport_width: f32,
126    /// Command history for undo/redo
127    pub(crate) history: CommandHistory,
128    /// Whether we're currently grouping commands (for smart undo)
129    pub(crate) is_grouping: bool,
130    /// Line wrapping enabled
131    pub(crate) wrap_enabled: bool,
132    /// Auto-indentation enabled
133    pub(crate) auto_indent_enabled: bool,
134    /// Auto-closing of brackets/quotes and surround-selection enabled
135    pub(crate) auto_close_brackets: bool,
136    /// Indentation style (spaces or tab)
137    pub(crate) indent_style: IndentStyle,
138    /// Wrap column (None = wrap at viewport width)
139    pub(crate) wrap_column: Option<usize>,
140    /// Whether code folding (collapse/expand blocks) is enabled.
141    pub(crate) folding_enabled: bool,
142    /// Header line indices of regions that are currently collapsed.
143    pub(crate) collapsed_folds: HashSet<usize>,
144    /// Monotonic revision counter for fold state.
145    ///
146    /// Bumped whenever the collapsed set or the folding toggle changes, so that
147    /// derived layout caches (visual lines) are invalidated.
148    pub(crate) fold_revision: u64,
149    /// Cached foldable regions, keyed by `buffer_revision`.
150    pub(crate) foldable_regions_cache:
151        RefCell<Option<(u64, Rc<Vec<folding::FoldRegion>>)>>,
152    /// Search state
153    pub(crate) search_state: search::SearchState,
154    /// Custom entries displayed before the built-in context-menu actions.
155    custom_context_menu_entries: Vec<ContextMenuEntry>,
156    /// Whether the built-in editing actions are shown in the context menu.
157    default_context_menu_enabled: bool,
158    /// Whether the built-in reveal-in-file-manager action is shown.
159    reveal_in_file_manager_enabled: bool,
160    /// Go-to-line dialog state
161    pub(crate) goto_line_state: goto_line::GotoLineState,
162    /// Whether Vim key handling is enabled for this editor instance.
163    vim_enabled: bool,
164    /// Per-editor Vim mode, parser prefixes and unnamed register.
165    pub(crate) vim_state: vim::VimState,
166    /// Translations for UI text
167    pub(crate) translations: Translations,
168    /// Whether search/replace functionality is enabled
169    pub(crate) search_replace_enabled: bool,
170    /// Whether line numbers are displayed
171    pub(crate) line_numbers_enabled: bool,
172    /// Whether to render whitespace characters visibly (spaces as `·`, tabs as `→`)
173    pub(crate) show_whitespace: bool,
174    /// Whether the matching-bracket/quote-pair highlight overlay is enabled.
175    pub(crate) bracket_match_highlight_enabled: bool,
176    /// Whether bracket-pair colorization (rainbow brackets) is enabled.
177    pub(crate) bracket_pair_colorization_enabled: bool,
178    /// Whether LSP support is enabled
179    pub(crate) lsp_enabled: bool,
180    /// Active LSP client connection, if configured.
181    pub(crate) lsp_client: Option<Box<dyn lsp::LspClient>>,
182    /// Metadata for the currently open LSP document.
183    pub(crate) lsp_document: Option<lsp::LspDocument>,
184    /// Pending incremental LSP text changes not yet flushed.
185    pub(crate) lsp_pending_changes: Vec<lsp::LspTextChange>,
186    /// Shadow copy of buffer content used to compute LSP deltas.
187    pub(crate) lsp_shadow_text: String,
188    /// Whether `lsp_shadow_text` still exactly matches the server document.
189    pub(crate) lsp_shadow_is_current: bool,
190    /// Current server-side line count, maintained incrementally.
191    pub(crate) lsp_synced_line_count: usize,
192    /// Length of the current server-side final line in Unicode scalar values.
193    pub(crate) lsp_synced_last_line_len: usize,
194    /// Pre-edit range used to build a bounded incremental LSP change.
195    pub(crate) lsp_edit_snapshot: Option<LspEditSnapshot>,
196    /// Whether to auto-flush LSP changes after edits.
197    pub(crate) lsp_auto_flush: bool,
198    /// Whether the canvas has user input focus (for keyboard events)
199    pub(crate) has_canvas_focus: bool,
200    /// Whether input processing is locked to prevent focus stealing
201    pub(crate) focus_locked: bool,
202    /// Whether to show the cursor (for rendering)
203    pub(crate) show_cursor: bool,
204    /// Current keyboard modifiers state (Ctrl, Alt, Shift, Logo).
205    ///
206    /// This is updated via subscription events and used to handle modifier-dependent
207    /// interactions, such as "Ctrl+Click" for jumping to a definition.
208    pub(crate) modifiers: Cell<iced::keyboard::Modifiers>,
209    /// Last left-button press (time, position, consecutive count), used to
210    /// detect double/triple clicks.
211    pub(crate) last_click: Cell<Option<(Instant, iced::Point, u8)>>,
212    /// The font used for rendering text
213    pub(crate) font: iced::Font,
214    /// IME pre-edit state (for CJK input)
215    pub(crate) ime_preedit: Option<ImePreedit>,
216    /// Font size in pixels
217    pub(crate) font_size: f32,
218    /// Full character width (wide chars like CJK) in pixels
219    pub(crate) full_char_width: f32,
220    /// Line height in pixels
221    pub(crate) line_height: f32,
222    /// Character width in pixels
223    pub(crate) char_width: f32,
224    /// Cached render window: the first visual line index included in the cache.
225    /// We keep a larger window than the currently visible range to avoid clearing
226    /// the canvas cache on every small scroll. Only when scrolling crosses the
227    /// window boundary do we re-window and clear the cache.
228    pub(crate) last_first_visible_line: usize,
229    /// Cached render window start line (inclusive)
230    pub(crate) cache_window_start_line: usize,
231    /// Cached render window end line (exclusive)
232    pub(crate) cache_window_end_line: usize,
233    /// Monotonic revision counter for buffer content.
234    ///
235    /// Any operation that changes the buffer must bump this counter to
236    /// invalidate derived layout caches (e.g. wrapping / visual lines). The
237    /// exact value is not semantically meaningful, so `wrapping_add` is used to
238    /// avoid overflow panics while still producing a different key.
239    pub(crate) buffer_revision: u64,
240    /// Cached result of line wrapping ("visual lines") for the current layout key.
241    ///
242    /// This is stored behind a `RefCell` because wrapping is needed during
243    /// rendering (where we only have `&self`), but we still want to memoize the
244    /// expensive computation without forcing external mutability.
245    visual_lines_cache: RefCell<Option<VisualLinesCache>>,
246    /// Sequential per-line syntax-highlight cache (see [`HighlightCache`]).
247    ///
248    /// Stored behind a `RefCell` because highlighting is performed during
249    /// rendering (where only `&self` is available) yet should be memoized.
250    /// Spans are reused across wrapped visual segments and across scroll-only
251    /// renders. On an edit the cache is truncated from the first changed line
252    /// (tracked via `pre_edit_line`) rather than fully cleared, so multi-line
253    /// constructs stay correct without re-parsing the whole file.
254    pub(crate) highlight_cache: RefCell<Option<HighlightCache>>,
255    /// Remaining syntax lines that may be parsed during the current content
256    /// render. `usize::MAX` keeps direct non-render uses (notably tests) uncapped.
257    pub(crate) highlight_lines_remaining: Cell<usize>,
258    /// Sequential per-line bracket-nesting-depth cache (see [`BracketDepthCache`]),
259    /// used by bracket-pair colorization. Stored behind a `RefCell` for the same
260    /// reason as `highlight_cache`: it is memoized during rendering (`&self`).
261    pub(crate) bracket_depth_cache: RefCell<BracketDepthCache>,
262    /// Topmost logical line touched by the cursors/selections before the
263    /// current edit, captured at the top of `update()`.
264    ///
265    /// Used as a conservative lower bound for the first line an edit may
266    /// change, to truncate `highlight_cache` precisely.
267    pub(crate) pre_edit_line: usize,
268    /// Bottommost logical line touched before the current edit.
269    ///
270    /// Together with `pre_edit_line`, this bounds the portion of the visual-line
271    /// cache that must be rebuilt after a localized edit.
272    pub(crate) pre_edit_last_line: usize,
273}
274
275/// Messages emitted by the code editor
276#[derive(Debug, Clone)]
277pub enum Message {
278    /// Character typed
279    CharacterInput(char),
280    /// A printable key interpreted by the Vim state machine.
281    VimKey(char),
282    /// Toggle Vim behavior for this editor instance.
283    ToggleVimMode,
284    /// Requests that the host save this editor's current document.
285    WriteRequested,
286    /// Backspace pressed
287    Backspace,
288    /// Delete pressed
289    Delete,
290    /// Enter pressed
291    Enter,
292    /// Tab pressed (inserts 4 spaces)
293    Tab,
294    /// Arrow key pressed (direction, shift_pressed)
295    ArrowKey(ArrowDirection, bool),
296    /// Mouse clicked at position
297    MouseClick(iced::Point),
298    /// Mouse drag for selection
299    MouseDrag(iced::Point),
300    /// Mouse moved within the editor without dragging
301    MouseHover(iced::Point),
302    /// Mouse released
303    MouseRelease,
304    /// Double-click: select the word under the cursor
305    DoubleClick(iced::Point),
306    /// Triple-click: select the whole line under the cursor
307    TripleClick(iced::Point),
308    /// Right-clicked in the editor to position and open the context menu
309    ContextMenuRequested(iced::Point),
310    /// A configured context-menu action was selected.
311    CustomContextMenuAction(String),
312    /// Requests that the host reveal the editor's file in the system file manager.
313    RevealInFileManager,
314    /// Cut selected text
315    Cut,
316    /// Copy selected text (Ctrl+C)
317    Copy,
318    /// Paste text from clipboard (Ctrl+V)
319    Paste(String),
320    /// Delete selected text (Shift+Delete)
321    DeleteSelection,
322    /// Select the complete document
323    SelectAll,
324    /// Request redraw for cursor blink
325    Tick,
326    /// Page Up pressed
327    PageUp,
328    /// Page Down pressed
329    PageDown,
330    /// Home key pressed (move to start of line, shift_pressed)
331    Home(bool),
332    /// End key pressed (move to end of line, shift_pressed)
333    End(bool),
334    /// Ctrl+Home pressed (move to start of document)
335    CtrlHome,
336    /// Ctrl+End pressed (move to end of document)
337    CtrlEnd,
338    /// Go to an explicit logical position (line, column), both 0-based.
339    GotoPosition(usize, usize),
340    /// Open the go-to-line dialog (Cmd/Ctrl+G).
341    OpenGotoLine,
342    /// Close the go-to-line dialog.
343    CloseGotoLine,
344    /// Change the one-based line number shown in the go-to-line input.
345    GotoLineChanged(String),
346    /// Submit the current go-to-line input.
347    SubmitGotoLine,
348    /// Viewport scrolled - track scroll position
349    Scrolled(iced::widget::scrollable::Viewport),
350    /// Horizontal scrollbar scrolled (only when wrap is disabled)
351    HorizontalScrolled(iced::widget::scrollable::Viewport),
352    /// Undo last operation (Ctrl+Z)
353    Undo,
354    /// Redo last undone operation (Ctrl+Y)
355    Redo,
356    /// Open search dialog (Ctrl+F)
357    OpenSearch,
358    /// Open search and replace dialog (Ctrl+H)
359    OpenSearchReplace,
360    /// Close search dialog (Escape)
361    CloseSearch,
362    /// Search query text changed
363    SearchQueryChanged(String),
364    /// Replace text changed
365    ReplaceQueryChanged(String),
366    /// Toggle case sensitivity
367    ToggleCaseSensitive,
368    /// Find next match (F3)
369    FindNext,
370    /// Find previous match (Shift+F3)
371    FindPrevious,
372    /// Replace current match
373    ReplaceNext,
374    /// Replace all matches
375    ReplaceAll,
376    /// Tab pressed in search dialog (cycle forward)
377    SearchDialogTab,
378    /// Shift+Tab pressed in search dialog (cycle backward)
379    SearchDialogShiftTab,
380    /// Shift+Tab pressed for focus navigation (when search dialog is not open)
381    FocusNavigationShiftTab,
382    /// Canvas gained focus (mouse click)
383    CanvasFocusGained,
384    /// Canvas lost focus (external widget interaction)
385    CanvasFocusLost,
386    /// Triggered when the user performs a Ctrl+Click (or Cmd+Click on macOS)
387    /// on the editor content, intending to jump to the definition of the symbol
388    /// under the cursor.
389    JumpClick(iced::Point),
390    /// IME input method opened
391    ImeOpened,
392    /// IME pre-edit update (content, selection range)
393    ImePreedit(String, Option<Range<usize>>),
394    /// IME commit text
395    ImeCommit(String),
396    /// IME input method closed
397    ImeClosed,
398    /// Alt+Click: add a new cursor at the given canvas position
399    AltClick(iced::Point),
400    /// Ctrl+Alt+Up: add a cursor on the line above the primary cursor
401    AddCursorAbove,
402    /// Ctrl+Alt+Down: add a cursor on the line below the primary cursor
403    AddCursorBelow,
404    /// Ctrl+D: select the next occurrence of the currently selected text (or word under cursor)
405    SelectNextOccurrence,
406    /// Toggle the collapsed state of the fold whose header is the given logical line.
407    ToggleFold(usize),
408    /// Toggle the collapsed state of the innermost block containing the primary cursor.
409    ToggleFoldAtCursor,
410    /// Fold every foldable block in the buffer.
411    FoldAll,
412    /// Unfold every collapsed block in the buffer.
413    UnfoldAll,
414    /// Alt+Up: move the current line (or selected line range) up by one line.
415    MoveLineUp,
416    /// Alt+Down: move the current line (or selected line range) down by one line.
417    MoveLineDown,
418    /// Shift+Alt+Up: duplicate the current line (or selected line range) above.
419    DuplicateLineUp,
420    /// Shift+Alt+Down: duplicate the current line (or selected line range) below.
421    DuplicateLineDown,
422    /// Ctrl+/: toggle line comments on the current line or primary selection.
423    ToggleComment,
424}
425
426/// Indentation style used when pressing the Tab key.
427///
428/// Controls whether indentation inserts spaces or a tab character.
429#[derive(Debug, Clone, Copy, PartialEq, Eq)]
430pub enum IndentStyle {
431    /// Insert `n` space characters.
432    Spaces(u8),
433    /// Insert a single tab character (`\t`).
434    Tab,
435}
436
437impl IndentStyle {
438    /// All standard indentation styles available for selection.
439    pub const ALL: [IndentStyle; 4] = [
440        IndentStyle::Spaces(2),
441        IndentStyle::Spaces(4),
442        IndentStyle::Spaces(8),
443        IndentStyle::Tab,
444    ];
445}
446
447impl std::fmt::Display for IndentStyle {
448    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
449        match self {
450            IndentStyle::Spaces(1) => write!(f, "1 space"),
451            IndentStyle::Spaces(n) => write!(f, "{n} spaces"),
452            IndentStyle::Tab => write!(f, "Tab"),
453        }
454    }
455}
456
457/// Arrow key directions
458#[derive(Debug, Clone, Copy)]
459pub enum ArrowDirection {
460    Up,
461    Down,
462    Left,
463    Right,
464}
465
466impl CodeEditor {
467    /// Creates a new canvas-based text editor.
468    ///
469    /// # Arguments
470    ///
471    /// * `content` - Initial text content
472    /// * `syntax` - Syntax highlighting language (e.g., "py", "lua", "rs")
473    ///
474    /// # Returns
475    ///
476    /// A new `CodeEditor` instance
477    pub fn new(content: &str, syntax: &str) -> Self {
478        // Generate a unique ID for this editor instance
479        let editor_id = EDITOR_ID_COUNTER.fetch_add(1, Ordering::Relaxed);
480
481        // Give focus to the first editor created (ID == 1)
482        if editor_id == 1 {
483            FOCUSED_EDITOR_ID.store(editor_id, Ordering::Relaxed);
484        }
485
486        let mut editor = Self {
487            editor_id,
488            buffer: TextBuffer::new(content),
489            cursors: cursor_set::CursorSet::new((0, 0)),
490            horizontal_scroll_offset: 0.0,
491            style: crate::theme::from_iced_theme(&iced::Theme::TokyoNightStorm),
492            syntax: syntax.to_string(),
493            last_blink: Instant::now(),
494            cursor_visible: true,
495            is_dragging: false,
496            content_cache: canvas::Cache::default(),
497            overlay_cache: canvas::Cache::default(),
498            scrollable_id: Id::unique(),
499            horizontal_scrollable_id: Id::unique(),
500            max_content_width_cache: RefCell::new(None),
501            viewport_scroll: 0.0,
502            viewport_height: 600.0, // Default, will be updated
503            viewport_width: 800.0,  // Default, will be updated
504            history: CommandHistory::new(100),
505            is_grouping: false,
506            wrap_enabled: true,
507            auto_indent_enabled: true,
508            auto_close_brackets: true,
509            indent_style: IndentStyle::Spaces(4),
510            wrap_column: None,
511            folding_enabled: true,
512            collapsed_folds: HashSet::new(),
513            fold_revision: 0,
514            foldable_regions_cache: RefCell::new(None),
515            search_state: search::SearchState::new(),
516            custom_context_menu_entries: Vec::new(),
517            default_context_menu_enabled: true,
518            reveal_in_file_manager_enabled: false,
519            goto_line_state: goto_line::GotoLineState::new(),
520            vim_enabled: false,
521            vim_state: vim::VimState::default(),
522            translations: Translations::default(),
523            search_replace_enabled: true,
524            line_numbers_enabled: true,
525            show_whitespace: true,
526            bracket_match_highlight_enabled: true,
527            bracket_pair_colorization_enabled: true,
528            lsp_enabled: true,
529            lsp_client: None,
530            lsp_document: None,
531            lsp_pending_changes: Vec::new(),
532            lsp_shadow_text: String::new(),
533            lsp_shadow_is_current: true,
534            lsp_synced_line_count: 1,
535            lsp_synced_last_line_len: 0,
536            lsp_edit_snapshot: None,
537            lsp_auto_flush: true,
538            has_canvas_focus: false,
539            focus_locked: false,
540            show_cursor: false,
541            modifiers: Cell::new(iced::keyboard::Modifiers::default()),
542            last_click: Cell::new(None),
543            font: iced::Font::MONOSPACE,
544            ime_preedit: None,
545            font_size: FONT_SIZE,
546            full_char_width: CHAR_WIDTH * 2.0,
547            line_height: LINE_HEIGHT,
548            char_width: CHAR_WIDTH,
549            // Initialize render window tracking for virtual scrolling:
550            // these indices define the cached visual line window. The window is
551            // expanded beyond the visible range to amortize redraws and keep scrolling smooth.
552            last_first_visible_line: 0,
553            cache_window_start_line: 0,
554            cache_window_end_line: 0,
555            buffer_revision: 0,
556            visual_lines_cache: RefCell::new(None),
557            highlight_cache: RefCell::new(None),
558            highlight_lines_remaining: Cell::new(usize::MAX),
559            bracket_depth_cache: RefCell::new(BracketDepthCache::new()),
560            pre_edit_line: 0,
561            pre_edit_last_line: 0,
562        };
563
564        // Perform initial character dimension calculation
565        editor.recalculate_char_dimensions(false);
566
567        editor
568    }
569
570    /// Returns the current text content as a string.
571    ///
572    /// # Returns
573    ///
574    /// The complete text content of the editor
575    pub fn content(&self) -> String {
576        self.buffer.to_string()
577    }
578
579    /// Resets the editor with new content.
580    ///
581    /// This method replaces the buffer content and resets all editor state
582    /// (cursor position, selection, scroll, history) to initial values.
583    /// Use this instead of creating a new `CodeEditor` instance to ensure
584    /// proper widget tree updates in iced.
585    ///
586    /// Returns a `Task` that scrolls the editor to the top, which also
587    /// forces a redraw of the canvas.
588    ///
589    /// # Arguments
590    ///
591    /// * `content` - The new text content
592    ///
593    /// # Returns
594    ///
595    /// A `Task<Message>` that should be returned from your update function
596    ///
597    /// # Example
598    ///
599    /// ```ignore
600    /// use iced_code_editor::CodeEditor;
601    ///
602    /// let mut editor = CodeEditor::new("initial content", "lua");
603    /// // Later, reset with new content and get the task
604    /// let task = editor.reset("new content");
605    /// // Return task.map(YourMessage::Editor) from your update function
606    /// ```
607    pub fn reset(&mut self, content: &str) -> iced::Task<Message> {
608        self.buffer = TextBuffer::new(content);
609        self.cursors.set_single((0, 0));
610        self.vim_state.reset();
611        self.horizontal_scroll_offset = 0.0;
612        self.is_dragging = false;
613        self.viewport_scroll = 0.0;
614        self.history = CommandHistory::new(100);
615        self.is_grouping = false;
616        self.last_blink = Instant::now();
617        self.cursor_visible = true;
618        self.content_cache = canvas::Cache::default();
619        self.overlay_cache = canvas::Cache::default();
620        self.buffer_revision = self.buffer_revision.wrapping_add(1);
621        *self.visual_lines_cache.borrow_mut() = None;
622        // The buffer is fully replaced, so discard the whole highlight prefix.
623        self.pre_edit_line = 0;
624        self.pre_edit_last_line = usize::MAX;
625        self.invalidate_highlight_from(0);
626        *self.bracket_depth_cache.borrow_mut() = BracketDepthCache::new();
627        self.enqueue_lsp_change();
628
629        // Scroll to top to force a redraw
630        snap_to(self.scrollable_id.clone(), RelativeOffset::START)
631    }
632
633    /// Resets the cursor blink animation.
634    pub(crate) fn reset_cursor_blink(&mut self) {
635        self.last_blink = Instant::now();
636        self.cursor_visible = true;
637    }
638}