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