1

I've changed my code a million times and can't get it right.

I want to compile the file I have open with whatever its name is minus the .c that comes after and I want to do it on a second terminal to see any errors in the code and fix them.

Right now, I'm getting an error on line 24, "undefined variable: gcc" which is one of the many errors I've gotten. Moving around code and using different ways to pass the command to the vim.cmd() function seems to give various errors, from saying that fileName is an undefined value or nil or an assortment of other errors.

local function get_file_name(file)
    return file:match("^.+/(.+)$")
end

local function finalCommand()
    local currentFile = vim.fn.expand("%:p")
    local FileName = get_file_name(currentFile)
    local FileName2 = string.sub(FileName, 1, -3)
    local x = "!gcc -o ".. FileName2 .." ".. FileName

    return x
end

local function gcc()
    vim.cmd("vsplit | terminal")
    local command = ":wincmd l"
    vim.cmd(command)
    local command2 = finalCommand()
    vim.cmd("call jobsend(b:terminal_job_id, ".. command2 ..")")
    local command3 = ':wincmd h'
    vim.cmd(command3)
end

vim.keymap.set("n", "<leader>gcc", function ()
    return gcc()
end)
4
  • May be could you explain what is not yet working with your actual code. It will be useful to be sure we reproduce your problem. Commented Sep 30, 2023 at 6:11
  • 2
    Just want to make sure you already know that :make foo will do 99% of what you want. It automatically finds foo.c, compiles it, and presents any errors in a window inside vim.
    – pipe
    Commented Sep 30, 2023 at 12:00
  • @pipe i will try this as soon as possible, thank you for the feedback
    – Baguaguy
    Commented Sep 30, 2023 at 13:11
  • 2
    Yeah, checkout :help :make, the surrounding document, and :help 30.1
    – D. Ben Knoble
    Commented Sep 30, 2023 at 17:57

1 Answer 1

1

I do believe that using :make is a better option but in case you would like to understand what was wrong with your code here is an adaptation of your code:

function finalCommand()
    local x = "gcc -o ".. vim.fn.expand("%:r") .." ".. vim.fn.expand("%:n")

    return x
end

function gcc()
    local command2 = finalCommand()
    vim.cmd("vsplit | terminal")
    vim.cmd("call jobsend(b:terminal_job_id, '" .. command2 .. "')")
    local command3 = ':wincmd h'
    vim.cmd(command3)
end

vim.keymap.set("n", "<leader>gcc", function ()
    gcc()
end)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.