Philipp Kiefer <phil.kie...@gmail.com> writes:

> This bug has been around ever since moving multiple selected headings 
> was made possible - I'm finally overcoming my laziness and reporting it.
>
> To reproduce (cf. attached screencast):
>
>   * select multiple headings (org-mark-element with M-h in the default
>     config, I think)
>   * call org-metaup (M-UP)
>
> Expected behaviour is to move the two headings up above the preceding 
> heading and keep the selection as is.
>
> However, the selection is extended downward by one heading so it 
> comprises 3 headings after the first execution, 4 after the second etc.

May you try the attached patch?
>From b807f73947ca52c8a140e63b9e2a0aed6b7f386e Mon Sep 17 00:00:00 2001
Message-ID: <b807f73947ca52c8a140e63b9e2a0aed6b7f386e.1742120364.git.yanta...@posteo.net>
From: Ihor Radchenko <yanta...@posteo.net>
Date: Sun, 16 Mar 2025 11:17:23 +0100
Subject: [PATCH] org-metaup: Fix region extending unexpectedly

* lisp/org.el (org-metaup): When `org-move-subtree-down' puts the
heading before region end marker, adjust the region to not include it.

Reported-by: Philipp Kiefer <phil.kie...@gmail.com>
Link: https://orgmode.org/list/d0cca792-39ce-4896-92da-dec3f30dd...@gmail.com
---
 lisp/org.el | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/lisp/org.el b/lisp/org.el
index bc61a7c462..e16158d874 100644
--- a/lisp/org.el
+++ b/lisp/org.el
@@ -17263,7 +17263,8 @@ (defun org-metaup (&optional _arg)
             (org-at-heading-p))))
     (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
     (let ((beg (region-beginning))
-          (end (region-end)))
+          (end (region-end))
+          (region-extended nil))
       (save-excursion
         ;; Go a little earlier because `org-move-subtree-down' will
         ;; insert before markers and we may overshoot in some cases.
@@ -17281,7 +17282,16 @@ (defun org-metaup (&optional _arg)
           ;; Drag first subtree above below the selected.
           (while (< (point) end)
             (call-interactively 'org-move-subtree-down)
-            (setq deactivate-mark (org--deactivate-mark)))))))
+            (setq deactivate-mark (org--deactivate-mark)))
+          ;; When `org-move-subtree-down' inserts before markers, the
+          ;; region boundaries will extend to the moved
+          ;; heading. Prevent this.
+          (when (<= (point) (region-end))
+            (setq region-extended t))))
+      (when region-extended
+        (if (= (region-beginning) (point))
+            (set-mark (1+ end))
+          (goto-char (1+ end))))))
    ((org-region-active-p)
     (let* ((a (save-excursion
                 (goto-char (region-beginning))
-- 
2.47.1

-- 
Ihor Radchenko // yantar92,
Org mode maintainer,
Learn more about Org mode at <https://orgmode.org/>.
Support Org development at <https://liberapay.com/org-mode>,
or support my work at <https://liberapay.com/yantar92>

Reply via email to