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