5

So, I have this function, which works just fine for me and does what I want it to:

(defun mwp-set-grade ()
  (interactive)
  (save-excursion
    (while 
        (re-search-forward "- Grade :: \\\(.*\\\)")
      (org-set-property "GRADE" (match-string 1))))
)

However, at some point it finds the last match, and then throws a message:

while: Search failed: "- Grade :: \\(.*\\)"

I figure there must be a way to exit gracefully while searching for something in a buffer. I bet the answer will also help me understand a little more about dealing with errors and failures in elisp, whihc I don't understand well.

Thanks as always...

  • 2
    C-h f re-search-forward -- ask Emacs! – Drew Nov 30 '15 at 18:23
9

re-search-forward has an option for not causing an error:

(re-search-forward REGEXP &optional BOUND NOERROR COUNT)

You should call (re-search-forward "..." nil t) and your while will receive a nil value when no match found.

Edit:

As Jordon notes in the comments, there is a more general way of ignoring errors, which is the ignore-errors macro:

(while (ignore-errors (re-search-forward "...")) body )
  • 2
    Alternatively if the function you were calling doesn't have a NOERROR-like parameter you could use (while (ignore-errors (do-something)) ... ) to demote the error to a nil value. – Jordon Biondo Nov 30 '15 at 16:19
  • Thanks, this is very helpful. @Jancho would you be willing to incorporate Jordan's pointer to ignore-errors? thanks so much. – Matt Nov 30 '15 at 16:36

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.