|
| 1 | +local M = {} |
| 2 | +local vim = vim |
| 3 | + |
| 4 | +local config = { |
| 5 | + enabled = true, |
| 6 | + handlers = { |
| 7 | + { ext = "java", action = "javac [name].[ext] && java [name]" }, |
| 8 | + { ext = "py", action = "python3 [name].[ext]" }, |
| 9 | + { ext = "go", action = "go run [name].[ext]" }, |
| 10 | + { ext = "js", action = "node [name].[ext]" }, |
| 11 | + { ext = "rs", action = "cargo run [name].[ext]" }, |
| 12 | + }, |
| 13 | + split_cmd = "botright split | resize -10" |
| 14 | +} |
| 15 | + |
| 16 | +local function random_char() |
| 17 | + local characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*)(-=][\';\"/.,_+}{|:?><" |
| 18 | + local random_index = math.random(1, string.len(characters)) |
| 19 | + local picked_character = string.sub(characters, random_index, random_index) |
| 20 | + return picked_character |
| 21 | +end |
| 22 | + |
| 23 | +function M.run() |
| 24 | + if not config.enabled then return end |
| 25 | + |
| 26 | + local dir, name, ext = vim.fn.expand("%:p:h"), vim.fn.expand("%:t:r"), vim.fn.expand("%:e") |
| 27 | + for _, h in ipairs(config.handlers) do |
| 28 | + if h.ext == ext then |
| 29 | + local cmd = h.action:gsub("%[name%]", name):gsub("%[ext%]", ext) |
| 30 | + |
| 31 | + -- open a split to show output |
| 32 | + vim.cmd(config.split_cmd) |
| 33 | + vim.cmd("enew") |
| 34 | + local buf = vim.api.nvim_get_current_buf() |
| 35 | + vim.api.nvim_buf_set_name(buf, "crunner: " .. name .. "." .. ext .. "_" .. random_char() .. random_char()) |
| 36 | + vim.api.nvim_buf_set_option(buf, "buftype", "nofile") |
| 37 | + vim.api.nvim_buf_set_option(buf, "bufhidden", "hide") -- hide on close |
| 38 | + vim.api.nvim_buf_set_option(buf, "buflisted", false) -- not in tabline |
| 39 | + vim.api.nvim_buf_set_option(buf, "swapfile", false) |
| 40 | + vim.api.nvim_buf_set_option(buf, "filetype", "crunner") |
| 41 | + |
| 42 | + -- run command asynchronously |
| 43 | + vim.fn.jobstart("cd " .. dir .. " &&" .. cmd, { |
| 44 | + stdout_buffered = true, |
| 45 | + stderr_buffered = true, |
| 46 | + on_stdout = function(_, data) |
| 47 | + if data then vim.api.nvim_buf_set_lines(buf, -1, -1, false, data) end |
| 48 | + end, |
| 49 | + on_stderr = function(_, data) |
| 50 | + if data then vim.api.nvim_buf_set_lines(buf, -1, -1, false, data) end |
| 51 | + end, |
| 52 | + }) |
| 53 | + |
| 54 | + return |
| 55 | + end |
| 56 | + end |
| 57 | + |
| 58 | + print("No handler configured for extension: " .. ext) |
| 59 | +end |
| 60 | + |
| 61 | +function M.setup(opts) |
| 62 | + if opts then config = vim.tbl_deep_extend("force", config, opts) end |
| 63 | +end |
| 64 | + |
| 65 | +return M |
0 commit comments