Handling optional commas in text
Unobtrusive parts in a TeX file can be made with a single character if it is an active character. Here is how you can do it with ;
for \optionalcomma
(if you don't need real semicolons).
\documentclass{memoir}
\newcommand{\optionalcomma}{,}
% \newcommand{\optionalcomma}{}
\catcode`;=\active
\newcommand;{\optionalcomma}
\begin{document}
Well, what do you think; about this?
\end{document}
Piece of cake if you're free to use LuaLaTeX. :-)
The code below sets up two Lua functions, called functionA
and functionB
, and two LaTeX utility macros, called \OptionA
and \OptionB
to activate the respective Lua functions. By "activating" a Lua function, I mean assigning it to LuaTeX's process_input_buffer
callback, which operates on the input at a very early stage, i.e., before TeX starts its usual macro expansion operations. Both functionA
and functionB
employ Lua's powerful gsub
("global substitution") string function.
I would assume that, in practice, your document will only contain either an \OptionA
directive or an \OptionB
directive. Ideally, you'd issue the directive immediately after \begin{document}
.
The following screenshot shows the output of Han så,, at jeg kom, og at jeg var glad.
if \OptionA
is executed at the start of the document
environment.
% !TEX TS-program = lualatex
\documentclass{memoir}
\usepackage[danish]{babel}
%% Set up two Lua functions:
\directlua{%
function functionA ( s ) return ( s:gsub(",," ,",") ) end
function functionB ( s ) return ( s:gsub(",," , "") ) end
}
%% Set up two LaTeX macros to activate the corresponding Lua functions:
\newcommand{\OptionA}{\directlua{luatexbase.add_to_callback(
"process_input_buffer" , functionA , "functionA")}}
\newcommand{\OptionB}{\directlua{luatexbase.add_to_callback(
"process_input_buffer" , functionB , "functionB")}}
\begin{document}
\OptionA % or: \OptionB
Han så,, at jeg kom, og at jeg var glad.
\end{document}
You might (ab)use \,
for the purpose. Use \thinspace
if you really need the original meaning of \,
in text mode.
\DeclareRobustCommand{\,}{\ifmmode\mskip\thinmuskip\else\optionalcomma\fi}
\newcommand{\optionalcomma}{} % standard, no comma
\newcommand{\activateoptionalcomma}{\renewcommand{\optionalcomma}{,}}
Example with no optional comma
\documentclass{memoir}
\DeclareRobustCommand{\,}{\ifmmode\mskip\thinmuskip\else\optionalcomma\fi}
\newcommand{\optionalcomma}{} % standard, no comma
\newcommand{\activateoptionalcomma}{\renewcommand{\optionalcomma}{,}}
\begin{document}
Well, what do you think\, about this?
\end{document}
Example with optional comma activated
\documentclass{memoir}
\DeclareRobustCommand{\,}{\ifmmode\mskip\thinmuskip\else\optionalcomma\fi}
\newcommand{\optionalcomma}{} % standard, no comma
\newcommand{\activateoptionalcomma}{\renewcommand{\optionalcomma}{,}}
\activateoptionalcomma
\begin{document}
Well, what do you think\, about this?
\end{document}