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