In answering this question, I noticed some trickiness regarding empty groups {} in an otherwise verbatim context.
Suppose you capture the contents of an environment verbatim (as in that question), except that \, {, and } still have their normal catcodes so that macros will work. Then the contents of the environment is written to a file. Any empty groups {} that are not consumed by macros will be written to file as literal {}. Is there a way to prevent this? Under such circumstances, what can be done to make macros behave as normally as possible?
Under these conditions, macros won't consume following spaces because the spaces are literal, so it would be logical to delimit the end of a macro with a {}. Except that that is resulting in a literal {}.
Minimal example
The example below uses both verbatim and fancyvrb. In the verbatim approach, each line is captured completely verbatim (stored in \verbatim@line), and then retokenized within \verbatim@processline. In practice, it would be more efficient to deal with each line only once, so using fancyvrb would be better. But both produce the same output, and the verbatim example is more hackable for demonstration purposes.
\documentclass{article}
\usepackage{verbatim}
\usepackage{fancyvrb}
\newwrite\outfile
\makeatletter
\newenvironment{verbatimoutexp}[1]%
{\immediate\openout\outfile=#1%
\def\verbatim@processline{%
\begingroup
% Redefine escapes so they write to file in literal fashion
\edef\{{\@charlb}%
\edef\}{\@charrb}%
\edef\\{\@backslashchar}
\let\textbackslash\@backslashchar
% Retokenize with new catcodes
\everyeof{\noexpand}%
\endlinechar-1\relax
\let\do\@makeother\dospecials%
\catcode`\\=0%
\catcode`\{=1%
\catcode`\}=2%
\xdef\verbatim@line@retok{\expandafter\scantokens\expandafter{\the\verbatim@line}}%
\endgroup
\immediate\write\outfile{\verbatim@line@retok}}%
\@bsphack
\let\do\@makeother\dospecials
\catcode`\^^M\active
\verbatim@start}%
{\@esphack
\immediate\closeout\outfile}
\makeatother
\begin{document}
\def\mymacro{MACRO}
\begin{verbatimoutexp}{test1.txt}
\mymacro{}FollowingText
\end{verbatimoutexp}
\begin{VerbatimOut}[commandchars=\\\{\}]{test2.txt}
\mymacro{}FollowingText
\end{VerbatimOut}
\end{document}
Output (same for both files):
MACRO{}FollowingText
Desired output:
MACROFollowingText
\def\mymacro#1{MYMACRO}– egreg Jan 13 '15 at 00:15{}; otherwise, the following literal character is gobbled. – G. Poore Jan 13 '15 at 00:38