1use std::cell::RefCell;
35use std::collections::BTreeMap;
36use std::path::PathBuf;
37use std::rc::Rc;
38
39use fast_text_plugin::{CommandInfo, CursorStyle, EditorAction, EditorContext, KeySpec};
40use textwrite::host::Host;
41use textwrite::Interpreter;
42pub use textwrite::Value;
43
44const AUTOMATOR_SRC: &str = include_str!("automator.tw");
46
47type Queue = Rc<RefCell<Vec<EditorAction>>>;
48type Commands = Rc<RefCell<BTreeMap<String, CommandInfo>>>;
49type Keybinds = Rc<RefCell<Vec<(KeySpec, String)>>>;
50type Themes = Rc<RefCell<BTreeMap<String, Vec<(String, u32)>>>>;
52
53static HOST_FUNCTIONS: &[&str] = &[
55 "print",
56 "write",
57 "message",
58 "insert",
59 "insert_at",
60 "delete",
61 "delete_selection",
62 "backspace",
63 "delete_forward",
64 "newline",
65 "set_cursor",
66 "select",
67 "select_all",
68 "move_caret",
69 "undo",
70 "redo",
71 "save",
72 "format",
73 "set_language",
74 "set_cursor_style",
75 "set_theme",
76 "define_theme",
77 "set_status",
78 "clear_status",
79 "wait",
80 "command",
81 "command_with_desc",
82 "bind",
83];
84
85struct EditorHost {
88 queue: Queue,
89 commands: Commands,
90 keybindings: Keybinds,
91 themes: Themes,
92}
93
94impl Host for EditorHost {
95 fn functions(&self) -> &'static [&'static str] {
96 HOST_FUNCTIONS
97 }
98
99 fn call(
100 &mut self,
101 name: &str,
102 args: Vec<Value>,
103 span: textwrite::Span,
104 ) -> textwrite::Result<Value> {
105 match name {
106 "print" => {
107 let text = args
108 .iter()
109 .map(Value::to_display)
110 .collect::<Vec<_>>()
111 .join(" ");
112 self.push(EditorAction::Message(text));
113 }
114 "write" => {
115 let text = args
116 .iter()
117 .map(Value::to_display)
118 .collect::<Vec<_>>()
119 .join("");
120 self.push(EditorAction::Message(text));
121 }
122 "message" => {
123 let text = args
124 .iter()
125 .map(Value::to_display)
126 .collect::<Vec<_>>()
127 .join(" ");
128 self.push(EditorAction::Message(text));
129 }
130 "insert" => self.push(EditorAction::Insert(arg_str(&args, 0, name, span)?)),
131 "insert_at" => {
132 let at = arg_usize(&args, 0, name, span)?;
133 let text = arg_str(&args, 1, name, span)?;
134 self.push(EditorAction::InsertAt { at, text });
135 }
136 "delete" => {
137 let start = arg_usize(&args, 0, name, span)?;
138 let end = arg_usize(&args, 1, name, span)?;
139 self.push(EditorAction::DeleteRange { start, end });
140 }
141 "delete_selection" => self.push(EditorAction::DeleteSelection),
142 "backspace" => self.push(EditorAction::Backspace),
143 "delete_forward" => self.push(EditorAction::DeleteForward),
144 "newline" => self.push(EditorAction::InsertNewline),
145 "set_cursor" => {
146 let at = arg_usize(&args, 0, name, span)?;
147 self.push(EditorAction::SetCursor(at));
148 }
149 "select" => {
150 let anchor = arg_usize(&args, 0, name, span)?;
151 let head = arg_usize(&args, 1, name, span)?;
152 self.push(EditorAction::Select { anchor, head });
153 }
154 "select_all" => self.push(EditorAction::SelectAll),
155 "move_caret" => {
156 let dir = arg_str(&args, 0, name, span)?;
157 let extend = args.get(1).map(Value::is_truthy).unwrap_or(false);
158 match EditorAction::movement(&dir, extend) {
159 Some(action) => self.push(action),
160 None => self.push(EditorAction::Message(format!("unknown move: {dir}"))),
161 }
162 }
163 "undo" => self.push(EditorAction::Undo),
164 "redo" => self.push(EditorAction::Redo),
165 "save" => self.push(EditorAction::Save),
166 "format" => self.push(EditorAction::Format),
167 "set_language" => {
168 let lang = arg_str(&args, 0, name, span)?;
169 self.push(EditorAction::SetLanguage(lang));
170 }
171 "set_cursor_style" => {
172 let style = arg_str(&args, 0, name, span)?;
173 match CursorStyle::parse(&style) {
174 Some(style) => self.push(EditorAction::SetCursorStyle(style)),
175 None => self.push(EditorAction::Message(format!(
176 "unknown cursor style: {style}"
177 ))),
178 }
179 }
180 "set_theme" => {
181 let theme = arg_str(&args, 0, name, span)?;
182 self.push(EditorAction::SetTheme(theme));
183 }
184 "set_status" => {
185 let text = arg_str(&args, 0, name, span)?;
186 self.push(EditorAction::SetStatus(Some(text)));
187 }
188 "clear_status" => self.push(EditorAction::SetStatus(None)),
189 "define_theme" => {
190 let theme = arg_str(&args, 0, name, span)?;
191 let colors = match args.get(1) {
192 Some(Value::Map(map)) => {
193 let entries = map.borrow();
194 let mut colors = Vec::with_capacity(entries.len());
195 for (key, value) in entries.iter() {
196 match value.as_i64() {
197 Some(n) => colors.push((key.to_string(), (n as u32) & 0xFF_FF_FF)),
198 None => {
199 return Err(textwrite::Error::runtime(
200 format!(
201 "`define_theme` colors must be ints like 0xRRGGBB; `{key}` is {}",
202 value.type_name()
203 ),
204 span,
205 ))
206 }
207 }
208 }
209 colors
210 }
211 Some(other) => {
212 return Err(textwrite::Error::runtime(
213 format!(
214 "`define_theme` expects a color map for argument 2, found {}",
215 other.type_name()
216 ),
217 span,
218 ))
219 }
220 None => {
221 return Err(textwrite::Error::runtime(
222 "`define_theme` expects 2 argument(s)".to_string(),
223 span,
224 ))
225 }
226 };
227 self.themes.borrow_mut().insert(theme, colors);
228 }
229 "wait" => {
230 let ms = arg_usize(&args, 0, name, span)?;
231 self.push(EditorAction::Wait(ms as u64));
232 }
233 "command" => {
234 let title = arg_str(&args, 0, name, span)?;
235 let fn_name = arg_str(&args, 1, name, span)?;
236 self.register_command(title, String::new(), fn_name);
237 }
238 "command_with_desc" => {
239 let title = arg_str(&args, 0, name, span)?;
240 let description = arg_str(&args, 1, name, span)?;
241 let fn_name = arg_str(&args, 2, name, span)?;
242 self.register_command(title, description, fn_name);
243 }
244 "bind" => {
245 let key = arg_str(&args, 0, name, span)?;
246 let title = arg_str(&args, 1, name, span)?;
247 if let Some(spec) = KeySpec::parse(&key) {
248 self.keybindings.borrow_mut().push((spec, title));
249 } else {
250 self.push(EditorAction::Message(format!("unknown key: {key}")));
251 }
252 }
253 _ => {
254 return Err(textwrite::Error::runtime(
255 format!("unknown editor function `{name}`"),
256 span,
257 ))
258 }
259 }
260 Ok(Value::None)
261 }
262}
263
264impl EditorHost {
265 fn push(&mut self, action: EditorAction) {
266 self.queue.borrow_mut().push(action);
267 }
268
269 fn register_command(&mut self, title: String, description: String, fn_name: String) {
270 self.commands.borrow_mut().insert(
271 title.clone(),
272 CommandInfo {
273 title,
274 description,
275 fn_name,
276 },
277 );
278 }
279}
280
281pub struct ScriptHost {
286 interp: textwrite::Interpreter,
287 queue: Queue,
288 commands: Commands,
289 keybindings: Keybinds,
290 themes: Themes,
291 sources: Vec<(String, String)>,
292 base_dir: Option<PathBuf>,
294 pub errors: Vec<String>,
296}
297
298impl Default for ScriptHost {
299 fn default() -> Self {
300 Self::new()
301 }
302}
303
304impl ScriptHost {
305 pub fn new() -> Self {
307 let queue: Queue = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
308 let commands: Commands =
309 std::rc::Rc::new(std::cell::RefCell::new(std::collections::BTreeMap::new()));
310 let keybindings: Keybinds = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
311 let themes: Themes = std::rc::Rc::new(std::cell::RefCell::new(BTreeMap::new()));
312
313 let interp = make_interpreter(&queue, &commands, &keybindings, &themes);
314 Self {
315 interp,
316 queue,
317 commands,
318 keybindings,
319 themes,
320 sources: Vec::new(),
321 base_dir: None,
322 errors: Vec::new(),
323 }
324 }
325
326 pub fn set_module_dir(&mut self, dir: impl Into<PathBuf>) {
329 self.base_dir = Some(dir.into());
330 if let Some(dir) = self.base_dir.clone() {
331 self.interp.set_module_base(dir);
332 }
333 }
334
335 pub fn add_script(&mut self, name: &str, source: &str) {
337 self.sources.retain(|(n, _)| n != name);
338 self.sources.push((name.to_string(), source.to_string()));
339 self.reload();
340 }
341
342 pub fn load_dir(&mut self, dir: &std::path::Path) {
344 self.base_dir = Some(dir.to_path_buf());
345 let mut entries: Vec<std::path::PathBuf> = match std::fs::read_dir(dir) {
346 Ok(rd) => rd
347 .filter_map(|e| e.ok())
348 .map(|e| e.path())
349 .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("tw"))
350 .collect(),
351 Err(_) => return,
352 };
353 entries.sort();
354 for path in entries {
355 match std::fs::read_to_string(&path) {
356 Ok(source) => {
357 let name = path
358 .file_name()
359 .map(|n| n.to_string_lossy().into_owned())
360 .unwrap_or_else(|| path.display().to_string());
361 self.add_script(&name, &source);
362 }
363 Err(e) => self.errors.push(format!("{}: {e}", path.display())),
364 }
365 }
366 }
367
368 fn reload(&mut self) {
369 self.errors.clear();
370 self.commands.borrow_mut().clear();
371 self.keybindings.borrow_mut().clear();
372 self.themes.borrow_mut().clear();
373 self.queue.borrow_mut().clear();
374 self.interp =
378 make_interpreter(&self.queue, &self.commands, &self.keybindings, &self.themes);
379 if let Some(dir) = self.base_dir.clone() {
380 self.interp.set_module_base(dir);
381 }
382 self.install_context(&EditorContext::default());
383
384 let combined = self
385 .sources
386 .iter()
387 .map(|(_, src)| src.as_str())
388 .collect::<Vec<_>>()
389 .join("\n");
390 if let Err(e) = self.interp.run(&combined) {
391 self.errors.push(format!("error loading scripts: {e}"));
392 }
393 self.queue.borrow_mut().clear();
394 }
395
396 fn install_context(&mut self, ctx: &EditorContext) {
398 let set = |interp: &mut Interpreter, name: &str, v: Value| interp.set_global(name, v);
399 set(&mut self.interp, "cursor", Value::Int(ctx.cursor as i64));
400 set(
401 &mut self.interp,
402 "selection_start",
403 Value::Int(ctx.selection_start as i64),
404 );
405 set(
406 &mut self.interp,
407 "selection_end",
408 Value::Int(ctx.selection_end as i64),
409 );
410 set(
411 &mut self.interp,
412 "has_selection",
413 Value::Bool(ctx.has_selection),
414 );
415 set(
416 &mut self.interp,
417 "selected_text",
418 Value::str(ctx.selected_text.clone()),
419 );
420 set(&mut self.interp, "line", Value::Int(ctx.line as i64));
421 set(&mut self.interp, "col", Value::Int(ctx.col as i64));
422 set(&mut self.interp, "doc_len", Value::Int(ctx.doc_len as i64));
423 set(
424 &mut self.interp,
425 "line_count",
426 Value::Int(ctx.line_count as i64),
427 );
428 set(
429 &mut self.interp,
430 "file_name",
431 Value::str(ctx.file_name.clone()),
432 );
433 set(
434 &mut self.interp,
435 "language",
436 Value::str(ctx.language.clone()),
437 );
438 set(&mut self.interp, "theme", Value::str(ctx.theme.clone()));
439 set(
440 &mut self.interp,
441 "document_text",
442 Value::str(ctx.doc_text.clone()),
443 );
444 }
445
446 pub fn commands(&self) -> Vec<CommandInfo> {
448 self.commands.borrow().values().cloned().collect()
449 }
450
451 pub fn command_titles(&self) -> Vec<String> {
453 self.commands.borrow().keys().cloned().collect()
454 }
455
456 pub fn keybindings(&self) -> Vec<(KeySpec, String)> {
458 self.keybindings.borrow().clone()
459 }
460
461 pub fn themes(&self) -> Vec<(String, Vec<(String, u32)>)> {
463 self.themes
464 .borrow()
465 .iter()
466 .map(|(name, colors)| (name.clone(), colors.clone()))
467 .collect()
468 }
469
470 pub fn theme_names(&self) -> Vec<String> {
472 self.themes.borrow().keys().cloned().collect()
473 }
474
475 pub fn lookup_key(&self, key: &KeySpec) -> Option<String> {
477 self.keybindings
478 .borrow()
479 .iter()
480 .find(|(k, _)| k == key)
481 .map(|(_, title)| title.clone())
482 }
483
484 pub fn has_command(&self, title: &str) -> bool {
486 self.commands.borrow().contains_key(title)
487 }
488
489 pub fn run_command(&mut self, title: &str, ctx: &EditorContext) -> Vec<EditorAction> {
491 let Some(info) = self.commands.borrow().get(title).cloned() else {
492 return Vec::new();
493 };
494 self.install_context(ctx);
495 self.queue.borrow_mut().clear();
496 if let Err(e) = self.interp.eval(&format!("{}()", info.fn_name)) {
497 self.errors.push(format!("{title}: {e}"));
498 }
499 std::mem::take(&mut *self.queue.borrow_mut())
500 }
501
502 pub fn eval(&mut self, source: &str, ctx: &EditorContext) -> textwrite::Result<Value> {
507 self.install_context(ctx);
508 self.queue.borrow_mut().clear();
509 self.interp.eval(source)
510 }
511
512 pub fn take_actions(&self) -> Vec<EditorAction> {
514 std::mem::take(&mut *self.queue.borrow_mut())
515 }
516
517 pub fn has_hook(&self, name: &str) -> bool {
519 matches!(self.interp.get_global(name), Some(Value::Func(_)))
520 }
521
522 pub fn run_hook(&mut self, name: &str, ctx: &EditorContext) -> Vec<EditorAction> {
528 if !self.has_hook(name) {
529 return Vec::new();
530 }
531 self.install_context(ctx);
532 self.queue.borrow_mut().clear();
533 if let Err(e) = self.interp.eval(&format!("{name}()")) {
534 self.errors.push(format!("hook {name}: {e}"));
535 return vec![EditorAction::Message(format!("{name} failed: {e}"))];
536 }
537 std::mem::take(&mut *self.queue.borrow_mut())
538 }
539
540 pub fn compile_file(&mut self, path: &str) -> textwrite::Result<()> {
543 let (source, dir) = read_script(path)?;
544 self.interp.set_module_base(dir);
545 self.interp.compile(&source)
546 }
547
548 pub fn run_file(
551 &mut self,
552 path: &str,
553 ctx: &EditorContext,
554 ) -> textwrite::Result<Vec<EditorAction>> {
555 let (source, dir) = read_script(path)?;
556 self.interp.set_module_base(dir);
557 self.install_context(ctx);
558 self.queue.borrow_mut().clear();
559 self.interp.run(&source)?;
560 Ok(std::mem::take(&mut *self.queue.borrow_mut()))
561 }
562}
563
564fn read_script(path: &str) -> textwrite::Result<(String, PathBuf)> {
567 let trimmed = path.trim();
568 let mut path = PathBuf::from(trimmed);
569 if !path.exists() && path.extension().is_none() {
570 path = path.with_extension("tw");
571 }
572 let source = std::fs::read_to_string(&path).map_err(|e| {
573 textwrite::Error::runtime(
574 format!("cannot read {}: {e}", path.display()),
575 textwrite::Span::zero(),
576 )
577 })?;
578 let dir = match path.parent() {
579 Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
580 _ => PathBuf::from("."),
581 };
582 Ok((source, dir))
583}
584
585fn make_interpreter(
587 queue: &Queue,
588 commands: &Commands,
589 keybindings: &Keybinds,
590 themes: &Themes,
591) -> Interpreter {
592 let host = EditorHost {
593 queue: queue.clone(),
594 commands: commands.clone(),
595 keybindings: keybindings.clone(),
596 themes: themes.clone(),
597 };
598 let mut interp = Interpreter::with_output(Box::new(std::io::sink()));
599 interp.set_host(Rc::new(RefCell::new(host)));
600 interp.register_module("fast-text/automator", AUTOMATOR_SRC);
601 interp.register_module("automator", AUTOMATOR_SRC);
602 interp
603}
604
605fn arg_str(
606 args: &[Value],
607 i: usize,
608 name: &str,
609 span: textwrite::Span,
610) -> textwrite::Result<String> {
611 match args.get(i) {
612 Some(Value::Str(s)) => Ok(s.to_string()),
613 Some(other) => Err(textwrite::Error::runtime(
614 format!(
615 "`{name}` expects a string for argument {}, found {}",
616 i + 1,
617 other.type_name()
618 ),
619 span,
620 )),
621 None => Err(textwrite::Error::runtime(
622 format!("`{name}` expects {} argument(s)", i + 1),
623 span,
624 )),
625 }
626}
627
628fn arg_usize(
629 args: &[Value],
630 i: usize,
631 name: &str,
632 span: textwrite::Span,
633) -> textwrite::Result<usize> {
634 match args.get(i).and_then(Value::as_i64) {
635 Some(n) if n >= 0 => Ok(n as usize),
636 Some(n) => Err(textwrite::Error::runtime(
637 format!("`{name}` expects a non-negative index, found {n}"),
638 span,
639 )),
640 None => Err(textwrite::Error::runtime(
641 format!("`{name}` expects {} argument(s)", i + 1),
642 span,
643 )),
644 }
645}
646
647#[cfg(test)]
648mod tests {
649 use super::*;
650
651 #[test]
652 fn detects_and_runs_lifecycle_hooks() {
653 let mut host = ScriptHost::new();
654 host.add_script(
655 "hooks.tw",
656 r#"
657 fn on_buffer_open() {
658 message("opened")
659 }
660 fn on_buffer_save() {
661 format()
662 }
663 "#,
664 );
665 assert!(host.errors.is_empty(), "{:?}", host.errors);
666 assert!(host.has_hook("on_buffer_open"));
667 assert!(host.has_hook("on_buffer_save"));
668 assert!(!host.has_hook("on_buffer_close"));
669 assert_eq!(
670 host.run_hook("on_buffer_open", &EditorContext::default()),
671 vec![EditorAction::Message("opened".to_string())]
672 );
673 assert_eq!(
674 host.run_hook("on_buffer_save", &EditorContext::default()),
675 vec![EditorAction::Format]
676 );
677 assert!(host
678 .run_hook("on_buffer_close", &EditorContext::default())
679 .is_empty());
680 }
681}