A function to close and open sections in a notebook?

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?

open_close_problem.nb (7.74 KB)
open_close_problem_processed.nb (8.19 KB)

Hi Vladimir,

Obviously, you are trying to use the solution from this old answer by Kuba.

First of all, I would say that the old solution is not only highly inefficient, but also can easily corrupt the contents of the Notebook – for example, if you click inside of the Notebook during evaluation of the script. The dangerous is NotebookWrite part which should be rewritten using FrontEndTokenExecute["OpenCloseGroup"].

The NotebookRead part makes that solution highly inefficient and should be rewritten using CurrentValue[cellObj, "CellGroupOpen"]. But I’m not sure that this command works in Mathematica version 9.

Unfortunately, I don’t have Mathematica 9 installed, so I can’t test specifically for that version. I recommend rewriting at least the NotebookWrite part which is the only part of the solution that could corrupt your Notebook.

Thank you, Alexey.

I’ll try to modify my code following your advice.

There is CurrentValue[] command in Mathematica 9.