0

I defined a new command called \dofile to reference a file that does not have a permanent name yet. The command by default returns the name of the file in typewriter font, since that is how I want it to appear in most places in the document. But since I wanted to have access to the file name without formatting just in case, I added an optional parameter that, when set equal to 1, returns the file name in plain text.

I am having trouble getting the spacing to be correct in all four possible use-cases.

In the provided working example, the spacing is correct in all but the second line, in which I call the command without the optional argument, outside of the \texttt{} environment. I was able to fix the spacing, but at the cost of adding extra space to the fourth case (fifth line), in which I call the command without the optional argument, inside of the \texttt{} environment.

My code is the following:

\documentclass{article}
\setlength\parindent{0pt}
\newcommand{\dofile}[1][0]{%
    \ifnum#1=1
    \texttt{MyFile.do}%
    \else%
    MyFile.do%
    \fi}
\begin{document}
    In this line I reference MyFile.do without the command.\\
    In this line I reference \dofile without the optional argument.\\
    In this line I reference \texttt{MyFile.do} without the command.\\
    In this line I reference \dofile[1] with the optional argument.\\
    In this line I reference \texttt{\dofile} without the optional argument.
\end{document}
  • 2
    LaTeX consumes spaces after macros without arguments. The easiest workaround is to add braces after your macro, that is type \dofile{}. This consequence, in general, is explained in another post. – Celdor Jun 05 '22 at 00:45
  • Thank you, this workaround works well enough for my purpose. I will have a look at the solution you linked. A followup question, if you don't mind: why does LaTeX not consume the space after the macro when it is called inside \texttt{}? – Felipe Tappata Jun 05 '22 at 00:53
  • 1
    Roughly speaking, it's just the way latex parses tokens, interprets a sequence of tokens as a macro, and then expands macros until primitives or regular characters are left. I'd read the link I provided because someone has already explained that in a better way than I can in this comment. For more info, overleaf has a blog on this topic: How TeX macros actually work – Celdor Jun 05 '22 at 02:11
  • 2
    An alternative to using {} at the end would be to load the xspace package and put \xspace at the of the definition of \dofile, though an argument could be made that this encourages bad habits. – frabjous Jun 05 '22 at 02:35
  • You are talking about TeX feature, no LaTeX feature. – wipet Jun 05 '22 at 12:33

0 Answers0