LuaTeX provides \luaescapestring for escaping characters in Lua strings:
\directlua{
PrintPrettyLatexCode("\luaescapestring\expandafter{\detokenize{LATEX CODE GOES HERE!}}")
}
Addition
The following defines an environment PrettyPrintLatexCode:
The environment contents is written to a temporary file using package filecontents.
The file contents is stored in a macro by \CatchFileEdef of package catchfile.
All characters are read verbatim by using a catcode table, where all slots are set to catcode 12 (other) and the line ends are read as byte 0x10 (\n).
The data are passed via \luatexluaescapestring (that is \luaescapestring in LuaLaTeX) to the function PrettyPrintLatexCode.
The full example:
\RequirePackage{filecontents}
\RequirePackage{catchfile}
\RequirePackage{luacode}
\makeatletter
\newcommand*{\PrettyPrint@FileName}{test.file}
\newenvironment*{PrettyPrintLatexCode}{%
\csname filecontents*\endcsname{\PrettyPrint@FileName}%
}{%
\csname endfilecontents*\endcsname
\CatchFileEdef{\PrettyPrint@FileData}{\PrettyPrint@FileName}{%
\PrettyPrint@CatchSetup
}%
\luadirect{%
PrettyPrintLatexCode("\luatexluaescapestring{\PrettyPrint@FileData}")%
}%
}
\begingroup
\lccode`\~=13 %
\lccode`\9=10 %
\lowercase{\endgroup
\def\PrettyPrint@CatchSetup{%
\luatexcatcodetable\CatcodeTableOther
\endlinechar=13 %
\catcode13=\active
\def~{9}%
}%
}
\makeatother
% Provide a dummy definition for PrettyPrintLatexCode
\luadirect{%
function PrettyPrintLatexCode(str)
texio.write_nl(
"*****************************",
str,
"*****************************",
""
)
end}
\begin{PrettyPrintLatexCode}
\section{Hello World}
Some text with "double" and 'single' quotes.
and unmatched (parentheses].
Umlauts: äöüß
\end{PrettyPrintLatexCode}
\stop
Result of the dummy PrettyPrintLatexCode in the terminal/log file:
*****************************
\section{Hello World}
Some text with "double" and 'single' quotes.
and unmatched (parentheses].
Umlauts: äöüß
*****************************