Including default parameter into \def
Just define \graffito
with an optional argument:
\documentclass{article}
\usepackage{lipsum}
\makeatletter
\newcommand{\graffito}[2][0.7em]{%
\marginpar
[\graffito@setup{#1}\raggedleft\hspace{0pt}#2]
{\graffito@setup{#1}\raggedright\hspace{0pt}#2}%
}
\newcommand\graffito@setup[1]{%
\vspace{#1}%
\parindent=0pt \lineskip=0pt \lineskiplimit=0pt
\tolerance=2000 \hyphenpenalty=300 \exhyphenpenalty=300
\doublehyphendemerits=100000
\finalhyphendemerits=\doublehyphendemerits
\itshape\footnotesize
\leavevmode\color{Black}%
}
\makeatother
\begin{document}
This has a graffito\graffito{This is a standard graffito}
\lipsum[1][1-5]
This has a graffito\graffito[-0.7em]{This is a moved up graffito}
\lipsum[1][1-5]
This has a graffito\graffito[1cm]{This is a moved down graffito}
\lipsum[1][1-5]
\end{document}
Side note: the original code has %
after 300
and 100000
: they are wrong.
Since you're using LaTeX syntax anyway, you can use the LaTeX command \newcommand
to set a default argument with: \newcommand\graffito@setup[1][0.7em]{\vspace{#1}...}
. If you want to not use LaTeX syntax for educational purposes, you can do the following:
We need a first macro which checks whether the optional argument follows. For this we use \futurelet
(definition made \protected
because we need an assignment here):
\protected\def\mycmd{\futurelet\next\mycmd@a}
We need to check whether the next token is a bracket, if it is the next macro reads its argument, else we give it its default.
\def\mycmd@a
{%
\ifx[\next
\afterelsefi{\mycmd@b}%
\else
\afterfi{\mycmd@b[0.7em]}%
\fi
}
Here I use the macros \afterelsefi
and \afterfi
for some logic branching. They eat their argument and put it after \fi
.
\long\def\afterelsefi#1\else#2\fi{\fi#1}
\long\def\afterfi#1\fi{\fi#1}
Finally the last macro needed for this, this one is the one generating the output:
\long\def\mycmd@b[#1]%
{%
Argument was: \texttt{\detokenize{#1}}%
}
Complete MWE:
\documentclass[]{article}
\makeatletter
\long\def\afterelsefi#1\else#2\fi{\fi#1}
\long\def\afterfi#1\fi{\fi#1}
\protected\def\mycmd{\futurelet\next\mycmd@a}
\def\mycmd@a
{%
\ifx[\next
\afterelsefi{\mycmd@b}%
\else
\afterfi{\mycmd@b[0.7em]}%
\fi
}
\long\def\mycmd@b[#1]%
{%
Argument was: \texttt{\detokenize{#1}}%
}
\makeatother
\begin{document}
\mycmd
\mycmd[1em]
\end{document}