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