Home > Enterprise >  How to create custom vim command with shell command
How to create custom vim command with shell command

Time:07-21

I often create new files with the name of today's date. So, I would like to make this a command that calls the shell date command. The date command I use is:

date  %Y-%m-%d-%B%d).md

I tried to call this same shell command from within Vim with this custom command in my .vimrc:

command Post e !date  %Y-%m-%d-%B%d.md

But that doesn't work because % means the current filename in Vim and the desired filename isn't created.

CodePudding user response:

You can use the built-in :help strftime() function instead of the date command. This makes the command a little bit more portable and, since the function is evaluated before :edit is executed, you don't get the unwanted side-effects of :help cmdline-special.

:command! Post execute 'edit ' .. strftime('%Y-%m-%d-%B%d') .. '.md'

CodePudding user response:

I agree that @romainl idea of using builtin functions is a better approach than just delegating in the shell. For the sake of displaying how would it be to open (:edit) a file name resulting of a shell command would be something like this:

:command! Post execute 'let file=system("date  \\%Y-\\%m-\\%d-\\%B\\%d.md") | normal! :e ' .. file .. '^M'
  • You need to quote the '%' with double \.
  • You need to invoke the shell command before calling the :edit command, if you do something like: execute "normal! :e !date %Y-%m-%d-%B%d.md" the date command will not be evaluate but just verboten pasted to :edit.
  • Related