具有数字范围的部分

具有数字范围的部分

我一直在做作业,其中两个问题非常相似,把它们写在同一部分会更容易。但问题是这会搞乱编号:

1 Section Title
(Question 1)
2 Section Title
(Question 2 and 3) 
3 Section Title
(Question 4)

我目前的方法是:

1 Section Title
(Question 1)
2 Section Title
(Question 2 and 3) 
\setcounter{section}{3}
4 Section Title
(Question 4)

理想情况下,我想做的是:

1 Section Title
(Question 1)
2-3 Section Title
(Question 2 and 3) 
4 Section Title
(Question 4)

这可能吗?我知道section计数器基于整数,但是有没有办法覆盖它们的视觉表示?

答案1

计数器的可视化表示section由宏指定\thesection,可以重新定义:

\section{Section Title}
(Question 1)

\let\savedthesection\thesection
\renewcommand*{\thesection}{%
  \arabic{section}--\the\numexpr\value{section}+1\relax
}
\section{Section Title}
\stepcounter{section}
\let\thesection\savedthesection
(Question 2 and 3)

\section{Section Title}
(Question 4)

完整示例包括目录补丁,以增加各部分的间距。

\documentclass{article}

% Patch section entries in table of contents to get
% more space for the section numbers
\usepackage{etoolbox}
\makeatletter
\patchcmd\l@section{1.5em}{2.5em}{}{%
  \errmessage{\noexpand\l@section could not be patched}%
}
\makeatother

\begin{document}

\tableofcontents

\section{First question}

\let\savedthesection\thesection
\renewcommand*{\thesection}{%
  \arabic{section}--\the\numexpr\value{section}+1\relax
}
\section{Second and third question}
\stepcounter{section}
\let\thesection\savedthesection

\section{Fourth question}

\end{document}

结果

\rangesection

下面的示例\rangesection使用以下参数进行定义:

\rangesection{<number of additional sections>}[<toc entry>]{<section title>}

还支持不同的数字方案。

\documentclass{article}

% Patch section entries in table of contents to get
% more space for the section numbers
\usepackage{etoolbox}
\makeatletter
\patchcmd\l@section{1.5em}{2.5em}{}{%
  \errmessage{\noexpand\l@section could not be patched}%
}

\newcommand*{\rangesection}[1]{%
  \@dblarg{\@rangesection{#1}}%
}
\def\@rangesection#1[#2]#3{%
  \let\saved@thesection\thesection
  \stepcounter{section}%
  \protected@edef\from@thesection{\thesection}%
  \addtocounter{section}{#1}%
  \protected@edef\to@thesection{\thesection}%
  \addtocounter{section}{-1}%
  \renewcommand*{\thesection}{%
    \from@thesection--\to@thesection
  }%
  \section[{#2}]{#3}%
  \let\thesection\saved@thesection
}
\makeatother

\begin{document}

\tableofcontents

\noindent\dotfill

\section{First question}

\rangesection{1}{Second and third question}

\section{Fourth question}

\renewcommand*{\thesection}{\Alph{section}}
\setcounter{section}{0}

\section{First appendix question}

\rangesection{4}{Second to sixth appendix question}

\section{Seventh appendix question}

\end{document}

结果

相关内容