Hi, All!
I want to write a function in Mathematica 9 that opens and closes all sections in my notebook. I do it as follows:
openCloseAll[nb_, target_String, to : (Open | Closed)] :=
Do[SelectionMove[cell, All, CellGroup, AutoScroll -> False];
With[{content =
Block[{$Context = "FrontEnd`", $ContextPath = {"System`"}},
NotebookRead[nb]], from = to /. {Closed -> Open, Open -> Closed}},
If[MatchQ[content, Cell[CellGroupData[{Cell[_, target, ___], __}, from]]],
NotebookWrite[nb, Cell[CellGroupData[content[[1, 1]], to]],
AutoScroll -> False]]];, {cell, Cells[CellStyle -> target]}]
Then I create two buttons to deal with sections:
Button["Close sections", openCloseAll[EvaluationNotebook[], "Section", Closed]]
and
Button["Open sections", openCloseAll[EvaluationNotebook[], "Section", Open]]
At last, I create a section with a single cell in it (a comment between two expressions - it is important!):
something1
(*a comment*)
something2
The resulting file attached below is the first notebook. When I push successively "Close sections" and "Open sections" buttons, I see a garbage in the section instead of the first two lines of the cell (see the second attached file). What happens?
Attachments: