LaTeX 中可以用 titlesec 宏包中的 titleformat 命令来改变章节编号等格式
首先需要导入宏包:
\usepackage{titlesec}
改变标题的代码如下:
\titleformat{command}[shape]{format}{label}{sep}{before}[after]
各个参数含义如下:
command 是要重新定义的各种标题命令,比如 \part,\chapter,\section,\subsection,\subsubsection,\paragraph,\subparagraph等;
shape 是用来设定段落形状的,可选的参数有hang、block、display等,详见 titlesec文档;
format 用于定义标题外观,比如使标题居中、字体加粗等;
label 用于定义标题的标签,就是标题内容前面的标号;
sep 定义标题的标签与标题内容之间的间隔距离;
before 用于在标题内容前再加些内容;
after 用于在标题内容后再加些内容。
我编写电子书常用的命令如下所示:
\renewcommand{\sectionmark}[1]{\markright{\thesection\quad #1}}
\titleformat{\section}
{\normalfont\sffamily\large\bfseries}
{}
{0pt}
{
\begin{tikzpicture}[baseline=(box.base)]
\node[
fill=maincolor,
text=white,
rounded corners=2pt,
inner xsep=6pt, inner ysep=3pt,
font=\sffamily\bfseries\normalsize
] (box) {\thesection};
\end{tikzpicture}
\hspace{0.5em}
\color{deepcolor}#1
}
[\vspace{-0.3ex}{\color{maincolor!35}\rule{\linewidth}{0.5pt}}]
效果如下所示:

\renewcommand{\sectionmark}[1]{\markright{\thesection\quad #1}}
作用是把 \sectionmark 重定义为一个带 1 个参数(#1)的宏,宏体是 \markright{\thesection\quad #1}
\renewcommand:重新定义已存在的命令(\sectionmark 是 LaTeX 内核已定义的,所以必须用 \renewcommand 而非 \newcommand)。
\sectionmark:LaTeX 在每次 \section 时自动调用的内部命令,原本用于把章节信息写入页眉标记。它的参数 #1 就是章节标题文字。
\markright{...}:设置右页(奇数页)页眉的标记内容。与之对应的是 \markboth{左}{右},可同时设置左右页眉。
\thesection:输出当前章节的编号(如 1、2.3 等,取决于文档类)。
\quad:插入一个 1em 宽的水平空白。
#1:章节标题本身。
所以,最终页眉右侧显示的是类似:
1 引言
即「章节编号 + 空格 + 章节标题」。
\titleformat 是 titlesec 宏包提供的命令,语法为:
\titleformat{<command>}[<shape>]{<format>}{<label>}{<sep>}{<before-code>}[<after-code>]
对应到代码为:
\titleformat{\section}
{\normalfont\sffamily\large\bfseries} % <format>:标题整体格式
{} % <label>:章节编号的显示方式(这里留空)
{0pt} % <sep>:编号与标题之间的间距
{% % <before-code>:编号和标题之前的代码
\begin{tikzpicture}[baseline=(box.base)]
\node[...] (box) {\thesection}; % 用 TikZ 画编号框
\end{tikzpicture}
\hspace{0.5em}
\color{deepcolor}#1 % 标题文字,着色为 deepcolor
}
[\vspace{-0.3ex}{\color{maincolor!35}\rule{\linewidth}{0.5pt}}] % <after-code>:标题后的横线
#1 是 <before-code> 的占位符在 titlesec 的机制中:
<before-code>(第五个参数) 是一个带 1 个参数的代码块,这个参数 #1 就是标题正文。
titlesec 在排版时会把你写的章节标题文字替换进 #1 的位置。
所以 \color{deepcolor}#1 的含义是:把章节标题文字用 deepcolor 着色后输出。
<label> 参数的区别注意不要混淆:
<label>(第三个参数 {}):控制编号(\thesection)如何显示。这里留空 {},意味着编号不由 <label> 输出,而是在 <before-code> 里用 TikZ 手动画出来了(\node ... {\thesection})。
<before-code> 里的 #1:是标题文字,不是编号。
若写:
\section{引言}
则:
\thesection → 1(画进 TikZ 方框里,白字填充 maincolor)
#1 → 引言(用 deepcolor 着色显示)
最终效果:一个带圆角彩色背景的编号方块,后跟 0.5em 空白,再跟深色着色的标题「引言」,标题下方有一条浅色细横线。效果如下所示:

评论专区
评论加载中...登录后即可发表评论