7

In my .vimrc and my vim plugin UltiSnips I've got a lot of code that looks like that

:py << EOF
print("Hi")
EOF

Now, I want to check if python3 is compiled into Vim via has("python3") and then use :py3 instead of :py. Keeping the python code compatible between python 2 and 3 is not the issue - the issue is to tell vim to use :py3 if is available and :py otherwise.

Has someone a good idea?

SirVer
  • 1,397
  • 1
  • 16
  • 15
  • The obvious way would be to have a `if has("python3")` each time you want to use `:py3`. – romainl Jan 10 '12 at 19:50
  • Or maybe a wrapper function that takes the Python code you want to run as argument and executes a single `if`. – romainl Jan 10 '12 at 19:57
  • Your first comment is the obvious solution which I chose for now. The second comment is what I wanted to do but I know of no way to make a user defined function accept the heredoc (<< EOF) syntax. Do you? – SirVer Jan 11 '12 at 08:02

2 Answers2

6

You can take advantage on the fact that user defined commands in vim are simply place-in-patter-and-eval statements, and write:

if has("python3")
    command! -nargs=1 Py py3 <args>
else
    command! -nargs=1 Py py <args>
endif

Then you can use :Py to run python commands the same way as you regularly use :py or :py3.

Idan Arye
  • 12,402
  • 5
  • 49
  • 68
  • No, this does not work with the << EOF syntax that the python command understands. However, it is slightly nicer than my let solution. – SirVer Jan 25 '12 at 17:39
  • Works perfectly fine for me: http://imageshack.us/photo/my-images/832/52433408.png/ – Idan Arye Jan 25 '12 at 19:06
  • Indeed... It works for me too. I must have done something wrong when I tried that myself. Maybe the -nargs=1 argument. Thanks for your persistence in helping me! I one-up your solution but I will still keep the one I mentioned below because it seems to be a bit obstrusive to define a new command for internal use only and because I have reports that exec solution works across various systems. – SirVer Jan 26 '12 at 10:20
0

I have solved this now in an ugly fashion by only checking ONCE for python3 or python, then setting a variable

let g:_uspy=":py "   or ":py3 "

and then throwing the << EOF syntax overboard and instead call each line of python via

exec g:_uspy "print('Hello')"

which seems to work okaish. See the full solution in this git blob:

https://github.com/SirVer/ultisnips/blob/da49b4b7c4669bc462a98c9abc71b42d43d408bc/plugin/UltiSnips.vim

SirVer
  • 1,397
  • 1
  • 16
  • 15