Insert output of a system command at the current location in vim

26,911

Solution 1

You can paste the contents of the clipboard buffer between characters with Ctrl-R * in insert mode (and a similar approach for other buffers). So if you can get the system command into a buffer, you should be set. (Source: https://stackoverflow.com/questions/1491135/paste-multi-line-string-into-gvim-at-cursor-position ).

:let @a=system("ls -l") will put the output of ls -l into register a. You can then paste it (in insert mode) with ^R-a.

Solution 2

:r !command 

will read the output from the command and insert it into the line under the current line. This is how vi is programmed you cannot change the behavior.

But say if you are in line number 3. If you try :r !date. It will insert the date value into line number 4.

If you want the date value to be appeared on line number 3, then you try :2r !date will insert the date value in line number 3.

Solution 3

Here is alternative way of pasting output from external command before the cursor:

:exe 'norm i' . system("ls -l")

or use expression register (:help @=):

"=system('ls -la')

then hit P. Or shorter way by:

<CTRL-R>=system('ls -la')<CR>

Solution 4

In addition to let and p, we can also employ vim's functions setreg() and put like so:

:call setreg('f',system("ls"))

:put f

Note, register f was chosen in this example simply for mnemonic representation for the word "files". There's nothing particularly special about it and you're free to choose your own register.

Share:
26,911

Related videos on Youtube

deshmukh
Author by

deshmukh

Updated on September 18, 2022

Comments

  • deshmukh
    deshmukh over 1 year

    In vim, when I use

    :r !ls somefilename

    it inserts output of that command on a new line below the current line.

    If I do

    let @a = system("ls")

    and later

    "ap

    it still inserts the output on a new line below the current line.

    Is there a way to make vim insert output at the current location?

  • deshmukh
    deshmukh over 11 years
    That inserts on a different line, but still on a line of its own. I want to insert it at the current location!
  • Bruno Bronosky
    Bruno Bronosky about 7 years
    Also, on most platforms the clipboard is synced with a register (usually *) so if you pipe your command output to your clipboard it will be in "* for you to use.
  • Jay
    Jay about 7 years
    This is the answer.
  • metasoarous
    metasoarous over 4 years
    Agreed! This should really be the correct answer, because it includes a more programmatic solution (with :exe) which can be included in commands.