Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update my cpp comments using BufWritePre

Tags:

vim

I'm putting some code in my .vimrc to automatically update the "Last Update" field on my .cpp and .h files documentation.

I've tried it for my .py files and it worked. The problem is searching the line that starts with the characters * Last Update. Here's what I have so far:

The comments in my cpp file

/**
 * @file  test.cpp
 * @author  John Doe
 * @version
 * @brief
 * @date
 *  Created:  21 mai 2019
 *  Last Update:
 */

and my .vimrc

autocmd BufWritePre *.h exe "%s/^ \*  Last Update:.*$/Last Update: " 
      \. strftime("%d %b %Y (%T)") . "/e"

This should update the comments to:

/**
 * @file  test.cpp
 * @author  John Doe
 * @version
 * @brief
 * @date
 *  Created:  21 mai 2019
 *  Last Update:  21 mai 2019 (21:15:48)
 */

But I got no changes at all.

Update: I have the same code in my header files (.h)

like image 229
Josivan Medeiros Avatar asked Sep 16 '25 02:09

Josivan Medeiros


1 Answers

Updated to work with .cpp and .h files

You need to add the following to your .vimrc or other file that gets sourced:

autocmd FileType cpp,h autocmd BufWritePre <buffer> :%s/^ \*  Last Update:.*$/\=printf(' *  Last Update: ') . strftime("%d %b %Y (%T)")/e

autocmd FileType cpp,h

  • makes sure, that it works only for .cpp or .h files

autocmd BufwritePre <buffer>

  • writes to the current buffer

:%s/^ \* Last Update:.*$/

  • that's the begin of the replacing command in which the pattern to be replaced is stated

\=printf(' * Last Update: ') . strftime("%d %b %Y (%T)")/e

  • this is the {replacement} and the end of the replacing command

When the {replacement} starts with \= it is evaluated as an expression. As a string is no expression printf is needed to output the first part of the string. The two functions printf and strftime are then concatenated via ..

like image 161
GiftZwergrapper Avatar answered Sep 17 '25 17:09

GiftZwergrapper