Refactor to minimal EditorAction architecture for scriptability

Move cursor movement logic from EditorCore/Cursor into Configuration layer.
This prepares the codebase for a Turing-complete scripting DSL by keeping
EditorAction minimal (only absolute MoveCursor { x, y }) and having the
scripting layer compute all movement targets via BufferQuery.

- Add BufferQuery trait for read-only buffer access
- Remove CursorMovement enum, replace with MoveCursor { x, y }
- Simplify Cursor to just hold position (remove move_cursor method)
- Configuration now computes movement targets using BufferQuery

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Greg ShuflinandClaude Opus 4.5 committed 2026-02-09 21:24:26 -08:00
1 parent f80cc2da0d
commit ed6280205e
7 files changed
+281 -69

No files matched your search

+132
View File
@@ -0,0 +1,132 @@
# Minimal EditorAction Architecture
This document describes the architectural approach for making pane-editor highly scriptable by keeping `EditorAction` minimal and pushing movement logic into the scripting/configuration layer.
## Goals
1. **Emacs-level scriptability** via a Turing-complete DSL (non-Lisp)
2. **Vim-like UX** - modal, light, fast
3. **Stable core** - EditorCore changes rarely, all "smarts" live in scripts
## Architecture Overview
```
┌─────────────────────────────────────────────────────┐
│ Scripting Layer (Configuration / future DSL) │
│ - Keybindings │
│ - Movement definitions (what is a "word"?) │
│ - Custom commands │
│ - Plugins │
│ │
│ [reads via BufferQuery] [writes via actions] │
└──────────┬─────────────────────────────────────────┬┘
│ │
▼ ▼
┌─────────────────────┐ ┌─────────────────────────┐
│ BufferQuery trait │ │ EditorAction │
│ │ │ │
│ - cursor() │ │ - MoveCursor { x, y } │
│ - line_count() │ │ - InsertCharacter(ch) │
│ - line_len(y) │ │ - DeleteChar │
│ - char_at(x, y) │ │ - SetMode(Mode) │
│ │ │ - etc. │
└──────────┬──────────┘ └────────────┬────────────┘
│ │
▼ ▼
┌─────────────────────────────────────────────────────┐
│ EditorCore │
│ - Buffers (Rope storage) │
│ - Cursor positions (just x, y - no logic) │
│ - Mode state │
│ - Undo history (future) │
│ │
│ (Dumb state container - no movement logic) │
└─────────────────────────────────────────────────────┘
```
## Key Design Decisions
### 1. EditorAction is Minimal
`EditorAction::MoveCursor` takes absolute `{ x, y }` coordinates only. There is no `NextWord`, `PrevLine`, or `EndOfLine` variant. The scripting layer computes target positions using `BufferQuery` and emits absolute moves.
```rust
pub enum EditorAction {
MoveCursor { x: usize, y: usize },
InsertCharacter(char),
DeleteChar,
SetMode(Mode),
// ...
}
```
### 2. BufferQuery Exposes Read-Only State
The scripting layer needs to inspect buffer contents to compute movement targets:
```rust
pub trait BufferQuery {
fn cursor(&self) -> (usize, usize);
fn line_count(&self) -> usize;
fn line_len(&self, y: usize) -> usize;
fn char_at(&self, x: usize, y: usize) -> Option<char>;
}
```
### 3. Cursor is a Dumb Position Holder
`Cursor` stores `(x, y)` and nothing else. No `move_cursor()` method. All movement computation happens in the scripting layer.
### 4. Configuration Gets Query Access
`Configuration::get_editor_action()` receives a `&dyn BufferQuery` so it can compute movement targets:
```rust
impl Configuration {
pub fn get_editor_action(
&self,
input: Input,
mode: Mode,
buffer: Option<&dyn BufferQuery>,
) -> Option<EditorAction>;
}
```
## Example: How "j" (move down) Works
1. User presses `j` in Normal mode
2. `EditorCore::send_input(Input::Character('j'))` is called
3. EditorCore passes the active buffer (as `&dyn BufferQuery`) to Configuration
4. Configuration queries `buffer.cursor()` → `(5, 10)` (x=5, y=10)
5. Configuration queries `buffer.line_count()` → `100`
6. Configuration computes: `new_y = min(10 + 1, 100 - 1) = 11`
7. Configuration returns `EditorAction::MoveCursor { x: 5, y: 11 }`
8. EditorCore sets cursor to (5, 11)
## Example: How "w" (next word) Will Work
1. User presses `w` in Normal mode
2. Configuration queries buffer for current position and text
3. Configuration's word-finding logic (eventually defined in DSL) scans forward:
- Skip current word characters
- Skip non-word characters
- Return position of next word start
4. Configuration returns `EditorAction::MoveCursor { x: new_x, y: new_y }`
The word definition (what characters are "word" vs "punctuation") lives entirely in the scripting layer, not in EditorCore.
## Benefits
- **EditorCore is stable**: Adding new movement types never requires EditorCore changes
- **Full scriptability**: DSL can define arbitrarily complex movements
- **Configurable word definitions**: "word" means whatever the user's config says
- **Testable**: Movement logic can be unit tested without EditorCore
- **Frontend agnostic**: EditorCore remains decoupled from input handling
## Migration Path
1. Replace `CursorMovement` enum with `MoveCursor { x, y }`
2. Add `BufferQuery` trait, implement on `TextBuffer`
3. Move movement logic from `Cursor::move_cursor()` to `Configuration`
4. Simplify `Cursor` to just hold position
5. (Future) Replace Configuration's Rust code with DSL interpreter
+67 -8
View File
@@ -1,9 +1,14 @@
/// The configuration module controls the mapping of `Input` items to `EditorActions`. This
/// should be freely user-editable in the future.
/// should be freely user-editable in the future, and will eventually be replaced by a
/// Turing-complete DSL.
///
/// Movement logic lives here (not in EditorCore) so that the scripting layer has full control
/// over cursor behavior. See docs/architecture/minimal-action-design.md for design rationale.
use tracing::warn;
use crate::core::{
actions::{CommandAction, CursorMovement, EditorAction},
actions::{CommandAction, EditorAction},
buffer_query::BufferQuery,
Input, Mode,
};
@@ -15,8 +20,13 @@ impl Configuration {
Self {}
}
#[tracing::instrument(skip(self))]
pub(crate) fn get_editor_action(&self, input: Input, mode: Mode) -> Option<EditorAction> {
#[tracing::instrument(skip(self, buffer))]
pub(crate) fn get_editor_action(
&self,
input: Input,
mode: Mode,
buffer: Option<&dyn BufferQuery>,
) -> Option<EditorAction> {
use EditorAction::*;
Some(match input {
@@ -24,10 +34,10 @@ impl Configuration {
Mode::Insert | Mode::Command => InsertCharacter(ch),
Mode::Normal if ch == 'i' => TransitionToMode(Mode::Insert),
Mode::Normal if ch == 'q' => Quit,
Mode::Normal if ch == 'h' => MoveCursor(CursorMovement::OppositeTextDirection),
Mode::Normal if ch == 'j' => MoveCursor(CursorMovement::NextLine),
Mode::Normal if ch == 'k' => MoveCursor(CursorMovement::PrevLine),
Mode::Normal if ch == 'l' => MoveCursor(CursorMovement::TextDirection),
Mode::Normal if ch == 'h' => self.move_left(buffer?)?,
Mode::Normal if ch == 'j' => self.move_down(buffer?)?,
Mode::Normal if ch == 'k' => self.move_up(buffer?)?,
Mode::Normal if ch == 'l' => self.move_right(buffer?)?,
Mode::Normal if ch == ':' => TransitionToMode(Mode::Command),
_ => return None,
},
@@ -56,4 +66,53 @@ impl Configuration {
}
})
}
// Movement computation methods
// These will eventually be defined in the DSL, not hardcoded here
fn move_left(&self, buffer: &dyn BufferQuery) -> Option<EditorAction> {
let (x, y) = buffer.cursor();
if x > 0 {
Some(EditorAction::MoveCursor { x: x - 1, y })
} else {
None // Already at start of line
}
}
fn move_right(&self, buffer: &dyn BufferQuery) -> Option<EditorAction> {
let (x, y) = buffer.cursor();
let line_len = buffer.line_len(y);
if x < line_len {
Some(EditorAction::MoveCursor { x: x + 1, y })
} else {
None // Already at end of line
}
}
fn move_up(&self, buffer: &dyn BufferQuery) -> Option<EditorAction> {
let (x, y) = buffer.cursor();
if y > 0 {
let new_y = y - 1;
let new_line_len = buffer.line_len(new_y);
// Clamp x to the length of the new line
let new_x = x.min(new_line_len);
Some(EditorAction::MoveCursor { x: new_x, y: new_y })
} else {
None // Already at first line
}
}
fn move_down(&self, buffer: &dyn BufferQuery) -> Option<EditorAction> {
let (x, y) = buffer.cursor();
let line_count = buffer.line_count();
if y + 1 < line_count {
let new_y = y + 1;
let new_line_len = buffer.line_len(new_y);
// Clamp x to the length of the new line
let new_x = x.min(new_line_len);
Some(EditorAction::MoveCursor { x: new_x, y: new_y })
} else {
None // Already at last line
}
}
}
+13 -3
View File
@@ -1,5 +1,6 @@
pub(crate) mod actions;
pub(crate) mod buffer;
pub(crate) mod buffer_query;
mod buffer_settings;
pub(crate) mod commands;
mod cursor;
@@ -19,6 +20,7 @@ use crate::{
core::{
actions::{CommandAction, EditorAction},
buffer::FinderBuffer,
buffer_query::BufferQuery,
error::BasicErrorKind,
pane_layout::PaneDescriptor,
},
@@ -110,7 +112,15 @@ impl EditorCore {
}
pub(crate) fn send_input(&mut self, input: Input) {
let action = self.configuration.get_editor_action(input, self.mode);
// Get a query interface to the active buffer for movement computation
let buffer_query: Option<&dyn BufferQuery> = match self.active_buffer() {
Buffer::Text(tb) => Some(tb),
Buffer::Finder(_) => None, // Finder doesn't support cursor movement yet
};
let action = self
.configuration
.get_editor_action(input, self.mode, buffer_query);
if let Some(action) = action {
self.handle_action(action);
}
@@ -182,10 +192,10 @@ impl EditorCore {
Quit => {
self.should_quit = true;
}
MoveCursor(movement) => {
MoveCursor { x, y } => {
let buf = self.active_buffer_mut();
if let Buffer::Text(ref mut tb) = buf {
tb.move_cursor(movement);
tb.set_cursor(x, y);
}
}
PopupHelp(toggle) => {
+7 -13
View File
@@ -5,7 +5,11 @@ use std::path::PathBuf;
/// `EditorAction`s are defined here as well.
use crate::core::Mode;
/// An `EditorAction` represents every possible thing the text editor can do
/// An `EditorAction` represents every possible thing the text editor can do.
///
/// This enum is intentionally minimal. Complex operations like "move to next word" are computed
/// by the scripting/configuration layer, which queries buffer state and emits absolute positions.
/// See docs/architecture/minimal-action-design.md for details.
#[derive(Debug)]
//TODO EditorAction should have metadata about whether an action comes from a command, a script,
//user input, network, etc.
@@ -20,8 +24,8 @@ pub(crate) enum EditorAction {
/// Change the editor's mode
TransitionToMode(Mode),
/// Move the cursor around the active buffer
MoveCursor(CursorMovement),
/// Move the cursor to an absolute position. The scripting layer computes target coordinates.
MoveCursor { x: usize, y: usize },
/// Represents actions relevant to building up a command-line command
Command(CommandAction),
@@ -42,16 +46,6 @@ pub(crate) enum EditorAction {
Error(String),
}
#[derive(Debug)]
pub(crate) enum CursorMovement {
TextDirection,
OppositeTextDirection,
PrevLine,
NextLine,
#[allow(dead_code)]
Goto(usize, usize),
}
#[derive(Debug)]
pub(crate) enum CommandAction {
Execute,
+30 -3
View File
@@ -7,7 +7,7 @@ use tracing::info;
use self::text::TextLines;
use super::actions::CursorMovement;
use super::buffer_query::BufferQuery;
use super::{buffer_settings::BufferSettings, cursor::Cursor, error::BasicError};
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
@@ -215,7 +215,34 @@ impl TextBuffer {
}
}
pub(super) fn move_cursor(&mut self, movement: CursorMovement) {
self.cursor_pos.move_cursor(movement, &self.text.inner);
/// Set the cursor to an absolute position. The caller is responsible for bounds checking.
pub(super) fn set_cursor(&mut self, x: usize, y: usize) {
self.cursor_pos.set(x, y);
}
}
impl BufferQuery for TextBuffer {
fn cursor(&self) -> (usize, usize) {
(self.cursor_pos.x() as usize, self.cursor_pos.y() as usize)
}
fn line_count(&self) -> usize {
let len = self.text.inner.line_len();
// Ensure we always have at least 1 line for empty buffers
if len == 0 { 1 } else { len }
}
fn line_len(&self, y: usize) -> usize {
if y >= self.text.inner.line_len() {
return 0;
}
self.text.inner.line(y).chars().count()
}
fn char_at(&self, x: usize, y: usize) -> Option<char> {
if y >= self.text.inner.line_len() {
return None;
}
self.text.inner.line(y).chars().nth(x)
}
}
+20
View File
@@ -0,0 +1,20 @@
/// BufferQuery provides read-only access to buffer state for the scripting/configuration layer.
///
/// This trait enables the configuration layer to compute cursor movement targets by inspecting
/// buffer contents, without giving it write access to the buffer.
///
/// See docs/architecture/minimal-action-design.md for the full design rationale.
pub(crate) trait BufferQuery {
/// Returns the current cursor position as (x, y) where x is column, y is line (0-indexed)
fn cursor(&self) -> (usize, usize);
/// Returns the total number of lines in the buffer
fn line_count(&self) -> usize;
/// Returns the length of line `y` in characters (not bytes).
/// Returns 0 if y is out of bounds.
fn line_len(&self, y: usize) -> usize;
/// Returns the character at position (x, y), or None if out of bounds
fn char_at(&self, x: usize, y: usize) -> Option<char>;
}
+12 -42
View File
@@ -2,8 +2,11 @@ use std::fmt;
use crop::Rope;
use crate::core::actions::CursorMovement;
/// Cursor is a simple position holder. It stores (x, y) coordinates and provides methods
/// for updating position in response to text edits. All movement logic lives in the
/// scripting/configuration layer, not here.
///
/// See docs/architecture/minimal-action-design.md for design rationale.
#[derive(Debug, Copy, Clone)]
pub(crate) struct Cursor {
x: u16,
@@ -20,6 +23,7 @@ impl Cursor {
pub(super) fn new() -> Self {
Self { x: 0, y: 0 }
}
pub(crate) fn x(&self) -> u16 {
self.x
}
@@ -28,6 +32,12 @@ impl Cursor {
self.y
}
/// Set cursor to an absolute position
pub(super) fn set(&mut self, x: usize, y: usize) {
self.x = x as u16;
self.y = y as u16;
}
pub(super) fn respond_to_new_char(&mut self, ch: char) {
if ch == '\n' {
self.y += 1;
@@ -51,44 +61,4 @@ impl Cursor {
self.x -= 1;
}
}
//TODO handle undisplayed newline
//TODO handle rtl text
pub(super) fn move_cursor(&mut self, movement: CursorMovement, text: &Rope) {
use CursorMovement::*;
match movement {
TextDirection => {
let cur_line = text.line(self.y().into());
let len = cur_line.chars().count();
if (self.x as usize) < len {
self.x += 1;
}
}
OppositeTextDirection => {
if self.x != 0 {
self.x -= 1;
}
}
PrevLine => {
if self.y != 0 {
let prev_line = text.line((self.y() as usize) - 1);
let prev_len = prev_line.chars().count();
self.y -= 1;
if (self.x as usize) > prev_len {
self.x = prev_len as u16;
}
}
}
NextLine => {
let total_lines = text.line_len();
if total_lines == 0 {
return;
}
if (self.y as usize) < total_lines - 1 {
self.y += 1;
}
}
Goto(_x, _y) => todo!(),
}
}
}