1

I'm writing a function that uses Vim's Python API. The function runs while I'm in insert mode and I want this function to set my mode to normal mode.

I tried a few things, like for example, this

import vim
vim.eval(r'execute normal! \<esc>')

But unfortunately this doesn't work. I just get the error VIM:E121: Undefined variable: execute. Any help would be greatly appreciated.

Also, generally speaking, I'd really like to know more about the vim module. It doesn't have a __file__ attribute, assuming that's because it's compiled. Is there source code anywhere I can view? Or generally where the file lives so that I can try importing it and running help(vim) without having to re-run my functions in a Vim environment. If you have any information on that, in particular, it'd help a lot. Thanks!

3

Your question is more of a vim issue than a python one. vim.eval is basically the same as vim's eval( which evaluates an expression and does not run a command like execute. Additionally, your syntax for execute is wrong since the command takes a string: execute "normal! \<esc>" would be more correct. You could instead use the expression form execute():

vim.eval(r'execute("normal! \<esc>")')

However, since you ultimately want to use a command I would recommend just using vim.command(cmd) instead. vim already has a command for leaving insert mode, stopinsert.

 vim.command('stopinsert')

The documentation for the methods in the built-in vim module can be found using :help python which brings up doc/if_pyth.txt.

  • I see a have a lot to learn. Thanks for your help. For some reason neither command works in the context that I need it in (the UltiSnips plugin) but I did a quick test using vimscript which calls Python and it works. – ColinKennedy Jan 27 '18 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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