I have a function with the following (simplified) structure:

myfunc[someInput_] :=
  Module[{var1, var2, var3},

   var1 = someInput*3;
   Print["text1: ", var1];
   var2 = someInput^5;
   Print["text2: ", var2];
   var3 = var1*var2;
   Print["text3: ", var3];

What I would like to do is the following: For each of the prints, I would like to print first the text (e.g. 'text1') in a single cell, and then the variable (e.g. 'var1') into another cell right underneath and then group just these two cells, such that I could collapse them later on and the only visible thing is the text ('text1').

The problem is that I am trying to find a way that does not involve the usage of Section, Subsection etc. since that would interfere with my Notebook layout... I would just like to have standard output cells which I group according to my liking (but 'automatically' within the function).

Based on this post I tried:

CellPrint@ExpressionCell[Print["text1: "]; Print[var3];, "Output"]; 

but this did not group the two cells and it also prints an additional, empty cell underneath. So far, I cannot come up with / find anything else and would thus appreciate any input!


1 Answer 1


You can observe how grouping is implemented if you do it manually (under the menu Cell > Grouping > Group Cells), and then inspect the cell expressions (Cell > Show Expression). Cells obtain the CellGroupingRules option, with cells in the same group having the same numerical priority.

To emulate this, you can use a global counter that you increase for every new printed group:

$GroupCounter = 1000;
printCellGroup[exprs__] := 
 With[{g = $GroupCounter ++}, 
  CellPrint[ExpressionCell[#, "Output", 
      CellGroupingRules -> {"GroupTogetherGrouping", g}] & /@ 

printCellGroup["Text 1", x, x^2]
printCellGroup["Text 2", y, y^3]

enter image description here


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.