使用方框编号和水平线进行节格式化

使用方框编号和水平线进行节格式化

我想将 (子) 节编号格式化为彩色框和标题下方的水平线。我需要类似以下内容:

在此处输入图片描述

我尝试了 sectsty 但无法让线路正常工作。

\documentclass{scrbook}
\usepackage{sectsty}
\usepackage[table]{xcolor}
\usepackage{blindtext}

\colorlet{sectitlecolor}{darkgray}
\colorlet{sectboxcolor}{darkgray}
\colorlet{secnumcolor}{white}
\sectionfont{\color{sectitlecolor}}
\makeatletter

\renewcommand\@seccntformat[1]{%
\colorbox{sectboxcolor}{\textcolor{secnumcolor}{\csname the#1\endcsname}
}%
\quad
}
\makeatother

\begin{document}
\section{Section 1}
\blindtext
\subsection{Subsection 1}
\blindtext
\end{document}

提前致谢!!

答案1

我不认为sectsty与兼容scrbook

这种\@seccntformat方法看起来不错,但可能有专门针对 KoMa 捆绑包的工具。

问题是,部分标题可以有降部,必须避免它们与规则冲突。我通过在彩色框中添加一条低于基线 2pt 的隐形规则来解决这个问题。规则在开头绘制,向下移动以匹配\colorbox

\documentclass{scrbook}
\usepackage[table]{xcolor}
\usepackage{blindtext}

\colorlet{sectitlecolor}{darkgray}
\colorlet{sectboxcolor}{darkgray}
\colorlet{secnumcolor}{white}
\setkomafont{disposition}{\color{sectitlecolor}\bfseries\sffamily}

\makeatletter
\renewcommand\@seccntformat[1]{%
  \makebox[0pt][l]{\rule[-\dimexpr\fboxsep+2pt\relax]{\columnwidth}{1.2pt}}%
  \colorbox{sectboxcolor}{%
    \rule[-2pt]{0pt}{0pt}%
    \color{secnumcolor}\csname the#1\endcsname
  }%
  \quad
}
\makeatother

\begin{document}

\section{Section 1 gyq}
\blindtext

\subsection{Subsection 1}
\blindtext

\end{document}

在此处输入图片描述

当然,这要求所有标题都放在一行上。

答案2

不要将secsty或等包titlesec与 KOMA-Script 类一起使用。KOMA-Script 提供了\sectionlinesformatchapterlinesformat可以重新定义的包:

\documentclass{scrbook}
\usepackage[table]{xcolor}
\usepackage{blindtext}

\colorlet{sectitlecolor}{darkgray}
\colorlet{sectboxcolor}{darkgray}
\colorlet{secnumcolor}{white}

\addtokomafont{section}{\color{sectitlecolor}}

\renewcommand*\sectionformat{\colorbox{sectboxcolor}{\textcolor{secnumcolor}{~\thesection}~}\quad}
\renewcommand*\subsectionformat{\colorbox{sectboxcolor}{\textcolor{secnumcolor}{~\thesubsection}~}\quad}

\newsavebox{\secnumbox}
\newlength{\secrulewidth}
\setlength{\secrulewidth}{1pt}
\newcommand*\boxedandruledsec[2]{%
  \IfUseNumber{\leavevmode\rlap{\color{sectboxcolor}\rule[\dimexpr-\fboxsep-\secrulewidth\relax]{\textwidth}{\secrulewidth}}}{}%
  \savebox{\secnumbox}{#1}%
  \parbox[b]{\wd\secnumbox}{\usebox{\secnumbox}}%
  \parbox[b]{\dimexpr\textwidth-\wd\secnumbox\relax}{#2}\par\nobreak%
}

\newcommand\originalsectionlinesformat{}
\let\originalsectionlinesformat\sectionlinesformat

\renewcommand\sectionlinesformat[4]{\setlength\fboxsep{\dp\strutbox}%
  \Ifstr{#1}{section}{\boxedandruledsec{#3}{#4}}{%
    \Ifstr{#1}{subsection}{\boxedandruledsec{#3}{#4}}{%
      \originalsectionlinesformat{#1}{#2}{#3}{#4}% other section levels
    }}%
}

\begin{document}
\chapter{Chapter 1}
\section{Section 1}
\blindtext
\subsection{Subsection 1}
\blindtext
\subsection{What should happen if the title is really really long and needs two or more lines?}
\blindtext
\subsection*{What should happen if a title is unnumbered?}
\blindtext
\end{document}

在此处输入图片描述

相关内容