僅對包含的檔案執行設定計數器

僅對包含的檔案執行設定計數器

我目前遇到以下情況:我在主文件中包含一個乳膠文件。該文件已經有幾個\section{}部分。現在我想讓他們1重新開始計數,但又不會弄亂我的主檔案中的全域計數。我嘗試了以下方法:

\subsection{First}
\setcounter{section}{0}
\input{first_file}
\subsection{Second}
\setcounter{section}{0}
\input{second_file}

這適用於重置計數器,但這也擾亂了我的全域計數。有沒有辦法重置計數器而不弄亂全域文件?我不想更改包含的文件,並且最好我想要一個便攜式解決方案。
編輯:混亂的解釋:我得到的是:

1
2
3
\begin{input}
1
2
\end{input}
3
4
5

我想要的是:

1
2
3
\begin{input}
1
2
\end{input}
4
5
6

答案1

定義一個輔助計數器並用它來暫時儲存節號。

然後用於\inputreset{file}輸入要重置方程式編號的檔案。

但是,您將擁有大的當您嘗試載入時出現問題hyperref

\newcounter{storedsection}

\newcommand{\inputreset}[1]{%
  \setcounter{storedsection}{\value{section}}%
  \setcounter{section}{0}%
  \input{#1}%
  \setcounter{section}{\value{storedsection}}%
}

答案2

\input這在使用第一個計數器之前使用臨時計數器來儲存節計數器值。此外,此\input命令變更為\refstepcounter輸入計數器,然後section依序重設計數器。

編輯自動儲存第一個部分的計數器值\input

一些缺點:每次\input使用 if 時,部分計數器都會重設。如果這是一個問題,可以在某個閾值後取消重置。

\documentclass{article}

\usepackage{etoolbox}
\usepackage{xpatch}

\usepackage[hypertexnames=false]{hyperref}
\newcounter{inputfilecounter}

\newcounter{storesection}


\xpretocmd{\input}{%
  \ifnumequal{\value{inputfilecounter}}{0}{%
    \setcounter{storesection}{\value{section}}%
  }{}%
  \refstepcounter{inputfilecounter}
}{}{}

\newcommand{\RestoreSectionCounter}{%
  \setcounter{section}{\value{storesection}}%
}

\makeatletter
\@addtoreset{section}{inputfilecounter}
\makeatother

\begin{document}

\tableofcontents

\section{Regular}
\clearpage

\input{firstfile}
\clearpage

\input{secondfile}

\RestoreSectionCounter
\clearpage
\section{Continued regular sections}
\end{document}

在此輸入影像描述

相關內容