Vim Function to Generate a Comment in Go

Adam Presley
2 min readJun 29, 2021
Photo by Kaysha on Unsplash

OK, I’ll admit it. Sometimes I don’t add comments to describe my Go structs and functions. There, I said it. And after my linter properly chastises me, I dutifully work down the list of errors, adding the code comments… One at a time. I know… I know… I should just add the comments while I’m writing the code.

Well, today I found that task tedious. So I decided to write my very first Vim function. What does it do? When you put your cursor on a word in normal mode, then call the function, a comment block will be inserted above your method or struct that starts your new comment.

How did I do it? I’ll show you! Remember though, this is my first Vim function in Vimscript, and I’m pretty new to it. Be gentle.

Here’s a line by line breakdown:

  1. Just a comment describing our Vim function
  2. The function declaration. My function is name GenerateComment
  3. Get the current line number where the cursor is at. Assign that to lineNumber
  4. Get the word under the cursor. Assign that to wordUnderCursor
  5. Execute some Vim commands in normal mode. In this case we are going to press “O” (the letter) then ESCAPE three times. This will insert three lines above the current cursor line
  6. Call setline, passing a list of strings. This will be the comment start, followed by the word under the cursor, then the closing of the comment. The first argument to setline is the line number to write to.
  7. Move the cursor to the line with the function name inside the comment, and at the end of the line (so I can start typing here)
  8. Close the function declaration

Nothing too fancy, but it works! I then bound this function to a keystroke so I can run it quickly.

nmap <leader>gnc :call GenerateComment()<CR>

Now I can press the leader key (for me that’s comma), followed by the letters g, n, then c, and you will see this happen.

Video of the function in action.

It’s simple, but for me, useful. If you’ve got cool or useful functions to share, leave a comment! I’m always looking for new tips and tricks. Cheers, and happy coding!



Adam Presley

Just a guy who loves his wife, kids, and writing software.