Use Python to change to normal mode

2018-01-25 20:18:32

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! \')

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!

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. A

  • 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! \" would be more correct. You could instead use the expression form execute():

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

    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.

    2018-01-25 21:43:25