
我正在創建一個環境,以便我可以寫一本包含所有基於環境模板以相同方式格式化的資訊的書。最終,我希望能夠寫
\begin{eqdescription}
\eqname{Bob Doe}
\eqcolor{Blue}
\eqnotes{Bob will help you.}
\end{eqdescription}
\begin{eqdescription}
\eqname{Jim Doe}
\eqnotes{Jim will NOT help you.}
\end{eqdescription}
eqdescription
並且透過執行以下操作,根據環境以相同的方式很好地格式化條目:
\newenvironment{eqdescription}{}{%
\section{\eqnameval}
Favorite Color: \eqcolorval
Notes: \eqnotesval
}
因為 Jim Doe 沒有最喜歡的顏色,所以他的顏色是空白的,所以我認為他的顏色會顯示一些預設值,例如no favorite color
。
我認為定義一些命令來初始化和設定環境中的值會很容易,如下所示:
\newcommand{\initcommand}[2]{%
% Set the Default Value:
\expandafter\newcommand\csname eq#1val\endcsname[0]{#2}
% Make a command \eq[name]{[avalue]} that sets it in the future.
\expandafter\newcommand\csname eq#1\endcsname [1] {%
\expandafter\renewcommand\csname eq#1val \endcsname[0]{##1}
}
}
我可以在環境的頂部放置:
\initcommand{notes}{Default Value.}
\initcommand{name}{No Name.}
\initcommand{color}{No favorite color.}
但 init 指令不僅會失敗,還會導致重新定義值時出現各種問題。
有沒有一種簡潔的方法來定義這樣的小模板,而無需複雜的語法和重複的程式碼?
答案1
您可以在 開始時g
全域設定預設值,然後在呼叫、或時將它們放入環境中。它將重新定義已經存在的一切。將具有本地範圍,但確實需要定義定義。這不是問題,因為您使用以下方式定義它們:def
eqdescription
\renewcommand
\eqname
\eqcolor
\eqnotes
\gdef
\renewcommand
\begin{eqdescription}
\documentclass{article}
\newcommand{\eqname}{\renewcommand\eqnameval}
\newcommand{\eqcolor}{\renewcommand\eqcolorval}
\newcommand{\eqnotes}{\renewcommand\eqnotesval}
\newenvironment{eqdescription}
{% Set defaults for this environment
\gdef\eqnameval{No name.}%
\gdef\eqcolorval{No favourite colour.}%
\gdef\eqnotesval{Default value.}%
}
{%
\section{\eqnameval}
Favorite Color: \eqcolorval
Notes: \eqnotesval%
}
\setlength{\parindent}{0pt}% Just for this example
\begin{document}
\begin{eqdescription}
\eqname{Bob Doe}
\eqcolor{Blue}
\eqnotes{Bob will help you.}
\end{eqdescription}
\begin{eqdescription}
\eqname{Jim Doe}
\eqnotes{Jim will NOT help you.}
\end{eqdescription}
\end{document}