Commenting out large blocks of code with vim


Last night I was helping a friend debug a really cool problem. During our debugging session he saw me use vim short cuts to comment and uncomment large chunks of code and append strings to numerous lines. He thought this was pretty cool and asked me to show him how to do this. I love teaching folks and sharing my knowledge so I put him on the keyboard and walked him through each item. I also told him I would note this in my blog for future reference.

I don’t recall where I originally read about visual blocks or the mass comment short cut. Most likely I came across is when I read the vim documentation. To illustrate this useful feature let’s say you are debugging a problem and want to comment out the following section of code (thanks kured for the snippet):

func commandReboot(nodeID string) {
        log.Infof("Commanding reboot")

        if slackHookURL != "" {
                if err := slack.NotifyReboot(slackHookURL, slackUsername, nodeID); err != nil {
                        log.Warnf("Error notifying slack: %v", err)
                }
        }

        // Relies on /var/run/dbus/system_bus_socket bind mount to talk to systemd
        rebootCmd := exec.Command("/bin/systemctl", "reboot")
        if err := rebootCmd.Run(); err != nil {
                log.Fatalf("Error invoking reboot command: %v", err)
        }
}

You can type j or k to move to the func line and then hit cntrl-v to enter visual mode. Next can now use the j character to move the block down to the end of the section you want to comment. Once all of the lines you want to comment are marked you can hit shift+I to insert and then type a comment character. Then you can hit escape and the comment character will be propagated to all of the lines in your visual block. To remove the comments you can type u to undo the change. If you closed out of the file you can reverse the steps above and use x to delete the highlight characters. When you hit escape it will be removed from all of the lines in your visual block.

One other nifty short cut is the ability to append text to multiple lines. Say you have are working on the following systemd unit file:

ExecStart=/usr/local/bin/kubelet.v1.9.2 
  --allow-privileged=true 
  --anonymous-auth=false 
  --client-ca-file=/kubernetes/rootca.pem 
  --cluster-dns=10.2.0.10 

To allow options to span lines you need to append a \ character to each line. To do this quickly with vim you can use cntrl-v to highlight the ExecStart block. Once the block is highlighted you can type shift $ to go to the end of the line. To add a slash to all of the marked lines you can type shift A to append and then type a \ followed by an escape. The entire block will now have a \ appended to it. Vim is crazy powerful and I learn a new tip or trick just about every day.

This article was posted by Matty on 2018-03-03 10:00:00 -0500 -0500