Vim Tips Wiki
(Need to use 'call' to call setline, remove my comment since code was updated to include it)
Line 39: Line 39:
   
 
== Comments ==
 
== Comments ==
  +
  +
How about,
  +
<pre>
  +
:redir => myvariable
  +
:!date
  +
:redir END
  +
:echo myvariable
  +
</pre>

Revision as of 14:10, 12 February 2010

No `backwhacks` in Vim

This sample function for a .vim script file illustrates the mechanism I worked out for capture of the output of external system commands (run by the system shell). It appends the output of the command (assuming the command is successfully executed) to the current line.

A shell of any sh-like type (a unix shell) has the backquotes syntax available as an easy means to capture the output of a command. Left-leaning grave accents, backticks, backwhacks, etc. are other names for this punctuation. Vim scripting lacks this facility and so we might use the kind of approach illustrated below.

Please do make yourself familiar with the vim strftime() function before simply copying this exact example into your working scripts. That function may do all you need and is certainly a better choice than calling out to a system command.

func! GimmeADate(format)
    let utilpath = '/bin/'
    let fmt = (a:format ? a:format : '+%A m%m/d%d/y%Y %R UTC')
    let SPECIALCHARS = 1
    let TemporalFormat = shellescape(fmt, SPECIALCHARS)
    let DStamp = substitute( system( utilpath .'date -u '. TemporalFormat )
             \ , '[\]\|[[:cntrl:]]', '', 'g')
    " Moves user's cursor: exec 'normal A'.DStamp
    " Does not move user's cursor:
    call setline(line('.'), getline('.') . DStamp)
endfu

" Suggested mapping:
" This thing is 'CTRL-&'
nnoremap ^_ :call GimmeADate('')<CR>

May it be useful. Comments welcomed. --Perlsomian 06:19, February 9, 2010 (UTC)

--Perlsomian 19:42, February 11, 2010 (UTC) Thank you, JamesVega, suggestion was taken.

Comments

How about,

:redir => myvariable
:!date
:redir END
:echo myvariable