In some situations I wish there was a way to define a command \tmp so that
- if
\tmpdoes not exist: Defined\tmp - if
\tmpdoes exits: Redefine\tmp
My current approach is simply to use either \newcommand or \renewcommand. However, this means that I often have to change from one version to the other if I reorder my documents and sometimes limits the overall reusability of my code.
In this question I learned about \providecommand, which almost solves my problem: It can be used irrespective of whether \tmp is defined, but it only defines on the first occurrence and does not overwrite. This lead me to the naive attempt:
\newcommand{\overwritecommand}[2]{
\providecommand{#1}{#2}
\renewcommand{#1}{#2}
}
However, this approach is obviously not general enough:
% it works for
\overwritecommand{\tmp}{test}
% but not for commands with arguments like
\overwritecommand{\tmp}[1]{test: #1}
% Error: You can't use `macro parameter character #' in horizontal mode.
Is there any other way to achive the define or overwrite behavior?
\def? – jon Feb 18 '15 at 18:13\defsomehow allow to use optional arguments as well? – bluenote10 Feb 18 '15 at 18:15\newcommand{\declarecommand}[1]{\providecommand{#1}{}\renewcommand{#1}}But, for your own safety, *don't* use it! Something like\declarecommand{\box}[1]{\fbox{#1}would be funnily disastrous. – egreg Feb 18 '15 at 18:15xparsehas\DeclareDocumentCommand, which is much easier to use; there's also various\def-related commands in the packageetoolbox. – jon Feb 18 '15 at 18:18