
数字を挿入するための大きなマクロを作成できるかどうか疑問に思っていました。次の内容を含めたいと考えていました:
\begin{figure} [H]
\centering
\includegraphics[scale=0.8]{#FILENAME}
\caption{#FIGURECAPTION \label{#LABELREF}}
\end{figure}
非常に長いので、このような長い「コード」を簡単に挿入できるようにしたいと思いました。プリアンブル内の環境として作成するべきでしょうか? それとも、新しいコマンドとしてでしょうか?
どのような形でも助けていただければ幸いです。
答え1
やってみました:
\newcommand\Figure[3]{%
\begin{figure} [H]
\centering
\includegraphics[scale=0.8]{#1}
\caption{#2}\label{#3}
\end{figure}
}
これを次のように使います
\Figure{filename}{caption}{label}
実際、さらに良いのは次のようになります。
\newcommand\Figure[4][scale=0.8]{%
\begin{figure} [H]
\centering
\includegraphics[#1]{#2}
\caption{#3}\label{#4}
\end{figure}
}
scale=0.8
2 番目のバリアントは、 に引数を渡すためのオプションの引数を定義します\includegraphics
。この引数のデフォルトは です。たとえば、 のように記述できます\Figure[width=3cm]{filename}{caption}{label}
。
編集: オプションの短いキャプション
Sigur はコメントで、オプションの短いキャプションを求めました。これは実際には少しトリッキーで、次のものは機能しません。
\newcommand\Figure[4][]{%
\begin{figure} [H]
\centering
\includegraphics[scale=0.8]{#2}
\caption[#1]{#3}\label{#4}
\end{figure}
}
なぜなら、オプション引数がない場合には#1
が空白になり、マクロは を挿入する\caption[]{...long caption...}
ため、短いキャプションは空になります。これを回避するには、代わりに のデフォルト値を#1
に等しくし\relax
、マクロで を使用します。
\ifx#1\relax\relax\caption{#3}\else\caption[#1]{#3}\fi
これでマクロは期待どおりに動作するようになりました。
しかし、より良い解決策は、\NewDocumentCommand
しかし、より良い解決策はxparseパッケージには 2 つのオプション引数を指定できるため、これを使用します。これを行う方法の 1 つを次に示します。
\documentclass{article}
\usepackage{mwe}
\usepackage{xparse}
\usepackage{float}
\NewDocumentCommand\Figure{o D<>{scale=0.8} m m m}{%
% [optional short caption]<optional includegraphics options>{image}{caption}{label}
\begin{figure}[H]
\centering
\includegraphics[#2]{#3}
\IfNoValueTF{#1}{\caption{#4}}{\caption[#1]{#4}}
\label{#5}
\end{figure}
}
\begin{document}
\Figure{example-image-a}{Normal figure}{f:normal}
\Figure<width=20mm>{example-image-a}{Width 20mm }{f:20mm}
\Figure[Short caption]<width=20mm>{example-image-a}{With 20mm with short caption}{f:20mm}
\Figure[Short caption]{example-image-a}{Short caption}{f:20mm}
\end{document}
間のオプションの引数は[...]
ショートキャプションになり、間のオプションの引数<...>
は に渡されます\includegraphics
(デフォルトは ) scale=0.8
。