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