
我想知道是否可以製作一個大宏來插入數字?我希望它包含:
\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
,用於將參數傳遞給\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
equal to \relax
,然後在巨集中使用
\ifx#1\relax\relax\caption{#3}\else\caption[#1]{#3}\fi
現在宏的行為符合預期。
然而,更好的解決方案是\NewDocumentCommand
使用解析包,因為這將允許您有兩個可選參數。這是一種方法:
\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
。