Skip to main content

Crate editor_core

Crate editor_core 

Source
Expand description

Editor Core - Industrial-Grade Headless Code Editor Kernel

§Overview

editor-core is a headless code editor kernel focused on state management, text metrics, and coordinate transformations.

It does not render UI. Hosts render from snapshots (e.g. HeadlessGrid) and drive edits via the command/state APIs.

§Core Features

  • Efficient Text Storage: Rope-backed text buffer with char-indexed access
  • Fast Line Index: Rope-based line access and coordinate conversion
  • Soft Wrapping Support: Headless layout engine, supporting arbitrary container widths
  • Style Management: Interval tree structure, O(log n + k) query complexity
  • Code Folding: Supports arbitrary levels of code folding
  • State Tracking: Version number mechanism and Change Notifications system
  • Workspace model: Multi-buffer + multi-view orchestration (Workspace, BufferId, ViewId) for tabs and split panes

§Architecture Layers

┌─────────────────────────────────────────────┐
│  Command Interface & State Management       │  ← Public API
├─────────────────────────────────────────────┤
│  Snapshot API (HeadlessGrid)                │  ← Rendering Data
├─────────────────────────────────────────────┤
│  Intervals & Visibility (Styles + Folding)  │  ← Visual Enhancement
├─────────────────────────────────────────────┤
│  Layout Engine (Soft Wrapping)              │  ← Text Layout
├─────────────────────────────────────────────┤
│  Line Index + TextBuffer (Rope-based)       │  ← Text Storage / Line Access
└─────────────────────────────────────────────┘

§Quick Start

§Using Command Interface

use editor_core::{CommandExecutor, Command, EditCommand, CursorCommand, Position};

let mut executor = CommandExecutor::empty(80);

// Insert text
executor.execute(Command::Edit(EditCommand::Insert {
    offset: 0,
    text: "fn main() {\n    println!(\"Hello\");\n}\n".to_string(),
})).unwrap();

// Move cursor
executor.execute(Command::Cursor(CursorCommand::MoveTo {
    line: 1,
    column: 4,
})).unwrap();

assert_eq!(executor.editor().cursor_position(), Position::new(1, 4));

§Using State Management

use editor_core::{EditorStateManager, StateChangeType};

let mut manager = EditorStateManager::new("Initial text", 80);

// Subscribe to state changes
manager.subscribe(|change| {
    println!("State changed: {:?}", change.change_type);
});

// Query state
let doc_state = manager.get_document_state();
println!("Line count: {}, Characters: {}", doc_state.line_count, doc_state.char_count);

§Using Workspace (multi-buffer / multi-view)

use editor_core::{Command, CursorCommand, EditCommand, Workspace};

let mut ws = Workspace::new();
let opened = ws
    .open_buffer(Some("file:///demo.txt".to_string()), "Hello\nWorld\n", 80)
    .unwrap();

// Commands always target a view.
let view = opened.view_id;
ws.execute(view, Command::Cursor(CursorCommand::MoveTo { line: 1, column: 0 }))
    .unwrap();
ws.execute(view, Command::Edit(EditCommand::InsertText { text: ">> ".into() }))
    .unwrap();

let grid = ws.get_viewport_content_styled(view, 0, 10).unwrap();
assert!(grid.actual_line_count() > 0);

§API Visibility

EditorCore keeps its storage, layout, style, folding, and cursor fields private so hosts cannot bypass synchronization invariants. Use read-only getters such as EditorCore::line_index, EditorCore::layout_engine, EditorCore::folding_manager, and EditorCore::viewport_width for inspection. Use CommandExecutor, EditorStateManager, Workspace, or narrowly scoped public methods for mutations that must update text, layout, folding, styles, and notifications together. Layout and interval/folding types are exposed from the crate root as facade re-exports rather than through public layout or intervals modules.

§Module Description

  • storage - deprecated Piece Table compatibility layer; it is not on the main editing path
  • line_index - Rope-based line index and canonical text access facade
  • LayoutEngine, WrapMode, and related root re-exports - soft wrapping layout facade
  • IntervalTree, FoldingManager, and related root re-exports - style intervals and code folding facade
  • snapshot - Headless snapshot API (HeadlessGrid)
  • commands - Unified command interface
  • state - State management and query interface

§Performance Goals

  • Loading: 1000 line document < 100ms
  • insertion: 100 random insertions < 100ms
  • line access: 1000 line accesses < 10ms
  • Memory: bounded command history with rope-backed text storage on the main editing path

