Execute files easily with nvim
| 1 | local data = require("execute.cache") |
| 2 | local M = {} |
| 3 | |
| 4 | local cwd = vim.fn.getcwd() |
| 5 | |
| 6 | |
| 7 | data.target.path = vim.fn.expand("%") |
| 8 | data.target.ft = vim.bo.filetype |
| 9 | end |
| 10 | |
| 11 | ---Runs a given path and filetype |
| 12 | ---@param path string absolute path |
| 13 | ---@param ft string file type |
| 14 | |
| 15 | vim.cmd("w") |
| 16 | local relative_path = "./" .. path:gsub("^" .. vim.pesc(cwd), "") |
| 17 | local basename = path:match("([^/]+)$") |
| 18 | local stem = basename:match("^(.+)%.") or basename |
| 19 | if ft == "python" then |
| 20 | vim.cmd("terminal python " .. relative_path) |
| 21 | elseif ft == "rust" then |
| 22 | if path:find("examples/") then |
| 23 | vim.cmd("terminal cargo run --example " .. stem) |
| 24 | elseif data.target.path:find("bin/") then |
| 25 | vim.cmd("terminal cargo run --bin " .. stem) |
| 26 | elseif data.target.path:find("test/") then |
| 27 | vim.cmd("terminal cargo test") |
| 28 | else |
| 29 | vim.cmd("terminal cargo run") |
| 30 | end |
| 31 | elseif ft == "lua" then |
| 32 | vim.cmd("luafile " .. path) |
| 33 | else |
| 34 | vim.cmd("terminal chmod +x " .. relative_path .. "&& " .. relative_path) |
| 35 | end |
| 36 | end |
| 37 | |
| 38 | ---Runs the current marked file |
| 39 | |
| 40 | M.run(data.target.path, data.target.ft) |
| 41 | end |
| 42 | |
| 43 | ---Runs the current file without marking it |
| 44 | |
| 45 | M.run(vim.fn.expand("%"), vim.bo.filetype) |
| 46 | end |
| 47 | |
| 48 | end |
| 49 | |
| 50 | return M |