TransWikia.com

Preserving newlines in body of NewDocumentEnvironment when writing to an external file

TeX - LaTeX Asked by midtiby on April 3, 2021

I am working on a system for providing hints for exercises in a different location of the typeset document.
The current approach is based on saving the content of the hint environment to a file.
This sort of works, but is problematic when used on verbatim content that covers multiple lines.
The issue appears to be that newlines in the body of the hint environment are removed before the
content is written to the file.

After running the code given at the end of the question, I would like the following content to be in the file "hintfile.tex"

Example
d
with 
multiple lines.

The content of the file is the following after running the code

Example d with multiple lines.

Here comes the code for the example

documentclass{article}

ExplSyntaxOn
% Open a file for writing
iow_new:N g_hintfile_iow
iow_open:Nn g_hintfile_iow {hintfile.tex}

% Create an environment that saves the body 
% to the opened file
NewDocumentEnvironment{hint}{O{}+b}{%
iow_now:Nn g_hintfile_iow { #2 }
}{}

% Create command to close the file
NewDocumentCommand{closehintandsolutionfile}{}{
iow_close:N g_hintfile_iow
}

ExplSyntaxOff

begin{document}
Hello world

begin{hint}
Example
d
with 
multiple lines.
end{hint}

begin{verbatim}
Example
d
with 
multiple lines.
end{verbatim}

section{From external file}

closehintandsolutionfile
input{hintfile}
end{document}

One Answer

Something like that?

documentclass{article}

usepackage{xparse} % added

ExplSyntaxOn
% Open a file for writing
iow_new:N g_hintfile_iow
iow_open:Nn g_hintfile_iow {hintfile.tex}

% Create an environment that saves the body 
% to the opened file
NewDocumentEnvironment{hint}{O{}+b}{%
iow_now:Nn g_hintfile_iow {setlength{parindent}{0pt} #2 }
}{}

% Create command to close the file
NewDocumentCommand{closehintandsolutionfile}{}{
iow_close:N g_hintfile_iow
}

ExplSyntaxOff

begin{document}
Hello world

begin{hint}
Example   
d     
with  
multiple lines.
end{hint}

begin{verbatim}
Example
d
with 
multiple lines.
end{verbatim}

section{From external file}

closehintandsolutionfile
input{hintfile}
end{document}

x

Answered by Simon Dispa on April 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP