# How to sort cells?

Is there a way to programmatically reorder the section cells in a notebook alphabetically?

For example:

• I think a similar question has been asked before, possibly relating to cells that are labeled by date, but I cannot find it now. Edit: never mind, I seem to have been thinking of your own question: (73544) – Mr.Wizard Jun 13 '15 at 2:36
• Yes very similar! – M.R. Jun 13 '15 at 2:59
• @Mr.Wizard 2181? :) – Kuba Jun 13 '15 at 5:38
• My answer should work for you but it would be nice to have more details described. What if those sections are gouped by Titles for example. Do you want to be able to do this only on selected part too. etc etc. I think a lot of such features may be implemented, I just don't like to think what others may need for edge cases. – Kuba Jun 13 '15 at 10:27

I will try to add a more general function later, meanwhile you can use this procedure:

Module[{cells, data},

cells = Cells[CellStyle -> "Section"];

data = (
SelectionMove[#, All, CellGroup, AutoScroll -> False];
) & /@ SortBy[cells, First@NotebookRead[#] &];

Do[
SelectionMove[cells[[i]], All, CellGroup, AutoScroll -> False];
NotebookWrite[EvaluationNotebook[], data[[i]], AutoScroll -> False]
,
{i, Length@cells}
]
]

• Oh no, I didn't realize this solution would destroy cell options like Cell["Python", "Section", WholeCellGroupOpener->True] – M.R. Jun 16 '15 at 17:30
• @M.R. well that's unexpected. Any other options behave strange? I've posted the question already: mathematica.stackexchange.com/q/86077/5478 – Kuba Jun 16 '15 at 18:30
• @M.R. Using "WholeCellGroupOpener" works but I don't know why :) – Kuba Jun 16 '15 at 21:33
• @M.R. I've post a solution to the problem of CellContext: 102269 so you can use this replacement rules. – Kuba Dec 22 '15 at 7:32