Execute Selected Lines of (Optionally) Marked-Up Python Code in a Vim Buffer

There are a number of solutions for executing Python code in your active buffer in Vim.
All of these expect the buffer lines to be well-formatted Python code, with correct indentation.
Many times, however, I am working on program or other documentation (in, for example reStructuredTex or Markdown format), and the code fragments that I want to execute have extra indentation or line leaders.

For example, a reStructuredText buffer might look like:

        How to Wuzzle the Wookie
        -------------------------

        The :func:`foo` function can be used to wuzzle the wookie by::

            >>> import bar
            >>> fuzzlewuzzle = bar.foo("the wookie")
            >>> for fuzz in fuzzlewuzzle:
            ...     if fuzz is bar.buzz():
            ...          bar.wuzzle(fuzz)

While a Markdown buffer might have:

        ## How to Wuzzle the Wookie

        The ``foo`` function can be used to to wuzzle the wookie by:

            import bar
            fuzzlewuzzle = bar.foo("the wookie")
            for fuzz in fuzzlewuzzle:
                if fuzz is bar.buzz():
                    bar.wuzzle(fuzz)

Simply passing the code lines in the above text to be evaluated in Python will not do: the extra decorators and indents required for embedding the code in the main document need to be dealt with.

Furthermore, many of the solutions that I could find (a) require Vim to have been built with Python enabled, and (b) use Vim’s internal Python to evaluate the lines.
The first seems like an unnecessary constraint, considering that native VimScript can handle the pre-processing quite well, while the second is problematical if there are external packages in your default system Python that the internal Vim Python does not have or if you prefer using the default system Python for whatever other reason.
Here I describe a pure-VimScript solution that handles the execution of optionally-marked-up visually-selected line ranges in your default system Python, and either shows the results in the command window or inserts the results in the current buffer.

Installation and Usage

Include the following code in your “~/.vimrc” or otherwise source it into your current Vim session.
Then select some lines of Python code and type “:EvalPy” to evaluate the lines in the default Python session and show the results in the command window, or “:EvalPy!” to evaluate the lines in the default Python session and insert the results in the current buffer.

Leave a Reply

Your email address will not be published. Required fields are marked *