org-mode goto last heading in the current tree.

Say This is my org-file, pipe indicates the cursor:

* Top|
** Apple
** Banana
** Cherry
* Middle
** Ape
** Bear
** Cat

I'd like to run a command and have my cursor now be here:

* Top|
** Apple
** Banana
** Cherry|
* Middle
** Ape
** Bear
** Cat
  • 2
    Last heading in the file, or the current tree?
    – Zavior
    Nov 9 '14 at 12:23
  • @Zavior Good question. I've clarified the original question. Nov 9 '14 at 13:13

There's actually an org-end-of-subtree function, but it's not interactive. You can simply define your own command:

(defun goto-last-heading ()

Here's a command, based on @itsjeyd's answer, that is robust to the edge case listed in the comment to that answer (that is, when you're on the last heading/subtree):

(defun org-end-of-subtree ()
  (let ((org-special-ctrl-a/e t))
    (if (condition-case nil
            (outline-forward-same-level 1)
          (error t))
          (goto-char (point-max))
      (outline-previous-visible-heading 1))
    (org-end-of-line 1)))

I don't think there's a built-in command for this, but you can easily define one yourself:

(defun org-goto-last-heading-in-tree ()
  (org-forward-heading-same-level 1)     ; 1. Move to next tree
  (outline-previous-visible-heading 1)   ; 2. Move to last heading in previous tree
  (let ((org-special-ctrl-a/e t))        ; 3. Ignore tags when
    (org-end-of-line)))                  ;    moving to the end of the line

And bind it to a key sequence of your choosing via:

(define-key org-mode-map (kbd "C-c g") 'org-goto-last-heading)
  • this is nice, thanks for sharing, however maybe I need to be clearer in my question. What I really want is to go to the end of the current tree... Nov 9 '14 at 13:11
  • @AlexBaranosky Yes, that was not clear from the way you originally worded the question. Give me a sec to adjust the code...
    – itsjeyd
    Nov 9 '14 at 13:12
  • @AlexBaranosky OK, that should do it. Thanks for clarifying your requirements!
    – itsjeyd
    Nov 9 '14 at 13:16
  • I'd suggest not using C-c l binding. It is the org mode suggested binding for org-store-link as it is very closely related to org-insert-link (C-c C-l). Nov 9 '14 at 13:59
  • @kaushalmodi Yes, thank you. I adjusted my answer.
    – itsjeyd
    Nov 9 '14 at 15:13

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.