3

I want to define a function org-move-subtree-top that calls org-move-subtree-up until it returns a user-error (in this case "Cannot move past superior level or buffer limit"). How can I do this in elisp?

2

Write an infinite loop, and catch the error outside the loop.

(condition-case nil
    (while t
      (org-move-subtree-up))
  (error nil))

Org mode 7.8.11 throws a plain error for this message. If you have a more recent version that calls user-error instead of error, replace error by user-error.

This hides all errors. It would be safer to catch only the specific error that you intended to happen, but that requires hard-coding the error message.

(condition-case err
    (while t
      (org-move-subtree-up))
  (error (or (equal (cdr err) "Cannot move past superior level or buffer limit")
             (signal (car err) (cdr err)))))

Alternatively, you could implement this without calling org-move-subtree-up: find the boundaries of the subtree, find the target position, and move it there. Untested.

(defun org-move-subtree-top ()
  "Move the current subtree just after the heading of its parent."
  (interactive "*")
  (let* ((target (save-excursion
                   (org-back-to-heading)
                   (outline-up-heading)
                   (forward-line)
                   (point)))
        (beg (progn
               (org-back-to-heading)
               (point))
        (end (progn
               (org-end-of-subtree)
               (point)))
        (text (buffer-substring beg end)))
    (delete-region text)
    (goto-char target)
    (insert text)))
  • The first snippet is essentially just ignore-errors. in order to only catch user errors (as the OP asked) you can replace the (error nil) with (user-error nil). – Malabarba Mar 29 '15 at 19:06
  • @Malabarba The Org mode version I have on my machine calls (error "Cannot move past superior level or buffer limit"). If newer versions call user-error then indeed error should be replaced by user-error in my snippet. – Gilles 'SO- stop being evil' Mar 29 '15 at 19:09

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.