Skip to main content

fast_text_plugin/
host.rs

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/// Metadata about a registered command.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct CommandInfo {
13    pub title: String,
14    pub description: String,
15    pub fn_name: String,
16}
17
18/// A snapshot of the editor, exposed to scripts as global constants.
19#[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    /// The name of the active color theme, e.g. `dark` or `monokai`.
33    pub theme: String,
34    /// The whole buffer as text (not just the selection).
35    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
42/// Loads Rhai plugins and runs their commands against the editor.
43pub struct PluginHost {
44    engine: Engine,
45    ast: AST,
46    sources: Vec<(String, String)>,
47    commands: Commands,
48    keybindings: Keybinds,
49    queue: Queue,
50    /// Errors encountered while loading or running plugins.
51    pub errors: Vec<String>,
52}
53
54impl Default for PluginHost {
55    fn default() -> Self {
56        Self::new()
57    }
58}
59
60impl PluginHost {
61    /// Creates a host with the editor API installed but no plugins loaded.
62    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    /// Adds (or replaces) a named plugin from source and rebuilds.
79    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    /// Loads every `.rhai` file in a directory.
86    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                // Execute top-level statements to collect command/binding registrations.
125                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    /// All registered commands, sorted by title.
136    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    /// All registered keybindings.
145    pub fn keybindings(&self) -> Vec<(KeySpec, String)> {
146        self.keybindings.lock().unwrap().clone()
147    }
148
149    /// Finds the command title bound to a key, if any.
150    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    /// Runs a command by title, returning the actions it requested.
160    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
193fn push_context(scope: &mut Scope<'static>, ctx: &EditorContext) {
194    scope.push_constant("cursor", ctx.cursor as i64);
195    scope.push_constant("selection_start", ctx.selection_start as i64);
196    scope.push_constant("selection_end", ctx.selection_end as i64);
197    scope.push_constant("has_selection", ctx.has_selection);
198    scope.push_constant("selected_text", ctx.selected_text.clone());
199    scope.push_constant("line", ctx.line as i64);
200    scope.push_constant("col", ctx.col as i64);
201    scope.push_constant("doc_len", ctx.doc_len as i64);
202    scope.push_constant("line_count", ctx.line_count as i64);
203    scope.push_constant("file_name", ctx.file_name.clone());
204    scope.push_constant("language", ctx.language.clone());
205    scope.push_constant("theme", ctx.theme.clone());
206    scope.push_constant("document_text", ctx.doc_text.clone());
207}
208
209fn build_engine(queue: Queue, commands: Commands, keybindings: Keybinds) -> Engine {
210    let mut engine = Engine::new();
211    engine.set_max_operations(2_000_000);
212    engine.set_max_call_levels(64);
213    engine.set_max_expr_depths(64, 32);
214
215    // --- Editing actions ---------------------------------------------------
216    {
217        let q = queue.clone();
218        engine.register_fn("insert", move |text: ImmutableString| {
219            q.lock()
220                .unwrap()
221                .push(EditorAction::Insert(text.to_string()));
222        });
223    }
224    {
225        let q = queue.clone();
226        engine.register_fn("insert_at", move |at: i64, text: ImmutableString| {
227            q.lock().unwrap().push(EditorAction::InsertAt {
228                at: at.max(0) as usize,
229                text: text.to_string(),
230            });
231        });
232    }
233    {
234        let q = queue.clone();
235        engine.register_fn("delete", move |start: i64, end: i64| {
236            q.lock().unwrap().push(EditorAction::DeleteRange {
237                start: start.max(0) as usize,
238                end: end.max(0) as usize,
239            });
240        });
241    }
242    {
243        let q = queue.clone();
244        engine.register_fn("delete_selection", move || {
245            q.lock().unwrap().push(EditorAction::DeleteSelection);
246        });
247    }
248    {
249        let q = queue.clone();
250        engine.register_fn("backspace", move || {
251            q.lock().unwrap().push(EditorAction::Backspace);
252        });
253    }
254    {
255        let q = queue.clone();
256        engine.register_fn("delete_forward", move || {
257            q.lock().unwrap().push(EditorAction::DeleteForward);
258        });
259    }
260    {
261        let q = queue.clone();
262        engine.register_fn("newline", move || {
263            q.lock().unwrap().push(EditorAction::InsertNewline);
264        });
265    }
266    {
267        let q = queue.clone();
268        engine.register_fn("set_cursor", move |at: i64| {
269            q.lock()
270                .unwrap()
271                .push(EditorAction::SetCursor(at.max(0) as usize));
272        });
273    }
274    {
275        let q = queue.clone();
276        engine.register_fn("select", move |anchor: i64, head: i64| {
277            q.lock().unwrap().push(EditorAction::Select {
278                anchor: anchor.max(0) as usize,
279                head: head.max(0) as usize,
280            });
281        });
282    }
283    {
284        let q = queue.clone();
285        engine.register_fn("select_all", move || {
286            q.lock().unwrap().push(EditorAction::SelectAll);
287        });
288    }
289    {
290        let q = queue.clone();
291        engine.register_fn("move_caret", move |dir: ImmutableString, extend: bool| {
292            let mut q = q.lock().unwrap();
293            match EditorAction::movement(dir.as_str(), extend) {
294                Some(a) => q.push(a),
295                None => q.push(EditorAction::Message(format!("unknown move: {dir}"))),
296            }
297        });
298    }
299    {
300        let q = queue.clone();
301        engine.register_fn("undo", move || {
302            q.lock().unwrap().push(EditorAction::Undo);
303        });
304    }
305    {
306        let q = queue.clone();
307        engine.register_fn("redo", move || {
308            q.lock().unwrap().push(EditorAction::Redo);
309        });
310    }
311    {
312        let q = queue.clone();
313        engine.register_fn("save", move || {
314            q.lock().unwrap().push(EditorAction::Save);
315        });
316    }
317    {
318        let q = queue.clone();
319        engine.register_fn("set_language", move |name: ImmutableString| {
320            q.lock()
321                .unwrap()
322                .push(EditorAction::SetLanguage(name.to_string()));
323        });
324    }
325    {
326        let q = queue.clone();
327        engine.register_fn("set_cursor_style", move |name: ImmutableString| {
328            let mut q = q.lock().unwrap();
329            match CursorStyle::parse(&name) {
330                Some(style) => q.push(EditorAction::SetCursorStyle(style)),
331                None => q.push(EditorAction::Message(format!(
332                    "unknown cursor style: {name}"
333                ))),
334            }
335        });
336    }
337    {
338        let q = queue.clone();
339        engine.register_fn("set_theme", move |name: ImmutableString| {
340            q.lock()
341                .unwrap()
342                .push(EditorAction::SetTheme(name.to_string()));
343        });
344    }
345    {
346        let q = queue.clone();
347        engine.register_fn("message", move |text: ImmutableString| {
348            q.lock()
349                .unwrap()
350                .push(EditorAction::Message(text.to_string()));
351        });
352    }
353
354    // --- Registration API --------------------------------------------------
355    {
356        let cmds = commands.clone();
357        engine.register_fn(
358            "command",
359            move |title: ImmutableString, fn_name: ImmutableString| {
360                cmds.lock().unwrap().insert(
361                    title.to_string(),
362                    CommandInfo {
363                        title: title.to_string(),
364                        description: String::new(),
365                        fn_name: fn_name.to_string(),
366                    },
367                );
368            },
369        );
370    }
371    {
372        let cmds = commands.clone();
373        engine.register_fn(
374            "command_with_desc",
375            move |title: ImmutableString,
376                  description: ImmutableString,
377                  fn_name: ImmutableString| {
378                cmds.lock().unwrap().insert(
379                    title.to_string(),
380                    CommandInfo {
381                        title: title.to_string(),
382                        description: description.to_string(),
383                        fn_name: fn_name.to_string(),
384                    },
385                );
386            },
387        );
388    }
389    {
390        let binds = keybindings.clone();
391        engine.register_fn(
392            "bind",
393            move |key: ImmutableString, title: ImmutableString| {
394                if let Some(spec) = KeySpec::parse(&key) {
395                    binds.lock().unwrap().push((spec, title.to_string()));
396                }
397            },
398        );
399    }
400
401    engine
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407
408    #[test]
409    fn runs_a_simple_command() {
410        let mut host = PluginHost::new();
411        host.add_plugin(
412            "test",
413            r#"
414                fn shout() {
415                    insert("HELLO");
416                }
417                command("Shout", "shout");
418            "#,
419        );
420        assert!(host.errors.is_empty(), "{:?}", host.errors);
421
422        let ctx = EditorContext::default();
423        let actions = host.run_command("Shout", &ctx);
424        assert_eq!(actions, vec![EditorAction::Insert("HELLO".to_string())]);
425    }
426
427    #[test]
428    fn sets_cursor_style() {
429        let mut host = PluginHost::new();
430        host.add_plugin(
431            "test",
432            r#"
433                fn bar() { set_cursor_style("bar"); }
434                command("Bar", "bar");
435            "#,
436        );
437        let actions = host.run_command("Bar", &EditorContext::default());
438        assert_eq!(
439            actions,
440            vec![EditorAction::SetCursorStyle(crate::CursorStyle::Bar)]
441        );
442    }
443
444    #[test]
445    fn sets_the_theme() {
446        let mut host = PluginHost::new();
447        host.add_plugin(
448            "test",
449            r#"
450                fn mono() { set_theme("monokai"); }
451                command("Monokai", "mono");
452            "#,
453        );
454        let actions = host.run_command("Monokai", &EditorContext::default());
455        assert_eq!(actions, vec![EditorAction::SetTheme("monokai".to_string())]);
456    }
457
458    #[test]
459    fn exposes_editor_context_constants() {
460        let mut host = PluginHost::new();
461        host.add_plugin(
462            "test",
463            r#"
464                fn wrap() {
465                    insert("<" + selected_text + ">");
466                }
467                command("Wrap", "wrap");
468            "#,
469        );
470        let ctx = EditorContext {
471            selected_text: "hi".to_string(),
472            has_selection: true,
473            ..Default::default()
474        };
475        let actions = host.run_command("Wrap", &ctx);
476        assert_eq!(actions, vec![EditorAction::Insert("<hi>".to_string())]);
477    }
478
479    #[test]
480    fn registers_keybindings() {
481        let mut host = PluginHost::new();
482        host.add_plugin(
483            "test",
484            r#"
485                fn upper() { insert("x"); }
486                command("Upper", "upper");
487                bind("ctrl+shift+u", "Upper");
488            "#,
489        );
490        let key = KeySpec::parse("ctrl+shift+u").unwrap();
491        assert_eq!(host.lookup_key(&key).as_deref(), Some("Upper"));
492        let titles = host.command_titles();
493        assert!(titles.contains(&"Upper".to_string()));
494    }
495
496    #[test]
497    fn movement_and_multi_actions() {
498        let mut host = PluginHost::new();
499        host.add_plugin(
500            "test",
501            r#"
502                fn jump() {
503                    set_cursor(0);
504                    move_caret("word_right", false);
505                }
506                command("Jump", "jump");
507            "#,
508        );
509        let actions = host.run_command("Jump", &EditorContext::default());
510        assert_eq!(
511            actions,
512            vec![
513                EditorAction::SetCursor(0),
514                EditorAction::MoveWordForward { extend: false },
515            ]
516        );
517    }
518
519    #[test]
520    fn compile_errors_are_reported() {
521        let mut host = PluginHost::new();
522        host.add_plugin("bad", "fn broken( {");
523        assert!(!host.errors.is_empty());
524    }
525}