1use std::collections::BTreeMap;
2use std::path::Path;
3use std::sync::{Arc, Mutex};
4
5use rhai::{Dynamic, Engine, ImmutableString, Scope, AST};
6
7use crate::action::{CursorStyle, EditorAction};
8use crate::key::KeySpec;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct CommandInfo {
13 pub title: String,
14 pub description: String,
15 pub fn_name: String,
16}
17
18#[derive(Debug, Clone, Default)]
20pub struct EditorContext {
21 pub cursor: usize,
22 pub selection_start: usize,
23 pub selection_end: usize,
24 pub has_selection: bool,
25 pub selected_text: String,
26 pub line: usize,
27 pub col: usize,
28 pub doc_len: usize,
29 pub line_count: usize,
30 pub file_name: String,
31 pub language: String,
32 pub theme: String,
34 pub doc_text: String,
36}
37
38type Queue = Arc<Mutex<Vec<EditorAction>>>;
39type Commands = Arc<Mutex<BTreeMap<String, CommandInfo>>>;
40type Keybinds = Arc<Mutex<Vec<(KeySpec, String)>>>;
41
42pub struct PluginHost {
44 engine: Engine,
45 ast: AST,
46 sources: Vec<(String, String)>,
47 commands: Commands,
48 keybindings: Keybinds,
49 queue: Queue,
50 pub errors: Vec<String>,
52}
53
54impl Default for PluginHost {
55 fn default() -> Self {
56 Self::new()
57 }
58}
59
60impl PluginHost {
61 pub fn new() -> Self {
63 let queue: Queue = Arc::new(Mutex::new(Vec::new()));
64 let commands: Commands = Arc::new(Mutex::new(BTreeMap::new()));
65 let keybindings: Keybinds = Arc::new(Mutex::new(Vec::new()));
66 let engine = build_engine(queue.clone(), commands.clone(), keybindings.clone());
67 Self {
68 engine,
69 ast: AST::empty(),
70 sources: Vec::new(),
71 commands,
72 keybindings,
73 queue,
74 errors: Vec::new(),
75 }
76 }
77
78 pub fn add_plugin(&mut self, name: &str, source: &str) {
80 self.sources.retain(|(n, _)| n != name);
81 self.sources.push((name.to_string(), source.to_string()));
82 self.rebuild();
83 }
84
85 pub fn load_dir(&mut self, dir: &Path) {
87 let Ok(entries) = std::fs::read_dir(dir) else {
88 return;
89 };
90 let mut paths: Vec<_> = entries
91 .filter_map(Result::ok)
92 .map(|e| e.path())
93 .filter(|p| p.extension().is_some_and(|e| e == "rhai"))
94 .collect();
95 paths.sort();
96 for path in paths {
97 match std::fs::read_to_string(&path) {
98 Ok(source) => {
99 let name = path
100 .file_name()
101 .unwrap_or_default()
102 .to_string_lossy()
103 .into_owned();
104 self.add_plugin(&name, &source);
105 }
106 Err(e) => self.errors.push(format!("{}: {e}", path.display())),
107 }
108 }
109 }
110
111 fn rebuild(&mut self) {
112 self.errors.clear();
113 self.commands.lock().unwrap().clear();
114 self.keybindings.lock().unwrap().clear();
115
116 let combined = self
117 .sources
118 .iter()
119 .map(|(_, src)| src.as_str())
120 .collect::<Vec<_>>()
121 .join("\n");
122 match self.engine.compile(&combined) {
123 Ok(ast) => {
124 let mut scope = Scope::new();
126 if let Err(e) = self.engine.run_ast_with_scope(&mut scope, &ast) {
127 self.errors.push(format!("error loading plugins: {e}"));
128 }
129 self.ast = ast;
130 }
131 Err(e) => self.errors.push(format!("compile error: {e}")),
132 }
133 }
134
135 pub fn commands(&self) -> Vec<CommandInfo> {
137 self.commands.lock().unwrap().values().cloned().collect()
138 }
139
140 pub fn command_titles(&self) -> Vec<String> {
141 self.commands.lock().unwrap().keys().cloned().collect()
142 }
143
144 pub fn keybindings(&self) -> Vec<(KeySpec, String)> {
146 self.keybindings.lock().unwrap().clone()
147 }
148
149 pub fn lookup_key(&self, key: &KeySpec) -> Option<String> {
151 self.keybindings
152 .lock()
153 .unwrap()
154 .iter()
155 .find(|(k, _)| k == key)
156 .map(|(_, title)| title.clone())
157 }
158
159 pub fn run_command(&mut self, title: &str, ctx: &EditorContext) -> Vec<EditorAction> {
161 self.queue.lock().unwrap().clear();
162
163 let fn_name = {
164 let commands = self.commands.lock().unwrap();
165 match commands.get(title) {
166 Some(c) => c.fn_name.clone(),
167 None => {
168 return vec![EditorAction::Message(format!("No such command: {title}"))];
169 }
170 }
171 };
172
173 let mut scope = Scope::new();
174 push_context(&mut scope, ctx);
175
176 if let Err(e) = self
177 .engine
178 .call_fn::<Dynamic>(&mut scope, &self.ast, &fn_name, ())
179 {
180 return vec![EditorAction::Message(format!(
181 "Plugin error in '{title}': {e}"
182 ))];
183 }
184
185 std::mem::take(&mut *self.queue.lock().unwrap())
186 }
187
188 pub fn is_empty(&self) -> bool {
189 self.sources.is_empty()
190 }
191
192 pub fn has_hook(&self, name: &str) -> bool {
194 self.ast.iter_functions().any(|f| f.name == name)
195 }
196
197 pub fn run_hook(&mut self, name: &str, ctx: &EditorContext) -> Vec<EditorAction> {
203 if !self.has_hook(name) {
204 return Vec::new();
205 }
206 self.queue.lock().unwrap().clear();
207 let mut scope = Scope::new();
208 push_context(&mut scope, ctx);
209 if let Err(e) = self
210 .engine
211 .call_fn::<Dynamic>(&mut scope, &self.ast, name, ())
212 {
213 self.errors.push(format!("hook {name}: {e}"));
214 return vec![EditorAction::Message(format!("{name} failed: {e}"))];
215 }
216 std::mem::take(&mut *self.queue.lock().unwrap())
217 }
218}
219
220fn push_context(scope: &mut Scope<'static>, ctx: &EditorContext) {
221 scope.push_constant("cursor", ctx.cursor as i64);
222 scope.push_constant("selection_start", ctx.selection_start as i64);
223 scope.push_constant("selection_end", ctx.selection_end as i64);
224 scope.push_constant("has_selection", ctx.has_selection);
225 scope.push_constant("selected_text", ctx.selected_text.clone());
226 scope.push_constant("line", ctx.line as i64);
227 scope.push_constant("col", ctx.col as i64);
228 scope.push_constant("doc_len", ctx.doc_len as i64);
229 scope.push_constant("line_count", ctx.line_count as i64);
230 scope.push_constant("file_name", ctx.file_name.clone());
231 scope.push_constant("language", ctx.language.clone());
232 scope.push_constant("theme", ctx.theme.clone());
233 scope.push_constant("document_text", ctx.doc_text.clone());
234}
235
236fn build_engine(queue: Queue, commands: Commands, keybindings: Keybinds) -> Engine {
237 let mut engine = Engine::new();
238 engine.set_max_operations(2_000_000);
239 engine.set_max_call_levels(64);
240 engine.set_max_expr_depths(64, 32);
241
242 {
244 let q = queue.clone();
245 engine.register_fn("insert", move |text: ImmutableString| {
246 q.lock()
247 .unwrap()
248 .push(EditorAction::Insert(text.to_string()));
249 });
250 }
251 {
252 let q = queue.clone();
253 engine.register_fn("insert_at", move |at: i64, text: ImmutableString| {
254 q.lock().unwrap().push(EditorAction::InsertAt {
255 at: at.max(0) as usize,
256 text: text.to_string(),
257 });
258 });
259 }
260 {
261 let q = queue.clone();
262 engine.register_fn("delete", move |start: i64, end: i64| {
263 q.lock().unwrap().push(EditorAction::DeleteRange {
264 start: start.max(0) as usize,
265 end: end.max(0) as usize,
266 });
267 });
268 }
269 {
270 let q = queue.clone();
271 engine.register_fn("delete_selection", move || {
272 q.lock().unwrap().push(EditorAction::DeleteSelection);
273 });
274 }
275 {
276 let q = queue.clone();
277 engine.register_fn("backspace", move || {
278 q.lock().unwrap().push(EditorAction::Backspace);
279 });
280 }
281 {
282 let q = queue.clone();
283 engine.register_fn("delete_forward", move || {
284 q.lock().unwrap().push(EditorAction::DeleteForward);
285 });
286 }
287 {
288 let q = queue.clone();
289 engine.register_fn("newline", move || {
290 q.lock().unwrap().push(EditorAction::InsertNewline);
291 });
292 }
293 {
294 let q = queue.clone();
295 engine.register_fn("set_cursor", move |at: i64| {
296 q.lock()
297 .unwrap()
298 .push(EditorAction::SetCursor(at.max(0) as usize));
299 });
300 }
301 {
302 let q = queue.clone();
303 engine.register_fn("select", move |anchor: i64, head: i64| {
304 q.lock().unwrap().push(EditorAction::Select {
305 anchor: anchor.max(0) as usize,
306 head: head.max(0) as usize,
307 });
308 });
309 }
310 {
311 let q = queue.clone();
312 engine.register_fn("select_all", move || {
313 q.lock().unwrap().push(EditorAction::SelectAll);
314 });
315 }
316 {
317 let q = queue.clone();
318 engine.register_fn("move_caret", move |dir: ImmutableString, extend: bool| {
319 let mut q = q.lock().unwrap();
320 match EditorAction::movement(dir.as_str(), extend) {
321 Some(a) => q.push(a),
322 None => q.push(EditorAction::Message(format!("unknown move: {dir}"))),
323 }
324 });
325 }
326 {
327 let q = queue.clone();
328 engine.register_fn("undo", move || {
329 q.lock().unwrap().push(EditorAction::Undo);
330 });
331 }
332 {
333 let q = queue.clone();
334 engine.register_fn("redo", move || {
335 q.lock().unwrap().push(EditorAction::Redo);
336 });
337 }
338 {
339 let q = queue.clone();
340 engine.register_fn("save", move || {
341 q.lock().unwrap().push(EditorAction::Save);
342 });
343 }
344 {
345 let q = queue.clone();
346 engine.register_fn("set_language", move |name: ImmutableString| {
347 q.lock()
348 .unwrap()
349 .push(EditorAction::SetLanguage(name.to_string()));
350 });
351 }
352 {
353 let q = queue.clone();
354 engine.register_fn("set_cursor_style", move |name: ImmutableString| {
355 let mut q = q.lock().unwrap();
356 match CursorStyle::parse(&name) {
357 Some(style) => q.push(EditorAction::SetCursorStyle(style)),
358 None => q.push(EditorAction::Message(format!(
359 "unknown cursor style: {name}"
360 ))),
361 }
362 });
363 }
364 {
365 let q = queue.clone();
366 engine.register_fn("set_theme", move |name: ImmutableString| {
367 q.lock()
368 .unwrap()
369 .push(EditorAction::SetTheme(name.to_string()));
370 });
371 }
372 {
373 let q = queue.clone();
374 engine.register_fn("set_status", move |text: ImmutableString| {
375 q.lock()
376 .unwrap()
377 .push(EditorAction::SetStatus(Some(text.to_string())));
378 });
379 }
380 {
381 let q = queue.clone();
382 engine.register_fn("clear_status", move || {
383 q.lock().unwrap().push(EditorAction::SetStatus(None));
384 });
385 }
386 {
387 let q = queue.clone();
388 engine.register_fn("format", move || {
389 q.lock().unwrap().push(EditorAction::Format);
390 });
391 }
392 {
393 let q = queue.clone();
394 engine.register_fn("message", move |text: ImmutableString| {
395 q.lock()
396 .unwrap()
397 .push(EditorAction::Message(text.to_string()));
398 });
399 }
400
401 {
403 let cmds = commands.clone();
404 engine.register_fn(
405 "command",
406 move |title: ImmutableString, fn_name: ImmutableString| {
407 cmds.lock().unwrap().insert(
408 title.to_string(),
409 CommandInfo {
410 title: title.to_string(),
411 description: String::new(),
412 fn_name: fn_name.to_string(),
413 },
414 );
415 },
416 );
417 }
418 {
419 let cmds = commands.clone();
420 engine.register_fn(
421 "command_with_desc",
422 move |title: ImmutableString,
423 description: ImmutableString,
424 fn_name: ImmutableString| {
425 cmds.lock().unwrap().insert(
426 title.to_string(),
427 CommandInfo {
428 title: title.to_string(),
429 description: description.to_string(),
430 fn_name: fn_name.to_string(),
431 },
432 );
433 },
434 );
435 }
436 {
437 let binds = keybindings.clone();
438 engine.register_fn(
439 "bind",
440 move |key: ImmutableString, title: ImmutableString| {
441 if let Some(spec) = KeySpec::parse(&key) {
442 binds.lock().unwrap().push((spec, title.to_string()));
443 }
444 },
445 );
446 }
447
448 engine
449}
450
451#[cfg(test)]
452mod tests {
453 use super::*;
454
455 #[test]
456 fn runs_a_simple_command() {
457 let mut host = PluginHost::new();
458 host.add_plugin(
459 "test",
460 r#"
461 fn shout() {
462 insert("HELLO");
463 }
464 command("Shout", "shout");
465 "#,
466 );
467 assert!(host.errors.is_empty(), "{:?}", host.errors);
468
469 let ctx = EditorContext::default();
470 let actions = host.run_command("Shout", &ctx);
471 assert_eq!(actions, vec![EditorAction::Insert("HELLO".to_string())]);
472 }
473
474 #[test]
475 fn sets_cursor_style() {
476 let mut host = PluginHost::new();
477 host.add_plugin(
478 "test",
479 r#"
480 fn bar() { set_cursor_style("bar"); }
481 command("Bar", "bar");
482 "#,
483 );
484 let actions = host.run_command("Bar", &EditorContext::default());
485 assert_eq!(
486 actions,
487 vec![EditorAction::SetCursorStyle(crate::CursorStyle::Bar)]
488 );
489 }
490
491 #[test]
492 fn sets_the_theme() {
493 let mut host = PluginHost::new();
494 host.add_plugin(
495 "test",
496 r#"
497 fn mono() { set_theme("monokai"); }
498 command("Monokai", "mono");
499 "#,
500 );
501 let actions = host.run_command("Monokai", &EditorContext::default());
502 assert_eq!(actions, vec![EditorAction::SetTheme("monokai".to_string())]);
503 }
504
505 #[test]
506 fn exposes_editor_context_constants() {
507 let mut host = PluginHost::new();
508 host.add_plugin(
509 "test",
510 r#"
511 fn wrap() {
512 insert("<" + selected_text + ">");
513 }
514 command("Wrap", "wrap");
515 "#,
516 );
517 let ctx = EditorContext {
518 selected_text: "hi".to_string(),
519 has_selection: true,
520 ..Default::default()
521 };
522 let actions = host.run_command("Wrap", &ctx);
523 assert_eq!(actions, vec![EditorAction::Insert("<hi>".to_string())]);
524 }
525
526 #[test]
527 fn registers_keybindings() {
528 let mut host = PluginHost::new();
529 host.add_plugin(
530 "test",
531 r#"
532 fn upper() { insert("x"); }
533 command("Upper", "upper");
534 bind("ctrl+shift+u", "Upper");
535 "#,
536 );
537 let key = KeySpec::parse("ctrl+shift+u").unwrap();
538 assert_eq!(host.lookup_key(&key).as_deref(), Some("Upper"));
539 let titles = host.command_titles();
540 assert!(titles.contains(&"Upper".to_string()));
541 }
542
543 #[test]
544 fn movement_and_multi_actions() {
545 let mut host = PluginHost::new();
546 host.add_plugin(
547 "test",
548 r#"
549 fn jump() {
550 set_cursor(0);
551 move_caret("word_right", false);
552 }
553 command("Jump", "jump");
554 "#,
555 );
556 let actions = host.run_command("Jump", &EditorContext::default());
557 assert_eq!(
558 actions,
559 vec![
560 EditorAction::SetCursor(0),
561 EditorAction::MoveWordForward { extend: false },
562 ]
563 );
564 }
565
566 #[test]
567 fn runs_buffer_lifecycle_hooks() {
568 let mut host = PluginHost::new();
569 host.add_plugin(
570 "hooks",
571 r#"
572 fn on_buffer_open() { message("opened"); }
573 fn on_buffer_save() { format(); }
574 "#,
575 );
576 assert!(host.has_hook("on_buffer_open"));
577 assert!(host.has_hook("on_buffer_save"));
578 assert!(!host.has_hook("on_buffer_close"));
579 assert_eq!(
580 host.run_hook("on_buffer_open", &EditorContext::default()),
581 vec![EditorAction::Message("opened".to_string())]
582 );
583 assert_eq!(
584 host.run_hook("on_buffer_save", &EditorContext::default()),
585 vec![EditorAction::Format]
586 );
587 assert!(host
588 .run_hook("on_buffer_close", &EditorContext::default())
589 .is_empty());
590 }
591
592 #[test]
593 fn compile_errors_are_reported() {
594 let mut host = PluginHost::new();
595 host.add_plugin("bad", "fn broken( {");
596 assert!(!host.errors.is_empty());
597 }
598}