Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

Before command

if(condition){
        do ...
}

After command

if(condition){
        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

3 Answers 3

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 ..."
  (interactive)
  (let (start text)
    (save-excursion
      (backward-sexp 3)
      (setq start (point))
      (end-of-line)
      (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 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 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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.