[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

org-sort-entries sorting by top-level with first entry at bob

From: Gustavo Barros
Subject: org-sort-entries sorting by top-level with first entry at bob
Date: Fri, 30 Oct 2020 12:04:37 -0300
User-agent: mu4e 1.4.13; emacs 27.1

Hi All,

`org-sort-entries' provides no easy way to sort by top-level when the first entry is at the beginning of buffer. This is true for both interactive and non-interactive uses of the function, but a little more inconvenient in the latter case.

Indeed, `org-sort-entries', when deciding what to sort, first tests for `org-region-active-p', then `org-at-heading-p' (or if after a heading), failing those tests, it falls back to top-level sorting. However, if the first heading is at the beginning of buffer and we want to sort by top-level, we'll never get to the fall back case, because `org-at-heading-p' will return non-nil, and the children of the first entry will be sorted instead.

Not an ECM, just an use case with the situation at hand. Consider a buffer with contents:

#+begin_src org
,* B Foo
,** B Baz
,** A Foo
,* A Bar

How to sort by top-level?

The currently existing alternative is to `mark-whole-buffer', and let `org-sort-entries' sort by region. While this is reasonable in the interactive case, it is less so if `org-sort-entries' is being called in code. Using `mark-whole-buffer' in your code will grant you a nice compiler warning and pretending you don't use it by doing the same thing yourself is explicitly advised against in its docstring: "it is usually a mistake for a Lisp function to use any subroutine that uses or sets the mark". Behind the scenes, Org is using `use-region-p', which means the region must not only exist but transient-mark-mode must be on and the mark must be active. It can be made to work, of course, but it is clearly less than ideal. Either way, currently the only way to ensure that sorting is done by top-level when you don't know whether there is something before the first heading (including possible narrowing) is to rely on the region case.

What to do with it is somewhat tricky, though. My first thought was to test if we are actually looking at a heading regexp, and sort on the heading's level in this case. But, on second thought, I believe this is not a good idea, because it will conflict with current and expected behavior for speed-keys, in particular. Perhaps test if point is at beginning of buffer, and handle this case specially?

Best regards,

reply via email to

[Prev in Thread] Current Thread [Next in Thread]