1
$\begingroup$
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*)
$\endgroup$
1

2 Answers 2

1
$\begingroup$

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*)

$\endgroup$
1
  • $\begingroup$ fine, I like your usage of Set for Boxes. $\endgroup$ Commented Jun 15, 2013 at 14:39
1
$\begingroup$

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*)"

$\endgroup$
3
  • $\begingroup$ "a (*what*)" this is also one expected result. $\endgroup$ Commented Jun 15, 2013 at 5:20
  • $\begingroup$ @HyperGroups Updated, hope it helps. $\endgroup$
    – jamtype7
    Commented Jun 15, 2013 at 5:55
  • $\begingroup$ Well,I need ToExpression, See my edit, better to not use StringReplace and make it suit for my original example. $\endgroup$ Commented Jun 15, 2013 at 6:28

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.