paperos 0.2.0

A programmable editor built on the Runact actor runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
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();

    // Handle CLI flags
    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(());
            }
            _ => {}
        }
    }

    // Find the first file argument (not a flag)
    let file_to_open: Option<String> = args.iter().skip(1).find(|a| !a.starts_with('-')).cloned();

    let mut runtime = EditorRuntime::new()?;

    // Shared echo/minibuffer message queue — command errors and status
    // messages land here instead of stdout (stdout corrupts the TUI).
    let message_sink = MessageSink::new(100);

    // BufferManager: spawns BufferActor instances and tracks the active one.
    // Keeps core minimal — buffer lifecycle is an extension concern.
    // Wrapped in Arc<Mutex> so command handlers can switch buffers.
    let mut buf_mgr = BufferManager::new();

    // Load file content if provided
    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());
    // Buffer switching: next/prev/switch-buffer commands + M-n/M-p keys.
    // The render extension follows the shared active buffer each frame.
    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)",
    );
    // `buffers` — list all open buffers as minibuffer candidates.
    runtime.register_command(
        "buffers".to_string(),
        Box::new(BuffersCommand {
            mgr: buf_mgr.clone(),
        }),
        "List all open buffers",
    );

    // Register buffer operation commands via Extension self-registration.
    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))?;

    // File I/O commands self-register via Extension.
    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))?;

    // Set up the render extension (terminal UI + event loop)
    let mut render = RenderExtension::new();

    // Register quit command — shares the render event loop's quit flag.
    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",
    );

    // Register vi-mode command (switches from Basic to Normal vi mode)
    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",
    );

    // Mode-switch commands that the keymap registry resolves to.
    // 'i' in Normal mode → insert-mode command, etc.
    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",
    );

    // Add the LuaExtension — provides config loading + paper.* API
    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))?;

    // Feed the real extension names to paper.extensions.list()
    {
        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);
        }
    }

    // Check if user requested quit after config load
    if let Some(ext) = runtime.extension::<LuaExtension>() {
        if ext.is_quit_requested() {
            runtime.shutdown()?;
            return Ok(());
        }
    }

    // Create the InputExtension (basic/text-editor keybindings: arrows, direct typing)
    let input = Arc::new(RwLock::new(InputExtension::new()));

    // Register scroll commands (owned by render, routed through command system)
    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);
    // Apply ui.line_numbers config option (default: on).
    if let Some(ext) = runtime.extension::<LuaExtension>() {
        if let Some(v) = ext.config_value("ui.line_numbers") {
            render.set_show_line_numbers(v != "false");
        }
        // Apply theme.* config entries (paper.theme.set).
        render.set_theme(Theme::from_config(&ext.config_map()));
    }
    // Clone Arcs before moving into render (needed for layer registration)
    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());

    // Register `commands` command to show all registered commands
    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",
    );

    // Register `help` command to show details for a specific command
    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",
    );

    // Wire the PanelRegistry: spawns the echo + statusbar panel buffers and
    // hands them to the RenderExtension so M-x / echo line actually work.
    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");
        // Apply statusline.format config option (default: classic format).
        if let Some(ext) = runtime.extension::<LuaExtension>() {
            if let Some(fmt) = ext.config_value("statusline.format") {
                p.set_statusline_format(fmt);
            }
        }
    }
    // Spawn Lua-requested custom panels (paper.panels.create), then flush
    // any paper.panel.write calls queued during config load.
    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());

    // Terminal extension: spawn the shell in a PTY, create the "terminal"
    // panel buffer, claim its rendering. Everything is a buffer — the
    // terminal panel is a read-only BufferActor holding the grid's text
    // projection; the styled grid itself lives in the extension.
    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));

    // `terminal` — enter Terminal mode (the panel + actor are alive from
    // startup; the command just focuses them).
    runtime.register_command(
        "terminal".to_string(),
        Box::new(ViModeCommand::new_with_mode(
            vi_input.clone(),
            EditorMode::Terminal,
        )),
        "Open the terminal panel",
    );
    // `terminal-send <text>` — write text to the PTY (Lua: paper.cmd sugar).
    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());

    // Build the central keymap registry by having each input extension
    // register its own default layers. No input-method knowledge in main.rs
    // — extensions own their mode names.
    let mut keymap_registry = KeymapRegistry::new();

    // Global layer: M-x enters command/minibuffer mode (always active,
    // this is a core editor function). All other global bindings come from
    // extensions via the Extension::global_bindings() trait hook.
    let mut global = Layer::new(
        "global-defaults",
        15,
        Some(crate::extensions::keymap_registry::Context::new("*")),
    );
    global.bind(Key::parse("M-x").unwrap(), "command-mode");
    // Buffer switching is global — works in every mode, terminal included
    // (the terminal extension never consumes Alt+<key>).
    global.bind(Key::parse("M-n").unwrap(), "next-buffer");
    global.bind(Key::parse("M-p").unwrap(), "prev-buffer");
    // Merge global bindings from all registered extensions:
    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);
            }
        }
    }
    // Also collect from the Arc-shared input extensions (not in runtime):
    {
        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);

    // Extension defaults (each knows its own modes)
    {
        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);
    }

    // Apply Lua-config key remaps to the runtime user layer.
    // `paper.keys.map(mode, key, cmd)` collected these during config load.
    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(())
}

/// Quit command handler — sets the quit flag on the RenderExtension so the
/// event loop exits cleanly.
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 }
    }
}

/// List command handler — shows all registered commands.
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
    }
}

/// Help command handler — shows details for a specific command.
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
    }
}

/// vi-mode command handler — switches ViInputExtension into a specified mode.
/// Used by the keymap registry to resolve mode-switch bindings like 'i',
/// Esc, etc.
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...");
        // Set quit flag so the event loop exits
        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
    }
}

/// `buffers` command — lists all open buffers (1-based index, path or
/// name, modified marker). Output is multi-line so the minibuffer
/// renders it as a scrollable candidate list.
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
    }
}