Some notes on things I learned writing a vim macro
I use the text editor vim, which I’m currently trying to learn better. This post is some notes I made about things I learned writing a new macro
I have an old macro that never worked. It was to update the time on a log entry.
map lnu 016llcf, to 12:13,jk0
I want to be able to convert:
## 09/05/20 07:40,
## 09/05/20 07:40 to 08:05,
## 09/05/20 07:40 to 08:05, Doing some work +PersonalProjects
to:
## 09/05/20 07:40 to 08:15,
## 09/05/20 07:40 to 08:15,
## 09/05/20 07:40 to 08:15, Doing some work +PersonalProjects
(So adding or updating an end time, maintaining the comment)
After a bit of playing, I discovered that I would do better with a substitute command than moving and changing. This one works for adding or replacing the end time with 11:11.
:s/\(^.\{12}\d\d:\d\d\).*,/\1 to 11:11,/
I discovered that substitute command lets you start the replacement with \= to show that it’s a function - but it seems that you can’t embed it within a larger expression, which is disappointing (you probably can if you know more about functions.
I discovered that “The expression register (“=) is used to deal with results of expressions.”, but it doesn’t work like a regular register - I can’t store stuff there for later, It’s like accessing a command line in another expression. So I wrote a macro that used it. That worked, but I couldn’t transfer the Macro to my vimrc in the normal ‘<CTRL-R>“qp’ way, because that pastes the macro as it appears before pressing enter: so the function had already returned and I got:
let lnu :s/\(^.\{12}\d\d:\d\d\).*,/\1 to 11:11,/
again.
It turns out that you can use <CTRL-R> twice to paste the macro literally:
:s/\(^.\{12}\d\d:\d\d\).*,/\1 to 11:11,/€kl€kl€kb€kb€kb€kb€kb^R=strftime('%H:%M')^M^M
which was my third discovery of the day. I did some small editing to get
map lnu :s/\(^.\{12}\d\d:\d\d\).*,/\1 to ^R=strftime('%H:%M')^M,/g
and it works nicely. Quite happy that I learned a fair amount of vim in the process.
I need to fix a bug about multiple commas, but I’m happy with that as my personal development for the day.
_ Note I pushed the change to my vimrc in this GitHub commit.