I had another answer to this question (now located here) that used the global variable $PreRead
to convert raw strings to InputForm
prior to evaluation. Unfortunately, that method only works when evaluating the package file interactively, as you would a notebook file. It does not work when loading a package with Get
, because $PreRead
is not applied to the expressions that are read in from the package file before they are evaluated.
On the other hand, if we are just interested in using raw strings in package files that are to be read in, we can easily preprocess the package files to replace raw strings as they are being read.
One method (possibly not for the faint of heart) is to overload Get
for designated package files. Suppose we want to implement the Python raw string syntax for any package file whose name ends with _raw.m
. In your init.m
file, place the following code:
Unprotect[Get];
Get[file_String] /; StringMatchQ[file, "*_raw.m"] && FileType[file] === File :=
ToExpression@StringReplace[
Import[file, "Text"],
"r\"\"\"" ~~ Shortest[str__] ~~ "\"\"\"" :> ToString@InputForm@str
]
Protect[Get];
Now make a test package file test_raw.m
with contents
s = r"""\documentclass[12pt,titlepage]{article}
\begin{document}
It is known that $\sin(0)=""" <> ToString[Sin[0]] <> r"""$
\end{document}"""
Print[s]
Now, at the command line,
$ math -script test_raw.m
returns
\documentclass[12pt,titlepage]{article}
\begin{document}
It is known that $\sin(0)=0$
\end{document}
It also works when using Get["test_raw.m"]
or << test_raw.m
. The "context" form <<test_raw`
doesn't work; to get it to work we'd have to sacrifice the underscore in the file name, which isn't allowed in a context specifier. Then we'd want to lengthen the designator suffix, maybe to rawstring.m
, to reduce the chance of other package files accidentally matching the pattern.
TextCell
but not sure I am doing it correctly. Screen shot !Mathematica graphics I do not know how to do the ctrl-9 and ctrl-0 stuff in text file. I use plain text .m files. If you can show how to do it, using my example above, without using notebook interface, just using plain text input, then that will help $\endgroup$InputForm
of Jens' solution isTextCell["\\abc\\def\\ghi"]
. $\endgroup$