Vim Tips Wiki
Advertisement

After weeks of manually updating compositeArtifacts.xml and compositeContent.xml files' timestamps using `date +%s000`, I finally snapped and went looking for a better way.

(Aside: these files are used in p2 repositories (aka Eclipse Update Sites) to provide references to other sites an allow compositing sites together; the timestamp is used by the p2 engine in Eclipse to know if the file is fresh/stale. All that's irrelevant to the tip below.)

So, rather than shell out from vim and run date +%s000, then copy and paste that new timestamp into a :%s/oldstamp/newstamp/ replacement, this script does it with three keystrokes and no mouse-based copy/paste.

" Add this to your ~/.vimrc file, then type '\ts' to update timestamp to current.
fun! ReplaceTimestamp()
  let tstamp = strftime("%s000")
  exe ":%s#<property name='p2.timestamp' value='[0-9]\\+'/>#<property name='p2.timestamp' value='" . tstamp . "'/>#g"
  echo "New time: " . tstamp
endfun
nnoremap <Leader>ts :call ReplaceTimestamp()<CR>

If you wanted something more generic, this would work too:

" Add this to your ~/.vimrc file, then type '\ts' to update timestamp to current.
fun! ReplaceTimestamp()
  let tstamp = strftime("%s000")
  exe ":%s#'[0-9]\\+'#'" . tstamp . "'#g"
  echo "New time: " . tstamp
endfun
nnoremap <Leader>ts :call ReplaceTimestamp()<CR>

In either case, this looks for a string of digits, and replaces them with the current timestamp in milliseconds past the epoch.

Comments

Thanks for the tip. Later I will insert a "new tip" header, and we will get around to discussing the tip at 201104, but here are some initial thoughts.

Relevant tips are:

The tip needs a couple of things:

  • Briefly explain what it does to someone who has never seen 'p2.timestamp' (readers shouldn't have to spend time decoding what the tip does).
  • Provide a short example (probably just one line?) of text that would be changed.
  • Quickly state what strftime('%s000') is, and mention that '%s' needs a Unix-based system (I think).

In the code, you don't need execute because substitute can replace with an expression. This should work:

  %s#<property name='p2.timestamp' value='\zs\d\+\ze'/>#\=tstamp#g

JohnBeckett 04:11, April 20, 2011 (UTC)

Advertisement