[Tex/LaTex] How to define optional second argument for macro

cross-referencingmacrosoptional arguments

I've defined a command which lets me quickly reference to the number (of figure or table) AND page at the same time:

Command

 \newcommand{\kplref}[2]{~\ref{#1}, S.~\pageref{#1}{#2}\xspace}

The second argument is used for adding something like "page 6f" or "page 6ff", but I would like to have it optional and do not want to be forced to enter an empty {} each time.

However, defined like that the command takes the first letter of a following word as its second argument (see example).

  • How can I change the command definition to avoid that?
  • Or is there maybe already a ready-made command which does exactly what I want?

Result

enter image description here

Example document

\documentclass[11pt, parskip=half]{scrbook}


\usepackage{xspace}
\newcommand{\kplref}[2]{~\ref{#1}, S.~\pageref{#1}{#2}\xspace}

\begin{document}

%\tableofcontents

\section{Section1}
\label{sec1}

This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph.

This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph.

\section{Section2}

Now lets refer to section~\kplref{sec1}.

It fails if other text is following and there is no second argument like here:\newline 
\kplref{sec1} shows the nonsense of this document.

\end{document}

Best Answer

You should define your command as

\newcommand{\kplref}[2][]{\ref{#2}, S.~\pageref{#2}#1\xspace}

and use the optional argument as in

\kplref[f]{sec1}

MWE:

\documentclass[11pt, parskip=half]{scrbook}


\usepackage{xspace}
\newcommand{\kplref}[2][]{\ref{#2}, S.~\pageref{#2}#1\xspace}

\begin{document}

%\tableofcontents

\section{Section1}
\label{sec1}

This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph.

This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph. This is a nonsense paragraph.

\section{Section2}

Now lets refer to section~\kplref{sec1}.

It doesn't fail if other text is following and there is no optional argument like here:\newline
\kplref{sec1} shows the nonsense of this document.

This is how to use the optional argument: \kplref[f]{sec1} which shows again the nonsense of this document.

\end{document} 

enter image description here

Related Question