我想定义两个环境:chapterexercises
和exercise
,它们将出现在每本书章节的末尾。输出格式示例:
Homework Exercises for Chapter 3 (centered, top of new page) The Direct Stiffness Method (centered chapter title
练习 3.1 [A:15]。使用...中介绍的方法。
练习 3.2 [C:20]。按照...中概述的方法进行编程。
等等等等
环境将被调用为
\begin{chapterexercises}
\begin{exercise}[A,15]
Using the method presented in ....
\end{exercise}
\begin{exercise}[C,20]
Program the method outlined in ...
\end{exercise}
\end{chapterexercises}
我很久以前(1984 年)就用 PlainTeX 编写了这些内容,用于支持课程笔记(每堂课一章),现在我正在为出版商将其转换为 LaTeX 书籍。有没有可以快速调整的类似现有实现?
答案1
这总结了以下几点:
enumitem
允许您使用自定义标签和标题定义枚举。xstring
允许您将 替换,
为:
。- 使用一些小技巧来解释后面的空白行
\begin{exercise}
(这可能会给你带来麻烦)。 - 将当前章节名称保存到宏中。
\documentclass{book}
\let\savepar=\par
\newcommand{\resetpar}{\let\par=\savepar}
\let\savechapter=\chapter
\newcommand{\currentchaptername}{}
\renewcommand{\chapter}[1]{\renewcommand{\currentchaptername}{#1}\savechapter{#1}}
\usepackage{xparse} % not necessary for TeXLive 2021+
\usepackage{xstring}
\usepackage{enumitem}
\newlist{chapterexercises}{enumerate}{1}
\setlist[chapterexercises]{
label={EXERCISE \arabic{chapter}.\arabic*},
before={
\clearpage\centering
Homework Exercises for Chapter \arabic{chapter}\\
\currentchaptername
}
}
\NewDocumentEnvironment{exercise}{o}{%
\item{}\IfNoValueTF{#1}{}{[\StrSubstitute{#1}{,}{:}].}
\let\par=\resetpar
% swallow one \par to allow one blank line after the environment begins.
% (This does mean that if the blank line isn't there,
% then the second paragraph will merge into the first.)
}{}
\begin{document}
\setcounter{chapter}{2}
\chapter{The Direct Stiffness Method}
Chapter content.
\begin{chapterexercises}
\begin{exercise}[A,15]
Using the method presented in ....
\end{exercise}
\begin{exercise}[C,20]
Program the method outlined in ...
\end{exercise}
\begin{exercise}[D,20]
Program the method outlined in ...
A second paragraph to make sure par has been reset.
\end{exercise}
\end{chapterexercises}
\end{document}