# Reshape output of TeXForm into one-line string

I am using Mathematica to generate some Matlab code. In order to have a bit of documentation I would like to have a commented line in the Matlab file which holds the Latex form of the original expression. However, there is an issue with linebreaking.

An example:

test = TeXForm[{{a, b, c}, {d, e, f}}]


Looking at test and also ToString@test reveals a couple of linebreaks which are nice for formatting and export to actual Latex documents but not for my purpose. The reason is that I would like to use a string (one line - which may be very long) like "% Expression: " <> ToString@TeXForm@test in the Matlab file ("%" creates comments in Matlab code), which fails because of the linebreaks (only the first row appears as a comment).

So I thought of operating on

test2 = ToString@FullForm@ToString@test
(* "\\left(\n\\begin{array}{ccc}\n a & b & c \\\\\n d & e & f \\\\\n\\\end{array}\n\\right)" *)


where I would then easily replace/delete the \n. Yet, to no avail - see:

StringDelete[test2, "\n"]
(* "\\left(\n\\begin{array}{ccc}\n a & b & c \\\\\n d & e & f \\\\\n\\\end{array}\n\\right)" *)
StringPosition[test2, "\n"]
{}


So I wonder how can I remove the linebreaks from TeXForm and ideally also replace the \\ with \ in the final string. This also seems to be a bit tricky because of Mathematica's special characters in strings.

The final result of something like customTeXForm[test] should be the string \left(\begin{array}{ccc}a & b & c \\d & e & f\\\end{array}\right)

• does StringReplace[ToString[test], { "\n" -> ""}] work?
– kglr
Jul 17, 2017 at 10:46
• @kglr In fact, it does. I would bet that I tried it before I asked the question here - but anyway... Thank you very much :) Jul 17, 2017 at 10:49
• in case you decide to keep the question, i posted the comment as an answer.
– kglr
Jul 17, 2017 at 10:54
• @kglr Am I missing something or does StringDelete[ToString[test], "\n"] work as well? This whole things seems like a simple mistake. Jul 17, 2017 at 12:50
• @MrWizard, yes it does! Just didn't occur to me:(
– kglr
Jul 17, 2017 at 12:54

StringReplace[ToString[test], { "\n" -> ""}]