There are two methods in this answer, the last one is the best IMO
First method
You could use
flattenThenAutoCollapse[] :=
(
SelectionMove[EvaluationCell[], All, GeneratedCell];
FrontEndTokenExecute["ExpandSelection"];
FrontEndTokenExecute["CellGroup"];
SelectionMove[EvaluationCell[], All, GeneratedCell];
FrontEndTokenExecute["SelectionCloseUnselectedCells"]
)
(Version 7 users can replace EvaluationCell
with EvaluationNotebook
)
And then this works
Print["hello"]
Print["bye"]
flattenThenAutoCollapse[]
Whereas this does not, as you correctly point out
Print["hello"]
Print["bye"]
AutoCollapse[]
This method does nothing in the case in which there is no output, but at least it will do no damage either.
Things can go horribly wrong if you use CellPrint
though. In this case the generated cells will not be grouped with the input cell. Expanding the selection will cause a cellgroup corresponding to SubSection or something similar to be selected, if you notebook is structured this way. Or simply all cells may be selected if you have no such structure. At that point FrontEndTokenExecute["CellGroup"]
will do damage.
Second method
The following is then a bit more stabile. It does however rely on inelegantly setting and restoring CellTags
.
flattenThenAutoCollapse[] :=
Block[{evCell, genCells, allCells, storedTags},
evCell = EvaluationCell[];
SelectionMove[evCell, All, GeneratedCell];
genCells = SelectedCells[];
allCells = Prepend[genCells, evCell];
storedTags = CurrentValue[#, CellTags] & /@ allCells;
SetOptions[#, CellTags -> "flattenThenAutoCollapse"] & /@ allCells;
NotebookLocate["flattenThenAutoCollapse"];
FrontEndTokenExecute["CellGroup"];
SelectionMove[evCell, All, GeneratedCell];
FrontEndTokenExecute["SelectionCloseUnselectedCells"];
SetOptions[#, CellTags -> #2] & @@@
Transpose[{allCells, storedTags}];
]
I suppose this cannot be made to work in version 7, because it works with CellObjects.
Example
Print[1]
Print[2]
CellPrint[Cell["hello"]]
Print[1]
flattenThenAutoCollapse[]
closes the input cell after grouping the generated cells with the input cell, despite the fact that printed cells are normally not grouped with the input cell.