0
$\begingroup$

I am trying to implement a function that takes a Graphics instruction as its argument and then duplicated it in a new InputCell. I'm aware about the render of Graphics is typesetting process as explained here. And use the techniques in that post I came up with the following

Unprotect@Hold;
mk : MakeBoxes[Blank[Hold], _] /; ! TrueQ[$hldGfx] ^:= 
  Block[{$hldGfx = True, Graphics, Graphics3D}, mk];
Protect@Hold;

SetAttributes[printGraphics, HoldFirst];
printGraphics[graphics_] :=
 CellPrint[Cell[BoxData[RowBox[{
      ToBoxes[Hold[graphics]]
      }]], "Input"]] 

RunningprintGraphics@Graphics[{Red, Disk[]}] will create a cell with Hold[Graphics[{Red, Disk[]}]].

My question is that if it's possible to create a cell without Hold.

If you are interested in the reason I need this, here is the functionality I'm working on: see Section Minimal example in here (Github: PrettyColorize). Plot, Plot3D or other plotting function can be easily printed while Graphics and Graphics3D are a little tricky and I'm not sure how to get over.

$\endgroup$
2
  • $\begingroup$ Use Unevaluated instead of Hold when calling ToBoxes. That should be all you need. $\endgroup$
    – b3m2a1
    May 21, 2019 at 5:59
  • $\begingroup$ Also that MakeBoxes is probably a bit more than you want if you can control the Print $\endgroup$
    – b3m2a1
    May 21, 2019 at 6:01

2 Answers 2

2
$\begingroup$

Here's a way to avoid the MakeBoxes call and the Hold at the same time:

SetAttributes[printGraphics, HoldFirst];
printGraphics[graphics_Graphics] :=
 Block[{myGraphics, gb},
  gb =
   Replace[Hold[graphics], 
    Hold[Graphics[a___]] :>
     (ToBoxes[Unevaluated@myGraphics[a]] /. "myGraphics" -> "Graphics")
    ];
  CellPrint[
   Cell[BoxData[gb], "Input"]
   ]
  ]
$\endgroup$
1
  • $\begingroup$ Cool! I do need to look more into these Hold/Unevaluated/Inactive/... functions. Thanks! $\endgroup$
    – Louis Yu
    May 21, 2019 at 15:05
1
$\begingroup$

One possibility is to use DisableFormatting:

printGraphics[graphics_] := CellPrint @ Cell[
    BoxData @ MakeBoxes[DisableFormatting[graphics]][[1, 1, 1]],
    "Input"
]

For example:

printGraphics[Graphics[{Circle[]}]]

Graphics[{Circle[{0, 0}]}]

$\endgroup$
1
  • $\begingroup$ Thanks! Good to know this DisableFormatting function. $\endgroup$
    – Louis Yu
    May 21, 2019 at 14:58

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.