How do I prevent a leading newline in Vim when using :r!date and other shell commands?

0

Most of the time when I'm inserting a date, I'm trying to do it in the middle of a line. By default, it looks like the :r! flavor of insertion always puts the result on a new line. This makes some sense to me since most shell commands output a newline before showing a command result, and this is certainly preferable in a terminal. In the case of shelling out from Vim for a tiny command like date +%x, this is not my preferred behavior. How do I work around this?

Seltzer

Posted 2018-10-23T18:59:10.770

Reputation: 105

Answers

2

In insert mode, you can use Ctrl-R= to insert a expression at the current cursor position.

You could use e.g. the system() function, unfortunately this only solves half of the problem, since the output of system() will always have at least the final linebreak added to it, so it will break the line after the input. For a solution to how to avoid those final linebreaks in the system() case, have a look at this answer at vi.stackexchange of mine.

(so you could e.g. use Ctrl-R=systemlist('date')[0]Enter).


An alternative way for inserting the date at the current cursor position would be to use Ctrl-R=strftime('%c')Enter

Ctrl-R= is using the expression register to insert content. You can find out more with the :help i_ctrl-r command, or view the documentation on appspot.

Christian Brabandt

Posted 2018-10-23T18:59:10.770

Reputation: 1 196

0

I believe that the problem is not so much that shell commands typically end with a newline, but that read is a line-oriented command (i.e., an ex command).  It was present in the original version of ed, in the 1970s, before :r!command existed, and the common use case was to read a bunch of lines (e.g., a C function or a paragraph of text) from one file into another.  Most users would have wanted to insert them as new, separate lines most of the time.

You can check / demonstrate this by doing :r!printf Tuesday.  Even though the printf Tuesday command doesn’t write a newline (since you didn’t specify \n), you will get Tuesday on a line all by itself.

Perhaps the simplest workaround is to do i Enter Esc (to break the current line), - or k to move back up a line, then do your :r!command, and then J to Join the lines back together.  If this is something you do very often, it might be beneficial to map a macro for it.

Disclosure: I know vi reasonably well, but there’s lots of stuff in vim that I haven’t learned.  There might be an easier way to do this in vim.

Scott

Posted 2018-10-23T18:59:10.770

Reputation: 17 653