Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to find an emacs command that will auto comment the code similar to this:

Before command

        do ...

After command

        do ...
} //Matches if(condition){

I know that when the block of code between the parentheses is too big to fit on the current page, it will show me the "Matches if(condition)" part when I insert the closing brace. I however, want to select a block of code, and then execute this command in emacs so that it will put that comment there for me. Please let me know if anything is unclear and I will be glad to specify. I also apologize if this question has been asked before, however, I looked and I couldn't find it. If it has been, please point me to that question.

Thanks in advance.

share|improve this question
up vote 0 down vote accepted

Add this to the bottom of your ~/.emacs file and restart Emacs. Change the keybinding to any key sequence of your choice:

(defun my-add-end-block-comment ()
  "Documentation goes here ..."
  (let (start text)
      (backward-sexp 3)
      (setq start (point))
      (setq text (buffer-substring start (point))))
    (insert (concat "  // " text))))

(global-set-key (kbd "C-z /") 'my-add-end-block-comment)

Then position your cursor after the close brace (}) and press C-z /. This should also work for while and for loops.

share|improve this answer
Thanks for the response, this worked! – raghav.mohan Jul 18 '12 at 22:14
I think it may fail for if-statements that have else clauses. If you desperately need that, let me know and I may be able to code something to handle that case. – Fran Jul 19 '12 at 0:09

You could use C-s (forward-search) to search for the if block, select the region and M-; (comment-dwim) to comment the region.

Anytime in doubt, use M-x apropos < RET > < your-search-term-here > < RET >.

share|improve this answer

You can use some snippet tool, like YASnippet, which will have another field at the end for the comment. It won't be the same behavior as you want, but at the end of the day it will do more or less the same.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .