There are many instances where I need to create my own commands and a lot of the time I also need them to have an optional argument. No problems there.
However, I needed to have one of my commands inside the title of a section and then no .pdf was produced. Here is a simplified code:
\documentclass[12pt]{article}
\makeatletter
\newcommand{\foo}{\@ifnextchar[{bracket}{parenthesis}}
\makeatother
\begin{document}
\section{\foo()}
\foo()
\section{\foo[]}
\foo[]
\end{document}
If \section{\foo()} and \section{\foo[]} are removed, then everything seems to work fine. Also, if you remove them, compile, get your .pdf, then add just one of them to the code, then you still get a .pdf even though you couldn't earlier, and if you add the second one it still complies. Always with a bunch of errors.
If I make it more complicated - let's say I have redefined a preexisting command - then not even the old definition of the command works inside the \section environment:
\documentclass[12pt]{article}
\let\doublevowelhyphen\H
\makeatletter
\renewcommand{\H}{\@ifnextchar[{\@foo}{\@ffoo}}
\def\@foo[#1]#2{#2.#1}
\def\@ffoo#1{#1.}
\makeatother
\begin{document}
\section{\doublevowelhyphen{o}}
\doublevowelhyphen{o}
\section{\H{1}}
\H{1}
\section{\H[1]{2}}
\H[1]{2}
\end{document}
Here I get a similar behaviour as before.
Finally, I seem to get additional errors if I'm using the hyperref package which I also need.
I suspect it has something to do with the @ symbol by I don't really understand what's going on. Can someone, please, explain why this is happening?
\fooand\Hare fragile and blow up when being written to the.tocfile. You need to make them robust. Also commands with optional arguments hardly work in PDF bookmarks, so you may have to need\texorpdfstringfromhyperref. If your command will have a mandatory argument (like in the second example) then you can usexparseand\NewExpandableDocumentCommand. Can you explain the exact use case, please? – Phelype Oleinik Jun 29 '19 at 16:59\protectbefore\Hand\foo? – Mico Jun 29 '19 at 17:39