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.

  • 8
    Use query-replace-regexp. Replace the line by the line prefixed with a comment start.
    – Drew
    Jan 7 '16 at 22:42
(defun my-comment-matching-line ()
  (interactive "*")
  (call-interactively 'search-forward)
  ;; don't comment the region maybe
  (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

If region is active, comment lines in active region instead.
Unlike `comment-dwim', this always comments whole lines."
  (interactive "p")
  (if (use-region-p)
         (goto-char (region-beginning))
         (goto-char (region-end))
    (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)))))
       (apply #'min range)
       (apply #'max range)))
    (forward-line 1)
    (unless (natnump n) (setq this-command 'comment-line-backward))))
  • Thanks for this, what you have here has returned "Symbol's function definition is void: comment-line" Jan 19 '16 at 15:37
  • @JaimeArturoGomez Seems being introduced recently. Provided a copy. Jan 24 '16 at 9:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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