diff --git a/home/.config/nvim/ftplugin/java.lua b/home/.config/nvim/ftplugin/java.lua index 698e54e..2c143c9 100644 --- a/home/.config/nvim/ftplugin/java.lua +++ b/home/.config/nvim/ftplugin/java.lua @@ -42,3 +42,45 @@ require("jdtls").start_or_attach({ }) require("plugins.mason").map_keys() + +function RunJava() + local function show_output(output) + vim.cmd("split") + vim.cmd("enew") + vim.fn.append(0, output) + --vim.cmd("1d") -- Remove the empty first line + vim.bo[0].modifiable = false + end + + local filename = vim.fn.expand("%") -- Get the current file name + local class_name = vim.fn.fnamemodify(filename, ":r") -- Extract the class name + local compile_cmd = "javac " .. filename + local run_cmd = "java " .. class_name + + -- Create a temporary file to capture the compile output + local temp_file = vim.fn.tempname() + + -- Run the compilation command and save the output to the temporary file + local compile_exit_code = vim.fn.system(compile_cmd .. " > " .. temp_file .. " 2>&1") + + -- Check the exit code of the compile command + if compile_exit_code == 0 then + -- Compilation was successful, run the Java program + show_output(vim.fn.systemlist(run_cmd)) + else + -- Compilation failed, display the error output from the temporary file + show_output(vim.fn.readfile(temp_file)) + end + + -- Clean up the temporary file and class file + vim.fn.delete(temp_file) + vim.fn.delete(vim.fn.expand("%:p:h") .. "/" .. class_name .. ".class") +end + +-- Define a VimScript command to execute the Lua function +vim.api.nvim_exec( + [[ + command! RunJava lua RunJava() +]], + false +)