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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
use crate::core::{BufferMessage, CommandHandler, EditorRuntime, EventBus, Extension};
use crate::extensions::extension_manager::ExtensionManager;
use crate::extensions::panel_registry::PanelRegistry;
use mlua::{Lua, RegistryKey, Result as LuaResult};
use runact::{ActorId, Runtime};
use std::any::Any;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, RwLock};
/// Convert a serde_json Value into the matching Lua value.
fn json_to_lua(lua: &Lua, value: &serde_json::Value) -> LuaResult<mlua::Value> {
Ok(match value {
serde_json::Value::Null => mlua::Value::Nil,
serde_json::Value::Bool(b) => mlua::Value::Boolean(*b),
serde_json::Value::Number(n) => {
if let Some(i) = n.as_i64() {
mlua::Value::Integer(i)
} else {
mlua::Value::Number(n.as_f64().unwrap_or_default())
}
}
serde_json::Value::String(s) => mlua::Value::String(lua.create_string(s)?),
serde_json::Value::Array(items) => {
let t = lua.create_table()?;
for (i, item) in items.iter().enumerate() {
t.set(i + 1, json_to_lua(lua, item)?)?;
}
mlua::Value::Table(t)
}
serde_json::Value::Object(map) => {
let t = lua.create_table()?;
for (k, v) in map {
t.set(k.as_str(), json_to_lua(lua, v)?)?;
}
mlua::Value::Table(t)
}
})
}
/// Error for unwired buffer/sender access from Lua.
fn borrow_err() -> mlua::Error {
mlua::Error::RuntimeError("buffer not wired".to_string())
}
/// Convert a Display error into an mlua runtime error.
fn mlua_err(e: impl std::fmt::Display) -> mlua::Error {
mlua::Error::RuntimeError(e.to_string())
}
/// Downcast a request reply to a concrete type, mapping failure to mlua.
fn downcast_reply<T: Send + 'static>(reply: Box<dyn Any + Send>) -> LuaResult<T> {
match reply.downcast::<T>() {
Ok(v) => Ok(*v),
Err(_) => Err(mlua::Error::RuntimeError(
"unexpected reply type from buffer".to_string(),
)),
}
}
/// A Lua callback registered as an editor command.
#[allow(dead_code)]
pub struct LuaCommand {
pub name: String,
pub key: RegistryKey,
pub description: String,
}
/// CommandHandler that invokes a stored Lua function.
///
/// The Lua function receives the args vector as a 1-indexed Lua table and
/// may return a string ( surfaced as the command's output) or nil.
#[allow(dead_code)]
pub struct LuaCommandHandler {
lua: Arc<Mutex<Lua>>,
key: RegistryKey,
name: String,
}
impl CommandHandler for LuaCommandHandler {
fn handle(
&mut self,
args: &[String],
_runtime: &Runtime,
_buffer: Option<ActorId>,
) -> Result<Option<String>, Box<dyn std::error::Error>> {
let lua = self
.lua
.lock()
.map_err(|_| format!("Lua state poisoned (command '{}')", self.name))?;
let func: mlua::Function = lua
.registry_value(&self.key)
.map_err(|e| format!("command '{}': lost its Lua function: {}", self.name, e))?;
let arg_table = lua.create_table()?;
for (i, a) in args.iter().enumerate() {
arg_table.set(i + 1, a.as_str())?;
}
let result: mlua::Value = func
.call(arg_table)
.map_err(|e| format!("command '{}' failed: {}", self.name, e))?;
match result {
mlua::Value::Nil => Ok(None),
mlua::Value::String(s) => Ok(Some(s.to_str()?.to_string())),
other => Ok(Some(format!("{:?}", other))),
}
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
/// LuaExtension: embeds a Lua runtime and exposes the `paper` global API.
/// Users write config/extensions in Lua at ~/.config/paperos/init.lua.
///
/// The Lua state is shared via `Arc<Mutex<Lua>>` so command handlers and
/// event-subscription closures (which outlive this struct's borrows) can
/// execute Lua callbacks through [`LuaExtension::lua_handle`].
#[allow(dead_code)]
pub struct LuaExtension {
lua: Arc<Mutex<Lua>>,
config: Arc<Mutex<HashMap<String, String>>>,
keybindings: Arc<Mutex<Vec<(String, String, String)>>>,
quit_requested: Arc<Mutex<bool>>,
/// Names of registered extensions, set by main.rs after add_extension.
extension_names: Arc<Mutex<Vec<String>>>,
/// Lua commands collected during config load, registered into the
/// command registry by `register_commands`.
collected_commands: Arc<Mutex<Vec<LuaCommand>>>,
/// Lua event handlers collected during config load, subscribed to the
/// event bus by `subscribe_events`.
collected_events: Arc<Mutex<Vec<LuaEventHandler>>>,
/// Shared event bus, wired in by main.rs before add_extension.
event_bus: Option<Arc<RwLock<EventBus>>>,
/// The document buffer actor, wired in by main.rs.
buffer: Option<ActorId>,
/// Runtime sender for buffer requests, wired in by main.rs.
sender: Option<runact::RuntimeSender>,
/// Commands queued by `paper.cmd`, drained and run by the render event
/// loop. Mailbox-style: Lua never needs `&mut EditorRuntime`.
cmd_queue: Arc<Mutex<Vec<String>>>,
/// Panel names requested via `paper.panels.create` — main.rs spawns
/// each as a named buffer in the PanelRegistry after config load.
requested_panels: Arc<Mutex<Vec<String>>>,
/// Panel writes queued by `paper.panel.write` — flushed by main.rs at
/// startup and by the render event loop thereafter (mailbox-style,
/// same as paper.cmd). (name, text) pairs.
pending_panel_writes: Arc<Mutex<Vec<(String, String)>>>,
/// Timers recorded by `paper.after(ms, fn)` — (deadline, callback)
/// pairs. The render event loop drains due ones and invokes the
/// callbacks in the shared Lua state.
timers: Arc<Mutex<Vec<(std::time::Instant, RegistryKey)>>>,
}
/// A Lua event handler collected during config load.
#[allow(dead_code)]
pub struct LuaEventHandler {
pub event: String,
pub key: RegistryKey,
}
impl Extension for LuaExtension {
fn name(&self) -> &str {
"lua"
}
fn init(&mut self, _runtime: &mut Runtime) -> Result<(), Box<dyn std::error::Error>> {
self.setup_paper_api()?;
self.load_config()?;
self.subscribe_events()?;
Ok(())
}
fn shutdown(&mut self, _runtime: &mut Runtime) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn on_key(&mut self, _ch: char) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn on_render(&mut self, _runtime: &Runtime) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn register_commands(
&mut self,
runtime: &mut EditorRuntime,
) -> Result<(), Box<dyn std::error::Error>> {
let commands = std::mem::take(&mut *self.collected_commands.lock().unwrap());
for cmd in commands {
// Descriptions must be 'static — leak the (small) config-time
// strings; they live for the process lifetime anyway.
let desc: &'static str = if cmd.description.is_empty() {
""
} else {
Box::leak(cmd.description.into_boxed_str())
};
runtime.register_command(
cmd.name.clone(),
Box::new(LuaCommandHandler {
lua: self.lua.clone(),
key: cmd.key,
name: cmd.name,
}),
desc,
);
}
Ok(())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
impl LuaExtension {
pub fn new() -> Self {
Self {
lua: Arc::new(Mutex::new(Lua::new())),
config: Arc::new(Mutex::new(HashMap::new())),
keybindings: Arc::new(Mutex::new(Vec::new())),
quit_requested: Arc::new(Mutex::new(false)),
extension_names: Arc::new(Mutex::new(Vec::new())),
collected_commands: Arc::new(Mutex::new(Vec::new())),
collected_events: Arc::new(Mutex::new(Vec::new())),
event_bus: None,
buffer: None,
sender: None,
cmd_queue: Arc::new(Mutex::new(Vec::new())),
requested_panels: Arc::new(Mutex::new(Vec::new())),
pending_panel_writes: Arc::new(Mutex::new(Vec::new())),
timers: Arc::new(Mutex::new(Vec::new())),
}
}
/// Panel names requested via `paper.panels.create` (main.rs drains
/// these after config load and spawns the buffers).
pub fn requested_panels(&self) -> Vec<String> {
self.requested_panels.lock().unwrap().clone()
}
/// Handle to the pending `paper.panel.write` queue — the render event
/// loop drains it each iteration (after the startup flush).
pub fn pending_panel_writes(&self) -> Arc<Mutex<Vec<(String, String)>>> {
self.pending_panel_writes.clone()
}
/// Take and deliver all queued `paper.panel.write` calls. Called by
/// main.rs after the requested panels have been spawned.
pub fn flush_panel_writes(&self, runtime: &Runtime, panels: &Arc<RwLock<PanelRegistry>>) {
let writes = std::mem::take(&mut *self.pending_panel_writes.lock().unwrap());
if writes.is_empty() {
return;
}
if let Ok(reg) = panels.read() {
for (name, text) in writes {
if let Err(e) = reg.send(runtime, &name, BufferMessage::Echo(text)) {
eprintln!("panel.write({name}): {e}");
}
}
}
}
/// Handle to the `paper.cmd` queue (shared with the render event loop).
pub fn cmd_queue(&self) -> Arc<Mutex<Vec<String>>> {
self.cmd_queue.clone()
}
/// Fire all `paper.after` timers whose deadline has passed. Returns
/// the number of callbacks invoked. Callbacks run in the shared Lua
/// state; their side effects (paper.cmd etc.) land in the usual
/// queues for the event loop to drain.
pub fn due_timers(&self, now: std::time::Instant) -> usize {
let due: Vec<RegistryKey> = {
let mut timers = self.timers.lock().unwrap();
let (due, pending): (Vec<_>, Vec<_>) =
timers.drain(..).partition(|(deadline, _)| *deadline <= now);
*timers = pending;
due.into_iter().map(|(_, key)| key).collect()
};
if due.is_empty() {
return 0;
}
let lua = self.lua.lock().unwrap();
let mut fired = 0;
for key in due {
match lua.registry_value::<mlua::Function>(&key) {
Ok(f) => {
if let Err(e) = f.call::<()>(()) {
eprintln!("timer callback error: {e}");
} else {
fired += 1;
}
}
Err(e) => eprintln!("timer callback lookup error: {e}"),
}
}
fired
}
/// Wire the document buffer actor (main.rs, before add_extension).
pub fn set_buffer(&mut self, buffer: ActorId) {
self.buffer = Some(buffer);
}
/// Wire the runtime sender for buffer requests (main.rs).
pub fn set_sender(&mut self, sender: runact::RuntimeSender) {
self.sender = Some(sender);
}
/// Wire the shared event bus (main.rs, before add_extension).
pub fn set_event_bus(&mut self, bus: Arc<RwLock<EventBus>>) {
self.event_bus = Some(bus);
}
/// Subscribe collected Lua event handlers to the bus.
///
/// Called from `init()` (after config load) and safe to call again —
/// takes the collected handlers, leaving the vec empty.
///
/// Lock discipline: the closure locks ONLY the Lua mutex. EventBus
/// handlers run under `publish(&self)` — a handler must never call
/// back into the bus write path (re-entrant publish) or it deadlocks.
fn subscribe_events(&mut self) -> Result<(), Box<dyn std::error::Error>> {
let Some(bus) = self.event_bus.clone() else {
return Ok(());
};
let handlers = std::mem::take(&mut *self.collected_events.lock().unwrap());
let lua = self.lua.clone();
let mut bus_guard = bus.write().unwrap();
for h in handlers {
let lua = lua.clone();
bus_guard.subscribe(
&h.event,
move |payload: &serde_json::Value| -> Result<(), Box<dyn std::error::Error>> {
let lua = lua
.lock()
.map_err(|_| "Lua state poisoned (event handler)")?;
let func: mlua::Function = lua
.registry_value(&h.key)
.map_err(|e| format!("event handler lost: {e}"))?;
let value = json_to_lua(&lua, payload)?;
func.call::<()>(value)
.map_err(|e| format!("event handler failed: {e}"))?;
Ok(())
},
);
}
Ok(())
}
/// Set the list of registered extension names (called by main.rs / the
/// test harness after all extensions are added). `paper.extensions.list`
/// reports these.
pub fn set_extension_names(&self, names: Vec<String>) {
*self.extension_names.lock().unwrap() = names;
}
/// Shared handle to the Lua state. Clones are cheap; lock to use.
/// With mlua's `send` feature `Lua` is `Send` but not `Sync` — the
/// `Arc<Mutex<Lua>>` wrapper is the correct sharing shape.
#[allow(dead_code)]
pub fn lua_handle(&self) -> Arc<Mutex<Lua>> {
self.lua.clone()
}
pub fn is_quit_requested(&self) -> bool {
*self.quit_requested.lock().unwrap()
}
#[allow(dead_code)]
pub fn keybindings(&self) -> Vec<(String, String, String)> {
self.keybindings.lock().unwrap().clone()
}
#[allow(dead_code)]
pub fn config_value(&self, key: &str) -> Option<String> {
self.config.lock().unwrap().get(key).cloned()
}
/// Full config map (all paper.config.set / paper.theme.set entries).
#[allow(dead_code)]
pub fn config_map(&self) -> HashMap<String, String> {
self.config.lock().unwrap().clone()
}
/// Load config outside the `init()` lifecycle (test harness / embedding).
/// Mirrors `init()`: API setup first, then config execution.
#[allow(dead_code)]
pub fn load_config_for_test(&self) -> Result<(), Box<dyn std::error::Error>> {
self.setup_paper_api_public()?;
self.load_config()
}
/// Expose the `paper.*` API on the shared Lua state (idempotent).
#[allow(dead_code)]
pub fn setup_paper_api_public(&self) -> Result<(), Box<dyn std::error::Error>> {
// setup_paper_api takes &mut self only for historical reasons; the
// implementation works on the shared Arc state and is idempotent.
// Reuse it via a temporary exclusive borrow of the same data.
self.setup_paper_api()
}
fn setup_paper_api(&self) -> Result<(), Box<dyn std::error::Error>> {
let lua = self.lua.lock().unwrap();
let globals = lua.globals();
let paper = lua.create_table()?;
// paper.config — set/get typed settings
let cfg = self.config.clone();
let config_table = lua.create_table()?;
{
let cfg_ref = cfg.clone();
config_table.set(
"set",
lua.create_function(move |_, (key, value): (String, mlua::Value)| {
let mut map = cfg_ref.lock().unwrap();
let s = match value {
mlua::Value::String(s) => s.to_str()?.to_string(),
mlua::Value::Integer(n) => n.to_string(),
mlua::Value::Number(n) => n.to_string(),
mlua::Value::Boolean(b) => b.to_string(),
mlua::Value::Nil => "nil".to_string(),
_ => {
return Err(mlua::Error::FromLuaConversionError {
from: "value",
to: "string".to_string(),
message: Some("unsupported value type".to_string()),
})
}
};
map.insert(key, s);
Ok(())
})?,
)?;
}
{
let cfg_ref = cfg.clone();
config_table.set(
"get",
lua.create_function(move |_, key: String| -> LuaResult<String> {
let map = cfg_ref.lock().unwrap();
Ok(map.get(&key).cloned().unwrap_or_default())
})?,
)?;
}
paper.set("config", config_table)?;
// paper.theme — theme colors, stored as theme.<name> config keys
// (consumed by Theme::from_config in main.rs).
let theme_cfg = self.config.clone();
let theme_table = lua.create_table()?;
theme_table.set(
"set",
lua.create_function(move |_, (name, color): (String, String)| {
let mut map = theme_cfg.lock().unwrap();
map.insert(format!("theme.{name}"), color);
Ok(())
})?,
)?;
paper.set("theme", theme_table)?;
// paper.commands — register named commands backed by Lua functions.
// Collected during config load; `register_commands` (called by
// add_extension after init) wires them into the command registry.
let collected = self.collected_commands.clone();
let cmds = lua.create_table()?;
cmds.set(
"register",
lua.create_function(
move |lua, (name, func, desc): (String, mlua::Function, Option<String>)| {
let key = lua.create_registry_value(func)?;
collected.lock().unwrap().push(LuaCommand {
name,
key,
description: desc.unwrap_or_default(),
});
Ok(())
},
)?,
)?;
paper.set("commands", cmds)?;
// paper.keys — key remapping
let keys = self.keybindings.clone();
let keys_table = lua.create_table()?;
keys_table.set(
"map",
lua.create_function(move |_, (mode, key, cmd): (String, String, String)| {
let mut kb = keys.lock().unwrap();
kb.push((mode, key, cmd));
Ok(())
})?,
)?;
paper.set("keys", keys_table)?;
// paper.extensions — query available extensions (real names, set
// via set_extension_names after all extensions are registered)
let ext_names = self.extension_names.clone();
let ext_table = lua.create_table()?;
ext_table.set(
"list",
lua.create_function(move |lua, ()| {
let names = ext_names.lock().unwrap();
let t = lua.create_table()?;
for (i, e) in names.iter().enumerate() {
t.set(i + 1, e.as_str())?;
}
Ok(t)
})?,
)?;
paper.set("extensions", ext_table)?;
// paper.events — subscribe Lua handlers to editor events.
// Collected during config load; `subscribe_events` wires them into
// the shared event bus.
let collected_ev = self.collected_events.clone();
let events_table = lua.create_table()?;
events_table.set(
"on",
lua.create_function(move |lua, (event, func): (String, mlua::Function)| {
let key = lua.create_registry_value(func)?;
collected_ev
.lock()
.unwrap()
.push(LuaEventHandler { event, key });
Ok(())
})?,
)?;
paper.set("events", events_table)?;
// paper.quit
let quit = self.quit_requested.clone();
paper.set(
"quit",
lua.create_function(move |_, _: ()| {
let mut q = quit.lock().unwrap();
*q = true;
Ok(())
})?,
)?;
// paper.buffer — real BufferMessage access on the wired document
// buffer. All functions error loudly when wiring is missing.
let buffer_id = self.buffer;
let sender = self.sender.clone();
let buffer_table = lua.create_table()?;
// content() -> string
let (b, s) = (buffer_id, sender.clone());
buffer_table.set(
"content",
lua.create_function(move |_, ()| -> LuaResult<String> {
let (buf, sender) = (
b.ok_or_else(borrow_err)?,
s.as_ref().ok_or_else(borrow_err)?,
);
let handle = sender
.request(buf, BufferMessage::GetContent)
.map_err(mlua_err)?;
let reply = handle
.recv_timeout(std::time::Duration::from_millis(200))
.map_err(mlua_err)?;
downcast_reply::<String>(reply)
})?,
)?;
// set_content(text)
let (b, s) = (buffer_id, sender.clone());
buffer_table.set(
"set_content",
lua.create_function(move |_, text: String| -> LuaResult<()> {
let (buf, sender) = (
b.ok_or_else(borrow_err)?,
s.as_ref().ok_or_else(borrow_err)?,
);
sender
.send(buf, BufferMessage::LoadContent(text))
.map_err(mlua_err)?;
Ok(())
})?,
)?;
// insert_text(text) — insert at cursor via InsertChar sequence
let (b, s) = (buffer_id, sender.clone());
buffer_table.set(
"insert_text",
lua.create_function(move |_, text: String| -> LuaResult<()> {
let (buf, sender) = (
b.ok_or_else(borrow_err)?,
s.as_ref().ok_or_else(borrow_err)?,
);
for ch in text.chars() {
sender
.send(buf, BufferMessage::InsertChar(ch))
.map_err(mlua_err)?;
}
Ok(())
})?,
)?;
// cursor() -> {row=, col=} (0-indexed)
let (b, s) = (buffer_id, sender.clone());
buffer_table.set(
"cursor",
lua.create_function(move |lua, ()| -> LuaResult<mlua::Table> {
let (buf, sender) = (
b.ok_or_else(borrow_err)?,
s.as_ref().ok_or_else(borrow_err)?,
);
let handle = sender
.request(buf, BufferMessage::GetCursorPosition)
.map_err(mlua_err)?;
let reply = handle
.recv_timeout(std::time::Duration::from_millis(200))
.map_err(mlua_err)?;
let (row, col) = downcast_reply::<(usize, usize)>(reply)?;
let t = lua.create_table()?;
t.set("row", row)?;
t.set("col", col)?;
Ok(t)
})?,
)?;
// move_to(row) — 1-indexed line, matching the `go` command
let (b, s) = (buffer_id, sender.clone());
buffer_table.set(
"move_to",
lua.create_function(move |_, row: usize| -> LuaResult<()> {
let (buf, sender) = (
b.ok_or_else(borrow_err)?,
s.as_ref().ok_or_else(borrow_err)?,
);
sender
.send(buf, BufferMessage::MoveToLine(row))
.map_err(mlua_err)?;
Ok(())
})?,
)?;
paper.set("buffer", buffer_table)?;
// paper.cmd — queue an editor command for the event loop to run.
let cmd_queue = self.cmd_queue.clone();
paper.set(
"cmd",
lua.create_function(move |_, cmd: String| {
cmd_queue.lock().unwrap().push(cmd);
Ok(())
})?,
)?;
// paper.after(ms, fn) — schedule a Lua callback. The render event
// loop fires due timers each tick; callbacks run in this Lua state.
// NOTE: use the closure's `lua` param for the registry value —
// self.lua is already locked while config executes.
let timers = self.timers.clone();
paper.set(
"after",
lua.create_function(move |lua, (ms, f): (u64, mlua::Function)| {
let key = lua.create_registry_value(f).map_err(mlua_err)?;
timers.lock().unwrap().push((
std::time::Instant::now() + std::time::Duration::from_millis(ms),
key,
));
Ok(())
})?,
)?;
// paper.open(path) / paper.save() — sugar over the command queue.
let q_open = self.cmd_queue.clone();
paper.set(
"open",
lua.create_function(move |_, path: String| {
q_open.lock().unwrap().push(format!("open {path}"));
Ok(())
})?,
)?;
let q_save = self.cmd_queue.clone();
paper.set(
"save",
lua.create_function(move |_, ()| {
q_save.lock().unwrap().push("write".to_string());
Ok(())
})?,
)?;
// paper.terminal.send(text) — write to the PTY via the command
// queue (terminal-send runs on the event loop; same mailbox
// pattern as paper.cmd — never direct actor access from Lua).
let q_term = self.cmd_queue.clone();
let terminal_table = lua.create_table()?;
terminal_table.set(
"send",
lua.create_function(move |_, text: String| {
q_term.lock().unwrap().push(format!("terminal-send {text}"));
Ok(())
})?,
)?;
// paper.terminal.open() — focus the terminal panel.
let q_open_term = self.cmd_queue.clone();
terminal_table.set(
"open",
lua.create_function(move |_, ()| {
q_open_term.lock().unwrap().push("terminal".to_string());
Ok(())
})?,
)?;
paper.set("terminal", terminal_table)?;
// paper.panels — create named panel buffers (everything is a buffer).
// Names are collected; main.rs spawns each in the PanelRegistry
// after config load, then flushes pending writes.
let requested = self.requested_panels.clone();
let panels_table = lua.create_table()?;
panels_table.set(
"create",
lua.create_function(move |_, name: String| {
let mut panels = requested.lock().unwrap();
if !panels.contains(&name) {
panels.push(name);
}
Ok(())
})?,
)?;
paper.set("panels", panels_table)?;
// paper.panel — write to a named panel buffer. Writes made before
// the panel exists (config time) are queued and flushed by main.rs
// once the panel buffers are spawned.
let pending = self.pending_panel_writes.clone();
let panel_table = lua.create_table()?;
panel_table.set(
"write",
lua.create_function(move |_, (name, text): (String, String)| {
pending.lock().unwrap().push((name, text));
Ok(())
})?,
)?;
paper.set("panel", panel_table)?;
globals.set("paper", paper)?;
Ok(())
}
fn load_config(&self) -> Result<(), Box<dyn std::error::Error>> {
let config_path = self.config_path();
if config_path.exists() {
let config_str = std::fs::read_to_string(&config_path)?;
let lua = self.lua.lock().unwrap();
// Prepend the config dir to package.path so init.lua can
// `require` user modules colocated with it.
if let Some(dir) = config_path.parent() {
let dir_str = dir.display().to_string().replace('\\', "/");
let prepend = format!(
r#"package.path = "{dir_str}/?.lua;{dir_str}/?/init.lua;" .. package.path"#
);
if let Err(e) = lua.load(&prepend).exec() {
eprintln!("package.path setup error: {}", e);
}
}
match lua.load(&config_str).exec() {
Ok(_) => {
println!("Loaded config from {}", config_path.display());
}
Err(e) => {
eprintln!("Config error: {}", e);
}
}
// Execute active extensions' init.lua in load order
// (ExtensionManager discovery; errors are non-fatal).
if let Some(dir) = config_path.parent() {
let mgr = ExtensionManager::with_config_dir(dir.to_path_buf());
for script in mgr.active_init_scripts() {
match std::fs::read_to_string(&script)
.map_err(|e| e.to_string())
.and_then(|src| lua.load(&src).exec().map_err(|e| e.to_string()))
{
Ok(()) => println!("Loaded extension {}", script.display()),
Err(e) => eprintln!("Extension {} error: {}", script.display(), e),
}
}
}
} else {
println!(
"No config found at {}, using defaults",
config_path.display()
);
}
Ok(())
}
fn config_path(&self) -> PathBuf {
// PAPEROS_CONFIG overrides the config directory (used by tests and
// alternative installs).
if let Ok(dir) = std::env::var("PAPEROS_CONFIG") {
return PathBuf::from(dir).join("init.lua");
}
let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
PathBuf::from(format!("{}/.config/paperos/init.lua", home))
}
}
impl Default for LuaExtension {
fn default() -> Self {
Self::new()
}
}