Skip to main content

Editor

Struct Editor 

Source
pub struct Editor {
Show 32 fields pub buffer: EditorBuffer, pub theme: EditorTheme, pub config: EditorConfig, pub hooks: Vec<Box<dyn EditorHook>>, pub highlighter: Option<Arc<dyn SyntaxHighlighter>>, pub highlighter_rev: u64, pub layout_cache: LayoutCache, pub face_availability: Option<FaceAvailability>, pub selected_font_family: Option<SharedString>, pub face_probe_key: Option<(Option<SharedString>, Option<SharedString>, Font)>, pub focus_handle: FocusHandle, pub scroll_row: usize, pub selection: Option<Selection>, pub cursor_style: CursorStyle, pub cursor_visible: bool, pub is_selecting: bool, pub selection_granularity: SelectionGranularity, pub drag_initial_range: Option<Range<usize>>, pub is_hovering_task: bool, pub hovered_link: Option<String>, pub last_bounds: Option<Bounds<Pixels>>, pub last_cursor_pixel: Option<Point<Pixels>>, pub visible_lines: Vec<VisibleLineLayout>, pub frame_stats: FrameStats, pub prompt: PromptState, pub context_menu: ContextMenuState, pub context_menu_anchor: Option<Point<Pixels>>, pub context_menu_selected: Option<usize>, pub pending_effects: Vec<HookEffect>, pub file_path: Option<PathBuf>, pub search_matches: Vec<Range<usize>>, pub search_highlight_all: bool, /* private fields */
}
Expand description

The main GPUI text editor view and controller.

Fields§

§buffer: EditorBuffer

The underlying text buffer managing document contents and undo/redo history.

§theme: EditorTheme

Visual color palette for canvas background, text, cursor, and syntax tokens.

§config: EditorConfig

Display and layout configurations (font size, line height, line numbers, wrapping).

§hooks: Vec<Box<dyn EditorHook>>

Extensible hooks chain intercepting keystrokes, edits, and selection changes.

§highlighter: Option<Arc<dyn SyntaxHighlighter>>

Active syntax highlighter computing semantic and direct style spans.

§highlighter_rev: u64

Revision bumped on every highlighter swap so LayoutCache epochs bust even when the buffer version is unchanged (e.g. conceal-mode cycling).

§layout_cache: LayoutCache

Per-version cache of highlight/conceal/link inputs, shared by prepaint and hit-testing so each row is parsed once per epoch, not per frame.

§face_availability: Option<FaceAvailability>

Bold/italic face availability from the last prepaint probe (None before first paint).

§selected_font_family: Option<SharedString>

Base family picked by candidate auto-select (None before first paint, or when no candidate has emphasis faces).

§face_probe_key: Option<(Option<SharedString>, Option<SharedString>, Font)>

Inputs the face probe last ran against: explicit families + host font. Re-probed on change only.

§focus_handle: FocusHandle

Focus handle for keyboard input tracking within GPUI.

§scroll_row: usize

First visible row index in the viewport.

§selection: Option<Selection>

Active selection range, if any.

§cursor_style: CursorStyle

Active visual cursor style (Bar, Block, Underline, Hidden).

§cursor_visible: bool

Whether the visual cursor is currently visible in its blink cycle.

§is_selecting: bool

Whether the user is currently mouse-drag selecting text.

§selection_granularity: SelectionGranularity

Active selection granularity for drag selection.

§drag_initial_range: Option<Range<usize>>

Anchor range for multi-click drag selection expansion.

§is_hovering_task: bool

Whether the mouse cursor is currently hovering over an interactive task checkbox.

§hovered_link: Option<String>

Target URL if the mouse cursor is currently hovering over a hyperlink.

§last_bounds: Option<Bounds<Pixels>>

Last rendered bounds in window pixel coordinates.

§last_cursor_pixel: Option<Point<Pixels>>

Last rendered cursor position in window pixel coordinates, computed during canvas prepaint.

§visible_lines: Vec<VisibleLineLayout>

Layout metrics and screen coordinates of currently visible lines, cached during prepaint.

§frame_stats: FrameStats

Rolling frame-rate samples, recorded once per canvas prepaint.

Powers the crate::fps_badge testing HUD: it updates whenever the editor repaints (typing, selection drags, scrolling) and freezes when idle, with no forced repaints of its own.

§prompt: PromptState

Shared headless prompt / input-box state, passed to hooks via twrite_core::HookContext and rendered by crate::prompt_bar::PromptBar when open.

§context_menu: ContextMenuState

Headless right-click menu state (items merged from defaults + hooks).

§context_menu_anchor: Option<Point<Pixels>>

Window-pixel anchor where the menu was opened; clamped at render time.

§context_menu_selected: Option<usize>

Keyboard-selected row inside the open menu, if any.

§pending_effects: Vec<HookEffect>

App-level requests queued by hooks; Self::flush_effects executes file effects inline, hosts drain the rest via Self::take_effects.

§file_path: Option<PathBuf>

File path for :w-style saves (Save { path: None }); set by Self::load_file.

§search_matches: Vec<Range<usize>>

Last synced search matches for the highlight-all wash.

§search_highlight_all: bool

Whether the highlight-all wash is enabled (from the search snapshot).

Implementations§

Source§

impl Editor

Source

pub fn delete_selection(&mut self) -> bool

Deletes the currently selected text, returning true if text was deleted.

Source

pub fn replace_selection_or_insert(&mut self, text: &str)

Replaces the active selection with text, or inserts text at the cursor position.

Source

pub fn copy(&self, cx: &App)

Copies the currently selected text to the system clipboard.

Source

pub fn cut(&mut self, cx: &App) -> bool

Cuts the currently selected text and copies it to the system clipboard.

Returns true if text was cut, or false if there was no selection.

Source

pub fn paste(&mut self, cx: &App) -> bool

Pastes text from the system clipboard, replacing the current selection or inserting at cursor.

Returns true if text was pasted, or false if the clipboard was empty.

Source§

impl Editor

Source

pub fn scroll_up(&mut self, count: usize)

Scrolls the viewport upward by a given number of lines.

Source

pub fn scroll_down(&mut self, count: usize)

Scrolls the viewport downward by a given number of lines.

Source

pub fn scroll_and_clamp_cursor( &mut self, count: usize, scroll_down: bool, select: bool, )

Scrolls the viewport by count rows and clamps the cursor into the visible range (Vim Ctrl+E / Ctrl+Y style).

Set scroll_down to true to scroll toward the end of the document, false to scroll toward the beginning.

If the cursor row is still visible after the scroll it is not moved. If it scrolled above the viewport the cursor moves to the first visible row. If it scrolled below the viewport the cursor moves to the last visible row. The cursor column is preserved and clamped to the target line length by the buffer.

Pass select = true when Shift is held to extend the selection instead of collapsing it.

The caller is responsible for running on_selection_change hooks, flush_effects, sync_search_state, and cx.notify() afterwards, matching the post-processing every other cursor-moving key path runs.

Source

pub fn move_cursor_to(&mut self, new_offset: usize, select: bool)

Moves the cursor to new_offset, expanding or creating a selection if select is true.

Source

pub fn scroll_to_cursor(&mut self, window: Option<&Window>)

Scrolls the viewport so that the cursor is visible.

Ensures a 1-line margin above and below the cursor when possible.

Source

pub fn offset_for_position( &mut self, pos: Point<Pixels>, window: &Window, ) -> usize

Calculates the byte offset in the text buffer corresponding to a window pixel position.

Shares crate::layout_cache::LayoutCache inputs with prepaint: the highlight/conceal work for the target row is a cache hit unless the buffer changed since paint.

Source

pub fn cursor_pixel_position(&self) -> Option<Point<Pixels>>

Returns the window pixel coordinates (X, Y) at the bottom of the active cursor.

This value is automatically computed and cached during each canvas render pass. Returns None if the editor has not yet been rendered, or if the cursor is scrolled outside the visible viewport.

