Execute current line in Bash from Vim

后端 未结 7 1890
误落风尘
误落风尘 2020-12-12 11:58

This question is similar to Vim: execute current file?, but instead of executing the current file I want to execute only the current line.

Is this possible?<

7条回答
  •  悲&欢浪女
    2020-12-12 12:40

    This could be a comment if I can comment.

    Concerning redirect/pipe lines of current buffer in Vim to external command, inspired by Daan Bakker's great answer, I wrote I answer here (Save and run at the same time in Vim), on an question concerning running a Python script (current buffer).

    Beside running the whole buffer, how to run a range of line via an external command is demonstrated.

    To save time, I just copy it below.

    #####################
    

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

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

    Suppose your current buffer contains the 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 runs the current line. The second one runs the visual selection, via the Python interpreter.

    #!! Be careful, in Vim ':w!python' and ':.w !python' are very different, the
    first writes (creates or overwrites) a file named 'python' with thew contents of
    the current buffer. The second redirects the selected cmdline range (here dot .,
    which mean current line) to an 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.

提交回复
热议问题