Hello Org-mode users!

I have observed a mini bug over some time now:

When I sort headings in org mode according to their priority (C-c ^ p), sometimes the last heading (lowest priority) will not get its own line, but will be put in one line with the second last heading, making it no longer a separate heading, but part of the second last actual heading.

This behavior depends on how one marks/selects/highlights the headings to be sorted. If one highlights the headings from top to bottom, moving the point to the next line after the last heading that shall be sorted, then it works without merging the last heading and the second last. However, if one does not move the point to the next line, then the described behavior occurs.

I have the suspicion, that this is about each heading being defined as consisting also of a final newline character and since one does not select that as well by moving the point past it, org mode does not consider the last heading to be a separate heading, but instead thinks it is part of the second last heading. Or perhaps, that it only considers selected text to be sorted, not headings that continue after selected text and therefore forgets to include a newline for the last heading and if that heading moves around without the newline, another heading will be joined on to it on the same line, if any heading comes afterwards in the sorted result.

When one highlights from bottom to top (so the other way around!) the same thing happens. If one started highlighting on the line below the last heading, then the sorting works without merging the last two lines. However, if one starts highlighting on the last heading line, then again org mode puts the last heading on the line of the second last heading.

Of course this is quite annoying, when one sorts a lot, and one has to always be careful how one selects the headings.

Note also, that this only happens, when org mode sorting actually would change the order of headings. If the headings are already sorted, then this does not happen.

Here is an example document:

~~~~
* 1
** [#A] 2.1
** [#C] 2.2
** [#B] 2.3
~~~~

In this document move the cursor:

~~~~
* 1
** [#A] 2.1
** [#C] 2.2
** [#B] 2.3
           ^
           `--- cursor here
~~~~

Then select until the start of the first level 2 heading, so that all level 2 headings are selected.

Then run `org-sort' or press `C-c ^' and then `p'.

The result is:

~~~~
* 1
** [#A] 2.1
** [#B] 2.3** [#C] 2.2
~~~~

Instead of:

~~~~
* 1
** [#A] 2.1
** [#B] 2.3
** [#C] 2.2
~~~~

This also happens, when I try it in an Emacs started with `emacs -Q'.

In my opinions org-sort should sort without merging headings. It should probably consider all text until the end of even a partially selected/highlighted heading including the final newline character to avoid this.

Please let me know, in case more details are required and how to get them.

Best regards,
Zelphir

-- 
repositories: https://notabug.org/ZelphirKaltstahl