Search code examples
linuxvimabbreviation

Defining linux command inside vim abbreviations


I often use abbreviations when using vim editor. Now I want to use Linux commands when defining vim abbreviations inside /etc/vimrc.

I tried various things but none worked.

My use case:

Inside vim: When I type #! and enter "tab" key, Then the output should be:

   #! /usr/bin/env bash
   #Author: Dhimant
   #Date: Realtime date at which command is fired
   #Description:

I completed up to first two lines by using "cr" tag

ab #!   #!/usr/bin/env bash<cr>#author: Dhimant Thanki

But when using "date command", it is not working

ab #!   #!/usr/bin/env bash<cr>#author: Dhimant Thanki <cr>#Date: `date` <cr>#Task: (NOT WORKING)

So need help in completing this task. Any help is appreciated.


Solution

  • You can use <C-r>= to insert a Vim expression:

    iabbr xxx # Date: <C-r>=strftime('%c')<CR><CR># Second line
    

    Note the two <CR>s: one to end the expression, and one to insert a newline.

    I used strftime() here instead of the date shell command, as that's easier and will work on all platforms, but you can also use <C-r>=system('date')[:-2]<CR> if you prefer (the [:-2] is to remove trailing newline).

    See: :help abbreviations, :help c_<C-R>.