nvim: compile/run code based on filetype in function from keymap using lua

I'm trying to map my F12 key to compile and run code in neovim using the term command. I've been able to get it to work for java files, but only if I opened nvim from the same location as the file I'm running. Otherwise I get an error like this:

Error: could not find or load main class CSC-101.Proj.4.Hangman
Caused by: Java.lang.NoClassDefFoundError: Hangman (wrong name: CSC-101/Proj/4/Hangman)

[process exited 1]

When I try with python, even when I run it from the same working directory I get nothing but:

[process exited 0]'

Which I don't understand because when I type ":term python3 %" in nvim, it works perfectly. Here is the function I'm using:

funcs.run_code = function()
    local filename = vim.fn.expand("%")
    local basename = vim.fn.expand("%:r")
    local filetype =
    local cmd = nil
    if filetype == "python" then
        cmd = "term: python3 "..filename
    elseif filetype == "java" then
        cmd = "term: javac "..filename.." && java "..basename
    if cmd then
        print("No interpreter or compiler defined for filetype: '"..filetype.."'")



  • vim.cmd pretty much executes the argument just like if you were typing it in the command bar (with an implicit preceding colon). It seems you’re executing “:term: python3” instead of “:term python3”. The terminal is trying to execute ": python3" and obviously failing. Remove the colon and you should be good.