mod core;
mod extensions;
use crate::core::{CommandHandler, EditorRuntime, Extension};
use crate::extensions::{
BufferCommands, BufferManager, EditorMode, FileExtension, HScrollCommand, InputExtension, Key,
KeymapRegistry, Layer, LuaExtension, MessageSink, PanelRegistry, RenderExtension,
ScrollCommand, SwitchBufferCommand, TermShared, TerminalActor, TerminalExtension,
TerminalSendCommand, Theme, ViInputExtension,
};
use std::sync::{Arc, RwLock};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().collect();
for arg in args.iter().skip(1) {
match arg.as_str() {
"--help" | "-h" => {
print_help();
return Ok(());
}
"--version" | "-V" => {
println!("paperos v{}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
_ => {}
}
}
let file_to_open: Option<String> = args.iter().skip(1).find(|a| !a.starts_with('-')).cloned();
let mut runtime = EditorRuntime::new()?;
let message_sink = MessageSink::new(100);
let mut buf_mgr = BufferManager::new();
let file_content = file_to_open
.as_ref()
.and_then(|f| std::fs::read_to_string(f).ok());
let buffer = buf_mgr.add_buffer(runtime.runtime_mut(), file_content, file_to_open.clone());
let active_buf_handle = buf_mgr.active_buf_handle();
let buf_mgr = Arc::new(RwLock::new(buf_mgr));
runtime.register_command(
"next-buffer".to_string(),
Box::new(SwitchBufferCommand::next(buf_mgr.clone())),
"Switch to the next buffer",
);
runtime.register_command(
"prev-buffer".to_string(),
Box::new(SwitchBufferCommand::prev(buf_mgr.clone())),
"Switch to the previous buffer",
);
runtime.register_command(
"switch-buffer".to_string(),
Box::new(SwitchBufferCommand::by_index(buf_mgr.clone())),
"Switch to buffer <n> (1-based)",
);
runtime.register_command(
"buffers".to_string(),
Box::new(BuffersCommand {
mgr: buf_mgr.clone(),
}),
"List all open buffers",
);
let mut buffer_cmds = BufferCommands::new();
buffer_cmds.set_buffer(buffer);
buffer_cmds.set_event_bus(runtime.event_bus());
runtime.add_extension(Box::new(buffer_cmds))?;
let mut file_ext = FileExtension::new();
file_ext.set_buffer(buffer);
file_ext.set_event_bus(runtime.event_bus());
runtime.add_extension(Box::new(file_ext))?;
let mut render = RenderExtension::new();
let quit_flag = render.quit_flag();
runtime.register_command(
"q".to_string(),
Box::new(QuitCommand::new(message_sink.clone(), quit_flag.clone())),
"Quit",
);
runtime.register_command(
"quit".to_string(),
Box::new(QuitCommand::new(message_sink.clone(), quit_flag)),
"Quit",
);
let vi_input = Arc::new(RwLock::new(ViInputExtension::new()));
runtime.register_command(
"vi-mode".to_string(),
Box::new(ViModeCommand::new(vi_input.clone())),
"Enable vi mode",
);
runtime.register_command(
"insert-mode".to_string(),
Box::new(ViModeCommand::new_with_mode(
vi_input.clone(),
EditorMode::Insert,
)),
"Enter insert mode",
);
runtime.register_command(
"normal-mode".to_string(),
Box::new(ViModeCommand::new_with_mode(
vi_input.clone(),
EditorMode::Normal,
)),
"Enter normal mode",
);
let mut lua_ext = LuaExtension::new();
lua_ext.set_event_bus(runtime.event_bus());
lua_ext.set_buffer(buffer);
lua_ext.set_sender(runtime.runtime_mut().sender());
runtime.add_extension(Box::new(lua_ext))?;
{
let names: Vec<String> = runtime
.extensions_iter()
.map(|e| e.name().to_string())
.collect();
if let Some(ext) = runtime.extension::<LuaExtension>() {
ext.set_extension_names(names);
}
}
if let Some(ext) = runtime.extension::<LuaExtension>() {
if ext.is_quit_requested() {
runtime.shutdown()?;
return Ok(());
}
}
let input = Arc::new(RwLock::new(InputExtension::new()));
let scroll_state = render.scroll_state();
for (cmd, dir, full) in &[
("scroll-up", -1i64, false),
("scroll-down", 1i64, false),
("page-up", -1i64, true),
("page-down", 1i64, true),
] {
let desc = match (*cmd, *full) {
("scroll-up", false) => "Scroll up half page",
("scroll-down", false) => "Scroll down half page",
("page-up", true) => "Scroll up full page",
("page-down", true) => "Scroll down full page",
_ => "",
};
runtime.register_command(
cmd.to_string(),
Box::new(ScrollCommand::new(scroll_state.clone(), *dir, *full)),
desc,
);
}
runtime.register_command(
"scroll-left".to_string(),
Box::new(HScrollCommand::new(scroll_state.clone(), -1)),
"Scroll left",
);
runtime.register_command(
"scroll-right".to_string(),
Box::new(HScrollCommand::new(scroll_state.clone(), 1)),
"Scroll right",
);
render.set_buffer(buffer);
render.set_active_buffer_handle(active_buf_handle);
if let Some(ext) = runtime.extension::<LuaExtension>() {
if let Some(v) = ext.config_value("ui.line_numbers") {
render.set_show_line_numbers(v != "false");
}
render.set_theme(Theme::from_config(&ext.config_map()));
}
let input_clone = input.clone();
let vi_input_clone = vi_input.clone();
render.set_input(input_clone);
render.set_vi_input(vi_input_clone);
render.set_message_sink(message_sink.clone());
let cmd_list = runtime
.list_commands()
.iter()
.map(|(name, desc)| {
if desc.is_empty() {
format!(" {}", name)
} else {
format!(" {:<18} {}", name, desc)
}
})
.collect::<Vec<_>>()
.join("\n");
runtime.register_command(
"commands".to_string(),
Box::new(ListCommand::new(cmd_list)),
"List all commands",
);
let cmd_descriptions = runtime
.list_commands()
.iter()
.map(|(name, desc)| (name.to_string(), desc.to_string()))
.collect::<Vec<_>>();
runtime.register_command(
"help".to_string(),
Box::new(HelpCommand::new(cmd_descriptions, message_sink.clone())),
"Show help for a command",
);
let panels = Arc::new(RwLock::new(PanelRegistry::new()));
{
let mut p = panels.write().unwrap();
let _ = p.create_panel(runtime.runtime_mut(), "echo");
let _ = p.create_panel(runtime.runtime_mut(), "statusbar");
if let Some(ext) = runtime.extension::<LuaExtension>() {
if let Some(fmt) = ext.config_value("statusline.format") {
p.set_statusline_format(fmt);
}
}
}
let requested = runtime
.extension::<LuaExtension>()
.map(|e| e.requested_panels())
.unwrap_or_default();
for name in &requested {
let mut p = panels.write().unwrap();
if p.get(name).is_none() {
let _ = p.create_panel(runtime.runtime_mut(), name);
}
}
if let Some(ext) = runtime.extension::<LuaExtension>() {
ext.flush_panel_writes(runtime.runtime(), &panels);
}
render.set_panels(panels.clone());
let term_shared = Arc::new(TermShared::new(80, 24));
let shell = std::env::var("SHELL").unwrap_or_else(|_| "sh".to_string());
let term_actor = TerminalActor::with_shared_shell(&shell, term_shared.clone())
.map_err(|e| format!("terminal spawn: {e}"))?;
let term_actor_id = runtime
.runtime_mut()
.spawn(term_actor)
.map_err(|e| format!("terminal actor: {e}"))?;
{
let mut p = panels.write().unwrap();
if p.get("terminal").is_none() {
let _ = p.create_panel(runtime.runtime_mut(), "terminal");
}
p.claim_render("terminal", "terminal")
.map_err(|e| format!("terminal claim: {e}"))?;
}
let mut term_ext = TerminalExtension::new(term_actor_id, term_shared);
term_ext.set_panels(panels.clone());
term_ext.set_vi_input(vi_input.clone());
let term_ext = Arc::new(RwLock::new(term_ext));
runtime.register_command(
"terminal".to_string(),
Box::new(ViModeCommand::new_with_mode(
vi_input.clone(),
EditorMode::Terminal,
)),
"Open the terminal panel",
);
runtime.register_command(
"terminal-send".to_string(),
Box::new(TerminalSendCommand::new(term_ext.clone())),
"Send text to the terminal",
);
render.set_terminal(term_ext.clone());
let mut keymap_registry = KeymapRegistry::new();
let mut global = Layer::new(
"global-defaults",
15,
Some(crate::extensions::keymap_registry::Context::new("*")),
);
global.bind(Key::parse("M-x").unwrap(), "command-mode");
global.bind(Key::parse("M-n").unwrap(), "next-buffer");
global.bind(Key::parse("M-p").unwrap(), "prev-buffer");
for ext in runtime.extensions_iter() {
for (key_spec, cmd) in ext.global_bindings() {
if let Some(k) = Key::parse(key_spec) {
global.bind(k, cmd);
}
}
}
{
let input_guard = input.read().unwrap();
for (key_spec, cmd) in input_guard.global_bindings() {
if let Some(k) = Key::parse(key_spec) {
global.bind(k, cmd);
}
}
}
{
let vi_guard = vi_input.read().unwrap();
for (key_spec, cmd) in vi_guard.global_bindings() {
if let Some(k) = Key::parse(key_spec) {
global.bind(k, cmd);
}
}
}
keymap_registry.register(global);
{
let input_arc = input.clone();
let input_guard = input_arc.read().unwrap();
input_guard.register_layers(&mut keymap_registry);
}
{
let vi_arc = vi_input.clone();
let vi_guard = vi_arc.read().unwrap();
vi_guard.register_layers(&mut keymap_registry);
}
if let Some(ext) = runtime.extension::<LuaExtension>() {
let remaps = ext.keybindings();
for (mode, key_spec, cmd) in remaps {
let ctx = crate::extensions::keymap_registry::Context::new(&mode);
let mut layer = Layer::new("lua-runtime", 100, Some(ctx));
if let Some(k) = crate::extensions::keymap_registry::Key::parse(&key_spec) {
layer.bind(k, &cmd);
keymap_registry.register(layer);
}
}
}
render.set_keymap_registry(keymap_registry);
render.run_event_loop(&mut runtime, Some(buffer))?;
runtime.shutdown()?;
Ok(())
}
struct QuitCommand {
sink: MessageSink,
quit_flag: Arc<std::sync::atomic::AtomicBool>,
}
impl QuitCommand {
fn new(sink: MessageSink, quit_flag: Arc<std::sync::atomic::AtomicBool>) -> Self {
Self { sink, quit_flag }
}
}
struct ListCommand {
commands: String,
}
impl ListCommand {
fn new(commands: String) -> Self {
Self { commands }
}
}
impl CommandHandler for ListCommand {
fn handle(
&mut self,
_args: &[String],
_runtime: &runact::Runtime,
_buffer: Option<runact::ActorId>,
) -> Result<Option<String>, Box<dyn std::error::Error>> {
let output = format!("Available commands:\n{}", self.commands);
Ok(Some(output))
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
struct HelpCommand {
descriptions: Vec<(String, String)>,
sink: MessageSink,
}
impl HelpCommand {
fn new(descriptions: Vec<(String, String)>, sink: MessageSink) -> Self {
Self { descriptions, sink }
}
}
impl CommandHandler for HelpCommand {
fn handle(
&mut self,
args: &[String],
_runtime: &runact::Runtime,
_buffer: Option<runact::ActorId>,
) -> Result<Option<String>, Box<dyn std::error::Error>> {
if args.is_empty() {
let msg = "Usage: help <command>\nExample: help open".to_string();
self.sink.push(msg.clone());
return Ok(Some(msg));
}
let cmd_name = args[0].trim_start_matches(':');
match self.descriptions.iter().find(|(name, _)| name == cmd_name) {
Some((name, desc)) => {
let msg = if desc.is_empty() {
format!("{} — no help available", name)
} else {
format!("{} — {}", name, desc)
};
self.sink.push(msg.clone());
Ok(Some(msg))
}
None => {
let msg = format!("Unknown command: {}", cmd_name);
self.sink.push(msg.clone());
Ok(Some(msg))
}
}
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
struct ViModeCommand {
vi_input: Arc<RwLock<ViInputExtension>>,
target_mode: EditorMode,
}
impl ViModeCommand {
fn new(vi_input: Arc<RwLock<ViInputExtension>>) -> Self {
Self {
vi_input,
target_mode: EditorMode::Normal,
}
}
fn new_with_mode(vi_input: Arc<RwLock<ViInputExtension>>, mode: EditorMode) -> Self {
Self {
vi_input,
target_mode: mode,
}
}
}
impl CommandHandler for ViModeCommand {
fn handle(
&mut self,
_args: &[String],
_runtime: &runact::Runtime,
_buffer: Option<runact::ActorId>,
) -> Result<Option<String>, Box<dyn std::error::Error>> {
if let Ok(mut vi) = self.vi_input.write() {
vi.set_mode(self.target_mode);
}
Ok(None)
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
fn print_help() {
println!(
"paperOS v{} — a programmable editor built on the Runact actor runtime",
env!("CARGO_PKG_VERSION")
);
println!();
println!("USAGE:");
println!(" paperos [OPTIONS] [FILE]");
println!();
println!("OPTIONS:");
println!(" -h, --help Show this help message");
println!(" -V, --version Print version and exit");
println!();
println!("ARGS:");
println!(" <FILE> File to open");
println!();
println!("CONFIG:");
println!(" Configuration is loaded from ~/.config/paperos/init.lua");
println!(" Extensions are loaded from ~/.config/paperos/extensions/");
}
impl CommandHandler for QuitCommand {
fn handle(
&mut self,
_args: &[String],
_runtime: &runact::Runtime,
_buffer: Option<runact::ActorId>,
) -> Result<Option<String>, Box<dyn std::error::Error>> {
self.sink.push("Quitting...");
self.quit_flag
.store(true, std::sync::atomic::Ordering::Relaxed);
Ok(None)
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
struct BuffersCommand {
mgr: Arc<RwLock<BufferManager>>,
}
impl CommandHandler for BuffersCommand {
fn handle(
&mut self,
_args: &[String],
_runtime: &runact::Runtime,
_buffer: Option<runact::ActorId>,
) -> Result<Option<String>, Box<dyn std::error::Error>> {
let mgr = self.mgr.read().map_err(|e| e.to_string())?;
let lines: Vec<String> = mgr
.list()
.iter()
.map(|(i, name, modified)| {
let marker = if *modified { " [+]" } else { "" };
format!(" {}. {}{}", i + 1, name, marker)
})
.collect();
if lines.is_empty() {
Ok(Some("No buffers".to_string()))
} else {
Ok(Some(lines.join("\n")))
}
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}