Skip to main content

CodeEditor

Struct CodeEditor 

Source
pub struct CodeEditor { /* private fields */ }
Expand description

Canvas-based high-performance text editor.

Implementations§

Source§

impl CodeEditor

Source

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).

Source§

impl CodeEditor

Source

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

Source§

impl CodeEditor

Source

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.

Source§

impl CodeEditor

Source

pub fn new(content: &str, syntax: &str) -> Self

Creates a new canvas-based text editor.

§Arguments
  • content - Initial text content
  • syntax - Syntax highlighting language (e.g., “py”, “lua”, “rs”)
§Returns

A new CodeEditor instance

Source

pub fn set_font(&mut self, font: Font)

Sets the font used by the editor

§Arguments
  • font - The iced font to set for the editor
Source

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 pixels
  • auto_adjust_line_height - Whether to automatically adjust the line height
Source

pub fn font_size(&self) -> f32

Returns the current font size.

§Returns

The font size in pixels

Source

pub fn char_width(&self) -> f32

Returns the width of a standard narrow character in pixels.

§Returns

The character width in pixels

Source

pub fn full_char_width(&self) -> f32

Returns the width of a wide character (e.g. CJK) in pixels.

§Returns

The full character width in pixels

Source

pub fn measure_text_width(&self, text: &str) -> f32

Measures the rendered width for a given text snippet using editor metrics.

Source

pub fn set_line_height(&mut self, height: f32)

Sets the line height used by the editor

§Arguments
  • height - The line height in pixels
Source

pub fn line_height(&self) -> f32

Returns the current line height.

§Returns

The line height in pixels

Source

pub fn viewport_height(&self) -> f32

Returns the current viewport height in pixels.

Source

pub fn viewport_width(&self) -> f32

Returns the current viewport width in pixels.

Source

pub fn viewport_scroll(&self) -> f32

Returns the current vertical scroll offset in pixels.

Source

pub fn content(&self) -> String

Returns the current text content as a string.

§Returns

The complete text content of the editor

Source

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

pub fn set_theme(&mut self, style: Style)

Sets the theme style for the editor.

§Arguments
  • style - The style to apply to the editor
§Example
use iced_code_editor::{CodeEditor, theme};

let mut editor = CodeEditor::new("fn main() {}", "rs");
editor.set_theme(theme::from_iced_theme(&iced::Theme::TokyoNightStorm));
Source

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);
Source

pub fn language(&self) -> Language

Returns the current UI language.

§Returns

The currently active language for UI text

§Example
use iced_code_editor::{CodeEditor, Language};

let editor = CodeEditor::new("fn main() {}", "rs");
let current_lang = editor.language();
Source

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.

§Arguments
  • client - The LSP client to notify
  • document - Document metadata describing the buffer
Source

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.

§Arguments
  • document - Document metadata describing the buffer
Source

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.

Source

pub fn lsp_did_save(&mut self)

Sends a did_save notification with the current buffer contents.

Source

pub fn lsp_request_hover(&mut self)

Requests hover information at the current cursor position.

Source

pub fn lsp_request_hover_at(&mut self, point: Point) -> bool

Requests hover information at a canvas point.

Returns true if the point maps to a valid buffer position and the request was sent.

Source

pub fn lsp_request_hover_at_position(&mut self, position: LspPosition) -> bool

Requests hover information at an explicit LSP position.

Returns true if an LSP client is attached and the request was sent.

Source

pub fn lsp_position_at_point(&self, point: Point) -> Option<LspPosition>

Converts a canvas point to an LSP position, if possible.

Source

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, which is useful for LSP hover and definition requests.

Source

pub fn lsp_request_completion(&mut self)

Requests completion items at the current cursor position.

Source

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.

Source

pub fn set_lsp_auto_flush(&mut self, auto_flush: bool)

Sets whether LSP changes are flushed automatically after edits.

Source

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();
Source

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");
}
Source

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 function
Source

pub fn is_modified(&self) -> bool

Returns whether the editor has unsaved changes.

§Returns

true if there are unsaved modifications, false otherwise

Source

pub fn mark_saved(&mut self)

Marks the current state as saved.

Call this after successfully saving the file to reset the modified state.

Source

pub fn can_undo(&self) -> bool

Returns whether undo is available.

Source

pub fn can_redo(&self) -> bool

Returns whether redo is available.

Source

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 wrapping
Source

pub fn wrap_enabled(&self) -> bool

Returns whether line wrapping is enabled.

§Returns

true if line wrapping is enabled, false otherwise

Source

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/replace
Source

pub fn search_replace_enabled(&self) -> bool

Returns whether search/replace functionality is enabled.

§Returns

true if search/replace is enabled, false otherwise

Source

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);
Source

pub fn lsp_enabled(&self) -> bool

Returns whether LSP support is enabled.

true if LSP is enabled, false otherwise

Source

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");
Source

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.

Source

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.

Source

pub fn close_search_dialog(&mut self) -> Task<Message>

Closes the search dialog programmatically.

§Returns

A Task<Message> for any follow-up UI work.

Source

pub fn with_wrap_enabled(self, enabled: bool) -> Self

Sets the line wrapping with builder pattern.

§Arguments
  • enabled - Whether to enable line wrapping
§Returns

Self for method chaining

§Example
use iced_code_editor::CodeEditor;

let editor = CodeEditor::new("fn main() {}", "rs")
    .with_wrap_enabled(false);
Source

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.

§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 characters
Source

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 numbers
Source

pub fn line_numbers_enabled(&self) -> bool

Returns whether line numbers are displayed.

§Returns

true if line numbers are displayed, false otherwise

Source

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);
Source

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();
Source

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

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);
}
Source

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

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.

Source

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.

§Returns

true if the request was successfully sent (i.e., a valid position was found and an LSP client is active), false otherwise.

Trait Implementations§

Source§

impl Program<Message> for CodeEditor

Source§

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 canvas
  • renderer - The renderer used for drawing
  • theme - The theme for styling
  • bounds - The rectangle bounds of the canvas
  • cursor - 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>>

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 presses
  • bounds - The rectangle bounds of the canvas widget
  • cursor - The current mouse cursor position and status
§Returns

An optional Action<Message> to perform, such as sending a message or redrawing the canvas

Source§

type State = ()

The internal state mutated by the Program.
Source§

fn mouse_interaction( &self, _state: &Self::State, _bounds: Rectangle, _cursor: Cursor, ) -> Interaction

Returns the current mouse interaction of the Program. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<State, Message> IntoBoot<State, Message> for State

Source§

fn into_boot(self) -> (State, Task<Message>)

Turns some type into the initial state of some Application.
Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> MaybeClone for T

Source§

impl<T> MaybeDebug for T