Emacs comment/uncomment current line

David Gomes picture David Gomes · Mar 13, 2012 · Viewed 15.7k times · Source

I know there's already an Emacs question on this, and that it was closed, but I find it quite relevant and important.

Basically, I want to comment/uncomment the current line. I was expecting this to be fairly easy with a macro, but I found that it really isn't.

If the current line is commented, uncomment. If it is uncommented, comment it. And I would also to comment out the whole line, not just from cursor position.

I tried a macro like this:

C-a

'comment-dwim

But this only work to comment a line, not to uncomment it, if it's already commented.

I'm not sure of how easy it is, but if there's some way, I'd really like it.

Also, the reason I love this idea so much is that when I used Geany, I just used C-e and it was perfect.

Answer

Gerstmann picture Gerstmann · Mar 14, 2012

Trey's function works perfectly, but it isn't very flexible.

Try this instead:

(defun comment-or-uncomment-region-or-line ()
    "Comments or uncomments the region or the current line if there's no active region."
    (interactive)
    (let (beg end)
        (if (region-active-p)
            (setq beg (region-beginning) end (region-end))
            (setq beg (line-beginning-position) end (line-end-position)))
        (comment-or-uncomment-region beg end)))

It comments/uncomments the current line or the region if one is active.


If you prefer, you can modify the function to jump to the next line after (un)commenting the current line like this:

(defun comment-or-uncomment-region-or-line ()
    "Comments or uncomments the region or the current line if there's no active region."
    (interactive)
    (let (beg end)
        (if (region-active-p)
            (setq beg (region-beginning) end (region-end))
            (setq beg (line-beginning-position) end (line-end-position)))
        (comment-or-uncomment-region beg end)
        (next-line)))

Note that only thing that's changed is the added next-line command at the end of the function.