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.

1
  • 8
    Use query-replace-regexp. Replace the line by the line prefixed with a comment start.
    – Drew
    Commented Jan 7, 2016 at 22:42

1 Answer 1

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))))
2
  • Thanks for this, what you have here has returned "Symbol's function definition is void: comment-line" Commented Jan 19, 2016 at 15:37
  • @JaimeArturoGomez Seems being introduced recently. Provided a copy. Commented Jan 24, 2016 at 9:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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