我需要在每个章节的第一段使用不同的字体排版,并且我不希望这会影响\lstlisting
。我尝试使用,\everypar
但如果\lstlisting
有,它会中断。我该怎么做?
答案1
以下适用于标准类(article
、report
、book
)。它利用了最近版本的 LaTeX 中引入的新钩子。
您可能需要自己处理异常,至少对于像下面示例中那样的简单事情,一切都会顺利。
\documentclass[]{book}
\usepackage{listings}
% change this for your setup, restoreparformat should revert all the changes you
% introduce with firstparformat
\newcommand*\firstparformat {\sffamily\large}
\newcommand*\restoreparformat{\rmfamily\normalsize}
% this injects the code into the hooks
% ------------------------------------
% changes should be global (just to make sure), hence we don't use `\newif`
\let\iffirstparformat\iffalse
\protected\def\firstparformatfalse{\global\let\iffirstparformat\iffalse}
\protected\def\firstparformattrue {\global\let\iffirstparformat\iftrue}
% sections are a hard thing, there are subsections and stuff all using the same
% internals
\protected\def\startsectionsaveform
{%
\global\let\startsectionsaveformTMP\iffirstparformat
\firstparformatfalse
}
\protected\def\startsectionrestoreform
{\global\let\iffirstparformat\startsectionsaveformTMP}
\AddToHook{cmd/section/before} {\firstparformattrue}
\AddToHook{cmd/@startsection/before} {\startsectionsaveform}
\AddToHook{cmd/@xsect/after} {\startsectionrestoreform}
% chapters are way easier
\AddToHook{cmd/chapter/before} {\firstparformatfalse}
\AddToHook{cmd/@chapter/after} {\firstparformattrue}
\AddToHook{cmd/@schapter/after} {\firstparformattrue}
% the paragraphs check whether they are the first and if so use the format
\AddToHook{para/begin}
{%
\iffirstparformat
\expandafter\firstparformat
\fi
}
% at the end of the paragraph we might need to revert these changes
\AddToHook{para/after}
{%
\iffirstparformat
\firstparformatfalse
\expandafter\restoreparformat
\fi
}
% exceptions
\AddToHook{env/lstlisting/before}{\firstparformatfalse}
\usepackage{duckuments}
\begin{document}
\chapter{Chapter}
\blindduck[1-2]
\section{Section}
\blindduck[1-2]
\subsection{Subsection}
\blindduck[1-2]
\chapter{Chapter}
\section{Section}
\blindduck[1-2]
\chapter{Chapter}
\begin{lstlisting}
listing
listing
\listing
\end{lstlisting}
\end{document}