Redirecting CellPrint output
a) notice that depending on the settings Print
may be printed to the MessagesNotebook
while CellPrint
always goes to the parent notebook.
b) I'm not sure what is the context so I will just leave those links here:
Can I Print to a different notebook? (within the context of the same kernel)
Temporarily redirect the output of Print[ ] to a second file
c) the answer:
The problem is that you are doing CellPrint @ ExpressionCell @ Cell[...
. Here is what you can do:
f[] := Module[{}, Print["Bob"];
CellPrint[Cell["", Background -> Blue, "Print"]];
Print["Bill"]]
printlist = {};
Block[{Print =
AppendTo[printlist, ExpressionCell[Row[{##}], "Print"]] &,
CellPrint = AppendTo[printlist, {##}] &}, f[]];
g[] := Map[CellPrint, Flatten[printlist, 1]]
h[] := CreateDocument[Flatten[printlist, 1]]
f[];
g[];
Why not wrap ExpressionCell
only around Print
calls? For example:
printlist={};
Block[
{
Print = AppendTo[printlist, Thread[ExpressionCell[{##}, "Print"]]]&,
CellPrint = AppendTo[printlist, #]&
},
f[]
];
g[] := CellPrint /@ Flatten @ printlist
h[] := CreateDocument[
Flatten @ printlist
]
Then:
g[];
and:
nb = h[];
CurrentNotebookImage[nb]
seem to do what you want.
CellPrint >> Details
:
In CellPrint[expr]
:
If expr has head TextCell, ExpressionCell, or CellGroup, it is inserted unchanged into the notebook.
So changing heads Cell
to Sequence
in the first argument of ExpressionCell
works:
ClearAll[g, h]
g[] := Map[CellPrint, ExpressionCell[# /. Cell -> Sequence, "Print"] & /@
Flatten[printlist, 1]]
h[] := CreateDocument[ExpressionCell[# /. Cell -> Sequence, "Print"] & /@
Flatten[printlist, 1]]
g[];
h[]