0

I am trying to record all the lines with the word bad in a Emacs-buffer with a simple elisp function

(defun bad-line-numbers ()
  (beginning-of-buffer)
  (setq sec-lines ())
  (while (re-search-forward "bad" t nil nil) 
    (cons (thing-at-point 'line) sec-lines ))
  (message sec-lines)
  )

I tried this function, by evaluating (bad-line-numbers) in a buffer but I get the error Wrong type argument: integer-or-marker-p, t after the point goes to the beginning of the buffer.
Where am i going wrong?

2

In addition to the things pointed out by @muffinmad, the code doesn't record the information found by the search.

The body of the loop is (cons .... sec-lines), which creates a new list containing the search result and whatever is in the list sec-lines. However, this new list is thrown away.

You can either write (setq set-lines (cons ... sec-lines)) or, simpler, (push ... sec-lines).

Some other things:

  • The arguments to re-search-forward are wrong, typically you pass nil as bound and t as noerror.
  • You'll need to change the last line to (message "%s" sec-lines).
  • To avoid moving the point, you can wrap everything in a save-excursion.

All included, the following would work:

(defun bad-line-numbers ()
  "Return list of lines containing `bad'."
  (save-excursion
    (goto-char (point-min))
    (let ((sec-lines ()))
      (while (re-search-forward "bad" nil t)
        (push (thing-at-point 'line) sec-lines))
      (message "%s" sec-lines)
      (nreverse sec-lines))))

Note that (things-at-line 'line) returns the full line. To find the line number (which the title indicates) you can use (line-number-at-pos).

2
  1. From C-h f beginning-of-buffer:

    This function is for interactive use only;
    in Lisp code use `(goto-char (point-min))' instead.
    
  2. From C-h f re-search-forward:

    The optional second argument BOUND is a buffer position that bounds
    the search.
    

    You passed t as second argument while it must be integer or marker. If you want to leave the second argument unspecified you can pass nil for it.

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.