TeX FAQ's "Patching existing commands" gives a method to add to existing commands that have an optional argument:
\documentclass{article}
\usepackage{letltxmacro}
\newcommand{\rough}[2][\default]{...}
\LetLtxMacro{\OldRough}{\rough}
\renewcommand{\rough}[2][\newdef]{\mumble\OldRough[{#1}]{#2}}
However, it assumes that you want a new default argument "\newdef
". If the default argument is to be kept, you may change "\newdef
" to "\default
", but that's only possible if you have internal knowledge of the previously defined command. Furthermore, if the that value is modified, you have to change it in your patching as well.
Is it possible to add to an existing command with optional arguments in a way that the default argument is kept, even if you don't know what that argument is?
Note: The argument has to still be usable inside the new definition.
Edit: After trying the suggested \xapptocmd
and \xapptocmd
I was still unable to reproduce the desired result in the command I'm working with, clevelref
's \label
.
I would expect the code below to write "aaa", and then apply the label, which is not the case, even when replaced by things such as math, the contents are still not present in the final document:
\documentclass[]{article}
\usepackage{cleveref,xpatch}
\xpretocmd\label{aaa}{}{}
\begin{document}
\label{example}
\end{document}
This gives me the impression that it's not being correctly appended.
Also, when trying to access the second argument of \label
, TeX throws the error Illegal parameter number in definition of \etb@resrvda. \xpretocmd\label{#1#2}
:
\documentclass[]{article}
\usepackage{cleveref,xpatch}
\xpretocmd\label{#1#2}{}{}
\begin{document}
\end{document}
I presume it is because it is detecting the standard definition of \label
, which only has a single parameter, instead of cleverf
's one.
How may these be corrected?
\OldRough
which is let equal to the old definition you can do:\newcommand{\rough}[2][\default]{...} \LetLtxMacro{\OldRough}{\rough} \renewcommand{\rough}{\mumble\OldRough}
.