0

I have this body:

\begin{center}
  \includegraphics[scale=0.8]{image.png}
  \captionof{figure}{Image Caption}
\end{center}

But I'd like to simplify it to:

\mygraphics[scale=0.8]{image.png}{Image Caption}

with:

\newcommand{\mygraphics}[2][???]{%
  \begin{center}%
    \includegraphics[???]{#1}%
    \captionon{figure}{#2}%
  \end{center}%
}
Stewart
  • 703
  • Does this mean it's a simple matter of \newcommand{\mygraphics}[2][]{ ... \includegraphics[#1]{#2}\caption{figure}{#3}...}? Even if someone puts several options into it like [xscale=\textwidth,yscale=\textheight]? – Stewart Mar 02 '21 at 08:59
  • \newcommand{\mygraphics}[3][]{ ...}. You have three arguments. The optional parameter is always the first. – campa Mar 02 '21 at 09:00
  • 2
    Fro bottom up: replace #2 with #3; #1 with #2, [???] with [#1]; [???] with []; [2] with [3] – egreg Mar 02 '21 at 09:03
  • I've just made those changes, but get an error. Question updated. – Stewart Mar 02 '21 at 09:04
  • 1
    As an aside, \begin{center}\centering... doesn't make much sense, \begin{center} should be enough. – Skillmon Mar 02 '21 at 09:16
  • Ok, yes that helps. Thanks! I needed to delete *.{aux,toc,lof} and rerun to solve the error. – Stewart Mar 02 '21 at 09:57

1 Answers1

0

Solution:

\newcommand{\mygraphics}[3][]{%
  \begin{center}%
    \includegraphics[{#1}]{#2}%
    \captionon{figure}{#3}%
  \end{center}%
}

After first changing my script to this I got:

! You can't use `macro parameter character #' in horizontal mode.

However I rm *.{aux,lof,lot,log,toc,out} and then everything worked.

Stewart
  • 703
  • 1
    When you forward optional arguments, you should use [{#1}] instead of [#1]. In the case of \includegraphics it is unlikely to make a difference (because of the values which can be passed to \includegraphics), but in general this is more stable (your version can break if the optional arguments should contain a ]). – Skillmon Mar 02 '21 at 11:37