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 "set_language",
73 "set_cursor_style",
74 "set_theme",
75 "define_theme",
76 "wait",
77 "command",
78 "command_with_desc",
79 "bind",
80];
81
82struct EditorHost {
85 queue: Queue,
86 commands: Commands,
87 keybindings: Keybinds,
88 themes: Themes,
89}
90
91impl Host for EditorHost {
92 fn functions(&self) -> &'static [&'static str] {
93 HOST_FUNCTIONS
94 }
95
96 fn call(
97 &mut self,
98 name: &str,
99 args: Vec<Value>,
100 span: textwrite::Span,
101 ) -> textwrite::Result<Value> {
102 match name {
103 "print" => {
104 let text = args
105 .iter()
106 .map(Value::to_display)
107 .collect::<Vec<_>>()
108 .join(" ");
109 self.push(EditorAction::Message(text));
110 }
111 "write" => {
112 let text = args
113 .iter()
114 .map(Value::to_display)
115 .collect::<Vec<_>>()
116 .join("");
117 self.push(EditorAction::Message(text));
118 }
119 "message" => {
120 let text = args
121 .iter()
122 .map(Value::to_display)
123 .collect::<Vec<_>>()
124 .join(" ");
125 self.push(EditorAction::Message(text));
126 }
127 "insert" => self.push(EditorAction::Insert(arg_str(&args, 0, name, span)?)),
128 "insert_at" => {
129 let at = arg_usize(&args, 0, name, span)?;
130 let text = arg_str(&args, 1, name, span)?;
131 self.push(EditorAction::InsertAt { at, text });
132 }
133 "delete" => {
134 let start = arg_usize(&args, 0, name, span)?;
135 let end = arg_usize(&args, 1, name, span)?;
136 self.push(EditorAction::DeleteRange { start, end });
137 }
138 "delete_selection" => self.push(EditorAction::DeleteSelection),
139 "backspace" => self.push(EditorAction::Backspace),
140 "delete_forward" => self.push(EditorAction::DeleteForward),
141 "newline" => self.push(EditorAction::InsertNewline),
142 "set_cursor" => {
143 let at = arg_usize(&args, 0, name, span)?;
144 self.push(EditorAction::SetCursor(at));
145 }
146 "select" => {
147 let anchor = arg_usize(&args, 0, name, span)?;
148 let head = arg_usize(&args, 1, name, span)?;
149 self.push(EditorAction::Select { anchor, head });
150 }
151 "select_all" => self.push(EditorAction::SelectAll),
152 "move_caret" => {
153 let dir = arg_str(&args, 0, name, span)?;
154 let extend = args.get(1).map(Value::is_truthy).unwrap_or(false);
155 match EditorAction::movement(&dir, extend) {
156 Some(action) => self.push(action),
157 None => self.push(EditorAction::Message(format!("unknown move: {dir}"))),
158 }
159 }
160 "undo" => self.push(EditorAction::Undo),
161 "redo" => self.push(EditorAction::Redo),
162 "save" => self.push(EditorAction::Save),
163 "set_language" => {
164 let lang = arg_str(&args, 0, name, span)?;
165 self.push(EditorAction::SetLanguage(lang));
166 }
167 "set_cursor_style" => {
168 let style = arg_str(&args, 0, name, span)?;
169 match CursorStyle::parse(&style) {
170 Some(style) => self.push(EditorAction::SetCursorStyle(style)),
171 None => self.push(EditorAction::Message(format!(
172 "unknown cursor style: {style}"
173 ))),
174 }
175 }
176 "set_theme" => {
177 let theme = arg_str(&args, 0, name, span)?;
178 self.push(EditorAction::SetTheme(theme));
179 }
180 "define_theme" => {
181 let theme = arg_str(&args, 0, name, span)?;
182 let colors = match args.get(1) {
183 Some(Value::Map(map)) => {
184 let entries = map.borrow();
185 let mut colors = Vec::with_capacity(entries.len());
186 for (key, value) in entries.iter() {
187 match value.as_i64() {
188 Some(n) => colors.push((key.to_string(), (n as u32) & 0xFF_FF_FF)),
189 None => {
190 return Err(textwrite::Error::runtime(
191 format!(
192 "`define_theme` colors must be ints like 0xRRGGBB; `{key}` is {}",
193 value.type_name()
194 ),
195 span,
196 ))
197 }
198 }
199 }
200 colors
201 }
202 Some(other) => {
203 return Err(textwrite::Error::runtime(
204 format!(
205 "`define_theme` expects a color map for argument 2, found {}",
206 other.type_name()
207 ),
208 span,
209 ))
210 }
211 None => {
212 return Err(textwrite::Error::runtime(
213 "`define_theme` expects 2 argument(s)".to_string(),
214 span,
215 ))
216 }
217 };
218 self.themes.borrow_mut().insert(theme, colors);
219 }
220 "wait" => {
221 let ms = arg_usize(&args, 0, name, span)?;
222 self.push(EditorAction::Wait(ms as u64));
223 }
224 "command" => {
225 let title = arg_str(&args, 0, name, span)?;
226 let fn_name = arg_str(&args, 1, name, span)?;
227 self.register_command(title, String::new(), fn_name);
228 }
229 "command_with_desc" => {
230 let title = arg_str(&args, 0, name, span)?;
231 let description = arg_str(&args, 1, name, span)?;
232 let fn_name = arg_str(&args, 2, name, span)?;
233 self.register_command(title, description, fn_name);
234 }
235 "bind" => {
236 let key = arg_str(&args, 0, name, span)?;
237 let title = arg_str(&args, 1, name, span)?;
238 if let Some(spec) = KeySpec::parse(&key) {
239 self.keybindings.borrow_mut().push((spec, title));
240 } else {
241 self.push(EditorAction::Message(format!("unknown key: {key}")));
242 }
243 }
244 _ => {
245 return Err(textwrite::Error::runtime(
246 format!("unknown editor function `{name}`"),
247 span,
248 ))
249 }
250 }
251 Ok(Value::None)
252 }
253}
254
255impl EditorHost {
256 fn push(&mut self, action: EditorAction) {
257 self.queue.borrow_mut().push(action);
258 }
259
260 fn register_command(&mut self, title: String, description: String, fn_name: String) {
261 self.commands.borrow_mut().insert(
262 title.clone(),
263 CommandInfo {
264 title,
265 description,
266 fn_name,
267 },
268 );
269 }
270}
271
272pub struct ScriptHost {
277 interp: textwrite::Interpreter,
278 queue: Queue,
279 commands: Commands,
280 keybindings: Keybinds,
281 themes: Themes,
282 sources: Vec<(String, String)>,
283 base_dir: Option<PathBuf>,
285 pub errors: Vec<String>,
287}
288
289impl Default for ScriptHost {
290 fn default() -> Self {
291 Self::new()
292 }
293}
294
295impl ScriptHost {
296 pub fn new() -> Self {
298 let queue: Queue = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
299 let commands: Commands =
300 std::rc::Rc::new(std::cell::RefCell::new(std::collections::BTreeMap::new()));
301 let keybindings: Keybinds = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
302 let themes: Themes = std::rc::Rc::new(std::cell::RefCell::new(BTreeMap::new()));
303
304 let interp = make_interpreter(&queue, &commands, &keybindings, &themes);
305 Self {
306 interp,
307 queue,
308 commands,
309 keybindings,
310 themes,
311 sources: Vec::new(),
312 base_dir: None,
313 errors: Vec::new(),
314 }
315 }
316
317 pub fn set_module_dir(&mut self, dir: impl Into<PathBuf>) {
320 self.base_dir = Some(dir.into());
321 if let Some(dir) = self.base_dir.clone() {
322 self.interp.set_module_base(dir);
323 }
324 }
325
326 pub fn add_script(&mut self, name: &str, source: &str) {
328 self.sources.retain(|(n, _)| n != name);
329 self.sources.push((name.to_string(), source.to_string()));
330 self.reload();
331 }
332
333 pub fn load_dir(&mut self, dir: &std::path::Path) {
335 self.base_dir = Some(dir.to_path_buf());
336 let mut entries: Vec<std::path::PathBuf> = match std::fs::read_dir(dir) {
337 Ok(rd) => rd
338 .filter_map(|e| e.ok())
339 .map(|e| e.path())
340 .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("tw"))
341 .collect(),
342 Err(_) => return,
343 };
344 entries.sort();
345 for path in entries {
346 match std::fs::read_to_string(&path) {
347 Ok(source) => {
348 let name = path
349 .file_name()
350 .map(|n| n.to_string_lossy().into_owned())
351 .unwrap_or_else(|| path.display().to_string());
352 self.add_script(&name, &source);
353 }
354 Err(e) => self.errors.push(format!("{}: {e}", path.display())),
355 }
356 }
357 }
358
359 fn reload(&mut self) {
360 self.errors.clear();
361 self.commands.borrow_mut().clear();
362 self.keybindings.borrow_mut().clear();
363 self.themes.borrow_mut().clear();
364 self.queue.borrow_mut().clear();
365 self.interp =
369 make_interpreter(&self.queue, &self.commands, &self.keybindings, &self.themes);
370 if let Some(dir) = self.base_dir.clone() {
371 self.interp.set_module_base(dir);
372 }
373 self.install_context(&EditorContext::default());
374
375 let combined = self
376 .sources
377 .iter()
378 .map(|(_, src)| src.as_str())
379 .collect::<Vec<_>>()
380 .join("\n");
381 if let Err(e) = self.interp.run(&combined) {
382 self.errors.push(format!("error loading scripts: {e}"));
383 }
384 self.queue.borrow_mut().clear();
385 }
386
387 fn install_context(&mut self, ctx: &EditorContext) {
389 let set = |interp: &mut Interpreter, name: &str, v: Value| interp.set_global(name, v);
390 set(&mut self.interp, "cursor", Value::Int(ctx.cursor as i64));
391 set(
392 &mut self.interp,
393 "selection_start",
394 Value::Int(ctx.selection_start as i64),
395 );
396 set(
397 &mut self.interp,
398 "selection_end",
399 Value::Int(ctx.selection_end as i64),
400 );
401 set(
402 &mut self.interp,
403 "has_selection",
404 Value::Bool(ctx.has_selection),
405 );
406 set(
407 &mut self.interp,
408 "selected_text",
409 Value::str(ctx.selected_text.clone()),
410 );
411 set(&mut self.interp, "line", Value::Int(ctx.line as i64));
412 set(&mut self.interp, "col", Value::Int(ctx.col as i64));
413 set(&mut self.interp, "doc_len", Value::Int(ctx.doc_len as i64));
414 set(
415 &mut self.interp,
416 "line_count",
417 Value::Int(ctx.line_count as i64),
418 );
419 set(
420 &mut self.interp,
421 "file_name",
422 Value::str(ctx.file_name.clone()),
423 );
424 set(
425 &mut self.interp,
426 "language",
427 Value::str(ctx.language.clone()),
428 );
429 set(&mut self.interp, "theme", Value::str(ctx.theme.clone()));
430 set(
431 &mut self.interp,
432 "document_text",
433 Value::str(ctx.doc_text.clone()),
434 );
435 }
436
437 pub fn commands(&self) -> Vec<CommandInfo> {
439 self.commands.borrow().values().cloned().collect()
440 }
441
442 pub fn command_titles(&self) -> Vec<String> {
444 self.commands.borrow().keys().cloned().collect()
445 }
446
447 pub fn keybindings(&self) -> Vec<(KeySpec, String)> {
449 self.keybindings.borrow().clone()
450 }
451
452 pub fn themes(&self) -> Vec<(String, Vec<(String, u32)>)> {
454 self.themes
455 .borrow()
456 .iter()
457 .map(|(name, colors)| (name.clone(), colors.clone()))
458 .collect()
459 }
460
461 pub fn theme_names(&self) -> Vec<String> {
463 self.themes.borrow().keys().cloned().collect()
464 }
465
466 pub fn lookup_key(&self, key: &KeySpec) -> Option<String> {
468 self.keybindings
469 .borrow()
470 .iter()
471 .find(|(k, _)| k == key)
472 .map(|(_, title)| title.clone())
473 }
474
475 pub fn has_command(&self, title: &str) -> bool {
477 self.commands.borrow().contains_key(title)
478 }
479
480 pub fn run_command(&mut self, title: &str, ctx: &EditorContext) -> Vec<EditorAction> {
482 let Some(info) = self.commands.borrow().get(title).cloned() else {
483 return Vec::new();
484 };
485 self.install_context(ctx);
486 self.queue.borrow_mut().clear();
487 if let Err(e) = self.interp.eval(&format!("{}()", info.fn_name)) {
488 self.errors.push(format!("{title}: {e}"));
489 }
490 std::mem::take(&mut *self.queue.borrow_mut())
491 }
492
493 pub fn eval(&mut self, source: &str, ctx: &EditorContext) -> textwrite::Result<Value> {
498 self.install_context(ctx);
499 self.queue.borrow_mut().clear();
500 self.interp.eval(source)
501 }
502
503 pub fn take_actions(&self) -> Vec<EditorAction> {
505 std::mem::take(&mut *self.queue.borrow_mut())
506 }
507
508 pub fn compile_file(&mut self, path: &str) -> textwrite::Result<()> {
511 let (source, dir) = read_script(path)?;
512 self.interp.set_module_base(dir);
513 self.interp.compile(&source)
514 }
515
516 pub fn run_file(
519 &mut self,
520 path: &str,
521 ctx: &EditorContext,
522 ) -> textwrite::Result<Vec<EditorAction>> {
523 let (source, dir) = read_script(path)?;
524 self.interp.set_module_base(dir);
525 self.install_context(ctx);
526 self.queue.borrow_mut().clear();
527 self.interp.run(&source)?;
528 Ok(std::mem::take(&mut *self.queue.borrow_mut()))
529 }
530}
531
532fn read_script(path: &str) -> textwrite::Result<(String, PathBuf)> {
535 let trimmed = path.trim();
536 let mut path = PathBuf::from(trimmed);
537 if !path.exists() && path.extension().is_none() {
538 path = path.with_extension("tw");
539 }
540 let source = std::fs::read_to_string(&path).map_err(|e| {
541 textwrite::Error::runtime(
542 format!("cannot read {}: {e}", path.display()),
543 textwrite::Span::zero(),
544 )
545 })?;
546 let dir = match path.parent() {
547 Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
548 _ => PathBuf::from("."),
549 };
550 Ok((source, dir))
551}
552
553fn make_interpreter(
555 queue: &Queue,
556 commands: &Commands,
557 keybindings: &Keybinds,
558 themes: &Themes,
559) -> Interpreter {
560 let host = EditorHost {
561 queue: queue.clone(),
562 commands: commands.clone(),
563 keybindings: keybindings.clone(),
564 themes: themes.clone(),
565 };
566 let mut interp = Interpreter::with_output(Box::new(std::io::sink()));
567 interp.set_host(Rc::new(RefCell::new(host)));
568 interp.register_module("fast-text/automator", AUTOMATOR_SRC);
569 interp.register_module("automator", AUTOMATOR_SRC);
570 interp
571}
572
573fn arg_str(
574 args: &[Value],
575 i: usize,
576 name: &str,
577 span: textwrite::Span,
578) -> textwrite::Result<String> {
579 match args.get(i) {
580 Some(Value::Str(s)) => Ok(s.to_string()),
581 Some(other) => Err(textwrite::Error::runtime(
582 format!(
583 "`{name}` expects a string for argument {}, found {}",
584 i + 1,
585 other.type_name()
586 ),
587 span,
588 )),
589 None => Err(textwrite::Error::runtime(
590 format!("`{name}` expects {} argument(s)", i + 1),
591 span,
592 )),
593 }
594}
595
596fn arg_usize(
597 args: &[Value],
598 i: usize,
599 name: &str,
600 span: textwrite::Span,
601) -> textwrite::Result<usize> {
602 match args.get(i).and_then(Value::as_i64) {
603 Some(n) if n >= 0 => Ok(n as usize),
604 Some(n) => Err(textwrite::Error::runtime(
605 format!("`{name}` expects a non-negative index, found {n}"),
606 span,
607 )),
608 None => Err(textwrite::Error::runtime(
609 format!("`{name}` expects {} argument(s)", i + 1),
610 span,
611 )),
612 }
613}