首页 > 解决方案 > 如何使用 BufWritePre 更新我的 cpp 评论

问题描述

我在 .vimrc 中添加了一些代码,以自动更新 .cpp 和 .h 文件文档中的“上次更新”字段。

我已经为我的 .py 文件尝试过它并且它有效。问题是搜索以字符开头的行* Last Update。这是我到目前为止所拥有的:

我的 cpp 文件中的注释

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

和我的 .vimrc

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

这应该将评论更新为:

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

但我根本没有任何变化。

更新:我的头文件(.h)中有相同的代码

标签: vim

解决方案


更新为使用.cpp .h文件

您需要将以下内容添加到您的.vimrc或其他获取来源的文件中:

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

autocmd FileType cpp,h

  • 确保它仅适用于.cpp.h文件

autocmd BufwritePre <buffer>

  • 写入当前缓冲区

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

  • 那是替换命令的开始,其中说明了要替换的模式

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

  • 这是 {replacement} 和替换命令的结尾

当 {replacement} 以它开头时,\=它被评估为一个表达式。由于字符串是不需要表达式printf来输出字符串的第一部分。这两个函数printf然后strftime通过 连接起来.


推荐阅读