Save and run at the same time in Vim

前端 未结 12 530
悲哀的现实
悲哀的现实 2021-01-30 03:13

I do a lot of Python quick simulation stuff and I\'m constantly saving (:w) and then running (:!!). Is there a way to combine these actions?

Maybe a "save and run&qu

12条回答
  •  后悔当初
    2021-01-30 03:39

    In Vim, you could simply redirect any range of your current buffer to an external command (be it Bash, the Python interpreter, or you own Python script).

    # Redirect whole buffer to 'python'
    :%w !python
    

    Suppose your current buffer contains two lines as below,

    import numpy as np
    print np.arange(12).reshape(3, 4)
    

    then :%w !python will run it, be it saved or not. And print something like below on your terminal,

    [[ 0  1  2  3]
     [ 4  5  6  7]
     [ 8  9 10 11]]
    

    Of course, you could make something persistent, for example, some keymaps.

    nnoremap  :.w !python
    vnoremap  :w !python
    

    The first one, run the current line. The second one, run the visual selection, via the Python interpreter.

    #!! Be careful, in Vim ':w!python' and ':.w !python' are very different. The
    first write (create or overwrite) a file named 'python' with contents of
    current buffer, and the second redirects the selected cmdline range (here dot .,
    which mean current line) to external command (here 'python').
    

    For cmdline range, see

    :h cmdline-ranges
    

    Not the below one, which concerning normal command, not cmdline one.

    :h command-range
    

    This was inspired by Execute current line in Bash from Vim.

提交回复
热议问题