Search code examples
pythonlinuxvimscriptingtty

"scripting" vim using python with greater granularity


I'm attempting to write a python script that can automate vim, but the python vim interface doesn't give me enough power to do everything I need. I want to communicate with vim as if my script were a tty (able to issue "visual mode" instructions etc). As far as vim is concerned, my script is a human running xterm (or whatever). Can this be done without building my own terminal emulator in python?


Solution

  • All non-vimscript interfaces are cursed: the only way to communicate with vim (unless you want to edit/get contents of a buffer which is available using buffer object) are execute (vim.command(string) in python) and eval (vim.eval(string) in python), both requiring serializing arguments. If you want to just start visual mode use

    vim.command("normal! V")
    

    or

    vim.eval("feedkeys('V')")
    

    . But if you want, for example, to return some value to a caller function you will have to use

    import json
    # Some code that puts result into variable r
    # This won't work if r contains non-unicode strings,
    # you will have to write your own serializer in this case.
    # As far as I know, it will also fail if some characters in the string
    # can be represented only using surrogate pairs.
    vim.command("let reply=".json.dumps(r))
    # Now in the caller function variable l:reply is defined