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