Write a command that includes a figure

includegraphicsmacros

I would like a shorthand command to include a figure.

  • Description and filename are mandatory
  • Short caption is optional
  • Optional arguments can be passed to \includegraphics

Here's the snippet I am trying to write:

    \newcommand\figH[4][]{
    \begin{figure}[H]
        \begin{center}
            \caption[#4]{\label{#2}#3}
            \includegraphics[#1]{#2}
        \end{center}
    \end{figure}%
    }
    
    \figH[width=\linewidth]{filename}{description}{short-description}
    \figH{filename}{description}{short-description}
    \figH{filename}{description}

I am still confused with the optional arguments in commands.

Best Answer

Instead of defining many arguments you could also define a key=value interface that sets the label, short-caption, or place for the float's placement. With expkv-cs you can use the ... handler to get all the unknown key=value pairs (and the keys without values) in a single argument to forward them to \includegraphics (resulting in a single optional key=value argument and two mandatory arguments).

\documentclass{article}

\usepackage{graphicx}
\usepackage{float}
\usepackage{expkv-cs}

\makeatletter
\newcommand\fig[2][]{\fig@kv{short={#2},#1}{#2}}
\ekvcSplitAndForward\fig@kv\fig@out
  {
    % defaults here
     short = {}% will get set for each call to match the caption argument
    ,internal-label = {} % empty, not for direct use (easier that way)
    ,place = tbp
    ,...
  }
\ekvcSecondaryKeys\fig@kv
  {
     nmeta H = place=H % shortcut
    ,meta label = internal-label=\label{#1} % wraps \label around the value
    % add more keys you want to be handled special here
  }
\newcommand\fig@out[6]
  {%
    \begin{figure}[#3]
      \centering
      \caption[{#1}]{#5#2}%
      \includegraphics[{#4}]{#6}%
    \end{figure}%
  }
\makeatother

\usepackage{duckuments}

\begin{document}
\listoffigures
\blindduck
\fig[H]{A lovely duck}{example-image-duck}

\fig[width=3cm, short=Ducky]{A frightening duck!}{example-image-duck-portrait}
\end{document}

enter image description here

Related Question