Elisp: Write Comment/Uncomment Command

By Xah Lee. Date: . Last updated: .

Writing a Comment Command Using newcomment.el


Emacs has a standard command to insert or delete comment, named comment-dwimAlt+;】, from newcomment.el.

When there is a text selection, comment-dwim comment or uncomment the region in a smart way.

If there is no text selection, comment-dwim insert a comment syntax at the end of line, or move to the beginning of comment if already exists.

The comment-dwim is the standard command to comment/uncomment code. Your major mode should support it. When a user press the keyboard shortcut for it while in your major mode, it should work.

comment-region, uncomment-region

comment-region and uncomment-region are lower level commands that do the actual work.

comment-dwim simply determine whether to comment or uncomment, and on what region boundary, then call comment-region or uncomment-region.

Make comment-dwim Work for Your Major Mode

All you have to do, is to set 2 Buffer Local Variable comment-start and comment-end

For example, here's code for emacs lisp:

(setq-local comment-start "; ")
(setq-local comment-end "")

Here's another example.

In CSS, comment has this syntax:

/* css comment syntax */

Here's code from emacs's css-mode:

(define-derived-mode css-mode fundamental-mode "CSS"
  "Major mode to edit Cascading Style Sheets."

  (setq-local font-lock-defaults css-font-lock-defaults)

  (setq-local comment-start "/*")
  (setq-local comment-start-skip "/\\*+[ \t]*")
  (setq-local comment-end "*/")
  (setq-local comment-end-skip "[ \t]*\\*+/")

  ;; ...


[see Elisp: Regex Tutorial]

Write Your Own Comment Command from Scratch

If your language's comment syntax is more complex, different from any of the form in C, Java, python, ruby, php, etc. You'll need to write your own comment/uncomment command.

See: Elisp: Write Comment Command from Scratch.

thanks to Daniel for correction.

Emacs lisp, writing a major mode. Essentials