0

Is it possible to build a macro accepting 0, 1 or 2 arguments ? Why ? I want to have the following functionalities.

  1. \exercice will print Exercice alone.
  2. \exercice{2} will print Exercice (2 pts).
  3. \exercice{2}{Source:...} will print Exercice (2 pts) [Source: ...].
  • Check the xparse documentation. It offers various ways to implement optional arguments. – Ulrike Fischer Oct 25 '17 at 14:04
  • 2
    Yes you can, although the usual way is to use optional arguments \exercise, \exercise[2] and \exercise[2][Source: ...]. With xparse package you can do \NewDocumentCommand\exercise{oo}{Exercise\IfValueT{#1}{ (#1 pts)}\IfValueT{#2}{ [#2]}} which defines \exercise[..][..]; and if you substitute oo for gg in the defintion you will define what you asked for: \exercise{..}{..}. – Manuel Oct 25 '17 at 14:05
  • I like the \NewDocumentCommand. I did not know it. – projetmbc Oct 25 '17 at 19:03
5

Better: use a key-value syntax.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\exercice}{O{}}
 {
  \group_begin:
  \keys_set:nn { projetmbc/ex } { #1 }
  \par\vspace{\topsep}\noindent Exercice
  \tl_if_empty:NF \l_projetembc_ex_pts_tl
   { ~(\tl_use:N \l_projetembc_ex_pts_tl\nobreakspace pts) }
  \tl_if_empty:NF \l_projetembc_ex_note_tl
   { ~[\tl_use:N \l_projetembc_ex_note_tl] }
  \group_end:
  \quad\ignorespaces
 }
\keys_define:nn { projetmbc/ex }
 {
  points .tl_set:N = \l_projetembc_ex_pts_tl ,
  note   .tl_set:N = \l_projetembc_ex_note_tl ,
 }
\ExplSyntaxOff

\begin{document}

\exercice Text

\exercice[points=2] Text

\exercice[note=Source: folklore] Text

\exercice[points=4,note=Source: folklore] Text

\end{document}

enter image description here

  • This API is very good. Thanks for this even if I think that in my case there is no really necessity to indicate the options. But regarding the generality of your solution, I have marked to be an accepted answer. – projetmbc Oct 25 '17 at 19:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.