pub struct CodeEditor { /* private fields */ }Expand description
Canvas-based high-performance text editor.
The editor is a self-contained Iced widget: build one with Self::new,
render it with Self::view, and feed the Messages it emits back into
Self::update. Everything else — syntax highlighting, multi-cursor,
search/replace, folding, Vim mode, LSP synchronization — is configured
through the builder methods and setters on this type.
§Examples
use iced_code_editor::{CodeEditor, Message};
// Configure with the builder methods...
let mut editor = CodeEditor::new("fn main() {}", "rs")
.with_wrap_enabled(false)
.with_line_numbers_enabled(true);
// ...then drive it with messages, as the host's `update` would.
let _ = editor.update(&Message::Paste("// hello\n".to_string()));
assert_eq!(editor.content(), "// hello\nfn main() {}");
assert!(editor.is_modified());Implementations§
Source§impl CodeEditor
impl CodeEditor
Sourcepub fn auto_close_brackets(&self) -> bool
pub fn auto_close_brackets(&self) -> bool
Returns whether auto-closing of brackets and quotes is enabled.
§Returns
true if auto-closing is enabled, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Enabled by default.
assert!(editor.auto_close_brackets());
editor.set_auto_close_brackets(true);
assert!(editor.auto_close_brackets());
editor.set_auto_close_brackets(false);
assert!(!editor.auto_close_brackets());Sourcepub fn auto_indent_enabled(&self) -> bool
pub fn auto_indent_enabled(&self) -> bool
Returns whether auto-indentation is enabled.
§Returns
true if auto-indentation is enabled, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Enabled by default.
assert!(editor.auto_indent_enabled());
editor.set_auto_indent_enabled(true);
assert!(editor.auto_indent_enabled());
editor.set_auto_indent_enabled(false);
assert!(!editor.auto_indent_enabled());Sourcepub fn bracket_match_highlight_enabled(&self) -> bool
pub fn bracket_match_highlight_enabled(&self) -> bool
Returns whether the matching-bracket/quote-pair highlight overlay is enabled.
§Returns
true if the highlight is enabled, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Enabled by default.
assert!(editor.bracket_match_highlight_enabled());
editor.set_bracket_match_highlight_enabled(true);
assert!(editor.bracket_match_highlight_enabled());
editor.set_bracket_match_highlight_enabled(false);
assert!(!editor.bracket_match_highlight_enabled());Sourcepub fn bracket_pair_colorization_enabled(&self) -> bool
pub fn bracket_pair_colorization_enabled(&self) -> bool
Returns whether bracket-pair colorization (rainbow brackets) is enabled.
§Returns
true if bracket-pair colorization is enabled, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Enabled by default.
assert!(editor.bracket_pair_colorization_enabled());
editor.set_bracket_pair_colorization_enabled(true);
assert!(editor.bracket_pair_colorization_enabled());
editor.set_bracket_pair_colorization_enabled(false);
assert!(!editor.bracket_pair_colorization_enabled());Sourcepub fn command_palette_enabled(&self) -> bool
pub fn command_palette_enabled(&self) -> bool
Returns whether the command palette can be opened.
§Returns
true if the palette can be opened, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Available by default.
assert!(editor.command_palette_enabled());
editor.set_command_palette_enabled(true);
assert!(editor.command_palette_enabled());
editor.set_command_palette_enabled(false);
assert!(!editor.command_palette_enabled());Sourcepub fn with_command_palette_enabled(self, enabled: bool) -> Self
pub fn with_command_palette_enabled(self, enabled: bool) -> Self
Sets command-palette availability using the builder pattern.
§Arguments
enabled- Whether the palette can be opened
§Returns
Self for method chaining
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_command_palette_enabled(false);
assert!(!editor.command_palette_enabled());Sourcepub fn default_command_palette_enabled(&self) -> bool
pub fn default_command_palette_enabled(&self) -> bool
Returns whether the built-in commands are listed in the palette.
§Returns
true if the built-in commands are listed, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Listed by default.
assert!(editor.default_command_palette_enabled());
editor.set_default_command_palette_enabled(true);
assert!(editor.default_command_palette_enabled());
editor.set_default_command_palette_enabled(false);
assert!(!editor.default_command_palette_enabled());Returns whether the built-in context-menu actions are enabled.
§Returns
true if the built-in actions are shown, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Shown by default.
assert!(editor.default_context_menu_enabled());
editor.set_default_context_menu_enabled(true);
assert!(editor.default_context_menu_enabled());
editor.set_default_context_menu_enabled(false);
assert!(!editor.default_context_menu_enabled());Sets built-in context-menu visibility using the builder pattern.
§Arguments
enabled- Whether to show the built-in actions
§Returns
Self for method chaining
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_default_context_menu_enabled(false);
assert!(!editor.default_context_menu_enabled());Sourcepub fn diagnostics_enabled(&self) -> bool
pub fn diagnostics_enabled(&self) -> bool
Returns whether diagnostics are underlined and reported on hover.
§Returns
true if diagnostics are shown, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Enabled by default.
assert!(editor.diagnostics_enabled());
editor.set_diagnostics_enabled(true);
assert!(editor.diagnostics_enabled());
editor.set_diagnostics_enabled(false);
assert!(!editor.diagnostics_enabled());Sourcepub fn with_diagnostics_enabled(self, enabled: bool) -> Self
pub fn with_diagnostics_enabled(self, enabled: bool) -> Self
Enables or disables diagnostics using the builder pattern.
§Arguments
enabled- Whether to underline and report diagnostics
§Returns
Self for method chaining
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_diagnostics_enabled(false);
assert!(!editor.diagnostics_enabled());Sourcepub fn folding_enabled(&self) -> bool
pub fn folding_enabled(&self) -> bool
Returns whether code folding is enabled.
§Returns
true if code folding is enabled, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Enabled by default.
assert!(editor.folding_enabled());
editor.set_folding_enabled(true);
assert!(editor.folding_enabled());
editor.set_folding_enabled(false);
assert!(!editor.folding_enabled());Sourcepub fn with_folding_enabled(self, enabled: bool) -> Self
pub fn with_folding_enabled(self, enabled: bool) -> Self
Enables or disables code folding using the builder pattern.
§Arguments
enabled- Whether to enable code folding
§Returns
Self for method chaining
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_folding_enabled(false);
assert!(!editor.folding_enabled());Sourcepub fn line_numbers_enabled(&self) -> bool
pub fn line_numbers_enabled(&self) -> bool
Returns whether line numbers are displayed.
§Returns
true if line numbers are displayed, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Displayed by default.
assert!(editor.line_numbers_enabled());
editor.set_line_numbers_enabled(true);
assert!(editor.line_numbers_enabled());
editor.set_line_numbers_enabled(false);
assert!(!editor.line_numbers_enabled());Sourcepub fn with_line_numbers_enabled(self, enabled: bool) -> Self
pub fn with_line_numbers_enabled(self, enabled: bool) -> Self
Sets the line numbers display with builder pattern.
§Arguments
enabled- Whether to display line numbers
§Returns
Self for method chaining
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_line_numbers_enabled(false);
assert!(!editor.line_numbers_enabled());Sourcepub fn reveal_in_file_manager_enabled(&self) -> bool
pub fn reveal_in_file_manager_enabled(&self) -> bool
Returns whether the reveal-in-file-manager action is shown.
§Returns
true if the reveal action is shown, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Off by default: the editor doesn't know its own file path.
assert!(!editor.reveal_in_file_manager_enabled());
editor.set_reveal_in_file_manager_enabled(true);
assert!(editor.reveal_in_file_manager_enabled());
editor.set_reveal_in_file_manager_enabled(false);
assert!(!editor.reveal_in_file_manager_enabled());Sourcepub fn search_replace_enabled(&self) -> bool
pub fn search_replace_enabled(&self) -> bool
Returns whether search/replace functionality is enabled.
§Returns
true if search/replace is enabled, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Enabled by default.
assert!(editor.search_replace_enabled());
editor.set_search_replace_enabled(true);
assert!(editor.search_replace_enabled());
editor.set_search_replace_enabled(false);
assert!(!editor.search_replace_enabled());Sourcepub fn with_search_replace_enabled(self, enabled: bool) -> Self
pub fn with_search_replace_enabled(self, enabled: bool) -> Self
Enables or disables search/replace using the builder pattern.
§Arguments
enabled- Whether to enable search/replace functionality
§Returns
Self for method chaining
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_search_replace_enabled(false);
assert!(!editor.search_replace_enabled());Sourcepub fn show_color_previews(&self) -> bool
pub fn show_color_previews(&self) -> bool
Returns whether inline color previews are drawn.
§Returns
true if color-preview swatches are rendered, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Enabled by default.
assert!(editor.show_color_previews());
editor.set_show_color_previews(true);
assert!(editor.show_color_previews());
editor.set_show_color_previews(false);
assert!(!editor.show_color_previews());Sourcepub fn with_show_color_previews(self, enabled: bool) -> Self
pub fn with_show_color_previews(self, enabled: bool) -> Self
Sets the inline color-preview display with builder pattern.
§Arguments
enabled- Whether to draw color-preview swatches
§Returns
Self for method chaining
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_show_color_previews(false);
assert!(!editor.show_color_previews());Sourcepub fn show_indent_guides(&self) -> bool
pub fn show_indent_guides(&self) -> bool
Returns whether indentation guides are drawn.
§Returns
true if indentation guides are rendered, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Enabled by default.
assert!(editor.show_indent_guides());
editor.set_show_indent_guides(true);
assert!(editor.show_indent_guides());
editor.set_show_indent_guides(false);
assert!(!editor.show_indent_guides());Sourcepub fn with_show_indent_guides(self, enabled: bool) -> Self
pub fn with_show_indent_guides(self, enabled: bool) -> Self
Sets the indentation-guide display with builder pattern.
§Arguments
enabled- Whether to draw indentation guides
§Returns
Self for method chaining
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_show_indent_guides(false);
assert!(!editor.show_indent_guides());Sourcepub fn show_whitespace(&self) -> bool
pub fn show_whitespace(&self) -> bool
Returns whether visible whitespace rendering is enabled.
§Returns
true if whitespace characters are rendered, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Enabled by default.
assert!(editor.show_whitespace());
editor.set_show_whitespace(true);
assert!(editor.show_whitespace());
editor.set_show_whitespace(false);
assert!(!editor.show_whitespace());Sourcepub fn sticky_scroll_enabled(&self) -> bool
pub fn sticky_scroll_enabled(&self) -> bool
Returns whether sticky scroll is enabled.
§Returns
true if enclosing block headers are pinned, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Enabled by default.
assert!(editor.sticky_scroll_enabled());
editor.set_sticky_scroll_enabled(true);
assert!(editor.sticky_scroll_enabled());
editor.set_sticky_scroll_enabled(false);
assert!(!editor.sticky_scroll_enabled());Sourcepub fn with_sticky_scroll_enabled(self, enabled: bool) -> Self
pub fn with_sticky_scroll_enabled(self, enabled: bool) -> Self
Sets sticky scroll with builder pattern.
§Arguments
enabled- Whether to pin enclosing block headers above the viewport
§Returns
Self for method chaining
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_sticky_scroll_enabled(false);
assert!(!editor.sticky_scroll_enabled());Sourcepub fn vim_enabled(&self) -> bool
pub fn vim_enabled(&self) -> bool
Returns whether Vim behavior is enabled for this editor instance.
§Returns
true if Vim behavior is enabled, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Off by default.
assert!(!editor.vim_enabled());
editor.set_vim_enabled(true);
assert!(editor.vim_enabled());
editor.set_vim_enabled(false);
assert!(!editor.vim_enabled());Sourcepub fn with_vim_enabled(self, enabled: bool) -> Self
pub fn with_vim_enabled(self, enabled: bool) -> Self
Sets whether Vim behavior is enabled using the builder pattern.
§Arguments
enabled- Whether to enable Vim behavior
§Returns
Self for method chaining
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_vim_enabled(false);
assert!(!editor.vim_enabled());Sourcepub fn wrap_enabled(&self) -> bool
pub fn wrap_enabled(&self) -> bool
Returns whether line wrapping is enabled.
§Returns
true if line wrapping is enabled, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Enabled by default.
assert!(editor.wrap_enabled());
editor.set_wrap_enabled(true);
assert!(editor.wrap_enabled());
editor.set_wrap_enabled(false);
assert!(!editor.wrap_enabled());Sourcepub fn with_wrap_enabled(self, enabled: bool) -> Self
pub fn with_wrap_enabled(self, enabled: bool) -> Self
Source§impl CodeEditor
impl CodeEditor
Replaces the custom context-menu entries.
Custom entries are shown in addition to the built-in editing actions;
see Self::set_default_context_menu_enabled to hide those.
§Arguments
entries- The entries to display, in order
§Example
use iced_code_editor::{CodeEditor, ContextMenuEntry};
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_custom_context_menu_entries(vec![
ContextMenuEntry::item("format", "Format Document")
.with_shortcut("Ctrl+Shift+F"),
ContextMenuEntry::separator(),
ContextMenuEntry::item("rename", "Rename Symbol").with_enabled(false),
]);
assert_eq!(editor.custom_context_menu_entries().len(), 3);Replaces the custom context-menu entries using the builder pattern.
§Arguments
entries- The entries to display, in order
§Returns
Self for method chaining
§Example
use iced_code_editor::{CodeEditor, ContextMenuEntry};
let editor = CodeEditor::new("fn main() {}", "rs")
.with_custom_context_menu_entries(vec![
ContextMenuEntry::item("format", "Format Document"),
]);
assert_eq!(editor.custom_context_menu_entries().len(), 1);Sets whether the built-in editing actions appear in the context menu.
The built-in actions are undo/redo, cut/copy/paste, and select all. Disabling them leaves only the custom entries, which is how a host application replaces the menu wholesale rather than extending it.
§Arguments
enabled- Whether to show the built-in actions
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_default_context_menu_enabled(false);
assert!(!editor.default_context_menu_enabled());Sourcepub fn set_custom_command_palette_entries(
&mut self,
entries: Vec<ContextMenuItem>,
)
pub fn set_custom_command_palette_entries( &mut self, entries: Vec<ContextMenuItem>, )
Replaces the custom command-palette entries.
Custom commands are listed before the built-in editor commands; see
Self::set_default_command_palette_enabled to hide those. Running
one emits Message::CommandPaletteAction carrying the entry’s id,
which the host application handles — the editor never acts on it.
Entries created with with_enabled(false) are left out of the list
entirely rather than dimmed: the palette is a search result list, so
every row it offers should be runnable.
§Arguments
entries- The commands to list, in order
§Example
use iced_code_editor::{CodeEditor, ContextMenuItem};
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_custom_command_palette_entries(vec![
ContextMenuItem::new("app.open_file", "Open File")
.with_shortcut("Ctrl+O"),
ContextMenuItem::new("app.new_tab", "New Tab"),
]);
assert_eq!(editor.custom_command_palette_entries().len(), 2);Sourcepub fn with_custom_command_palette_entries(
self,
entries: Vec<ContextMenuItem>,
) -> Self
pub fn with_custom_command_palette_entries( self, entries: Vec<ContextMenuItem>, ) -> Self
Replaces the custom command-palette entries using the builder pattern.
§Arguments
entries- The commands to list, in order
§Returns
Self for method chaining
§Example
use iced_code_editor::{CodeEditor, ContextMenuItem};
let editor = CodeEditor::new("fn main() {}", "rs")
.with_custom_command_palette_entries(vec![
ContextMenuItem::new("app.open_file", "Open File"),
]);
assert_eq!(editor.custom_command_palette_entries().len(), 1);Sourcepub fn custom_command_palette_entries(&self) -> &[ContextMenuItem]
pub fn custom_command_palette_entries(&self) -> &[ContextMenuItem]
Sourcepub fn set_default_command_palette_enabled(&mut self, enabled: bool)
pub fn set_default_command_palette_enabled(&mut self, enabled: bool)
Sets whether the built-in editor commands are listed in the palette.
Disabling them leaves only the custom entries, which is how a host application takes the palette over rather than extending it.
§Arguments
enabled- Whether to list the built-in commands
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_default_command_palette_enabled(false);
assert!(!editor.default_command_palette_enabled());Sourcepub fn with_default_command_palette_enabled(self, enabled: bool) -> Self
pub fn with_default_command_palette_enabled(self, enabled: bool) -> Self
Sets built-in command visibility using the builder pattern.
§Arguments
enabled- Whether to list the built-in commands
§Returns
Self for method chaining
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_default_command_palette_enabled(false);
assert!(!editor.default_command_palette_enabled());Sourcepub fn set_command_palette_enabled(&mut self, enabled: bool)
pub fn set_command_palette_enabled(&mut self, enabled: bool)
Sets whether the command palette can be opened.
Turning it off makes Ctrl/Cmd+Shift+P and
CodeEditor::open_command_palette no-ops, freeing the shortcut for
a host application that provides its own palette.
§Arguments
enabled- Whether the palette can be opened
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_command_palette_enabled(false);
assert!(!editor.command_palette_enabled());Sourcepub fn set_reveal_in_file_manager_enabled(&mut self, enabled: bool)
pub fn set_reveal_in_file_manager_enabled(&mut self, enabled: bool)
Sets whether the built-in reveal-in-file-manager action is shown.
The action is only useful when the host application knows the file path backing the editor, so it is off by default and the host opts in.
§Arguments
enabled- Whether to show the reveal action
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_reveal_in_file_manager_enabled(true);
assert!(editor.reveal_in_file_manager_enabled());Sourcepub fn with_reveal_in_file_manager_enabled(self, enabled: bool) -> Self
pub fn with_reveal_in_file_manager_enabled(self, enabled: bool) -> Self
Sets reveal-in-file-manager visibility using the builder pattern.
§Arguments
enabled- Whether to show the reveal action
§Returns
Self for method chaining
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_reveal_in_file_manager_enabled(true);
assert!(editor.reveal_in_file_manager_enabled());Sourcepub fn set_vim_enabled(&mut self, enabled: bool)
pub fn set_vim_enabled(&mut self, enabled: bool)
Enables or disables Vim behavior for this editor instance.
Changing this setting enters a clean Normal mode without modifying the buffer or command history. Any secondary cursors are collapsed onto the primary one, since Vim owns its own selection model.
§Arguments
enabled- Whether to enable Vim behavior
§Example
use iced_code_editor::{CodeEditor, VimMode};
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_vim_enabled(true);
// Vim always starts in Normal mode.
assert_eq!(editor.vim_mode(), Some(VimMode::Normal));Sourcepub fn vim_mode(&self) -> Option<VimMode>
pub fn vim_mode(&self) -> Option<VimMode>
Returns the active Vim mode, or None when Vim behavior is disabled.
Use this to drive a mode indicator in the host application’s status bar.
§Returns
Some(mode) when Vim is enabled, None otherwise
§Example
use iced_code_editor::{CodeEditor, VimMode};
let editor = CodeEditor::new("fn main() {}", "rs");
// `None` rather than a default mode, so a status bar can tell
// "Vim is off" apart from "Vim is in Normal mode".
assert_eq!(editor.vim_mode(), None);
let editor = editor.with_vim_enabled(true);
assert_eq!(editor.vim_mode(), Some(VimMode::Normal));Sourcepub fn set_language(&mut self, language: Language)
pub fn set_language(&mut self, language: Language)
Sets the language for UI translations.
This changes the language used for all UI text elements in the editor, including search dialog tooltips, placeholders, and labels.
§Arguments
language- The language to use for UI text
§Example
use iced_code_editor::{CodeEditor, Language};
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_language(Language::French);Sourcepub fn set_wrap_enabled(&mut self, enabled: bool)
pub fn set_wrap_enabled(&mut self, enabled: bool)
Sets whether line wrapping is enabled.
When enabled, long lines will wrap at the viewport width or at a configured column width.
§Arguments
enabled- Whether to enable line wrapping
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_wrap_enabled(false); // Disable wrappingSourcepub fn set_show_whitespace(&mut self, enabled: bool)
pub fn set_show_whitespace(&mut self, enabled: bool)
Enables or disables visible whitespace rendering.
When enabled, space characters are rendered as · and tab characters
as →, both drawn in a dimmed color to remain non-intrusive. Toggling
this setting clears the content cache to trigger an immediate redraw.
§Arguments
enabled- Whether to show whitespace characters
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_show_whitespace(true);Sourcepub fn set_show_indent_guides(&mut self, enabled: bool)
pub fn set_show_indent_guides(&mut self, enabled: bool)
Enables or disables indentation guides.
Indentation guides are faint vertical lines drawn at every indentation
level, making the nesting of a block visible at a glance. Their spacing
follows CodeEditor::indent_style. Toggling this setting clears the
content cache to trigger an immediate redraw.
§Arguments
enabled- Whether to draw indentation guides
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_show_indent_guides(false);Sourcepub fn set_show_color_previews(&mut self, enabled: bool)
pub fn set_show_color_previews(&mut self, enabled: bool)
Enables or disables inline color previews.
An inline color preview is a small square drawn just after a color
literal — #1e1e2e, 0xFF6B6B, rgb(58, 123, 213) — filled with the
color the literal denotes, so a palette can be read without decoding
hexadecimal by eye. Toggling this setting clears the content cache to
trigger an immediate redraw.
§Arguments
enabled- Whether to draw color-preview swatches
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("body { color: #f0c; }", "css");
editor.set_show_color_previews(false);Sourcepub fn set_diagnostics_enabled(&mut self, enabled: bool)
pub fn set_diagnostics_enabled(&mut self, enabled: bool)
Enables or disables diagnostics.
While disabled, no diagnostic is underlined and
CodeEditor::diagnostics_at returns nothing, so a host shows no
message on hover. The list passed to CodeEditor::set_diagnostics is
still stored and kept up to date, so enabling diagnostics again shows
the current list at once, without waiting for the source to publish
again. Toggling this setting clears the overlay cache to trigger an
immediate redraw.
§Arguments
enabled- Whether to underline and report diagnostics
§Example
use iced_code_editor::{
CodeEditor, Diagnostic, DiagnosticSeverity, LspPosition, LspRange,
};
let mut editor = CodeEditor::new("let x = 1;", "rs");
let at = LspPosition { line: 0, character: 4 };
editor.set_diagnostics(vec![Diagnostic::new(
LspRange { start: at, end: at },
DiagnosticSeverity::Warning,
"unused variable",
)]);
editor.set_diagnostics_enabled(false);
assert!(editor.diagnostics_at(at).is_empty());
assert_eq!(editor.diagnostics().len(), 1); // still stored
editor.set_diagnostics_enabled(true);
assert_eq!(editor.diagnostics_at(at).len(), 1);Sourcepub fn set_sticky_scroll_enabled(&mut self, enabled: bool)
pub fn set_sticky_scroll_enabled(&mut self, enabled: bool)
Enables or disables sticky scroll.
Sticky scroll pins the header lines of the blocks enclosing the topmost visible line to the top of the viewport, so the structural context stays readable while scrolling deep inside a long block. Clicking a pinned header scrolls back to it. Enclosing blocks are detected from indentation, exactly like code folding, so the feature is language-agnostic but follows the file’s indentation rather than its syntax tree.
Independent of CodeEditor::set_folding_enabled, despite sharing that
detection: turning code folding off removes the fold chevrons and leaves
the pinned headers alone.
§Arguments
enabled- Whether to pin enclosing block headers above the viewport
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {\n let x = 1;\n}", "rs");
editor.set_sticky_scroll_enabled(false);Sourcepub fn set_bracket_match_highlight_enabled(&mut self, enabled: bool)
pub fn set_bracket_match_highlight_enabled(&mut self, enabled: bool)
Enables or disables the matching-bracket/quote-pair highlight overlay.
When enabled, placing the cursor next to a bracket ((, ), [,
], {, }) or a quote (", ') highlights it and its matching
pair. When disabled, no matching scan or highlight is performed.
§Arguments
enabled- Whether to enable the bracket/quote-matching highlight
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_bracket_match_highlight_enabled(false); // DisableSourcepub fn set_bracket_pair_colorization_enabled(&mut self, enabled: bool)
pub fn set_bracket_pair_colorization_enabled(&mut self, enabled: bool)
Enables or disables bracket-pair colorization (rainbow brackets).
When enabled, each ( ) [ ] { } is colored by its nesting depth, so a
matching pair always shares the same color, cycling through a fixed
palette as depth increases. When disabled, brackets render with their
normal syntax-highlight color.
§Arguments
enabled- Whether to enable bracket-pair colorization
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_bracket_pair_colorization_enabled(false); // DisableSourcepub fn set_folding_enabled(&mut self, enabled: bool)
pub fn set_folding_enabled(&mut self, enabled: bool)
Enables or disables code folding (collapse/expand blocks).
When disabled, no fold chevrons are drawn and all lines are shown regardless of the collapsed state (which is preserved, so re-enabling restores the previously collapsed blocks).
§Arguments
enabled- Whether to enable code folding
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_folding_enabled(true);Sourcepub fn set_fold_markers(&mut self, markers: FoldMarkers)
pub fn set_fold_markers(&mut self, markers: FoldMarkers)
Sets when fold markers (the ▼/▶ chevrons) are drawn in the gutter.
FoldMarkers::Never also frees the fold-marker column, so the text
moves closer to the line numbers; blocks can still be folded with the
keyboard shortcuts and the API. The fold state is kept across changes.
§Arguments
markers- When fold markers are drawn
§Example
use iced_code_editor::{CodeEditor, FoldMarkers};
let mut editor = CodeEditor::new("fn main() {\n body();\n}", "rs");
editor.set_fold_markers(FoldMarkers::Never);
assert_eq!(editor.fold_markers(), FoldMarkers::Never);Sourcepub fn fold_markers(&self) -> FoldMarkers
pub fn fold_markers(&self) -> FoldMarkers
Returns when fold markers are drawn in the gutter.
§Example
use iced_code_editor::{CodeEditor, FoldMarkers};
let editor = CodeEditor::new("fn main() {}", "rs");
assert_eq!(editor.fold_markers(), FoldMarkers::Always);Sourcepub fn set_fold_marker_position(&mut self, position: FoldMarkerPosition)
pub fn set_fold_marker_position(&mut self, position: FoldMarkerPosition)
Sets which side of the line numbers the fold-marker column sits on.
§Arguments
position- Where the fold-marker column goes
§Example
use iced_code_editor::{CodeEditor, FoldMarkerPosition};
let mut editor = CodeEditor::new("fn main() {\n body();\n}", "rs");
editor.set_fold_marker_position(FoldMarkerPosition::BeforeLineNumbers);Sourcepub fn fold_marker_position(&self) -> FoldMarkerPosition
pub fn fold_marker_position(&self) -> FoldMarkerPosition
Returns which side of the line numbers the fold-marker column sits on.
§Example
use iced_code_editor::{CodeEditor, FoldMarkerPosition};
let editor = CodeEditor::new("fn main() {}", "rs");
assert_eq!(
editor.fold_marker_position(),
FoldMarkerPosition::AfterLineNumbers
);Sourcepub fn set_auto_indent_enabled(&mut self, enabled: bool)
pub fn set_auto_indent_enabled(&mut self, enabled: bool)
Enables or disables automatic indentation on Enter.
When enabled, pressing Enter copies the leading whitespace of the current line to the new line. When disabled, the cursor is placed at column 0 on the new line.
§Arguments
enabled-trueto enable auto-indentation,falseto disable
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_auto_indent_enabled(false);
assert!(!editor.auto_indent_enabled());Sourcepub fn set_auto_close_brackets(&mut self, enabled: bool)
pub fn set_auto_close_brackets(&mut self, enabled: bool)
Enables or disables auto-closing of brackets and quotes.
When enabled, typing an opening bracket/quote ((, [, {, ",
') auto-inserts its matching closing character with the cursor
placed between them, typing the closing character right before an
already-inserted match moves the cursor past it instead of
duplicating it, and typing an opening bracket/quote while text is
selected wraps the selection in the pair instead of replacing it.
§Arguments
enabled-trueto enable auto-closing,falseto disable
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_auto_close_brackets(false); // Disable auto-closingSourcepub fn set_indent_style(&mut self, style: IndentStyle)
pub fn set_indent_style(&mut self, style: IndentStyle)
Sets the indentation style used when pressing the Tab key.
§Arguments
style- The indentation style (IndentStyle::Spaces(n)orIndentStyle::Tab)
§Example
use iced_code_editor::{CodeEditor, IndentStyle};
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Indent with a real tab character instead of the default 4 spaces.
editor.set_indent_style(IndentStyle::Tab);
assert_eq!(editor.indent_style(), IndentStyle::Tab);
// Or pick a different space width.
editor.set_indent_style(IndentStyle::Spaces(2));
assert_eq!(editor.indent_style(), IndentStyle::Spaces(2));Sourcepub fn indent_style(&self) -> IndentStyle
pub fn indent_style(&self) -> IndentStyle
Returns the current indentation style.
§Returns
The current IndentStyle configured for this editor
§Example
use iced_code_editor::{CodeEditor, IndentStyle};
let editor = CodeEditor::new("fn main() {}", "rs");
assert_eq!(editor.indent_style(), IndentStyle::Spaces(4));Sourcepub fn set_search_replace_enabled(&mut self, enabled: bool)
pub fn set_search_replace_enabled(&mut self, enabled: bool)
Enables or disables the search/replace functionality.
When disabled, search/replace keyboard shortcuts (Ctrl+F, Ctrl+H, F3) will be ignored. If the search dialog is currently open, it will be closed.
§Arguments
enabled- Whether to enable search/replace functionality
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_search_replace_enabled(false); // Disable search/replaceSourcepub fn syntax(&self) -> &str
pub fn syntax(&self) -> &str
Returns the syntax highlighting language identifier for this editor.
This is the language key passed at construction (e.g., "lua", "rs", "py").
§Examples
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
assert_eq!(editor.syntax(), "rs");Sourcepub fn syntax_name(&self) -> &'static str
pub fn syntax_name(&self) -> &'static str
Returns the display name of the grammar actually used to highlight this editor’s content.
CodeEditor::syntax returns the raw identifier the host set; this
returns what the highlighter resolved it to, so it also reports the
plain-text fallback when no grammar matches. It is the value to show in
a status bar: it tells the user which language the editor is really
coloring with, not which one was requested.
§Returns
The grammar’s name (e.g. "Rust", "Lua", "Plain Text").
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
assert_eq!(editor.syntax_name(), "Rust");
// An identifier no bundled grammar matches degrades to plain text.
let unknown = CodeEditor::new("...", "no-such-language");
assert_eq!(unknown.syntax_name(), "Plain Text");Sourcepub fn set_syntax(&mut self, syntax: &str)
pub fn set_syntax(&mut self, syntax: &str)
Sets the syntax highlighting language identifier for this editor.
Use this when the content a single editor shows changes language –
typically after opening or saving a file under a different extension.
The identifier is the same key CodeEditor::new takes: a file
extension ("rs", "py", "toml") or one of the aliases
resolve_syntax normalizes ("rust", "python", "markdown", …).
An unknown identifier falls back to plain text rather than losing the
content.
Changing the identifier drops the cached per-line highlighting, so the visible lines are re-tokenized on the next render. Setting the current identifier again does nothing.
§Arguments
syntax- Syntax highlighting language identifier (e.g."rs")
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("-- comment", "lua");
assert_eq!(editor.syntax(), "lua");
editor.set_syntax("rs");
assert_eq!(editor.syntax(), "rs");Sourcepub fn with_wrap_column(self, column: Option<usize>) -> Self
pub fn with_wrap_column(self, column: Option<usize>) -> Self
Sets the wrap column (fixed width wrapping).
When set to Some(n), lines will wrap at column n.
When set to None, lines will wrap at the viewport width.
Zero is normalized to one narrow-character column.
§Arguments
column- The column to wrap at, or None for viewport-based wrapping
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_wrap_column(Some(80)); // Wrap at 80 charactersSourcepub fn set_wrap_column(&mut self, column: Option<usize>)
pub fn set_wrap_column(&mut self, column: Option<usize>)
Sets the soft-wrap width in narrow-character columns.
None uses the viewport width; Some(0) is normalized to Some(1).
This does not modify document text or enable wrapping. Changing the
width invalidates text and overlay geometry. While wrapping is enabled,
horizontal scrolling is reset so the new visual segments stay visible.
§Arguments
column- Wrap width in columns, orNonefor the viewport width
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_wrap_column(Some(80));
assert_eq!(editor.wrap_column(), Some(80));
editor.set_wrap_column(Some(0)); // Normalized to one column
assert_eq!(editor.wrap_column(), Some(1));
editor.set_wrap_column(None); // Back to viewport-based wrapping
assert_eq!(editor.wrap_column(), None);Sourcepub fn wrap_column(&self) -> Option<usize>
pub fn wrap_column(&self) -> Option<usize>
Returns the soft-wrap width in narrow-character columns.
None means viewport-based wrapping. The value is retained while
wrapping is disabled; zero is normalized to one by the setter.
§Returns
The fixed wrap width, or None when wrapping follows the viewport
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
assert_eq!(editor.wrap_column(), None); // Viewport width by default
editor.set_wrap_column(Some(100));
editor.set_wrap_enabled(false);
assert_eq!(editor.wrap_column(), Some(100)); // Kept while disabledSourcepub fn set_line_numbers_enabled(&mut self, enabled: bool)
pub fn set_line_numbers_enabled(&mut self, enabled: bool)
Sets whether line numbers are displayed.
When disabled, the gutter is completely removed (0px width), providing more space for code display.
§Arguments
enabled- Whether to display line numbers
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_line_numbers_enabled(false); // Hide line numbersSource§impl CodeEditor
impl CodeEditor
Sourcepub fn set_diagnostics(&mut self, diagnostics: Vec<Diagnostic>)
pub fn set_diagnostics(&mut self, diagnostics: Vec<Diagnostic>)
Replaces the diagnostic ranges underlined by the editor.
Columns count characters, not UTF-16 code units, and the end is exclusive. The ranges are not moved when the text is edited: pass a new list whenever the diagnostics change. An empty list clears them.
§Example
use iced_code_editor::{
CodeEditor, Diagnostic, DiagnosticSeverity, LspPosition, LspRange,
};
let mut editor = CodeEditor::new("let answer = 42;", "rs");
let diagnostic = Diagnostic::new(
LspRange {
start: LspPosition { line: 0, character: 4 },
end: LspPosition { line: 0, character: 10 },
},
DiagnosticSeverity::Warning,
"unused variable",
);
editor.set_diagnostics(vec![diagnostic.clone()]);
assert_eq!(editor.diagnostics(), &[diagnostic]);Sourcepub fn diagnostics(&self) -> &[Diagnostic]
pub fn diagnostics(&self) -> &[Diagnostic]
The diagnostic ranges currently underlined by the editor.
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
assert!(editor.diagnostics().is_empty());Sourcepub fn diagnostics_at(&self, position: LspPosition) -> Vec<&Diagnostic>
pub fn diagnostics_at(&self, position: LspPosition) -> Vec<&Diagnostic>
The diagnostics covering position, in the order they were set.
Always empty while diagnostics are disabled
(CodeEditor::set_diagnostics_enabled).
position is in logical lines and character columns, as returned by
CodeEditor::lsp_position_at_point. Hosts use it to show the
messages of the diagnostics under the pointer.
§Example
use iced_code_editor::{
CodeEditor, Diagnostic, DiagnosticSeverity, LspPosition, LspRange,
};
let mut editor = CodeEditor::new("let answer = 42;", "rs");
editor.set_diagnostics(vec![Diagnostic::new(
LspRange {
start: LspPosition { line: 0, character: 4 },
end: LspPosition { line: 0, character: 10 },
},
DiagnosticSeverity::Warning,
"unused variable",
)]);
let hovered = editor.diagnostics_at(LspPosition { line: 0, character: 6 });
assert_eq!(hovered.len(), 1);
assert_eq!(hovered[0].message, "unused variable");
assert!(editor.diagnostics_at(LspPosition { line: 0, character: 0 }).is_empty());Source§impl CodeEditor
impl CodeEditor
Sourcepub fn set_cursor(&mut self, line: usize, col: usize) -> Task<Message>
pub fn set_cursor(&mut self, line: usize, col: usize) -> Task<Message>
Sets the cursor position to the specified line and column.
This method ensures the new position is within the bounds of the text buffer. It also resets the blinking animation, clears the overlay cache (to redraw the cursor immediately), and scrolls the view to make the cursor visible.
§Arguments
line- The target line index (0-based).col- The target column index (0-based).
§Returns
A Task that may produce a Message (e.g., if scrolling is needed).
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("one\ntwo\nthree", "txt");
let _task = editor.set_cursor(1, 2);
assert_eq!(editor.cursor_position(), (1, 2));
// Out-of-range coordinates clamp to the document rather than failing,
// which is what makes this safe to call with a position from an
// external source such as an LSP jump target.
let _task = editor.set_cursor(99, 99);
assert_eq!(editor.cursor_position(), (2, 5));Source§impl CodeEditor
impl CodeEditor
Sourcepub fn cursor_screen_position(&self) -> Option<Point>
pub fn cursor_screen_position(&self) -> Option<Point>
Returns the screen position of the cursor.
This method returns the (x, y) coordinates of the current cursor position relative to the editor canvas, accounting for gutter width and line height.
§Returns
An Option<iced::Point> containing the cursor position, or None if
the cursor position cannot be determined.
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
if let Some(point) = editor.cursor_screen_position() {
println!("Cursor at: ({}, {})", point.x, point.y);
}Sourcepub fn cursor_position(&self) -> (usize, usize)
pub fn cursor_position(&self) -> (usize, usize)
Returns the current cursor position as (line, column).
This method returns the logical cursor position in the buffer, where line and column are both 0-indexed.
§Returns
A tuple (line, column) representing the cursor position.
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
let (line, col) = editor.cursor_position();
println!("Cursor at line {}, column {}", line, col);Source§impl CodeEditor
impl CodeEditor
Sourcepub fn is_modified(&self) -> bool
pub fn is_modified(&self) -> bool
Returns whether the editor has unsaved changes.
Use this to drive a “modified” indicator in a tab title, or to prompt before closing.
§Returns
true if there are unsaved modifications, false otherwise
§Example
use iced_code_editor::{CodeEditor, Message};
let mut editor = CodeEditor::new("hello", "rs");
assert!(!editor.is_modified());
let _ = editor.update(&Message::Paste("!".to_string()));
assert!(editor.is_modified());Sourcepub fn mark_saved(&mut self)
pub fn mark_saved(&mut self)
Marks the current state as saved.
Call this after successfully saving the file to reset the modified state.
§Example
use iced_code_editor::{CodeEditor, Message};
let mut editor = CodeEditor::new("hello", "rs");
let _ = editor.update(&Message::Paste("!".to_string()));
editor.mark_saved();
assert!(!editor.is_modified());Sourcepub fn can_undo(&self) -> bool
pub fn can_undo(&self) -> bool
Returns whether undo is available.
§Returns
true if undo would do something, false otherwise
§Example
use iced_code_editor::{CodeEditor, Message};
let mut editor = CodeEditor::new("hello", "rs");
assert!(!editor.can_undo());
let _ = editor.update(&Message::Paste("!".to_string()));
assert!(editor.can_undo());Sourcepub fn can_redo(&self) -> bool
pub fn can_redo(&self) -> bool
Returns whether redo is available.
§Returns
true if redo would do something, false otherwise
§Example
use iced_code_editor::{CodeEditor, Message};
let mut editor = CodeEditor::new("hello", "rs");
let _ = editor.update(&Message::Paste("!".to_string()));
assert!(!editor.can_redo());
let _ = editor.update(&Message::Undo);
assert!(editor.can_redo());Source§impl CodeEditor
impl CodeEditor
Sourcepub fn selection_range(&self) -> Option<((usize, usize), (usize, usize))>
pub fn selection_range(&self) -> Option<((usize, usize), (usize, usize))>
Returns the primary cursor’s selection as (start, end) positions.
Positions are (line, column), 0-indexed, with the column counted in
characters (like CodeEditor::cursor_position). The range is
normalized: start comes before end, whichever way the selection
was made. Returns None when nothing is selected. With several
cursors, only the primary one is considered.
§Example
use iced_code_editor::{CodeEditor, Message};
let mut editor = CodeEditor::new("one\ntwo", "txt");
assert_eq!(editor.selection_range(), None);
let _ = editor.update(&Message::SelectAll);
assert_eq!(editor.selection_range(), Some(((0, 0), (1, 3))));Sourcepub fn selected_text(&self) -> Option<String>
pub fn selected_text(&self) -> Option<String>
Returns the text selected by the primary cursor.
Lines are joined with \n. Returns None when nothing is selected.
With several cursors, only the primary one is considered.
§Example
use iced_code_editor::{CodeEditor, Message};
let mut editor = CodeEditor::new("one\ntwo", "txt");
assert_eq!(editor.selected_text(), None);
let _ = editor.update(&Message::SelectAll);
assert_eq!(editor.selected_text().as_deref(), Some("one\ntwo"));Source§impl CodeEditor
impl CodeEditor
Sourcepub fn open_command_palette(&mut self) -> Task<Message>
pub fn open_command_palette(&mut self) -> Task<Message>
Opens the command palette programmatically.
Use this to wire a menu item or toolbar button, alongside the built-in
Ctrl/Cmd+Shift+P shortcut.
§Returns
A Task<Message> that focuses the palette’s input
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
let _task = editor.open_command_palette();Sourcepub fn close_command_palette(&mut self) -> Task<Message>
pub fn close_command_palette(&mut self) -> Task<Message>
Closes the command palette without running anything.
Safe to call when the palette is already closed.
§Returns
A Task<Message> returning focus to the editor canvas
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
let _task = editor.open_command_palette();
let _task = editor.close_command_palette();Source§impl CodeEditor
impl CodeEditor
Sourcepub fn is_folded(&self, header_line: usize) -> bool
pub fn is_folded(&self, header_line: usize) -> bool
Returns whether the region whose header is header_line is collapsed.
§Arguments
header_line- Logical line index of the region header
§Returns
true if that region is currently collapsed, false otherwise –
including when header_line is not a fold header at all.
§Example
use iced_code_editor::CodeEditor;
// A single block: the `fn` header on line 0 encloses lines 1 and 2.
let mut editor = CodeEditor::new(
"fn main() {\n let a = 1;\n let b = 2;\n}",
"rs",
);
assert!(!editor.is_folded(0));
editor.toggle_fold(0);
assert!(editor.is_folded(0));Sourcepub fn toggle_fold(&mut self, header_line: usize)
pub fn toggle_fold(&mut self, header_line: usize)
Toggles the collapsed state of the foldable region whose header is
header_line.
The call is a no-op if header_line is not currently a fold header.
When collapsing, any cursor that would land on a hidden line is moved up
to the header line so the caret stays visible.
§Arguments
header_line- Logical line index of the region header
§Example
use iced_code_editor::CodeEditor;
// A single block: the `fn` header on line 0 encloses lines 1 and 2.
let mut editor = CodeEditor::new(
"fn main() {\n let a = 1;\n let b = 2;\n}",
"rs",
);
editor.toggle_fold(0);
assert!(editor.is_folded(0));
editor.toggle_fold(0);
assert!(!editor.is_folded(0));
// Line 1 sits inside the block but does not head it, so nothing moves.
editor.toggle_fold(1);
assert!(!editor.is_folded(0));
assert!(!editor.is_folded(1));Sourcepub fn toggle_fold_at(&mut self, line: usize)
pub fn toggle_fold_at(&mut self, line: usize)
Toggles the collapsed state of the innermost foldable region containing
line.
Folds the region if it is expanded, unfolds it if it is collapsed. Does
nothing if line is not inside any foldable region. This is the
cursor-driven primitive used by the keyboard shortcut and mirrors a click
on the fold chevron.
§Arguments
line- A logical line inside (or heading) the region to toggle
§Example
use iced_code_editor::CodeEditor;
// A single block: the `fn` header on line 0 encloses lines 1 and 2.
let mut editor = CodeEditor::new(
"fn main() {\n let a = 1;\n let b = 2;\n}",
"rs",
);
// Line 1 is inside the block, so the block's header collapses.
editor.toggle_fold_at(1);
assert!(editor.is_folded(0));
editor.toggle_fold_at(1);
assert!(!editor.is_folded(0));Sourcepub fn fold_at(&mut self, line: usize)
pub fn fold_at(&mut self, line: usize)
Folds the innermost foldable region containing line.
Does nothing if line is not inside any foldable region or the region
is already collapsed. This is the cursor-driven counterpart to
Self::toggle_fold.
§Arguments
line- A logical line inside (or heading) the region to fold
§Example
use iced_code_editor::CodeEditor;
// A single block: the `fn` header on line 0 encloses lines 1 and 2.
let mut editor = CodeEditor::new(
"fn main() {\n let a = 1;\n let b = 2;\n}",
"rs",
);
editor.fold_at(2);
assert!(editor.is_folded(0));
// Already collapsed: a second call is a no-op rather than a re-open.
editor.fold_at(2);
assert!(editor.is_folded(0));Sourcepub fn unfold_at(&mut self, line: usize)
pub fn unfold_at(&mut self, line: usize)
Unfolds the innermost collapsed region containing line.
Does nothing if no collapsed region contains line.
§Arguments
line- A logical line inside (or heading) the region to unfold
§Example
use iced_code_editor::CodeEditor;
// A single block: the `fn` header on line 0 encloses lines 1 and 2.
let mut editor = CodeEditor::new(
"fn main() {\n let a = 1;\n let b = 2;\n}",
"rs",
);
editor.fold_at(1);
assert!(editor.is_folded(0));
editor.unfold_at(1);
assert!(!editor.is_folded(0));
// Nothing is collapsed any more, so unfolding again does nothing.
editor.unfold_at(1);
assert!(!editor.is_folded(0));Sourcepub fn fold_all(&mut self)
pub fn fold_all(&mut self)
Folds every foldable block in the buffer.
Nested blocks are collapsed too, so the outermost header is the only line each top-level block leaves on screen.
§Example
use iced_code_editor::CodeEditor;
// Two sibling blocks: headers on lines 0 and 3.
let mut editor = CodeEditor::new(
"fn a() {\n let x = 1;\n}\nfn b() {\n let y = 2;\n}",
"rs",
);
editor.fold_all();
assert!(editor.is_folded(0));
assert!(editor.is_folded(3));Sourcepub fn unfold_all(&mut self)
pub fn unfold_all(&mut self)
Unfolds every collapsed block in the buffer.
§Example
use iced_code_editor::CodeEditor;
// Two sibling blocks: headers on lines 0 and 3.
let mut editor = CodeEditor::new(
"fn a() {\n let x = 1;\n}\nfn b() {\n let y = 2;\n}",
"rs",
);
editor.fold_all();
assert!(editor.is_folded(0));
editor.unfold_all();
assert!(!editor.is_folded(0));
assert!(!editor.is_folded(3));Source§impl CodeEditor
impl CodeEditor
Sourcepub fn open_goto_line_dialog(&mut self) -> Task<Message>
pub fn open_goto_line_dialog(&mut self) -> Task<Message>
Opens the go-to-line dialog programmatically.
The input is pre-filled with the current one-based line number. Use
this to wire a “Go to Line…” menu item, alongside the built-in
Ctrl/Cmd+G shortcut.
§Returns
A Task<Message> that focuses and selects the dialog’s input
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("one\ntwo\nthree", "txt");
let _task = editor.open_goto_line_dialog();Sourcepub fn close_goto_line_dialog(&mut self) -> Task<Message>
pub fn close_goto_line_dialog(&mut self) -> Task<Message>
Closes the go-to-line dialog programmatically.
Leaves the cursor where it is. Safe to call when the dialog is already closed.
§Returns
A Task<Message> returning focus to the editor canvas
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("one\ntwo\nthree", "txt");
let _task = editor.open_goto_line_dialog();
let _task = editor.close_goto_line_dialog();Source§impl CodeEditor
impl CodeEditor
Sourcepub fn is_search_open(&self) -> bool
pub fn is_search_open(&self) -> bool
Returns whether the search dialog is currently open.
Both Self::open_search_dialog and
Self::open_search_replace_dialog open it; only
Self::close_search_dialog closes it. A host driving the dialog from
its own toolbar needs this to keep that button’s pressed state in sync
with the dialog the user may also have opened by keyboard.
§Returns
true while the dialog is shown, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
assert!(!editor.is_search_open());
let _task = editor.open_search_dialog();
assert!(editor.is_search_open());Sourcepub fn open_search_dialog(&mut self) -> Task<Message>
pub fn open_search_dialog(&mut self) -> Task<Message>
Opens the search dialog programmatically.
This is useful when wiring your own UI button instead of relying on keyboard shortcuts.
§Returns
A Task<Message> that focuses the search input.
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Returned to the host's `update`, the task focuses the query field.
let _task = editor.open_search_dialog();
assert!(editor.is_search_open());Sourcepub fn open_search_replace_dialog(&mut self) -> Task<Message>
pub fn open_search_replace_dialog(&mut self) -> Task<Message>
Opens the search-and-replace dialog programmatically.
This is useful when wiring your own UI button instead of relying on keyboard shortcuts.
§Returns
A Task<Message> that focuses the search input.
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Same dialog as `open_search_dialog`, with the replace row shown.
let _task = editor.open_search_replace_dialog();
assert!(editor.is_search_open());Sourcepub fn close_search_dialog(&mut self) -> Task<Message>
pub fn close_search_dialog(&mut self) -> Task<Message>
Closes the search dialog programmatically.
§Returns
A Task<Message> for any follow-up UI work.
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
let _task = editor.open_search_dialog();
let _task = editor.close_search_dialog();
assert!(!editor.is_search_open());Source§impl CodeEditor
impl CodeEditor
Sourcepub fn request_focus(&self)
pub fn request_focus(&self)
Requests focus for this editor.
This method programmatically sets the focus to this editor instance, allowing it to receive keyboard events. Other editors will automatically lose focus.
§Example
use iced_code_editor::CodeEditor;
let mut editor1 = CodeEditor::new("fn main() {}", "rs");
let mut editor2 = CodeEditor::new("fn test() {}", "rs");
// Give focus to editor2
editor2.request_focus();Sourcepub fn is_focused(&self) -> bool
pub fn is_focused(&self) -> bool
Checks if this editor currently has focus.
Returns true if this editor will receive keyboard events,
false otherwise.
§Returns
true if focused, false otherwise
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
if editor.is_focused() {
println!("Editor has focus");
}Sourcepub fn lose_focus(&mut self)
pub fn lose_focus(&mut self)
Removes canvas focus from this editor.
This method programmatically removes focus from the canvas, preventing it from receiving keyboard events. The cursor will be hidden, but the selection will remain visible.
Call this when focus should move to another widget (e.g., text input).
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.lose_focus();Sourcepub fn reset_focus_lock(&mut self)
pub fn reset_focus_lock(&mut self)
Resets the focus lock state.
This method can be called to manually unlock focus processing after a focus transition has completed. This is useful when you want to allow the editor to process input again after programmatic focus changes.
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.reset_focus_lock();Source§impl CodeEditor
impl CodeEditor
Sourcepub fn update(&mut self, message: &Message) -> Task<Message>
pub fn update(&mut self, message: &Message) -> Task<Message>
Updates the editor state based on messages and returns scroll commands.
§Arguments
message- The message to process for updating the editor state
§Returns
A Task<Message> for any asynchronous operations, such as scrolling to keep the cursor visible after state updates
§Example
use iced_code_editor::{CodeEditor, Message};
let mut editor = CodeEditor::new("hello", "rs");
// Forward the messages the editor emits, and send your own to drive
// commands from a menu or toolbar.
let _task = editor.update(&Message::Paste(" world".to_string()));
assert_eq!(editor.content(), " worldhello");
let _task = editor.update(&Message::Undo);
assert_eq!(editor.content(), "hello");Source§impl CodeEditor
impl CodeEditor
Sourcepub fn apply_lsp_text_edits(&mut self, edits: &[LspTextChange]) -> bool
pub fn apply_lsp_text_edits(&mut self, edits: &[LspTextChange]) -> bool
Applies a batch of LSP text edits to the buffer as one undo step.
This is how a TextEdit[] reply — a textDocument/formatting
response, for instance — reaches the document. Positions outside the
buffer are clamped onto it, so an end-of-document range expressed as a
line past the last one still lands correctly.
The cursor keeps its line and column where the reformatted document still has one, clamped onto the nearest position where it does not, and any selection is dropped: after a whole-document rewrite the old selection no longer covers what the user selected.
§Arguments
edits- Edits from the server, all in coordinates of the current document
§Returns
true when the buffer was modified; false when edits is empty,
contains only no-op edits, or describes overlapping ranges — which LSP
forbids and which cannot be applied without corrupting the buffer
§Example
use iced_code_editor::{CodeEditor, LspPosition, LspRange, LspTextChange};
let mut editor = CodeEditor::new("fn main() {}", "rs");
// The server asks for the double space to become a single one.
let edit = LspTextChange {
range: LspRange {
start: LspPosition { line: 0, character: 2 },
end: LspPosition { line: 0, character: 4 },
},
text: " ".to_string(),
};
assert!(editor.apply_lsp_text_edits(&[edit]));
assert_eq!(editor.content(), "fn main() {}");
// An empty reply — an already-formatted document — changes nothing.
assert!(!editor.apply_lsp_text_edits(&[]));Source§impl CodeEditor
impl CodeEditor
Sourcepub fn attach_lsp(&mut self, client: Box<dyn LspClient>, document: LspDocument)
pub fn attach_lsp(&mut self, client: Box<dyn LspClient>, document: LspDocument)
Attaches an LSP client and opens a document for the current buffer.
This sends an initial did_open with the current buffer contents and
resets any pending LSP change state. It is a no-op while LSP support is
disabled — see Self::set_lsp_enabled.
§Arguments
client- The LSP client to notifydocument- Document metadata describing the buffer
§Example
use std::cell::RefCell;
use std::rc::Rc;
use iced_code_editor::{CodeEditor, LspClient, LspDocument};
/// Records the text the editor sent on `did_open`.
struct RecordingClient(Rc<RefCell<Option<String>>>);
impl LspClient for RecordingClient {
fn did_open(&mut self, _document: &LspDocument, text: &str) {
*self.0.borrow_mut() = Some(text.to_string());
}
}
let opened = Rc::new(RefCell::new(None));
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.attach_lsp(
Box::new(RecordingClient(Rc::clone(&opened))),
LspDocument::new("file:///tmp/main.rs", "rust"),
);
// Attaching opens the document with the buffer's current contents.
assert_eq!(opened.borrow().as_deref(), Some("fn main() {}"));Sourcepub fn lsp_open_document(&mut self, document: LspDocument)
pub fn lsp_open_document(&mut self, document: LspDocument)
Opens a new document on the attached LSP client.
If a document is already open, this will close it before opening the new one and reset pending change tracking. Use this when the same editor widget is reused for a different file, so the server is told about the swap rather than seeing the old document mutate into the new one.
Does nothing when no client is attached.
§Arguments
document- Document metadata describing the buffer
§Example
use std::cell::RefCell;
use std::rc::Rc;
use iced_code_editor::{CodeEditor, LspClient, LspDocument};
/// Records the URIs the editor closed.
struct ClosingClient(Rc<RefCell<Vec<String>>>);
impl LspClient for ClosingClient {
fn did_close(&mut self, document: &LspDocument) {
self.0.borrow_mut().push(document.uri.clone());
}
}
let closed = Rc::new(RefCell::new(Vec::new()));
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.attach_lsp(
Box::new(ClosingClient(Rc::clone(&closed))),
LspDocument::new("file:///tmp/first.rs", "rust"),
);
// Switching files closes the previous document first.
editor.lsp_open_document(LspDocument::new("file:///tmp/second.rs", "rust"));
assert_eq!(closed.borrow().as_slice(), ["file:///tmp/first.rs"]);Sourcepub fn detach_lsp(&mut self)
pub fn detach_lsp(&mut self)
Detaches the current LSP client and closes any open document.
This clears all LSP-related state on the editor instance, including any changes queued but not yet flushed. Safe to call when nothing is attached.
§Example
use std::cell::RefCell;
use std::rc::Rc;
use iced_code_editor::{CodeEditor, LspClient, LspDocument};
/// Records whether the document was closed.
struct ClosingClient(Rc<RefCell<bool>>);
impl LspClient for ClosingClient {
fn did_close(&mut self, _document: &LspDocument) {
*self.0.borrow_mut() = true;
}
}
let closed = Rc::new(RefCell::new(false));
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.attach_lsp(
Box::new(ClosingClient(Rc::clone(&closed))),
LspDocument::new("file:///tmp/main.rs", "rust"),
);
editor.detach_lsp();
assert!(*closed.borrow());
// Detaching again is harmless.
editor.detach_lsp();Sourcepub fn lsp_did_save(&mut self)
pub fn lsp_did_save(&mut self)
Sends a did_save notification with the current buffer contents.
Call this after the host application has written the file to disk, so servers that re-run diagnostics or formatting on save see the new state. Does nothing when no client and document are attached.
§Example
use std::cell::RefCell;
use std::rc::Rc;
use iced_code_editor::{CodeEditor, LspClient, LspDocument};
/// Records the text sent on save.
struct SavingClient(Rc<RefCell<Option<String>>>);
impl LspClient for SavingClient {
fn did_save(&mut self, _document: &LspDocument, text: &str) {
*self.0.borrow_mut() = Some(text.to_string());
}
}
let saved = Rc::new(RefCell::new(None));
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.attach_lsp(
Box::new(SavingClient(Rc::clone(&saved))),
LspDocument::new("file:///tmp/main.rs", "rust"),
);
editor.lsp_did_save();
assert_eq!(saved.borrow().as_deref(), Some("fn main() {}"));Sourcepub fn lsp_request_hover(&mut self)
pub fn lsp_request_hover(&mut self)
Requests hover information at the current cursor position.
The request is fire-and-forget: the reply reaches the host through
whatever channel the LspClient implementation uses, not through a
return value. Does nothing when no client is attached.
§Example
use std::cell::RefCell;
use std::rc::Rc;
use iced_code_editor::{CodeEditor, LspClient, LspDocument, LspPosition};
/// Records the position each hover request asked about.
struct HoverClient(Rc<RefCell<Vec<LspPosition>>>);
impl LspClient for HoverClient {
fn request_hover(&mut self, _document: &LspDocument, position: LspPosition) {
self.0.borrow_mut().push(position);
}
}
let hovers = Rc::new(RefCell::new(Vec::new()));
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.attach_lsp(
Box::new(HoverClient(Rc::clone(&hovers))),
LspDocument::new("file:///tmp/main.rs", "rust"),
);
editor.lsp_request_hover();
// The cursor starts at the top of the document.
assert_eq!(hovers.borrow().as_slice(), [LspPosition { line: 0, character: 0 }]);Sourcepub fn lsp_request_hover_at(&mut self, point: Point) -> bool
pub fn lsp_request_hover_at(&mut self, point: Point) -> bool
Requests hover information at a canvas point.
Use this to drive hover-on-mouse-move; Self::lsp_position_at_point
resolves the point first, so a point over the gutter sends nothing.
§Arguments
point- The position in canvas coordinates
§Returns
true if the point maps to a valid buffer position and the request was
sent; false if it does not, or if no client is attached
§Example
use iced::Point;
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// With no client attached there is nothing to send.
assert!(!editor.lsp_request_hover_at(Point::new(50.0, 5.0)));Sourcepub fn lsp_request_hover_at_position(&mut self, position: LspPosition) -> bool
pub fn lsp_request_hover_at_position(&mut self, position: LspPosition) -> bool
Requests hover information at an explicit LSP position.
Unlike Self::lsp_request_hover_at, this skips point-to-position
resolution — pair it with a position previously obtained from
Self::lsp_hover_anchor_at_point so a hover that lingers stays
anchored to the word rather than following the mouse.
§Arguments
position- The zero-based document position to query
§Returns
true if a client is attached and the request was sent, false otherwise
§Example
use iced_code_editor::{CodeEditor, LspPosition};
let mut editor = CodeEditor::new("fn main() {}", "rs");
let position = LspPosition { line: 0, character: 3 };
// With no client attached there is nothing to send.
assert!(!editor.lsp_request_hover_at_position(position));Sourcepub fn lsp_position_at_point(&self, point: Point) -> Option<LspPosition>
pub fn lsp_position_at_point(&self, point: Point) -> Option<LspPosition>
Converts a canvas point to an LSP position, if possible.
Requires no attached client — this is pure hit-testing against the editor’s current layout.
§Arguments
point- The position in canvas coordinates
§Returns
Some(position) when the point falls on text, None when it lands in
the gutter
§Example
use iced::Point;
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
// The origin sits in the line-number gutter, which maps to nothing.
assert!(editor.lsp_position_at_point(Point::ORIGIN).is_none());
// A point past the end of the document clamps to its last position.
let position = editor
.lsp_position_at_point(Point::new(5_000.0, 5_000.0))
.expect("a point past the text clamps rather than failing");
assert_eq!(position.line, 0);
assert_eq!(position.character, 12);Sourcepub fn lsp_hover_anchor_at_point(
&self,
point: Point,
) -> Option<(LspPosition, Point)>
pub fn lsp_hover_anchor_at_point( &self, point: Point, ) -> Option<(LspPosition, Point)>
Returns the hover anchor position and its canvas point for a given cursor location.
The anchor is the start of the word under the cursor. Anchoring to the word start rather than the exact mouse position keeps a hover popup from jittering as the pointer moves within one identifier, and gives the host a stable canvas point to position the popup against.
§Arguments
point- The position in canvas coordinates
§Returns
Some((position, anchor_point)) when the point falls on text, None
when it lands in the gutter
§Example
use iced::Point;
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
// A gutter point has no word to anchor to.
assert!(editor.lsp_hover_anchor_at_point(Point::ORIGIN).is_none());Sourcepub fn lsp_request_completion(&mut self)
pub fn lsp_request_completion(&mut self)
Requests completion items at the current cursor position.
Like the hover requests, this is fire-and-forget; the items arrive
through the LspClient implementation. Does nothing when no client is
attached.
§Example
use std::cell::RefCell;
use std::rc::Rc;
use iced_code_editor::{CodeEditor, LspClient, LspDocument, LspPosition};
/// Counts completion requests.
struct CompletionClient(Rc<RefCell<usize>>);
impl LspClient for CompletionClient {
fn request_completion(&mut self, _document: &LspDocument, _position: LspPosition) {
*self.0.borrow_mut() += 1;
}
}
let requests = Rc::new(RefCell::new(0));
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.attach_lsp(
Box::new(CompletionClient(Rc::clone(&requests))),
LspDocument::new("file:///tmp/main.rs", "rust"),
);
editor.lsp_request_completion();
assert_eq!(*requests.borrow(), 1);Sourcepub fn lsp_flush_pending_changes(&mut self)
pub fn lsp_flush_pending_changes(&mut self)
Flushes pending LSP text changes to the attached client.
This increments the document version and sends did_change with all
queued changes. Changes stay queued while no client is attached, so a
client attached later still receives a consistent document.
Only needed when automatic flushing is off; see
Self::set_lsp_auto_flush.
§Example
use std::cell::RefCell;
use std::rc::Rc;
use iced_code_editor::{CodeEditor, LspClient, LspDocument, LspTextChange};
/// Records how many changes each batch carried.
struct BatchClient(Rc<RefCell<Vec<usize>>>);
impl LspClient for BatchClient {
fn did_change(&mut self, _document: &LspDocument, changes: &[LspTextChange]) {
self.0.borrow_mut().push(changes.len());
}
}
let batches = Rc::new(RefCell::new(Vec::new()));
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Take over flushing, then drive it from a debounce timer.
editor.set_lsp_auto_flush(false);
editor.attach_lsp(
Box::new(BatchClient(Rc::clone(&batches))),
LspDocument::new("file:///tmp/main.rs", "rust"),
);
// Flushing an empty queue is a no-op, so a timer can call this
// unconditionally without sending empty notifications.
editor.lsp_flush_pending_changes();
assert!(batches.borrow().is_empty());Sourcepub fn set_lsp_auto_flush(&mut self, auto_flush: bool)
pub fn set_lsp_auto_flush(&mut self, auto_flush: bool)
Sets whether LSP changes are flushed automatically after edits.
On by default, which is what most hosts want. Turn it off to batch
rapid typing behind a debounce timer and call
Self::lsp_flush_pending_changes yourself, so a chatty server isn’t
sent one notification per keystroke.
§Arguments
auto_flush-trueto flush after every edit,falseto flush manually
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Take over flushing so edits can be debounced by the host.
editor.set_lsp_auto_flush(false);Sourcepub fn set_lsp_enabled(&mut self, enabled: bool)
pub fn set_lsp_enabled(&mut self, enabled: bool)
Sets whether LSP support is enabled.
When set to false, any attached LSP client is detached automatically.
Calling attach_lsp while disabled is a no-op.
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_lsp_enabled(false);Sourcepub fn lsp_enabled(&self) -> bool
pub fn lsp_enabled(&self) -> bool
Returns whether LSP support is enabled.
§Returns
true if LSP is enabled, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Enabled by default, though no client is attached until you attach one.
assert!(editor.lsp_enabled());
editor.set_lsp_enabled(false);
assert!(!editor.lsp_enabled());Sourcepub fn lsp_document_uri(&self) -> Option<&str>
pub fn lsp_document_uri(&self) -> Option<&str>
URI of the document this editor has open with its LSP client.
None until a document is attached or opened. Hosts use it to route
per-document server events, such as diagnostics, to the right editor.
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
assert_eq!(editor.lsp_document_uri(), None);Sourcepub fn lsp_request_definition(&mut self)
pub fn lsp_request_definition(&mut self)
Initiates a “Go to Definition” request for the symbol at the current cursor position.
This method converts the current cursor coordinates into an LSP-compatible position
and delegates the request to the active LspClient, if one is attached.
Fire-and-forget: the resolved location arrives through the client implementation, and the host decides whether to follow it.
§Example
use std::cell::RefCell;
use std::rc::Rc;
use iced_code_editor::{CodeEditor, LspClient, LspDocument, LspPosition};
/// Records the position each definition request asked about.
struct DefinitionClient(Rc<RefCell<Vec<LspPosition>>>);
impl LspClient for DefinitionClient {
fn request_definition(&mut self, _document: &LspDocument, position: LspPosition) {
self.0.borrow_mut().push(position);
}
}
let requests = Rc::new(RefCell::new(Vec::new()));
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.attach_lsp(
Box::new(DefinitionClient(Rc::clone(&requests))),
LspDocument::new("file:///tmp/main.rs", "rust"),
);
editor.lsp_request_definition();
assert_eq!(requests.borrow().len(), 1);Sourcepub fn lsp_request_definition_at(&mut self, point: Point) -> bool
pub fn lsp_request_definition_at(&mut self, point: Point) -> bool
Initiates a “Go to Definition” request for the symbol at the specified screen coordinates.
This is typically used for mouse interactions (e.g., Ctrl+Click). It first resolves the screen coordinates to a text position and then sends the request.
§Arguments
point- The click position in canvas coordinates
§Returns
true if the request was successfully sent (i.e., a valid position was found and an LSP client is active),
false otherwise.
§Example
use iced::Point;
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// With no client attached there is nothing to send.
assert!(!editor.lsp_request_definition_at(Point::new(50.0, 5.0)));Sourcepub fn lsp_request_formatting(&mut self) -> bool
pub fn lsp_request_formatting(&mut self) -> bool
Requests formatting edits for the whole document.
The formatting options are derived from the editor’s own
IndentStyle, so the server formats the way this editor indents.
Queued changes are flushed first: the server formats the document it
has, so an unflushed keystroke would come back reformatted away.
Like every other request this is fire-and-forget. The reply is a batch
of edits, which the host applies with
Self::apply_lsp_text_edits.
§Returns
true if the request was sent; false when no client and document are
attached
§Example
use std::cell::RefCell;
use std::rc::Rc;
use iced_code_editor::{
CodeEditor, IndentStyle, LspClient, LspDocument, LspFormattingOptions,
};
/// Records the options each formatting request carried.
struct FormattingClient(Rc<RefCell<Vec<LspFormattingOptions>>>);
impl LspClient for FormattingClient {
fn request_formatting(
&mut self,
_document: &LspDocument,
options: LspFormattingOptions,
) {
self.0.borrow_mut().push(options);
}
}
let requests = Rc::new(RefCell::new(Vec::new()));
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Nothing is attached yet, so there is nobody to ask.
assert!(!editor.lsp_request_formatting());
editor.set_indent_style(IndentStyle::Spaces(2));
editor.attach_lsp(
Box::new(FormattingClient(Rc::clone(&requests))),
LspDocument::new("file:///tmp/main.rs", "rust"),
);
assert!(editor.lsp_request_formatting());
assert_eq!(requests.borrow()[0].tab_size, 2);Source§impl CodeEditor
impl CodeEditor
Sourcepub fn set_font(&mut self, font: Font)
pub fn set_font(&mut self, font: Font)
Sets the font used by the editor
Character dimensions are re-measured with the new font, but the line
height is left alone — use Self::set_line_height to change it.
§Arguments
font- The iced font to set for the editor
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_font(iced::Font::MONOSPACE);
// Character widths are re-measured for the new font.
assert!(editor.char_width() > 0.0);Sourcepub fn set_font_size(&mut self, size: f32, auto_adjust_line_height: bool)
pub fn set_font_size(&mut self, size: f32, auto_adjust_line_height: bool)
Sets the font size and recalculates character dimensions.
If auto_adjust_line_height is true, line_height will also be scaled to maintain
the default proportion (Line Height ~ 1.43x).
§Arguments
size- The font size in pixelsauto_adjust_line_height- Whether to automatically adjust the line height
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
// Scale the line height along with the font, the usual "zoom" case.
editor.set_font_size(28.0, true);
assert!((editor.font_size() - 28.0).abs() < f32::EPSILON);
// Doubling 14px doubles the 20px default line height.
assert!((editor.line_height() - 40.0).abs() < f32::EPSILON);
// Or keep a line height the host controls itself.
editor.set_font_size(14.0, false);
assert!((editor.line_height() - 40.0).abs() < f32::EPSILON);Sourcepub fn char_width(&self) -> f32
pub fn char_width(&self) -> f32
Returns the width of a standard narrow character in pixels.
Measured from the current font rather than assumed, so it stays correct
after Self::set_font or Self::set_font_size.
§Returns
The character width in pixels
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
let narrow = editor.char_width();
assert!(narrow > 0.0);
// A larger font measures wider characters.
editor.set_font_size(28.0, true);
assert!(editor.char_width() > narrow);Sourcepub fn full_char_width(&self) -> f32
pub fn full_char_width(&self) -> f32
Returns the width of a wide character (e.g. CJK) in pixels.
Measured from 汉 as the reference glyph. Kept separate from
Self::char_width so mixed-script lines are measured correctly
instead of assuming every character is one cell wide.
§Returns
The full character width in pixels
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
// A wide glyph is never narrower than a narrow one.
assert!(editor.full_char_width() >= editor.char_width());Sourcepub fn measure_text_width(&self, text: &str) -> f32
pub fn measure_text_width(&self, text: &str) -> f32
Measures the rendered width for a given text snippet using editor metrics.
Each character counts as either Self::char_width or
Self::full_char_width depending on whether it is a wide glyph, so
the result is correct for mixed-script text.
§Arguments
text- The snippet to measure
§Returns
The width in pixels
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
assert!((editor.measure_text_width("") - 0.0).abs() < f32::EPSILON);
// Width grows with the text.
assert!(editor.measure_text_width("hello") > editor.measure_text_width("hi"));Sourcepub fn set_line_height(&mut self, height: f32)
pub fn set_line_height(&mut self, height: f32)
Sourcepub fn line_height(&self) -> f32
pub fn line_height(&self) -> f32
Sourcepub fn viewport_height(&self) -> f32
pub fn viewport_height(&self) -> f32
Returns the current viewport height in pixels.
Set by the layout each frame; the default applies only until the editor has been drawn once.
§Returns
The viewport height in pixels
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_viewport_height(480.0);
assert!((editor.viewport_height() - 480.0).abs() < f32::EPSILON);Sourcepub fn viewport_width(&self) -> f32
pub fn viewport_width(&self) -> f32
Returns the current viewport width in pixels.
This is the width line wrapping is computed against when no fixed wrap column is configured.
§Returns
The viewport width in pixels
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
assert!(editor.viewport_width() > 0.0);Sourcepub fn viewport_scroll(&self) -> f32
pub fn viewport_scroll(&self) -> f32
Returns the current vertical scroll offset in pixels.
Zero means the first line is at the top of the viewport.
§Returns
The scroll offset in pixels
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
// A fresh editor is scrolled to the top.
assert!((editor.viewport_scroll() - 0.0).abs() < f32::EPSILON);Sourcepub fn with_viewport_height(self, height: f32) -> Self
pub fn with_viewport_height(self, height: f32) -> Self
Sets the viewport height for the editor.
This determines the minimum height of the canvas, ensuring proper background rendering even when content is smaller than the viewport.
§Arguments
height- The viewport height in pixels
§Returns
Self for method chaining
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs")
.with_viewport_height(500.0);Source§impl CodeEditor
impl CodeEditor
Sourcepub fn view(&self) -> Element<'_, Message>
pub fn view(&self) -> Element<'_, Message>
Creates the view element with scrollable wrapper.
The backgrounds (editor and gutter) are handled by container styles to ensure proper clipping when the pane is resized.
Call this from the host application’s view, mapping the editor’s
Message into the host’s own message type.
§Returns
An Element rendering the editor, its gutter, and any open overlay
§Example
use iced::Element;
use iced_code_editor::{CodeEditor, Message};
/// The host application's own message type.
#[derive(Debug, Clone)]
enum AppMessage {
Editor(Message),
}
fn view(editor: &CodeEditor) -> Element<'_, AppMessage> {
editor.view().map(AppMessage::Editor)
}Source§impl CodeEditor
impl CodeEditor
Sourcepub fn new(content: &str, syntax: &str) -> Self
pub fn new(content: &str, syntax: &str) -> Self
Creates a new canvas-based text editor.
§Arguments
content- Initial text contentsyntax- Syntax highlighting language (e.g., “py”, “lua”, “rs”)
§Returns
A new CodeEditor instance
§Example
use iced_code_editor::CodeEditor;
let editor = CodeEditor::new("fn main() {}", "rs");
assert_eq!(editor.content(), "fn main() {}");
assert_eq!(editor.syntax(), "rs");
// A new editor starts clean, with nothing to undo.
assert!(!editor.is_modified());
assert!(!editor.can_undo());Sourcepub fn content(&self) -> String
pub fn content(&self) -> String
Returns the current text content as a string.
The buffer’s original line endings and trailing newline are preserved, so the result round-trips back to disk unchanged when nothing was edited.
This allocates the whole document, so prefer calling it when saving rather than on every frame.
§Returns
The complete text content of the editor
§Example
use iced_code_editor::{CodeEditor, Message};
let mut editor = CodeEditor::new("fn main() {}", "rs");
assert_eq!(editor.content(), "fn main() {}");
let _ = editor.update(&Message::Paste("// note\n".to_string()));
assert_eq!(editor.content(), "// note\nfn main() {}");Sourcepub fn is_dialog_open(&self) -> bool
pub fn is_dialog_open(&self) -> bool
Returns whether any built-in editor dialog is currently open.
Covers the search/replace dialog, the go-to-line dialog and the command
palette. They are drawn inside the editor’s own widget stack, so a host
that layers its own floating UI above Self::view needs this to step
aside while one of them is shown.
§Returns
true while at least one dialog is open, false otherwise
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("fn main() {}", "rs");
assert!(!editor.is_dialog_open());
let _task = editor.open_command_palette();
assert!(editor.is_dialog_open());Sourcepub fn reset(&mut self, content: &str) -> Task<Message>
pub fn reset(&mut self, content: &str) -> Task<Message>
Resets the editor with new content.
This method replaces the buffer content and resets all editor state
(cursor position, selection, scroll, history) to initial values.
Use this instead of creating a new CodeEditor instance to ensure
proper widget tree updates in iced.
Returns a Task that scrolls the editor to the top, which also
forces a redraw of the canvas.
§Arguments
content- The new text content
§Returns
A Task<Message> that should be returned from your update function
§Example
use iced_code_editor::CodeEditor;
let mut editor = CodeEditor::new("initial content", "lua");
// Later, reset with new content and get the task
let task = editor.reset("new content");
// Return task.map(YourMessage::Editor) from your update functionTrait Implementations§
Source§impl Program<Message> for CodeEditor
impl Program<Message> for CodeEditor
Source§fn draw(
&self,
_state: &Self::State,
renderer: &Renderer,
_theme: &Theme,
bounds: Rectangle,
_cursor: Cursor,
) -> Vec<Geometry>
fn draw( &self, _state: &Self::State, renderer: &Renderer, _theme: &Theme, bounds: Rectangle, _cursor: Cursor, ) -> Vec<Geometry>
Renders the code editor’s visual elements on the canvas, including text layout, syntax highlighting, cursor positioning, and other graphical aspects.
§Arguments
state- The current state of the canvasrenderer- The renderer used for drawingtheme- The theme for stylingbounds- The rectangle bounds of the canvascursor- The mouse cursor position
§Returns
A vector of Geometry objects representing the drawn elements
Source§fn update(
&self,
state: &mut Self::State,
event: &Event,
bounds: Rectangle,
cursor: Cursor,
) -> Option<Action<Message>>
fn update( &self, state: &mut Self::State, event: &Event, bounds: Rectangle, cursor: Cursor, ) -> Option<Action<Message>>
Handles Canvas trait events, specifically keyboard input events and focus management for the code editor widget.
§Arguments
_state- The mutable state of the canvas (unused in this implementation)event- The input event to handle, such as keyboard pressesbounds- The rectangle bounds of the canvas widgetcursor- The current mouse cursor position and status
§Returns
An optional Action<Message> to perform, such as sending a message or redrawing the canvas
Source§fn mouse_interaction(
&self,
_state: &Self::State,
bounds: Rectangle,
cursor: Cursor,
) -> Interaction
fn mouse_interaction( &self, _state: &Self::State, bounds: Rectangle, cursor: Cursor, ) -> Interaction
Uses the text-selection cursor over the editable code area.
The gutter keeps the default cursor, except for an interactive fold
chevron. Checking the cursor against bounds is important because a
canvas program’s interaction can otherwise remain active out of bounds.
Auto Trait Implementations§
impl !Freeze for CodeEditor
impl !RefUnwindSafe for CodeEditor
impl !Send for CodeEditor
impl !Sync for CodeEditor
impl !UnwindSafe for CodeEditor
impl Forget for CodeEditor
impl Move for CodeEditor
impl Unpin for CodeEditor
impl UnsafeUnpin for CodeEditor
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can
then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be
further downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<State, Message> IntoBoot<State, Message> for State
impl<State, Message> IntoBoot<State, Message> for State
Source§fn into_boot(self) -> (State, Task<Message>)
fn into_boot(self) -> (State, Task<Message>)
Application.