Mathematica Asked on January 8, 2021
Suppose that I have a Head A
that appears pretty often in my code and, in order to make my outputs look nicer, I define
Format[A[x_]]:=Subscript[A,x];
Now if $A_1$ appears in the output and I try to copy and paste it, the result of the paste is Subscript[A,1]
rather than A[1]
.
I would like to find a way such that the data copied to clipboard is not the representation of the expression, but rather its underlying structure. Just like when, for example, I assign it to a variable.
I suggest a minor adjustment using this code:
Format[A[x_]] := Interpretation[
Subscript[A, x], A[x]];
which does what you expect with copy/paste.
There are other ways to get fancy with Mathematica which can do a lot more, but this code seems to do what is required.
However, if you want the pasted form to be the "raw" form, you can do that with a slight tweak using Defer[]
which was
designed for this purpose. Code follows:
Format[A[x_]] := Interpretation[
Subscript[A, x], (Defer@A)[x]];
Correct answer by Somos on January 8, 2021
You could use MakeBoxes
and create a TemplateBox
that controls both display and interpretation:
A /: MakeBoxes[A[x_], StandardForm] := TemplateBox[
{MakeBoxes[x]},
"A",
DisplayFunction -> Function[SubscriptBox["A", #]],
InterpretationFunction -> Function[RowBox[{"A", "[", #, "]"}]]
]
Answered by Carl Woll on January 8, 2021
Another alternative:
ToInterpretationBox[raw_][formatted_]:=With[{box=ToBoxes[formatted]},InterpretationBox[RowBox[{box}],raw]]
A/:MakeBoxes[A[x_],StandardForm]/;BoxForm`UseIcons:=ToInterpretationBox[A[x]][Subscript[A,x]];
which sets up an InterpretationBox
for A
and this InterpretationBox
is copied by default. Using Copy as -> Input Text
one can copy the input form. If one really wants the behavior OP described I would recommend the approach presented by Carl Woll in his answer to this question.
As a warning when setting up custom output formats: I would recommend using
MakeBoxes[..., StandartForm] /; BoxForm`UseIcons := ...
related to the discussion in https://mathematica.stackexchange.com/a/231387/ the undocumented condition BoxForm`UseIcons
prevents formatting in certain environments especially when using Information
, which might otherwise lead to serious problems: the least of which is lost readability in the documentation the worst are serious errors, when one does not exclude Patterns when setting up the formatting.
Answered by N0va on January 8, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP