3

I want to be able to insert the results of -

date +"%y-%m-%d %H:%M:00"

at the cursor in vim. How would you run the above command in BASH but get the results and insert them directly at the cursor?

Right now I am running the command as -

:r!date +"\%y-\%m-\%d \%H:\%M:\%S"

But this inserts the contents on a new line. What is the correct method to evaluate a bash script AT the cursor?

Current Issue -
Date:
15-07-02 14:36:24

Expected Result -
Date: 15-07-02 14:36:24
  • Using visual selector with ! also does not work because it replaces the whole line and doesn't just insert on a single character. – ILikeTurtles Jul 2 '15 at 21:43
5

The built-in strftime() does exactly what you want:

<C-r>=strftime('%y-%m-%d %H:%M:%S')

To turn that into a mapping:

inoremap <expr> <key> strftime('%y-%m-%d %H:%M:%S')

You can of course use whatever external command you need but it is important to keep in mind that the output of Unix commands usually ends with a newline character that needs to be removed in one way or another. The general solution is to strip that newline from the output before inserting it:

<C-r>=substitute(system("date +'%y-%m-%d %H:%M:%S'"), "\n", "", "")

which is an ideal client for a mapping.

Reference:

:help strftime()
:help system()
:help substitute()
:help i_ctrl-r
:help "=
:help :map-expression
  • I got it working using C-f Thanks a ton! inoremap <expr> <C-f> strftime('%y-%m-%d %H:%M:%S') – ILikeTurtles Jul 2 '15 at 22:08
  • 1
    I love using abbreviations for this! If you set :ab idt <c-r>=strftime('%y-%m-%d %H:%M:%S')<cr> then you can simply type "idt" while in insert mode. – Vitor Jul 8 '15 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.