1
ToExpression[RowBox[{"a","(*","what", "*)"}],StandardForm]

This conversion above ignores the commment content (*what*)

The result I expected is something like the DisplayForm below.

RowBox[{"a","(*","what","*)"}]//DisplayForm

enter image description here

Update: one of my test code, how to improve it, and not use (StringReplace) if possible.

RowBoxtoString[x_]:=StringReplace[
ToString[ToExpression[x/.RowBox[{"(*",t_,"*)"}]:>"CommentLeft"<>(StringJoin@@t)<>"ComentRight"],
StandardForm],
Shortest["CommentLeft"~~t__~~"ComentRight"]:>"(*"<>t<>"*)"]

RowBoxtoString[RowBox[{"(*","Comment Content","*)"}]]
(*Comment Content*)
HyperGroups
  • 8,619
  • 1
  • 26
  • 63

2 Answers2

1

I guess commment is not expression, so use NotebookWrite[nb, content] may help.

NotebookWrite[SelectedNotebook[], StringJoin @@ RowBox[{"a", "(*", "what", "*)"}]]

results: a (*what*) which a is still a symbol.

If you want the output to be a single string:

NotebookWrite[SelectedNotebook[], 
  "\"" <> (StringJoin @@ RowBox[{"a", "(*", "what", "*)"}]) <> "\""]

results: "a(*what*)"

jamtype7
  • 401
  • 3
  • 6
1

Here's a way, with a couple of output methods :-

First, setting up a RowBox template, with some non-comment objects. (The template is useful for setting up more complex FullForm expressions.)

Clear[a, b]
c = FullForm@ToBoxes[a == b]

RowBox[List["a", "\[Equal", "b"]]

Now editing the RowBox parameters, (or substituting values into the FullForm object):

c[[1, 1, 2]] = "(*what*)";
c[[1, 1, 3]] = Sequence[];
c

RowBox[List["a", "(*what*)"]]

c still has a FullForm wrapper at this point, so First is used to reach the RowBox object.

DisplayForm@First@c

a(*what*)

Alternatively, displaying as regular output, (or as "Input", ready for evaluation):

CellPrint@Cell[BoxData@First@c, "Output"]

a(*what*)

Finally as a function :-

RowBoxtoString[x_, y_] := Module[{a, b, c},
  c = FullForm@ToBoxes[a == b];
  c[[1, 1, 1]] = x;
  c[[1, 1, 2]] = y;
  c[[1, 1, 3]] = Sequence[];
  CellPrint@Cell[BoxData@First@c, "Output"]]

RowBoxtoString["a", "(*what*)"]

a(*what*)

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108