There are several questions in Mma.SE related to programmatically opening and closing cells, but I could not find quite what I'm seeking.

Here's a minimal example:

   {ExpressionCell[x + y,
       Background -> LightOrange, 
       CellGroupingRules -> "OutputGrouping"]}]

When I evaluate this code it produces (almost) what I want: the expression in the Equation cell, properly grouped with the code that produced it.

However I would like to automatically collapse (Close) the source code cell, while preserving the existing grouping. I would like to go back, if necessary, to manually open the source cell, but the default should be that upon execution the source cell closes.

My kludge at present is to manually double click on the output cell, thereby collapsing the source code cell, but I'd rather it be automatic.


2 Answers 2

Cell[CellPrint[{ExpressionCell[x + y, Background -> LightOrange, 
     "Equation", CellGroupingRules -> "OutputGrouping"]}], 
  CellEpilog -> SetOptions[EvaluationCell[], CellOpen -> False]];
  • $\begingroup$ Yep. Perfect. Thanks! ($+1$, $\checkmark$) $\endgroup$ Aug 11, 2022 at 23:14
  • 2
    $\begingroup$ The outermost Cell is redundant, because what really works is SetOptions[EvaluationCell[], CellOpen -> False], which can simply be placed on the next line after CellPrint. $\endgroup$ Aug 12, 2022 at 16:31
  • $\begingroup$ Good point. Thank you. $\endgroup$ Aug 12, 2022 at 16:36

Here is another option:

 CellEpilog :> (SelectionMove[EvaluationNotebook[], All, GeneratedCell];

Simply evaluate that in your Notebook, and then after evaluation every input cell will be automatically hidden in a closed CellGroup containing its output(s), which will become the only what is visible:


Inspired by these answers:

  • $\begingroup$ Thanks for your answer. I didn't get the errors you mentioned (v. 11.3), and I don't want this automatic closure to occur for every cell, so setting a default might not be appropriate. $\endgroup$ Aug 12, 2022 at 15:41
  • $\begingroup$ @DavidG.Stork In the second linked answer you can find another approach, which may be more appropriate for you. $\endgroup$ Aug 12, 2022 at 15:59
  • $\begingroup$ Yep. Thanks very much. (I'm only now learning notebook-level programming.). I'd REALLY like to solve the following problem, which has remained unanswered for years. Perhaps you can help! mathematica.stackexchange.com/questions/72903/… $\endgroup$ Aug 12, 2022 at 16:32

Your Answer

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

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