1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
function Compile_and_run_cpp()
local filename = vim.fn.expand("%:p")
local basename = vim.fn.expand("%:r")
local output_file = "output.txt" -- Change this to the desired output file name
local input_file = "input.txt" -- Change this to the desired input file name
-- Check if current file is a valid C++ or C file
local valid_extensions = {"cpp", "c"}
local valid_file = false
for _, ext in ipairs(valid_extensions) do
if filename:match("%." .. ext .. "$") then
valid_file = true
break
end
end
-- Exit function if file is not valid
if not valid_file then
vim.api.nvim_err_writeln("Not a valid C++ or C file.")
return
end
-- Check if input file exists, create if it doesn't
local input_fd = io.open(input_file, "a+") -- Open in append mode to create if it doesn't exist
if input_fd == nil then
vim.api.nvim_err_writeln("Failed to open or create input file: " ..
input_file)
return
end
input_fd:close()
-- Check if output file exists, create if it doesn't
local output_fd = io.open(output_file, "a+") -- Open in append mode to create if it doesn't exist
if output_fd == nil then
vim.api.nvim_err_writeln("Failed to open or create output file: " ..
output_file)
return
end
output_fd:close()
-- Check if input file buffer is already open
local input_bufnr = vim.fn.bufnr(input_file)
if input_bufnr == -1 then
-- Open input file in a new split at top right side
vim.cmd("vsp " .. input_file)
else
-- Switch to existing buffer for input file
vim.cmd(input_bufnr .. "wincmd w")
end
-- Check if input file buffer is already open
local output_butnr = vim.fn.bufnr(output_file)
if output_butnr == -1 then
-- Open input file in a new split at top right side
vim.cmd("split " .. output_file)
else
-- Switch to existing buffer for input file
vim.cmd(input_bufnr .. "wincmd w")
end
vim.cmd("vertical resize 40%")
local file = vim.fn.bufnr(filename)
vim.cmd(file .. "wincmd w")
-- Compile and run C++ file
local compile_cmd = string.format("g++ %s -o %s && ./%s < %s > %s",
filename, basename, basename, input_file,
output_file)
vim.cmd("silent w") -- Save the current file
vim.cmd("silent !clear") -- Clear the terminal
vim.cmd("silent !" .. compile_cmd) -- Execute the compile and run command
-- Open the output file in a new buffer
-- vim.cmd("edit " .. output_file)
end
vim.api.nvim_set_keymap("n", "mb", ":lua Compile_and_run_cpp()<CR>",
{noremap = true, silent = true})
|