§Unicode Support

  • UTF-8 internal encoding
  • Proper handling of CJK double-width characters
  • Public offsets and positions are char-indexed Unicode scalar coordinates
  • Layout columns and snapshot ranges use Unicode scalar positions plus rendered cell widths, not grapheme-cluster indices
  • Dedicated grapheme cursor/delete commands use UAX #29 boundaries; dedicated word movement and deletion commands use Unicode word boundaries
  • Editor-friendly word selection and expansion use configurable ASCII token boundaries, treating non-ASCII scalars as single-character word units
  • editor-core-lsp provides UTF-16 code unit coordinate conversion for LSP integrations
  • editor-core-sublime provides optional .sublime-syntax syntax highlighting and folding

Re-exports§

pub use anchors::AnchorBias;
pub use anchors::TextAnchor;
pub use commands::AutoPair;
pub use commands::AutoPairsConfig;
pub use commands::Command;
pub use commands::CommandError;
pub use commands::CommandExecutor;
pub use commands::CommandResult;
pub use commands::CursorCommand;
pub use commands::EditCommand;
pub use commands::EditorCore;
pub use commands::ExpandSelectionDirection;
pub use commands::ExpandSelectionUnit;
pub use commands::Position;
pub use commands::Selection;
pub use commands::SelectionDirection;
pub use commands::StyleCommand;
pub use commands::TabKeyBehavior;
pub use commands::TextEditSpec;
pub use commands::UndoHistoryRestoreError;
pub use commands::UndoHistorySelectionSet;
pub use commands::UndoHistorySnapshot;
pub use commands::UndoHistoryStep;
pub use commands::UndoHistoryTextEdit;
pub use commands::ViewCommand;
pub use decorations::Decoration;
pub use decorations::DecorationKind;
pub use decorations::DecorationLayerId;
pub use decorations::DecorationPlacement;
pub use decorations::DecorationRange;
pub use delta::TextDelta;
pub use delta::TextDeltaEdit;
pub use diagnostics::Diagnostic;
pub use diagnostics::DiagnosticRange;
pub use diagnostics::DiagnosticSeverity;
pub use intelligence::CallHierarchyIncomingCall;
pub use intelligence::CallHierarchyOutgoingCall;
pub use intelligence::CallHierarchyResultSet;
pub use intelligence::HierarchyItem;
pub use intelligence::IntelligenceResultSet;
pub use intelligence::ReferencesResultSet;
pub use intelligence::ResultSetId;
pub use intelligence::ResultSetKind;
pub use intelligence::TypeHierarchyResultSet;
pub use intelligence::WorkspaceIntelligence;
pub use line_ending::LineEnding;
pub use line_index::LineIndex;
pub use processing::DocumentProcessor;
pub use processing::ProcessingEdit;
pub use search::SearchError;
pub use search::SearchMatch;
pub use search::SearchOptions;
pub use snapshot::Cell;
pub use snapshot::ComposedCell;
pub use snapshot::ComposedCellSource;
pub use snapshot::ComposedGrid;
pub use snapshot::ComposedLine;
pub use snapshot::ComposedLineKind;
pub use snapshot::HeadlessGrid;
pub use snapshot::HeadlessLine;
pub use snapshot::MinimapGrid;
pub use snapshot::MinimapLine;
pub use snapshot::SnapshotGenerator;
pub use snippets::SnippetRange;
pub use snippets::SnippetSession;
pub use snippets::SnippetTabstop;
pub use snippets::SnippetTemplate;
pub use snippets::parse_snippet;
pub use state::CursorState;
pub use state::DecorationsState;
pub use state::DiagnosticsState;
pub use state::DocumentState;
pub use state::EditorState;
pub use state::EditorStateManager;
pub use state::FoldingState;
pub use state::SmoothScrollState;
pub use state::StateChange;
pub use state::StateChangeCallback;
pub use state::StateChangeType;
pub use state::StyleState;
pub use state::UndoRedoState;
pub use state::ViewportState;
pub use storage::PieceTable;
pub use symbols::DocumentOutline;
pub use symbols::DocumentSymbol;
pub use symbols::SymbolKind;
pub use symbols::SymbolLocation;
pub use symbols::SymbolRange;
pub use symbols::Utf16Position;
pub use symbols::Utf16Range;
pub use symbols::WorkspaceSymbol;
pub use workspace::BufferId;
pub use workspace::BufferMetadata;
pub use workspace::JumpTarget;
pub use workspace::OpenBufferResult;
pub use workspace::ViewId;
pub use workspace::ViewSmoothScrollState;
pub use workspace::Workspace;
pub use workspace::WorkspaceError;
pub use workspace::WorkspaceSearchResult;
pub use workspace::WorkspaceUndoHistoryRestoreError;
pub use workspace::WorkspaceViewportState;

