use std::cell::RefCell; use std::fs; use std::path::Path; use std::rc::Rc; use crate::command::{Command, CommandAction}; use crate::exit_status::ExitStatus; use crate::EditorState; #[cfg(feature = "editor")] use crate::run_repl_command as exec_command; #[cfg(not(feature = "editor"))] use crate::run_sued_command as exec_command; use dirs::config_dir; use mlua::Lua; const DEFAULT_CONFIG: &str = r#"-- sued Lua initialisation file -- Write whatever Lua code you want in here. -- sued:eager-loading-enable -- Delete the above line if you want to defer Lua initialisation to the first -- ~eval or ~script command. -- Sample function to print sued's current buffer contents. -- To run in sued, `~eval print_buffer` function print_buffer() for index, line in ipairs(sued.buffer.contents) do print(index .. "│" .. line) end end -- Sample function to count the lines of a file. -- To run in sued, `~eval count_lines(sued.buffer.file_path)` function count_lines(filename) local file = io.open(filename, "r") if not file then print("Error: Could not open file " .. filename) return 0 end local line_count = 0 for line in file:lines() do line_count = line_count + 1 end file:close() return line_count end -- This'll be loaded as soon as the Lua environment is active. -- If eager loading is enabled, you'll see this as soon as sued starts. print("" .. _VERSION:lower() .. " bindings loaded") "#; /// Initialises the Lua state into a Lua environment. /// /// **If `features=config`,** this is eagerly loaded, instantiation performed on /// editor startup ONLY if `init.lua` contains the directive `-- sued:eager-loading-enable`. /// /// **If not,** this is lazy-loaded, and instantiation is deferred on /// [evaluate_lua]'s first call in the session. pub fn init(state: &mut EditorState, check_eager: bool) -> ExitStatus { let init = if cfg!(feature = "config") { let config_dir = config_dir().unwrap(); let config_path = config_dir.join("sued"); let config_file = config_path.join("init.lua"); if !config_path.exists() { fs::create_dir_all(&config_path).expect("failed to create config directory"); } if !config_file.exists() { fs::write(&config_file, DEFAULT_CONFIG).expect("failed to write default config"); } config_file } else { Path::new("lua").join("main.lua") }; let init_file = fs::read_to_string(&init).unwrap(); if check_eager { let mut found_directive = false; for line in init_file.lines() { if line == "-- sued:eager-loading-enable" { found_directive = true; break; } } if !found_directive { return ExitStatus::Failure("Eager loading directive not found".to_string()); } } ExitStatus::Success(evaluate_lua(init_file, state, false)) } fn setup_state( state: &mut EditorState, shared_state: Rc>, lua: &Lua, ) -> Result<(), String> { let globals = lua.globals(); let run_command = match lua .create_function(move |_lua, args: Vec| { let mut state = shared_state.borrow_mut(); let arguments = args.iter().map(|s| s.as_str()).collect(); let status = exec_command(arguments, &mut state); match status { ExitStatus::Success(out) => Ok(out), ExitStatus::Failure(msg) => Err(mlua::prelude::LuaError::RuntimeError(msg)), } }) .map_err(|e| e.to_string()) { Ok(fun) => fun, Err(e) => return Err(format!("failed to create run_command command: {}", e)), }; let state_table = match lua.create_table().map_err(|e| e.to_string()) { Ok(table) => table, Err(e) => return Err(format!("failed to create state table: {}", e)), }; let buffer_table = match lua.create_table().map_err(|e| e.to_string()) { Ok(table) => table, Err(e) => return Err(format!("failed to create buffer table: {}", e)), }; if let Err(e) = buffer_table.set("contents", state.buffer.contents.clone()) { return Err(format!("failed to set buffer.contents: {}", e)); } if let Err(e) = buffer_table.set("file_path", state.buffer.file_path.clone()) { return Err(format!("failed to set buffer.file_path: {}", e)); } if let Err(e) = state_table.set("buffer", buffer_table) { return Err(format!("failed to set state global: {}", e)); } if let Err(e) = state_table.set("command", run_command) { return Err(format!("failed to set sued_cmd: {}", e)); } if let Err(e) = globals.set("sued", state_table) { return Err(format!("failed to set state global: {}", e)); } Ok(()) } /// Evaluates the given Lua code and returns the result as a string. /// /// The state's buffer contents are exposed as a global variable named `buffer.contents`. /// The state's `run_sued_command` function is also exposed as `run_sued_command`. /// If `feedback` is true, the return value is also printed to stdout. /// /// After running the script, the buffer contents are synchronised back to the editor /// state if they were modified. pub fn evaluate_lua(code: String, state: &mut EditorState, feedback: bool) -> String { if state.lua.is_none() { state.lua = Some(Lua::new()); } let lua = state.lua.as_ref().unwrap().clone(); let shared_state = std::rc::Rc::new(std::cell::RefCell::new(EditorState::default())); let shared_state_c = shared_state.clone(); if let Err(e) = setup_state(state, shared_state_c, &lua) { return e; } std::mem::swap(&mut *shared_state.borrow_mut(), state); let mut is_error: bool = false; let result = match lua.load(&code).eval::() { Ok(value) => match value { mlua::Value::Nil => "nil".to_string(), mlua::Value::Boolean(b) => b.to_string(), mlua::Value::Integer(n) => n.to_string(), mlua::Value::Number(n) => n.to_string(), mlua::Value::String(s) => match s.to_str() { Ok(s) => s.to_string(), Err(_) => format!("invalid string {:?}", s), }, mlua::Value::Table(t) => { let table = t.pairs::(); let table_output = table.map(|result| match result { Ok((_k, v)) => v, Err(e) => format!("invalid table entry: {}", e), }); format!("[{}]", table_output.collect::>().join(", ")) } mlua::Value::Error(e) => { is_error = true; format!("error: {}", e) } _ => { let return_type = value.type_name(); format!("unsupported return type: {}", return_type) } }, Err(e) => e.to_string(), }; std::mem::swap(state, &mut *shared_state.borrow_mut()); match lua.globals().get::("sued") { Ok(sued_table) => match sued_table.get::("buffer") { Ok(buffer_table) => { match buffer_table.get::>("contents") { Ok(new_contents) => { if new_contents != state.buffer.contents { println!("modifications synchronised"); state.buffer.contents = new_contents; } } Err(e) => println!("failed to get buffer contents from Lua: {}", e), } if let Ok(new_path) = buffer_table.get::("file_path") { if Some(new_path.clone()) != state.buffer.file_path { println!("file path updated from Lua"); state.buffer.file_path = Some(new_path); } } } Err(e) => println!("couldn't read back buffer table: {}", e), }, Err(e) => println!("failed to get sued table from Lua: {}", e), } if !feedback { if is_error { return format!("error: {result}"); } return "eval finished".to_string(); } format!("=> {result}") } pub fn eval() -> Command { Command { name: "eval", arguments: vec!["lua_code"], description: "evaluate lua", documentation: "this command evaluates lua code from the arguments \ and displays the result, if any\n\ the buffer contents are added as a lua global, `buffer.contents` \ and like with ~runhere, any modifications made to the buffer \ are synchronised back", action: CommandAction::new(|args: Vec<&str>, state: &mut EditorState| { if args.len() < 2 { return format!( "eval what? try {}eval [lua_code]\n\ if you want to run the buffer as lua, use {}script this instead\n\ or if you want to run a lua file, {}script [filename]", state.prefix, state.prefix, state.prefix ); } let code = args[1..].join(" "); if state.lua.is_none() { state.lua = Some(Lua::new()); init(state, false); } evaluate_lua(code, state, true) }), ..Command::default() } } pub fn script() -> Command { Command { name: "script", arguments: vec!["filename"], description: "run a lua script", documentation: "this command imports and runs a lua script at filename\n\ if `this` is specified instead of the filename, it'll \ treat the buffer contents as a lua script\n\ like ~eval, `buffer.contents` is added as a lua global and \ any modifications made to the buffer are synchronised back\n\ unlike ~eval, the return value is not printed unless \ it's an error", action: CommandAction::new(|args: Vec<&str>, state: &mut EditorState| { if args.len() < 2 { return format!( "what script? try {}script [filename] or {}script this", state.prefix, state.prefix ); } let filename = args[1..].join(" "); let code = if filename == "this" { state.buffer.contents.join("\n") } else { match std::fs::read_to_string(&filename) { Ok(contents) => contents, Err(e) => { match e.kind() { std::io::ErrorKind::NotFound => { return format!("{} doesn't exist\n\ if you want to run a lua expression, use {}eval [expr] instead", &filename, state.prefix) }, _ => { return format!("failed to read file: {}", e) } } } } }; if state.lua.is_none() { state.lua = Some(Lua::new()); init(state, false); } evaluate_lua(code, state, true) }), ..Command::default() } }