Emacs

How to Comment Multiple Lines at Once in Emacs

Emacs is one of the best text editors. It comes in Graphical and command-line versions, making it suitable for both terminal and Graphical users.

However, many users tend to shy away from using Emacs because of its unconventional use of shortcuts for basic commands.

This tutorial will show you how to comment out code using the Emacs editor. Having this skill will help improve your Emacs workflow and skill.

How to Comment a Single Line In Emacs

Let us start with the basics. To comment out a single line of code using Emacs, press CTRL + X and then CTRL + ;

This comments out the current line and goes to the following line.

NOTE: If the line is commented out, Emacs will uncomment it.

How to Comment a Specified Number of Lines In Emacs

Emacs also allows you to pass the number of lines you need to comment or uncomment. To do this:

Start by pressing the CTRL + U key, followed by the number of lines to comment out.

Finally, press CTRL + X and then CTRL + ;

As you can see from the screenshot above, Emacs comments out 10 lines from the current cursor position.

How to Comment a Block of Code In Emacs

To comment on a specific block of code, start by selecting the region you wish to comment out by pressing CTRL + SPACE. Doing this will start the selection, and you can use the up and down arrow keys to select the region.

Once you have the target region selected, use the CTRL + X and CTRL +; to comment out the region as:

QUICK TIP. It is good to note that the CTRL + X and CTRL +; keys always operate on the set line. So, if the cursor is at the end of the line, the whole line will be commented or uncommented out.

How to Comment a Region of code In Emacs

As mentioned above, the CTRL +; key in Emacs comments out the entire line where the cursor or the region is located.

If you want to comment out only the selected region, you can use the ALT +; key. For example, consider the following selected region.

To comment out only the highlighted region, use the ALT +; key.

The result for this is:

As you can see, Emacs only comments out the select part of the code.

Conclusion

In this guide, we discussed various ways to comment out a single line or multiple lines at once in the Emacs text editor. Emacs is a great tool and very useful when working in the terminal.

Refer to Emacs manual and help pages to learn more.

https://www.gnu.org/software/emacs/manual/

Thank you for reading!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list