Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333use 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) endend
-- 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_countend
-- 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<RefCell<EditorState>>, lua: &Lua,) -> Result<(), String> { let globals = lua.globals();
let run_command = match lua .create_function(move |_lua, args: Vec<String>| { 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::<mlua::Value>() { 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::<String, String>(); let table_output = table.map(|result| match result { Ok((_k, v)) => v, Err(e) => format!("invalid table entry: {}", e), }); format!("[{}]", table_output.collect::<Vec<String>>().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::<mlua::Table>("sued") { Ok(sued_table) => match sued_table.get::<mlua::Table>("buffer") { Ok(buffer_table) => { match buffer_table.get::<Vec<String>>("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::<String>("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() }}