Alabhya Jindal

Custom Run Command in Neovim

I use Neovim to quickly open and modify files. I also use it to write small single-file programs.

Here’s a snippet from my init.lua config file. It creates a Run function that runs the current file. This function can then be invoked by a user defined shortcut, <Leader>r in our case.

-- Run the current file
vim.api.nvim_create_user_command(
  'Run',
  function()
    local filetype = vim.bo.filetype
    local interpreters = {
      python = 'python',
      javascript = 'node',
      ruby = 'ruby',
      haskell = 'runghc'
    }

    local interpreter = interpreters[filetype]

    if not interpreter then
      print('File type not supported')
      return
    end

    local file = vim.fn.expand('%:p')
    local filename = vim.fn.fnamemodify(file, ':t')
    local command = string.format('!%s ./%s', interpreter, filename)

    vim.cmd('silent w')
    vim.cmd(command)
  end,
  {}
)

-- Shortcut to trigger file run
vim.api.nvim_set_keymap('n', '<Leader>r', ':Run<CR>', { silent = true })

I wanted to modify how a file is run, depending on its location. This was surprisingly easy to do:

-- Pipe the input if solving algorithms
if file == vim.fn.expand('/home/alabhya/Desktop/algorithms/main.py') then
    vim.cmd('!cat input.txt | python main.py')
    return
end

Now when I’m solving coding challenges, I can press <Leader>r and run the file with the input piped in. Amazing!