重新定义带星号的命令 \section*

重新定义带星号的命令 \section*

\usepackage[explicit]{titlesec}已经定义\section

\titleformat{\section}
  {\ttfamily\Large\bfseries\color{red}}
  {\thesection}
  {1em}
  {#1}

我想重新定义带星号的版本部分,\section*使其变得像\section(带数字),除了后面的文本位于部分标题前面(运行)

答案1

有一个numberless键(与 一起使用name)可以完成这项工作:

\documentclass[12pt, a4paper]{article}%

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}

\usepackage[x11names]{xcolor}
\usepackage[explicit]{titlesec}%
\usepackage{titletoc} %

\titleformat{\section}
  {\ttfamily\Large\bfseries\color{red}}
  {\thesection}
  {1em}
  {#1}%
%
\titleformat{name = \section, numberless}
  {\ttfamily\Large\bfseries\color{red}}
  {}
  {0em}
  {\addcontentsline{toc}{section}{#1}#1}%

\begin{document}

\section{A Numbered Section}
Text text text text text text text text text text text text text text text text text text text text text text text text text text text text text.

\section*{An Unnumbered Section}
Text text text text text text text text text text text text text text text text text text text text text text text text text text text text text.

\section{Still Another Numbered Section}
Text text text text text text text text text text text text text text text text text text text text text text text text text text text text text.

\end{document} 

在此处输入图片描述

答案2

如果您不需要目录,您可以删除 toc 重新定义的行。但是,使用特殊宏的解决方案\Ssection}可能是更好的选择,那么\ţableofcontents就不必重新定义:

\documentclass[12pt, a4paper]{article}%
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{xcolor}
\usepackage[explicit]{titlesec}%
\let\TableOfContents\tableofcontents
\renewcommand\tableofcontents{{\titleformat{\section}%
   {\Large\bfseries}{\thesection}{1em}{##1}\let\section\Section\TableOfContents}}
\let\Section\section
\makeatletter
\renewcommand\section{\@ifstar\starsection\Section}
\makeatother
\newcommand\starsection[1]{%
  \par\bigskip\noindent\refstepcounter{section}%
  \addcontentsline{toc}{section}{\thesection\hspace{0.8em}#1}%
  {\ttfamily\Large\bfseries\textcolor{red}{\thesection\hspace{1em}#1}\hspace{1em}}}

\titleformat{\section}
  {\ttfamily\Large\bfseries\color{red}}
  {\thesection}
  {1em}
  {#1}

\begin{document}
\tableofcontents
\section{A Numbered Section}
Text text text text text text text text text text text text text text text text text text text text text text text text text text text text text.

\section*{An Unnumbered Section}
Text text text text text text text text text text text text text text text text text text text text text text text text text text text text text.

\end{document} 

在此处输入图片描述

相关内容