10

Is it possible to collapse all cell groups in the current notebook? I tried

nb = SelectedNotebook[];
SelectionMove[nb, Before, CellGroup]
FrontEndTokenExecute["OpenCloseGroup"]

but nothing changes.

Karsten W.
  • 1,383
  • 8
  • 21

2 Answers2

16

Try:

nb = SelectedNotebook[];
SelectionMove[nb, All, Notebook]
FrontEndTokenExecute["SelectionCloseAllGroups"]

Or:

nb = SelectedNotebook[];
FrontEndExecute[FrontEndToken[nb, "SelectAll"]]
FrontEndTokenExecute["SelectionCloseAllGroups"]

The token may be found in Tokens Related to the Cell Menu in the help browser.

This specific operation may be found under the Scope section of the FrontEndToken documentation.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
4

You could use

nb = SelectedNotebook[];
SelectionMove[nb, All, Notebook];
FrontEndTokenExecute[nb, "OpenCloseGroup"]

although it only works if the notebook starts with a cell group, and not with a lone cell. (The menu item behaves the same way.)

If you know there are cellGroupCount groups, you could also do something like:

nb = SelectedNotebook[];
SelectionMove[nb, Before, Notebook]
Do[SelectionMove[nb, Next, CellGroup];
 FrontEndTokenExecute[nb, "OpenCloseGroup"], {cellGroupCount}]
Brett Champion
  • 20,779
  • 2
  • 64
  • 121