我正在构建章节和子章节。子章节上的 beforesep 通常很可取,但如果子章节在章节之后直接调用,则不合适。有什么方法可以解决这个问题吗?
我曾尝试使用\pretocmd
etoolbox 执行此操作,但不幸的是没有按预期工作。请参阅下面的 MWE。期望的结果是第 1 节和第 1 小节之间没有空格,但“此处有一些文本(第 1 小节)”和第 2 小节之间有标准空格:
\documentclass{article}
\usepackage{titlesec}
\usepackage{etoolbox}
% Define a toggle to check if a section was just created
\newtoggle{aftersection}
% Formatting the section titles
\titleformat{\section}
{\Large\bfseries}
{\thesection}
{1em}
{\toggletrue{aftersection}} % Set the toggle to true after creating a section
% Formatting the subsection titles
\titleformat{\subsection}
{\large\bfseries}
{\thesubsection}
{1em}
{}
% Adjusting the space before and after section titles
\titlespacing{\section}
{0pt} % left
{2ex} % beforesep
{1ex} % aftersep
% Adjusting the space before and after subsection titles
\titlespacing{\subsection}
{0pt} % left
{0pt} % beforesep (set to 0pt initially)
{0.5ex} % aftersep
% Update the spacing before subsections depending on the toggle
\pretocmd{\subsection}{%
\iftoggle{aftersection}{
\vspace{-2cm} % Remove the space before the subsection
\togglefalse{aftersection} % Reset the toggle
}{
\vspace{2cm} % Add the space before the subsection
}
}{\typeout{Success}}{\typeout{Failed to patch \string\subsection}}
\begin{document}
\section{Section 1}
\subsection{Subsection 1}
Some text here.
\subsection{Subsection 2}
Some more text here.
\end{document}
答案1
发现如果间距纯粹是在标题间距内配置的,它会尊重后续部分,并且不会添加更多间距