paperos 0.2.0

A programmable editor built on the Runact actor runtime
Documentation
use crate::core::{BufferMessage, CommandHandler, EventBus, Extension};
use runact::{ActorId, Runtime};
use std::any::Any;
use std::sync::{Arc, Mutex, RwLock};

/// Command handler that maps editor commands to BufferMessage sends.
/// Every buffer operation (movement, insertion, deletion, undo/redo) is
/// registered as a command so users can invoke them via `:command`.
/// Implements Extension so it self-registers its commands.
#[allow(dead_code)]
#[derive(Clone)]
pub struct BufferCommands {
    buffer: Option<ActorId>,
    event_bus: Option<Arc<RwLock<EventBus>>>,
}

impl CommandHandler for BufferCommands {
    fn handle(
        &mut self,
        args: &[String],
        runtime: &Runtime,
        buffer: Option<ActorId>,
    ) -> Result<Option<String>, Box<dyn std::error::Error>> {
        let buffer_id = buffer.or(self.buffer).expect("no buffer set");

        let cmd = args.first().map(|s| s.as_str()).unwrap_or("");

        let msg = match cmd {
            "left" | "h" => Some(BufferMessage::MoveLeft),
            "right" | "l" => Some(BufferMessage::MoveRight),
            "up" | "k" => Some(BufferMessage::MoveUp),
            "down" | "j" => Some(BufferMessage::MoveDown),
            "home" | "^" | "0" => Some(BufferMessage::MoveToStart),
            "end" | "$" => Some(BufferMessage::MoveToEnd),
            "w" | "nextword" => Some(BufferMessage::MoveToNextWord),
            "b" | "prevword" => Some(BufferMessage::MoveToPrevWord),
            "e" | "endword" => Some(BufferMessage::MoveToEndOfWord),
            "go" | "line" => args
                .get(1)
                .and_then(|s| s.parse::<usize>().ok())
                .map(BufferMessage::MoveToLine),
            "lastline" | "G" => Some(BufferMessage::MoveToLastLine),
            "insert" | "i" => {
                if let Some(arg) = args.get(1) {
                    arg.chars().next().map(BufferMessage::InsertChar)
                } else {
                    None
                }
            }
            "insert-tab" => Some(BufferMessage::InsertChar('\t')),
            "delete" | "x" => Some(BufferMessage::DeleteChar),
            "deleteline" | "dd" => Some(BufferMessage::DeleteLine),
            "newline" | "enter" => Some(BufferMessage::InsertLine),
            "undo" | "u" => Some(BufferMessage::Undo),
            "redo" | "U" | "ctrl-r" => Some(BufferMessage::Redo),
            _ => None,
        };

        if let Some(message) = msg {
            let _ = runtime.send(buffer_id, message);
            // Notify subscribers (statusline refresh, Lua handlers, ...)
            if let Some(bus) = &self.event_bus {
                let _ = bus.read().unwrap().publish(
                    "buffer.changed",
                    &serde_json::json!({
                        "command": cmd,
                        "buffer": format!("{:?}", buffer_id),
                    }),
                );
            }
            Ok(None)
        } else {
            Err(format!("Unknown command: {}", cmd).into())
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

impl BufferCommands {
    pub fn new() -> Self {
        Self {
            buffer: None,
            event_bus: None,
        }
    }

    pub fn set_buffer(&mut self, buffer: ActorId) {
        self.buffer = Some(buffer);
    }

    /// Wire the shared event bus (main.rs) — enables buffer.changed events.
    pub fn set_event_bus(&mut self, bus: Arc<RwLock<EventBus>>) {
        self.event_bus = Some(bus);
    }
}

impl Default for BufferCommands {
    fn default() -> Self {
        Self::new()
    }
}

impl Extension for BufferCommands {
    fn name(&self) -> &str {
        "buffer-commands"
    }

    fn register_commands(
        &mut self,
        runtime: &mut crate::core::EditorRuntime,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let shared = SharedBufferCommands::new(self.clone());
        let commands: &[(&str, &str)] = &[
            ("h", "Move cursor left"),
            ("j", "Move cursor down"),
            ("k", "Move cursor up"),
            ("l", "Move cursor right"),
            ("w", "Move to next word"),
            ("b", "Move to previous word"),
            ("e", "Move to end of word"),
            ("G", "Go to last line"),
            ("u", "Undo"),
            ("U", "Redo"),
            ("0", "Go to start of line"),
            ("$", "Go to end of line"),
            ("left", "Move cursor left"),
            ("right", "Move cursor right"),
            ("up", "Move cursor up"),
            ("down", "Move cursor down"),
            ("home", "Go to start of line"),
            ("end", "Go to end of line"),
            ("nextword", "Move to next word"),
            ("prevword", "Move to previous word"),
            ("endword", "Move to end of word"),
            ("lastline", "Go to last line"),
            ("insert", "Insert character"),
            ("insert-tab", "Insert tab character"),
            ("delete", "Delete character"),
            ("deleteline", "Delete line"),
            ("newline", "Insert new line"),
            ("undo", "Undo"),
            ("redo", "Redo"),
            ("ctrl-r", "Redo"),
            ("go", "Go to line"),
            ("line", "Go to line"),
        ];
        for (name, desc) in commands {
            runtime.register_command(name.to_string(), Box::new(shared.clone_handler()), desc);
        }
        Ok(())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

/// Shared wrapper so multiple command names can dispatch to the same handler.
#[allow(dead_code)]
pub struct SharedBufferCommands {
    inner: Arc<Mutex<BufferCommands>>,
}

impl SharedBufferCommands {
    pub fn new(cmds: BufferCommands) -> Self {
        Self {
            inner: Arc::new(Mutex::new(cmds)),
        }
    }

    pub fn clone_handler(&self) -> SharedBufferCommands {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl CommandHandler for SharedBufferCommands {
    fn handle(
        &mut self,
        args: &[String],
        runtime: &Runtime,
        buffer: Option<ActorId>,
    ) -> Result<Option<String>, Box<dyn std::error::Error>> {
        let mut cmds = self.inner.lock().unwrap();
        cmds.handle(args, runtime, buffer)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}