10
$\begingroup$

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.

$\endgroup$
0

2 Answers 2

16
$\begingroup$

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.

$\endgroup$
7
  • $\begingroup$ Note that "OpenCloseGroup" and "SelectionCloseAllGroups" work differently when you have nested cell groups. $\endgroup$ Jun 14, 2012 at 15:38
  • $\begingroup$ @Brett the OP asked to "collapse all cell groups" -- isn't that what "SelectionCloseAllGroups" does? $\endgroup$
    – Mr.Wizard
    Jun 14, 2012 at 16:13
  • $\begingroup$ And yet the sample code used "OpenCloseGroup". But the OP might not have been aware of the differences between them. $\endgroup$ Jun 14, 2012 at 16:44
  • $\begingroup$ @Brett Okay. I thought you were politely trying to tell me my answer was wrong. $\endgroup$
    – Mr.Wizard
    Jun 14, 2012 at 16:51
  • $\begingroup$ @Mr.Wizard is it possible to only close or open one level deep? $\endgroup$
    – chris
    Sep 10, 2012 at 19:42
4
$\begingroup$

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}]
$\endgroup$
1
  • $\begingroup$ Thanks for pointing out the dependance on the notebook start, that clarifies things $\endgroup$
    – Karsten W.
    Jun 14, 2012 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.