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