Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command to uncomment multiple lines without selecting them

Is there a command in emacs to uncomment an entire comment block without having to mark it first?

For instance, let's say the point is inside a comment in the following code:

  (setq doing-this t)
  ;; (progn |<--This is the point
  ;;   (er/expand-region 1)
  ;;   (uncomment-region (region-beginning) (region-end)))

I would like a command that turns that into this:

  (setq doing-this t)
  (progn
    (er/expand-region 1)
    (uncomment-region (region-beginning) (region-end)))

It's fairly easy to write a command that (un)comments a single line, but I've yet to find one that uncomments as many lines as possible. Is there one available?

like image 756
Malabarba Avatar asked Mar 27 '26 00:03

Malabarba


2 Answers

A quick reply --- code could be improved and made more useful. You might want to extend it to other kinds of comments, besides ;;;, for instance.

(defun uncomment-these-lines ()
  (interactive)
  (let ((opoint  (point))
        beg end)
    (save-excursion
      (forward-line 0)
      (while (looking-at "^;;; ") (forward-line -1))
      (unless (= opoint (point))
        (forward-line 1)
        (setq beg  (point)))
      (goto-char opoint)
      (forward-line 0)
      (while (looking-at "^;;; ") (forward-line 1))
      (unless (= opoint (point))
        (setq end  (point)))
      (when (and beg  end)
        (comment-region beg end '(4))))))

The key is comment-region. FWIW, I bind comment-region to C-x C-;. Just use it with C-u to uncomment.

like image 145
Drew Avatar answered Apr 01 '26 09:04

Drew


You can use Emacs' comment handling functions to make a generalised version of Drew's command.

(defun uncomment-current ()
  (interactive)
  (save-excursion
    (goto-char (point-at-eol))
    (goto-char (nth 8 (syntax-ppss)))
    (uncomment-region
     (progn
       (forward-comment -10000)
       (point))
     (progn
       (forward-comment 10000)
       (point)))))
like image 27
event_jr Avatar answered Apr 01 '26 09:04

event_jr