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...

Drew
  • 77,472
  • 10
  • 114
  • 243
Matt
  • 115
  • 5

1 Answers1

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 )
Juancho
  • 5,455
  • 16
  • 20
  • 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