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.
74///
75/// The editor is a self-contained Iced widget: build one with [`Self::new`],
76/// render it with [`Self::view`], and feed the [`Message`]s it emits back into
77/// [`Self::update`]. Everything else โ€” syntax highlighting, multi-cursor,
78/// search/replace, folding, Vim mode, LSP synchronization โ€” is configured
79/// through the builder methods and setters on this type.
80///
81/// # Examples
82///
83/// ```
84/// use iced_code_editor::{CodeEditor, Message};
85///
86/// // Configure with the builder methods...
87/// let mut editor = CodeEditor::new("fn main() {}", "rs")
88///     .with_wrap_enabled(false)
89///     .with_line_numbers_enabled(true);
90///
91/// // ...then drive it with messages, as the host's `update` would.
92/// let _ = editor.update(&Message::Paste("// hello\n".to_string()));
93/// assert_eq!(editor.content(), "// hello\nfn main() {}");
94/// assert!(editor.is_modified());
95/// ```
96pub struct CodeEditor {
97    /// Unique ID for this editor instance (for focus management)
98    pub(crate) editor_id: u64,
99    /// Text buffer
100    pub(crate) buffer: TextBuffer,
101    /// All cursor positions (multi-cursor support).
102    pub(crate) cursors: cursor_set::CursorSet,
103    /// Horizontal scroll offset in pixels, only used when wrap_enabled = false
104    pub(crate) horizontal_scroll_offset: f32,
105    /// Editor theme style
106    pub(crate) style: Style,
107    /// Syntax highlighting language
108    pub(crate) syntax: String,
109    /// Last cursor blink time
110    pub(crate) last_blink: Instant,
111    /// Cursor visible state
112    pub(crate) cursor_visible: bool,
113    /// Mouse is currently dragging for selection
114    pub(crate) is_dragging: bool,
115    /// Cached geometry for the "content" layer.
116    ///
117    /// This layer includes expensive-to-build, mostly static visuals such as:
118    /// - syntax-highlighted text glyphs
119    /// - line numbers / gutter text
120    ///
121    /// It is intentionally kept stable across selection/cursor movement so
122    /// that mouse-drag selection feels smooth.
123    pub(crate) content_cache: canvas::Cache,
124    /// Cached geometry for the "overlay" layer.
125    ///
126    /// This layer includes visuals that change frequently without modifying the
127    /// underlying buffer, such as:
128    /// - cursor and current-line highlight
129    /// - selection highlight
130    /// - search match highlights
131    /// - IME preedit decorations
132    ///
133    /// Keeping overlays in a separate cache avoids invalidating the content
134    /// layer on every cursor blink or selection drag.
135    pub(crate) overlay_cache: canvas::Cache,
136    /// Scrollable ID for programmatic scrolling
137    pub(crate) scrollable_id: Id,
138    /// ID for the horizontal scrollable widget (only used when wrap_enabled = false)
139    pub(crate) horizontal_scrollable_id: Id,
140    /// Incremental per-line width index for the horizontal scrollbar.
141    pub(crate) max_content_width_cache: RefCell<Option<MaxContentWidthCache>>,
142    /// Current viewport scroll position (Y offset)
143    pub(crate) viewport_scroll: f32,
144    /// Viewport height (visible area)
145    pub(crate) viewport_height: f32,
146    /// Viewport width (visible area)
147    pub(crate) viewport_width: f32,
148    /// Command history for undo/redo
149    pub(crate) history: CommandHistory,
150    /// Whether we're currently grouping commands (for smart undo)
151    pub(crate) is_grouping: bool,
152    /// Line wrapping enabled
153    pub(crate) wrap_enabled: bool,
154    /// Auto-indentation enabled
155    pub(crate) auto_indent_enabled: bool,
156    /// Auto-closing of brackets/quotes and surround-selection enabled
157    pub(crate) auto_close_brackets: bool,
158    /// Indentation style (spaces or tab)
159    pub(crate) indent_style: IndentStyle,
160    /// Wrap column (None = wrap at viewport width)
161    pub(crate) wrap_column: Option<usize>,
162    /// Whether code folding (collapse/expand blocks) is enabled.
163    pub(crate) folding_enabled: bool,
164    /// Header line indices of regions that are currently collapsed.
165    pub(crate) collapsed_folds: HashSet<usize>,
166    /// Monotonic revision counter for fold state.
167    ///
168    /// Bumped whenever the collapsed set or the folding toggle changes, so that
169    /// derived layout caches (visual lines) are invalidated.
170    pub(crate) fold_revision: u64,
171    /// Cached foldable regions, keyed by `buffer_revision`.
172    pub(crate) foldable_regions_cache:
173        RefCell<Option<(u64, Rc<Vec<folding::FoldRegion>>)>>,
174    /// Search state
175    pub(crate) search_state: search::SearchState,
176    /// Custom entries displayed before the built-in context-menu actions.
177    custom_context_menu_entries: Vec<ContextMenuEntry>,
178    /// Whether the built-in editing actions are shown in the context menu.
179    default_context_menu_enabled: bool,
180    /// Whether the built-in reveal-in-file-manager action is shown.
181    reveal_in_file_manager_enabled: bool,
182    /// Go-to-line dialog state
183    pub(crate) goto_line_state: goto_line::GotoLineState,
184    /// Whether Vim key handling is enabled for this editor instance.
185    vim_enabled: bool,
186    /// Per-editor Vim mode, parser prefixes and unnamed register.
187    pub(crate) vim_state: vim::VimState,
188    /// Translations for UI text
189    pub(crate) translations: Translations,
190    /// Whether search/replace functionality is enabled
191    pub(crate) search_replace_enabled: bool,
192    /// Whether line numbers are displayed
193    pub(crate) line_numbers_enabled: bool,
194    /// Whether to render whitespace characters visibly (spaces as `ยท`, tabs as `โ†’`)
195    pub(crate) show_whitespace: bool,
196    /// Whether the matching-bracket/quote-pair highlight overlay is enabled.
197    pub(crate) bracket_match_highlight_enabled: bool,
198    /// Whether bracket-pair colorization (rainbow brackets) is enabled.
199    pub(crate) bracket_pair_colorization_enabled: bool,
200    /// Whether LSP support is enabled
201    pub(crate) lsp_enabled: bool,
202    /// Active LSP client connection, if configured.
203    pub(crate) lsp_client: Option<Box<dyn lsp::LspClient>>,
204    /// Metadata for the currently open LSP document.
205    pub(crate) lsp_document: Option<lsp::LspDocument>,
206    /// Pending incremental LSP text changes not yet flushed.
207    pub(crate) lsp_pending_changes: Vec<lsp::LspTextChange>,
208    /// Shadow copy of buffer content used to compute LSP deltas.
209    pub(crate) lsp_shadow_text: String,
210    /// Whether `lsp_shadow_text` still exactly matches the server document.
211    pub(crate) lsp_shadow_is_current: bool,
212    /// Current server-side line count, maintained incrementally.
213    pub(crate) lsp_synced_line_count: usize,
214    /// Length of the current server-side final line in Unicode scalar values.
215    pub(crate) lsp_synced_last_line_len: usize,
216    /// Pre-edit range used to build a bounded incremental LSP change.
217    pub(crate) lsp_edit_snapshot: Option<LspEditSnapshot>,
218    /// Whether to auto-flush LSP changes after edits.
219    pub(crate) lsp_auto_flush: bool,
220    /// Whether the canvas has user input focus (for keyboard events)
221    pub(crate) has_canvas_focus: bool,
222    /// Whether input processing is locked to prevent focus stealing
223    pub(crate) focus_locked: bool,
224    /// Whether to show the cursor (for rendering)
225    pub(crate) show_cursor: bool,
226    /// Current keyboard modifiers state (Ctrl, Alt, Shift, Logo).
227    ///
228    /// This is updated via subscription events and used to handle modifier-dependent
229    /// interactions, such as "Ctrl+Click" for jumping to a definition.
230    pub(crate) modifiers: Cell<iced::keyboard::Modifiers>,
231    /// Last left-button press (time, position, consecutive count), used to
232    /// detect double/triple clicks.
233    pub(crate) last_click: Cell<Option<(Instant, iced::Point, u8)>>,
234    /// The font used for rendering text
235    pub(crate) font: iced::Font,
236    /// IME pre-edit state (for CJK input)
237    pub(crate) ime_preedit: Option<ImePreedit>,
238    /// Font size in pixels
239    pub(crate) font_size: f32,
240    /// Full character width (wide chars like CJK) in pixels
241    pub(crate) full_char_width: f32,
242    /// Line height in pixels
243    pub(crate) line_height: f32,
244    /// Character width in pixels
245    pub(crate) char_width: f32,
246    /// Cached render window: the first visual line index included in the cache.
247    /// We keep a larger window than the currently visible range to avoid clearing
248    /// the canvas cache on every small scroll. Only when scrolling crosses the
249    /// window boundary do we re-window and clear the cache.
250    pub(crate) last_first_visible_line: usize,
251    /// Cached render window start line (inclusive)
252    pub(crate) cache_window_start_line: usize,
253    /// Cached render window end line (exclusive)
254    pub(crate) cache_window_end_line: usize,
255    /// Monotonic revision counter for buffer content.
256    ///
257    /// Any operation that changes the buffer must bump this counter to
258    /// invalidate derived layout caches (e.g. wrapping / visual lines). The
259    /// exact value is not semantically meaningful, so `wrapping_add` is used to
260    /// avoid overflow panics while still producing a different key.
261    pub(crate) buffer_revision: u64,
262    /// Cached result of line wrapping ("visual lines") for the current layout key.
263    ///
264    /// This is stored behind a `RefCell` because wrapping is needed during
265    /// rendering (where we only have `&self`), but we still want to memoize the
266    /// expensive computation without forcing external mutability.
267    visual_lines_cache: RefCell<Option<VisualLinesCache>>,
268    /// Sequential per-line syntax-highlight cache (see [`HighlightCache`]).
269    ///
270    /// Stored behind a `RefCell` because highlighting is performed during
271    /// rendering (where only `&self` is available) yet should be memoized.
272    /// Spans are reused across wrapped visual segments and across scroll-only
273    /// renders. On an edit the cache is truncated from the first changed line
274    /// (tracked via `pre_edit_line`) rather than fully cleared, so multi-line
275    /// constructs stay correct without re-parsing the whole file.
276    pub(crate) highlight_cache: RefCell<Option<HighlightCache>>,
277    /// Remaining syntax lines that may be parsed during the current content
278    /// render. `usize::MAX` keeps direct non-render uses (notably tests) uncapped.
279    pub(crate) highlight_lines_remaining: Cell<usize>,
280    /// Sequential per-line bracket-nesting-depth cache (see [`BracketDepthCache`]),
281    /// used by bracket-pair colorization. Stored behind a `RefCell` for the same
282    /// reason as `highlight_cache`: it is memoized during rendering (`&self`).
283    pub(crate) bracket_depth_cache: RefCell<BracketDepthCache>,
284    /// Topmost logical line touched by the cursors/selections before the
285    /// current edit, captured at the top of `update()`.
286    ///
287    /// Used as a conservative lower bound for the first line an edit may
288    /// change, to truncate `highlight_cache` precisely.
289    pub(crate) pre_edit_line: usize,
290    /// Bottommost logical line touched before the current edit.
291    ///
292    /// Together with `pre_edit_line`, this bounds the portion of the visual-line
293    /// cache that must be rebuilt after a localized edit.
294    pub(crate) pre_edit_last_line: usize,
295}
296
297/// Messages emitted by the code editor
298///
299/// A host application forwards these to [`CodeEditor::update`]. They are also
300/// the programmatic control surface: sending a variant directly performs the
301/// same action as the user gesture that would normally produce it, which is
302/// how a host wires its own menu items and toolbar buttons to editor commands.
303///
304/// # Examples
305///
306/// ```
307/// use iced_code_editor::{CodeEditor, Message};
308///
309/// let mut editor = CodeEditor::new("hello", "rs");
310///
311/// // Drive an edit as if the user had pasted.
312/// let _ = editor.update(&Message::Paste(" world".to_string()));
313/// assert_eq!(editor.content(), " worldhello");
314///
315/// // And undo it the same way a menu item would.
316/// let _ = editor.update(&Message::Undo);
317/// assert_eq!(editor.content(), "hello");
318/// ```
319#[derive(Debug, Clone)]
320pub enum Message {
321    /// Character typed
322    CharacterInput(char),
323    /// A printable key interpreted by the Vim state machine.
324    VimKey(char),
325    /// Toggle Vim behavior for this editor instance.
326    ToggleVimMode,
327    /// Requests that the host save this editor's current document.
328    WriteRequested,
329    /// Backspace pressed
330    Backspace,
331    /// Delete pressed
332    Delete,
333    /// Enter pressed
334    Enter,
335    /// Tab pressed (inserts 4 spaces)
336    Tab,
337    /// Arrow key pressed (direction, shift_pressed)
338    ArrowKey(ArrowDirection, bool),
339    /// Mouse clicked at position
340    MouseClick(iced::Point),
341    /// Mouse drag for selection
342    MouseDrag(iced::Point),
343    /// Mouse moved within the editor without dragging
344    MouseHover(iced::Point),
345    /// Mouse released
346    MouseRelease,
347    /// Double-click: select the word under the cursor
348    DoubleClick(iced::Point),
349    /// Triple-click: select the whole line under the cursor
350    TripleClick(iced::Point),
351    /// Right-clicked in the editor to position and open the context menu
352    ContextMenuRequested(iced::Point),
353    /// A configured context-menu action was selected.
354    CustomContextMenuAction(String),
355    /// Requests that the host reveal the editor's file in the system file manager.
356    RevealInFileManager,
357    /// Cut selected text
358    Cut,
359    /// Copy selected text (Ctrl+C)
360    Copy,
361    /// Paste text from clipboard (Ctrl+V)
362    Paste(String),
363    /// Delete selected text (Shift+Delete)
364    DeleteSelection,
365    /// Select the complete document
366    SelectAll,
367    /// Request redraw for cursor blink
368    Tick,
369    /// Page Up pressed
370    PageUp,
371    /// Page Down pressed
372    PageDown,
373    /// Home key pressed (move to start of line, shift_pressed)
374    Home(bool),
375    /// End key pressed (move to end of line, shift_pressed)
376    End(bool),
377    /// Ctrl+Home pressed (move to start of document)
378    CtrlHome,
379    /// Ctrl+End pressed (move to end of document)
380    CtrlEnd,
381    /// Go to an explicit logical position (line, column), both 0-based.
382    GotoPosition(usize, usize),
383    /// Open the go-to-line dialog (Cmd/Ctrl+G).
384    OpenGotoLine,
385    /// Close the go-to-line dialog.
386    CloseGotoLine,
387    /// Change the one-based line number shown in the go-to-line input.
388    GotoLineChanged(String),
389    /// Submit the current go-to-line input.
390    SubmitGotoLine,
391    /// Viewport scrolled - track scroll position
392    Scrolled(iced::widget::scrollable::Viewport),
393    /// Horizontal scrollbar scrolled (only when wrap is disabled)
394    HorizontalScrolled(iced::widget::scrollable::Viewport),
395    /// Undo last operation (Ctrl+Z)
396    Undo,
397    /// Redo last undone operation (Ctrl+Y)
398    Redo,
399    /// Open search dialog (Ctrl+F)
400    OpenSearch,
401    /// Open search and replace dialog (Ctrl+H)
402    OpenSearchReplace,
403    /// Close search dialog (Escape)
404    CloseSearch,
405    /// Search query text changed
406    SearchQueryChanged(String),
407    /// Replace text changed
408    ReplaceQueryChanged(String),
409    /// Toggle case sensitivity
410    ToggleCaseSensitive,
411    /// Find next match (F3)
412    FindNext,
413    /// Find previous match (Shift+F3)
414    FindPrevious,
415    /// Replace current match
416    ReplaceNext,
417    /// Replace all matches
418    ReplaceAll,
419    /// Tab pressed in search dialog (cycle forward)
420    SearchDialogTab,
421    /// Shift+Tab pressed in search dialog (cycle backward)
422    SearchDialogShiftTab,
423    /// Shift+Tab pressed for focus navigation (when search dialog is not open)
424    FocusNavigationShiftTab,
425    /// Canvas gained focus (mouse click)
426    CanvasFocusGained,
427    /// Canvas lost focus (external widget interaction)
428    CanvasFocusLost,
429    /// Triggered when the user performs a Ctrl+Click (or Cmd+Click on macOS)
430    /// on the editor content, intending to jump to the definition of the symbol
431    /// under the cursor.
432    JumpClick(iced::Point),
433    /// IME input method opened
434    ImeOpened,
435    /// IME pre-edit update (content, selection range)
436    ImePreedit(String, Option<Range<usize>>),
437    /// IME commit text
438    ImeCommit(String),
439    /// IME input method closed
440    ImeClosed,
441    /// Alt+Click: add a new cursor at the given canvas position
442    AltClick(iced::Point),
443    /// Ctrl+Alt+Up: add a cursor on the line above the primary cursor
444    AddCursorAbove,
445    /// Ctrl+Alt+Down: add a cursor on the line below the primary cursor
446    AddCursorBelow,
447    /// Ctrl+D: select the next occurrence of the currently selected text (or word under cursor)
448    SelectNextOccurrence,
449    /// Toggle the collapsed state of the fold whose header is the given logical line.
450    ToggleFold(usize),
451    /// Toggle the collapsed state of the innermost block containing the primary cursor.
452    ToggleFoldAtCursor,
453    /// Fold every foldable block in the buffer.
454    FoldAll,
455    /// Unfold every collapsed block in the buffer.
456    UnfoldAll,
457    /// Alt+Up: move the current line (or selected line range) up by one line.
458    MoveLineUp,
459    /// Alt+Down: move the current line (or selected line range) down by one line.
460    MoveLineDown,
461    /// Shift+Alt+Up: duplicate the current line (or selected line range) above.
462    DuplicateLineUp,
463    /// Shift+Alt+Down: duplicate the current line (or selected line range) below.
464    DuplicateLineDown,
465    /// Ctrl+/: toggle line comments on the current line or primary selection.
466    ToggleComment,
467}
468
469/// Indentation style used when pressing the Tab key.
470///
471/// Controls whether indentation inserts spaces or a tab character.
472///
473/// Implements [`Display`](std::fmt::Display) with a human-readable label
474/// (`"4 spaces"`, `"Tab"`), so it can be dropped straight into a settings
475/// picker.
476///
477/// # Examples
478///
479/// ```
480/// use iced_code_editor::{CodeEditor, IndentStyle};
481///
482/// let mut editor = CodeEditor::new("fn main() {}", "rs");
483/// assert_eq!(editor.indent_style(), IndentStyle::Spaces(4));
484///
485/// editor.set_indent_style(IndentStyle::Tab);
486/// assert_eq!(editor.indent_style().to_string(), "Tab");
487/// assert_eq!(IndentStyle::Spaces(2).to_string(), "2 spaces");
488/// ```
489#[derive(Debug, Clone, Copy, PartialEq, Eq)]
490pub enum IndentStyle {
491    /// Insert `n` space characters.
492    Spaces(u8),
493    /// Insert a single tab character (`\t`).
494    Tab,
495}
496
497impl IndentStyle {
498    /// All standard indentation styles available for selection.
499    ///
500    /// Iterate this to build a settings picker, rather than hardcoding the
501    /// list at each call site.
502    ///
503    /// # Examples
504    ///
505    /// ```
506    /// use iced_code_editor::IndentStyle;
507    ///
508    /// let labels: Vec<String> =
509    ///     IndentStyle::ALL.iter().map(ToString::to_string).collect();
510    /// assert_eq!(labels, ["2 spaces", "4 spaces", "8 spaces", "Tab"]);
511    /// ```
512    pub const ALL: [IndentStyle; 4] = [
513        IndentStyle::Spaces(2),
514        IndentStyle::Spaces(4),
515        IndentStyle::Spaces(8),
516        IndentStyle::Tab,
517    ];
518}
519
520impl std::fmt::Display for IndentStyle {
521    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
522        match self {
523            IndentStyle::Spaces(1) => write!(f, "1 space"),
524            IndentStyle::Spaces(n) => write!(f, "{n} spaces"),
525            IndentStyle::Tab => write!(f, "Tab"),
526        }
527    }
528}
529
530/// Arrow key directions
531///
532/// Carried by [`Message::ArrowKey`] alongside a flag for whether Shift was
533/// held, which is what turns a move into a selection.
534///
535/// # Examples
536///
537/// ```
538/// use iced_code_editor::{ArrowDirection, CodeEditor, Message};
539///
540/// let mut editor = CodeEditor::new("hello", "rs");
541///
542/// // Move right without extending a selection.
543/// let _ = editor.update(&Message::ArrowKey(ArrowDirection::Right, false));
544/// ```
545#[derive(Debug, Clone, Copy)]
546pub enum ArrowDirection {
547    /// Up arrow key.
548    Up,
549    /// Down arrow key.
550    Down,
551    /// Left arrow key.
552    Left,
553    /// Right arrow key.
554    Right,
555}
556
557impl CodeEditor {
558    /// Creates a new canvas-based text editor.
559    ///
560    /// # Arguments
561    ///
562    /// * `content` - Initial text content
563    /// * `syntax` - Syntax highlighting language (e.g., "py", "lua", "rs")
564    ///
565    /// # Returns
566    ///
567    /// A new `CodeEditor` instance
568    ///
569    /// # Example
570    ///
571    /// ```
572    /// use iced_code_editor::CodeEditor;
573    ///
574    /// let editor = CodeEditor::new("fn main() {}", "rs");
575    /// assert_eq!(editor.content(), "fn main() {}");
576    /// assert_eq!(editor.syntax(), "rs");
577    ///
578    /// // A new editor starts clean, with nothing to undo.
579    /// assert!(!editor.is_modified());
580    /// assert!(!editor.can_undo());
581    /// ```
582    pub fn new(content: &str, syntax: &str) -> Self {
583        // Generate a unique ID for this editor instance
584        let editor_id = EDITOR_ID_COUNTER.fetch_add(1, Ordering::Relaxed);
585
586        // Give focus to the first editor created (ID == 1)
587        if editor_id == 1 {
588            FOCUSED_EDITOR_ID.store(editor_id, Ordering::Relaxed);
589        }
590
591        let mut editor = Self {
592            editor_id,
593            buffer: TextBuffer::new(content),
594            cursors: cursor_set::CursorSet::new((0, 0)),
595            horizontal_scroll_offset: 0.0,
596            style: crate::theme::from_iced_theme(&iced::Theme::TokyoNightStorm),
597            syntax: syntax.to_string(),
598            last_blink: Instant::now(),
599            cursor_visible: true,
600            is_dragging: false,
601            content_cache: canvas::Cache::default(),
602            overlay_cache: canvas::Cache::default(),
603            scrollable_id: Id::unique(),
604            horizontal_scrollable_id: Id::unique(),
605            max_content_width_cache: RefCell::new(None),
606            viewport_scroll: 0.0,
607            viewport_height: 600.0, // Default, will be updated
608            viewport_width: 800.0,  // Default, will be updated
609            history: CommandHistory::new(100),
610            is_grouping: false,
611            wrap_enabled: true,
612            auto_indent_enabled: true,
613            auto_close_brackets: true,
614            indent_style: IndentStyle::Spaces(4),
615            wrap_column: None,
616            folding_enabled: true,
617            collapsed_folds: HashSet::new(),
618            fold_revision: 0,
619            foldable_regions_cache: RefCell::new(None),
620            search_state: search::SearchState::new(),
621            custom_context_menu_entries: Vec::new(),
622            default_context_menu_enabled: true,
623            reveal_in_file_manager_enabled: false,
624            goto_line_state: goto_line::GotoLineState::new(),
625            vim_enabled: false,
626            vim_state: vim::VimState::default(),
627            translations: Translations::default(),
628            search_replace_enabled: true,
629            line_numbers_enabled: true,
630            show_whitespace: true,
631            bracket_match_highlight_enabled: true,
632            bracket_pair_colorization_enabled: true,
633            lsp_enabled: true,
634            lsp_client: None,
635            lsp_document: None,
636            lsp_pending_changes: Vec::new(),
637            lsp_shadow_text: String::new(),
638            lsp_shadow_is_current: true,
639            lsp_synced_line_count: 1,
640            lsp_synced_last_line_len: 0,
641            lsp_edit_snapshot: None,
642            lsp_auto_flush: true,
643            has_canvas_focus: false,
644            focus_locked: false,
645            show_cursor: false,
646            modifiers: Cell::new(iced::keyboard::Modifiers::default()),
647            last_click: Cell::new(None),
648            font: iced::Font::MONOSPACE,
649            ime_preedit: None,
650            font_size: FONT_SIZE,
651            full_char_width: CHAR_WIDTH * 2.0,
652            line_height: LINE_HEIGHT,
653            char_width: CHAR_WIDTH,
654            // Initialize render window tracking for virtual scrolling:
655            // these indices define the cached visual line window. The window is
656            // expanded beyond the visible range to amortize redraws and keep scrolling smooth.
657            last_first_visible_line: 0,
658            cache_window_start_line: 0,
659            cache_window_end_line: 0,
660            buffer_revision: 0,
661            visual_lines_cache: RefCell::new(None),
662            highlight_cache: RefCell::new(None),
663            highlight_lines_remaining: Cell::new(usize::MAX),
664            bracket_depth_cache: RefCell::new(BracketDepthCache::new()),
665            pre_edit_line: 0,
666            pre_edit_last_line: 0,
667        };
668
669        // Perform initial character dimension calculation
670        editor.recalculate_char_dimensions(false);
671
672        editor
673    }
674
675    /// Returns the current text content as a string.
676    ///
677    /// The buffer's original line endings and trailing newline are preserved,
678    /// so the result round-trips back to disk unchanged when nothing was
679    /// edited.
680    ///
681    /// This allocates the whole document, so prefer calling it when saving
682    /// rather than on every frame.
683    ///
684    /// # Returns
685    ///
686    /// The complete text content of the editor
687    ///
688    /// # Example
689    ///
690    /// ```
691    /// use iced_code_editor::{CodeEditor, Message};
692    ///
693    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
694    /// assert_eq!(editor.content(), "fn main() {}");
695    ///
696    /// let _ = editor.update(&Message::Paste("// note\n".to_string()));
697    /// assert_eq!(editor.content(), "// note\nfn main() {}");
698    /// ```
699    pub fn content(&self) -> String {
700        self.buffer.to_string()
701    }
702
703    /// Resets the editor with new content.
704    ///
705    /// This method replaces the buffer content and resets all editor state
706    /// (cursor position, selection, scroll, history) to initial values.
707    /// Use this instead of creating a new `CodeEditor` instance to ensure
708    /// proper widget tree updates in iced.
709    ///
710    /// Returns a `Task` that scrolls the editor to the top, which also
711    /// forces a redraw of the canvas.
712    ///
713    /// # Arguments
714    ///
715    /// * `content` - The new text content
716    ///
717    /// # Returns
718    ///
719    /// A `Task<Message>` that should be returned from your update function
720    ///
721    /// # Example
722    ///
723    /// ```no_run
724    /// use iced_code_editor::CodeEditor;
725    ///
726    /// let mut editor = CodeEditor::new("initial content", "lua");
727    /// // Later, reset with new content and get the task
728    /// let task = editor.reset("new content");
729    /// // Return task.map(YourMessage::Editor) from your update function
730    /// ```
731    pub fn reset(&mut self, content: &str) -> iced::Task<Message> {
732        self.buffer = TextBuffer::new(content);
733        self.cursors.set_single((0, 0));
734        self.vim_state.reset();
735        self.horizontal_scroll_offset = 0.0;
736        self.is_dragging = false;
737        self.viewport_scroll = 0.0;
738        self.history = CommandHistory::new(100);
739        self.is_grouping = false;
740        self.last_blink = Instant::now();
741        self.cursor_visible = true;
742        self.content_cache = canvas::Cache::default();
743        self.overlay_cache = canvas::Cache::default();
744        self.buffer_revision = self.buffer_revision.wrapping_add(1);
745        *self.visual_lines_cache.borrow_mut() = None;
746        // The buffer is fully replaced, so discard the whole highlight prefix.
747        self.pre_edit_line = 0;
748        self.pre_edit_last_line = usize::MAX;
749        self.invalidate_highlight_from(0);
750        *self.bracket_depth_cache.borrow_mut() = BracketDepthCache::new();
751        self.enqueue_lsp_change();
752
753        // Scroll to top to force a redraw
754        snap_to(self.scrollable_id.clone(), RelativeOffset::START)
755    }
756
757    /// Resets the cursor blink animation.
758    pub(crate) fn reset_cursor_blink(&mut self) {
759        self.last_blink = Instant::now();
760        self.cursor_visible = true;
761    }
762}