[Tex/LaTex] How to remove trailing spaces at the end of each line in a block of code

environmentsspacing

NOTE: I have to adapt this question to reflect Martin's answer (that actually not 100% solves the original problem) so I can accept it. 🙂

If I work without standalone document class, I usually put the following setting

\newsavebox\IBox
\savebox\IBox{\raisebox{\depth}[\totalheight]{XeTeX runs very slowly!}}    
% trimmed for simplicity

in the preamble.

However, when using standalone document class (to divide my project into one main input file & several sub-files), I am forced to move a setting related to each sub-file to its body as follows.

% sub-file.tex
\documentclass{standalone}    
\usepackage{pstricks}

\begin{document}
\newsavebox\IBox%
\savebox\IBox{\raisebox{\depth}[\totalheight]{XeTeX runs very slowly!}}%    
% trimmed for simplicity    

\begin{pspicture}(\LEFT,\BOTTOM)(\RIGHT,\TOP)
% trimmed for simplicity
\end{pspicture}%
\end{document}

Adding a trailing % to the end of each line of setting code is cumbersome so I need a way not to do this manually. The following code shows what I need; There is a \RemoveTrailingSpaceInThisBlock macro to do the job.

% sub-file.tex
\documentclass{standalone}    
\usepackage{pstricks}    

\begin{document}
\RemoveTrailingSpaceInThisBlock% to remove trailing space in the current block
\newsavebox\IBox
\savebox\IBox{\raisebox{\depth}[\totalheight]{XeTeX runs very slowly!}}    
% trimmed for simplicity    

\begin{pspicture}(\LEFT,\BOTTOM)(\RIGHT,\TOP)
% trimmed for simplicity
\end{pspicture}
\end{document}

Is there such a macro to remove the trailing spaces at the end of each line in a code block?

Best Answer

You could use \endlinechar=-1\relax to make TeX ignore all line endings and not take them as spaces. If you want to make this an environment place it in the begin code of it. Otherwise you could just place it inside \begin{document} and it will be valid till the end of that environment, even when the file is processed as sub-file.

Note that the \relax is just an end-marker to terminate the number. You can also use a space or use \m@ne instead of -1. This needs \makeatletter of course.

However, this will not ignore any real spaces at the end of any line, just the space insert by the end-of-line character.


The LaTeX3 package expl3 also provides \ExplSyntaxOff and \ExplSyntaxOn which will switch into a similar mode as the one of the preamble and back again. This mode AFAIK ignores spaces completely. It also allows _ and : to be used in macro names which will interfere with the normal usage of this characters (e.g. in math expressions). Therefore you shouldn't use it for all of your document, just for the preamble-like stuff.