Returns the target URL if pos is over a hyperlink.

Source§

impl Editor

Source

pub fn press_search_key( &mut self, code: KeyCode, ctrl: bool, alt: bool, shift: bool, window: Option<&Window>, cx: &mut Context<'_, Self>, )

Feeds a synthetic key through the hook chain with full post-processing.

Used by prompt-bar chips and arrow buttons so clicks share the exact keyboard path (e.g. Alt+C toggles Match Case, plain Down walks to the next match).

Source

pub fn press_search_action( &mut self, action: SearchAction, window: Option<&Window>, cx: &mut Context<'_, Self>, )

Feeds a synthetic search-panel action (prompt-bar clicks) through the hook chain with the same post-processing as consumed keys.

Pointer chrome cannot produce a KeyCode, so actions travel on [EditorHook::on_search_action] instead of through KeyEvent.

Source§

impl Editor

Source

pub fn new(initial_text: &str, cx: &mut Context<'_, Self>) -> Self

Creates a new editor entity with initial_text.

Resets the cursor blink cycle to visible and schedules periodic toggling.

Sets whether cursor blinking is enabled and resets the blink cycle.

Source

pub fn add_hook(&mut self, hook: impl EditorHook)

Adds an editor hook to the execution chain.

Source

pub fn clear_hooks(&mut self)

Clears all registered editor hooks.

Source

pub fn status_text(&self) -> Option<&str>

Returns the active status or mode text reported by registered hooks.

Source

pub fn is_block_cursor(&self) -> bool

Returns true if the cursor is currently in block mode.

Source

pub fn resolved_base_font(&self, host: &Font) -> Font

Resolves the base font: explicit family, else auto-selected family, else host.

Source

pub fn resolved_code_font(&self, host: &Font) -> Font

Resolves the Code-span font (follows auto-select unless overridden).

Source

pub fn set_highlighter(&mut self, highlighter: impl SyntaxHighlighter)

Sets the active syntax highlighter.

Source

pub fn clear_highlighter(&mut self)

Clears the active syntax highlighter, reverting to plain text.

Source

pub fn enable_markdown(&mut self)

Enables out-of-the-box CommonMark and GFM editing using self.config.markdown.

Automatically configures twrite_core::MarkdownHighlighter, twrite_core::AutoPairsHook, and twrite_core::MarkdownHook.

Source

pub fn enable_markdown_with_config(&mut self, config: MarkdownConfig)

Enables out-of-the-box CommonMark and GFM editing with custom Markdown configuration.

Source

pub fn load_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), EditorError>

Loads document text from a file into the editor, resetting cursor and undo history.

Source

pub fn flush_effects(&mut self)

Executes queued file effects (Save / Load) inline, keeping app-level effects (Quit / Message) queued for the host to drain via Self::take_effects. Runs automatically after input events.

Source

pub fn take_effects(&mut self) -> Vec<HookEffect>

Takes app-level effects (Quit / Message) left by Self::flush_effects.

Source

pub fn search_snapshot(&self) -> Option<SearchSnapshot>

Returns the live search-panel snapshot from the first hook that provides one (twrite_core::SearchHook; composite hooks forward their own).

Source

pub fn sync_search_state(&mut self)

Refreshes Self::search_matches / Self::search_highlight_all from the hook snapshot; clears both when no hook is active. Runs automatically after key input (see Self::dispatch_key).

Source

pub fn save_file<P: AsRef<Path>>(&self, path: P) -> Result<(), EditorError>

Saves the current editor document contents to a file.

Trait Implementations§

Source§

impl Render for Editor

Source§

fn render( &mut self, _window: &mut Window, cx: &mut Context<'_, Self>, ) -> impl IntoElement

Render this view into an element tree.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Editor

§

impl !Send for Editor

§

impl !Sync for Editor

§

impl !UnwindSafe for Editor

§

impl Freeze for Editor

§

impl Unpin for Editor

§

impl UnsafeUnpin for Editor

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
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert 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.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

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

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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