I would like to create custom macros with conditions. For example, I would like to add an "if-condition" to a macro that I created to write derivatives of any order in relation to a single variable. Here is the current code of my macro:

\newcommand{\drv}[3]{\dfrac{\df #2^#1}{\df #3^#1}}

The first argument #1 is the order of derivation, the second #2 the function that we take the derivative and the third #3 the variable of derivation. For example,


will give

enter image description here

I would like to change this code so that it don't display the derivation order #1 if it is equal to 1. But I don't know the syntax, this is why I need your help. I want to write something like

      if #1=1
         \dfrac{\df #2}{\df #3}
         \dfrac{\df ^#1 #2}{\df #3^#1}

Thank you for your help, have a good day.

  • @ChristianHupfer Thank you. I know but I would like to create my own macros, this is just a simple example to understand the use of conditions.
    – user178668
    Jan 1, 2019 at 10:13
  • There already exist esdiff and diffcoeff packages which already can do that (and more: they consider the case of partial derivatives of any order). Why reinvent the wheel?
    – Bernard
    Jan 1, 2019 at 10:25
  • @Bernard the OP said this was just a specific example of a more general question about writing macros.
    – alephzero
    Jan 1, 2019 at 10:29
  • @Bernard I think the question of the OP goes more in the direction of 'How to create macros with conditions?' The derivative is just an example, so using a package will not help him in this case
    – caverac
    Jan 1, 2019 at 10:29
  • @Bernard thank you for introducing me to these packages. Indeed, I was mainly looking to know how to use "if-conditions", the derivation was only one example.
    – user178668
    Jan 1, 2019 at 10:32

1 Answer 1


It's easy with xparse:


\newcommand{\df}{\mathop{}\!d} % use \mathrm{d} if you really prefer it





enter image description here

With o an optional argument is denoted; if it is present, \IfValueT{#1} will return true and use the argument as shown.

With the given definition, \df will behave as expected also in integrals, leaving a thin space before it when necessary.

  • 1
    Thank you, this is perfect. I just do not understand the use of \kern-\scriptspace.
    – user178668
    Jan 1, 2019 at 10:53
  • @Loïc: \scriptspace is the amount of space inserted after a superscript and \kern<length> inserts horizontal space. Thus \kern-\scriptspace precisely cancels the space inserted between e.g. d^{n+1} and f. Jan 1, 2019 at 19:34

You must log in to answer this question.