Modules§

anchors
Anchored offsets that stay stable under text edits.
commands
Command Interface Layer
decorations
First-class decorations (virtual text) data model.
delta
Structured text change deltas.
diagnostics
First-class diagnostics data model.
intelligence
UI-agnostic language intelligence data models.
line_ending
Line ending helpers.
line_index
Stage 2: Logical Line Index
processing
Generic document processing interfaces.
search
Text search helpers.
snapshot
Phase 6: Headless Output Snapshot (Headless Snapshot API)
snippets
Snippet parsing + placeholder navigation primitives.
state
Editor State Interface
storage
Deprecated Piece Table compatibility layer.
symbols
First-class symbol / outline data model.
workspace
Workspace and multi-buffer / multi-view model.

Structs§

CommentConfig
Comment tokens/config for a given language.
FoldRegion
Fold region
FoldingManager
Folding manager
IndentationConfig
Indentation configuration for a language.
Interval
Interval structure
IntervalTextEdit
Text edit delta used to shift style intervals after text changes.
IntervalTree
Interval tree - manages style intervals
LayoutEngine
Layout engine - manages visual representation of all lines
StyleLayerId
Style layer ID
VisualLineInfo
Visual line information
WrapPoint
Wrap point

Enums§

IndentStyle
How the language prefers indentation.
WrapIndent
Wrapped-line indentation policy.
WrapMode
Soft wrapping mode.

Constants§

CODE_LENS_STYLE_ID
Built-in style id for LSP code lens virtual text (textDocument/codeLens).
DEFAULT_TAB_WIDTH
Default tab width (in cells) used when a caller does not specify a tab width.
DIFF_ADD_LINE_STYLE_ID
Built-in style id for added lines in headless diff projections.
DIFF_REMOVE_LINE_STYLE_ID
Built-in style id for removed lines in headless diff projections.
DIFF_SPACER_STYLE_ID
Built-in style id for filler spacer rows in headless diff projections.
DOCUMENT_HIGHLIGHT_READ_STYLE_ID
Built-in style id for LSP textDocument/documentHighlight (kind: Read).
DOCUMENT_HIGHLIGHT_TEXT_STYLE_ID
Built-in style id for LSP textDocument/documentHighlight (kind: Text/unspecified).
DOCUMENT_HIGHLIGHT_WRITE_STYLE_ID
Built-in style id for LSP textDocument/documentHighlight (kind: Write).
DOCUMENT_LINK_STYLE_ID
Built-in style id for LSP document links (textDocument/documentLink).
FOLD_PLACEHOLDER_STYLE_ID
Built-in style id used for folding placeholder text (e.g. /*...*/, use ...).
IME_MARKED_TEXT_STYLE_ID
Built-in style id for IME marked text (composition / preedit).
INLAY_HINT_STYLE_ID
Built-in style id for LSP inlay hints virtual text (textDocument/inlayHint).
MATCH_HIGHLIGHT_STYLE_ID
Built-in style id for match highlights (e.g. search matches, bracket matches).

Functions§

calculate_wrap_points
Calculate wrap points for text
calculate_wrap_points_with_tab_width
Calculate wrap points for text, interpreting '\t' using tab_width.
calculate_wrap_points_with_tab_width_and_mode
Calculate wrap points for text using a configurable WrapMode.
calculate_wrap_points_with_tab_width_mode_and_indent
Calculate wrap points for text using a configurable WrapMode and WrapIndent.
cell_width_at
Calculate visual width (in cells) for a character at a specific cell offset within the line.
char_width
Calculate visual width of a character (based on UAX #11)
str_width
Calculate total visual width of a string
str_width_with_tab_width
Calculate total visual width of a string, interpreting '\t' using tab_width.
visual_x_for_column
Calculate the visual cell offset from the start of the line to the given character column.

Type Aliases§

StyleId
Style ID type