3

Is there a clean alias that I can put in my vimrc that will run the current file using python if there is a python extension?

At the moment I have nnoremap <leader>r :!%:p<Enter> as suggested in this question (when I hit \+r it runs the open file). It works great for bash files, where the convention is to add a shebang line and make the file executable, but for python files it obviously exits 1.

As a workaround I have added a new command - command PyBang :call append(0, "#!/usr/bin/env python") - that adds a python shebang to the top of the file. The problem is that this is not really convention for .py files and making them all executable seems like a lot of effort for some reason.

So I am struggling to write an alias that will run :!%:p<Enter> if there is no extension and prepend python if there is a .py extension on the file in the buffer.

Any ideas are really appreciated.

Callum
  • 65
  • 1
  • 7
  • 1
    Is there a reason you can't create a vim command for running python programs? `:! python3 %` for instance. Or is your question about how to detect what filetype your file is and then choose what to run? – wxz Jun 29 '21 at 13:08
  • I would essentially like one 'run' command, so I don't have to remember which command to use for each language is used for the file I am working on. But, your solution is what I am working with for now so thanks for that! As it is easier than shabanging everything – Callum Jun 29 '21 at 13:31
  • Use something like [this](https://stackoverflow.com/q/5998374/13020139) to help you get the `if else` statements working. So you can have "if bash, do this; if python do this;" – wxz Jun 29 '21 at 13:52
  • 1
    @wxz This is exactly what I was looking for. After looking at it I may have found the answer [here](https://vi.stackexchange.com/questions/24898/autocmd-with-a-python-file-not-working) – Callum Jun 29 '21 at 14:02
  • @wxz, feel free to put it in as an answer and I will happily accept it. I am now using `autocmd filetype python nnoremap r :!python %:p` which seems to be working but still needs testing. Cheers – Callum Jun 29 '21 at 14:10

1 Answers1

3

The easiest way to do this is to use vim's exclamation mark to run shell commands. For instance,

: ! python3 % will run the current file % with python3 outside of vim, in whatever shell you're in.

You can use this in combination with vim scripting to create your own shortcuts for this command.

To combine this with your current bash function, you will need conditional logic in your vim function to detect filetypes (see here and here for how to work with filetypes and their detection)

wxz
  • 2,254
  • 1
  • 10
  • 31