From 92fec81e2e91323911de630dbf6a70faf1e3490a Mon Sep 17 00:00:00 2001 From: Ihor Radchenko Date: Sun, 17 Dec 2023 14:55:43 +0100 Subject: [PATCH] lisp/org.el (org-sort-entries): Fix sorting partially selected subtree * lisp/org.el (org-sort-entries): Make sure that we extend sorted region to the full subtree if it spans beyond end of region. * testing/lisp/test-org.el (test-org/sort-entries): Add test. --- lisp/org.el | 20 ++++++++++++++++---- testing/lisp/test-org.el | 20 +++++++++++++++++++- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/lisp/org.el b/lisp/org.el index f3679dd9b..8868388bf 100644 --- a/lisp/org.el +++ b/lisp/org.el @@ -7702,12 +7702,24 @@ function is being called interactively." ;; Find beginning and end of region to sort (cond ((org-region-active-p) + (setq start (region-beginning) + end (region-end)) ;; we will sort the region - (setq end (region-end) + ;; Limit the region to full headings. + (goto-char start) + ;; Move to beginning of heading. + ;; If we are inside heading, move to next. + ;; If we are on heading, move to its begin position. + (if (org-at-heading-p) + (forward-line 0) + (outline-next-heading)) + (setq start (point)) + ;; Extend region end beyond the last subtree. + (goto-char end) + (org-end-of-subtree nil t) + (setq end (point) what "region") - (goto-char (region-beginning)) - (unless (org-at-heading-p) (outline-next-heading)) - (setq start (point))) + (goto-char start)) ((or (org-at-heading-p) (ignore-errors (progn (org-back-to-heading) t))) ;; we will sort the children of the current headline diff --git a/testing/lisp/test-org.el b/testing/lisp/test-org.el index 612bfa1e5..2fab3ff88 100644 --- a/testing/lisp/test-org.el +++ b/testing/lisp/test-org.el @@ -3916,7 +3916,25 @@ SCHEDULED: <2017-05-06 Sat> (org-test-with-temp-text "\n* B\n* A\n# Local Variables:\n# foo: t\n# End:" (org-sort-entries nil ?a) - (buffer-string))))) + (buffer-string)))) + ;; Sort region + (should + (equal " +* [#A] h2 +* [#B] h3 +* [#C] h1 +" + (org-test-with-temp-text + " +* [#C] h1 +* [#A] h2 +* [#B] h3" + (transient-mark-mode 1) + (push-mark (point) t t) + (search-forward "h3") + (org-sort-entries nil ?p) + (buffer-string)))) + ) (ert-deftest test-org/string-collate-greaterp () "Test `org-string-collate-greaterp' specifications."