9

I am hoping to figure out how to do a query search that will comment out a line instead of query replace. That is, do an interactive query search, and if I say yes, comment out the line the match is on.

Does this command exist? If not, how would I write it? I'm new to elisp, and don't know how to program my own functions.

Dan
  • 32,980
  • 7
  • 102
  • 169
  • 8
    Use query-replace-regexp. Replace the line by the line prefixed with a comment start. – Drew Jan 07 '16 at 22:42

1 Answers1

1
(defun my-comment-matching-line ()
  (interactive "*")
  (call-interactively 'search-forward)
  (beginning-of-line)
  ;; don't comment the region maybe
  (push-mark)
  (comment-line 1))

Should comment-line not be available, here from a recent newcomment.el:

(defun comment-line (n)
  "Comment or uncomment current line and leave point after it.
With positive prefix, apply to N lines including current one.
With negative prefix, apply to -N lines above.  Also, further
consecutive invocations of this command will inherit the negative
argument.

If region is active, comment lines in active region instead.
Unlike `comment-dwim', this always comments whole lines."
  (interactive "p")
  (if (use-region-p)
      (comment-or-uncomment-region
       (save-excursion
         (goto-char (region-beginning))
         (line-beginning-position))
       (save-excursion
         (goto-char (region-end))
         (line-end-position)))
    (when (and (eq last-command 'comment-line-backward)
               (natnump n))
      (setq n (- n)))
    (let ((range
           (list (line-beginning-position)
                 (goto-char (line-end-position n)))))
      (comment-or-uncomment-region
       (apply #'min range)
       (apply #'max range)))
    (forward-line 1)
    (back-to-indentation)
    (unless (natnump n) (setq this-command 'comment-line-backward))))
Andreas Röhler
  • 1,886
  • 11
  • 10