2

Aim

The aim is to update a number in a file if one writes to a file using Vim. If the date resides in the file the date part should be left unchanged, but the last digit needs to be incremented by one.


Attempts

Attempt 1

/home/user/.vimrc

autocmd BufWritePre /tmp/test :%s/\d\{10}/\=strftime("%Y%m%d00")/

/temp/test

4014122100

writing the file results in:

2014122100

"/tmp/test" 2L, 29C written

Attempt 2

/home/user/.vimrc

autocmd BufWritePre /tmp/test :%s/\d\{10}/\=strftime("%Y%m%d00")/
autocmd BufWritePre /tmp/test :%s/\d\{10}/\=submatch(0)+1

/temp/test

4014122100

writing the file results in:

2014122101

"/tmp/test" 2L, 29C written

Attempt 3

function! ChangeDateIfApplicableAndIncrementLastDigit()
  if !match(getline(1,"$"),strftime("%Y%m%d")) >= 0
    autocmd BufWritePre /tmp/test :%s/\d\{10}/\=strftime("%Y%m%d00")/
  endif
  autocmd BufWritePre /tmp/test :%s/\d\{10}/\=submatch(0)+1
endfunction

autocmd BufWriteCmd /tmp/test call ChangeDateIfApplicableAndIncrementLastDigit()

Expected results

Number of writesExpected result
1                          2014122101     
2                          2014122102     
3                          2014122103     


Current outcome

Number of writesCurrent outcome
1                          2014122101       
2                          2014122101       
3                          2014122101       

1 Answer 1

0

So, if I get you right, your first and second attempts show that the basic mechanism works, but you're struggling with putting everything together, right?!

The problem is with the BufWriteCmd; that hook is supposed to write the buffer contents on its own. The netrw plugin uses those to implement remote filesystem access, for instance. You just need to define a single BufWritePre hook for your function, and then act depending on whether you've found a current date:

function! ChangeDateIfApplicableAndIncrementLastDigit()
  if !match(getline(1,"$"),strftime("%Y%m%d")) >= 0
    %s/\d\{10}/\=strftime("%Y%m%d00")/
  else
    %s/\d\{10}/\=submatch(0)+1
  endif
endfunction

autocmd BufWritePre /tmp/test call ChangeDateIfApplicableAndIncrementLastDigit()
1
  • Thank you for posting an answer. 1234567890 results in 2014122200, but this digit persists once subsequent writes have been executed while the expectation was 2014122201
    – 030
    Dec 22, 2014 at 19:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .