递归导入任意级别的子文档

递归导入任意级别的子文档

笔记:这个问题和接受的答案中的想法已被整理成CTAN 套件被称为“模块化”


考虑下面的subimportlevel宏:

包.tex

\usepackage{import}
\usepackage{coseoul}

\newcommand{\subimportlevel}[3]{
\setcounter{currentlevel}{#3}
\subimport*{#1}{#2}
\setcounter{currentlevel}{#3}
}

宏的目的是导入文档的模块化部分,同时确保节/子节级别正确,而不管导入了什么子文档。此宏的问题在于,子导入的文件可能会发生变化,currentlevel因此最终文件\setcounter{currentlevel}{#3}无法执行正确的操作(它应该重置currentlevel为导入之前的状态)\subimport

下面是一个说明该问题的示例用法:

主文本

\documentclass{article}
\input{packages.tex}

\author{Daniel Sank}
\title{Example}

\begin{document}
\maketitle
\subimportlevel{./}{content}{5}
\end{document}

内容.tex

\subimportlevel{./}{section1}{\value{currentlevel}}  % <-- can change currentlevel inside section1.tex
\subimportlevel{./}{section2}{\value{currentlevel}}

第1节.tex

\levelstay{Section 1}
This is the first section

\leveldown{A subsection}
This is a subsection

\levelstay{Another subsection}
This is another subsection of the first section.

第2节.tex

\levelstay{Section 2}
This is the second section

\leveldown{Subsection}
This should be a subsection of the second section.

\levelstay{Another subsection}
This is supposed to be another subsection of the second section.

构建main.tex结果输出如下

在此处输入图片描述

\value{currentlevel}请注意,第二部分被编号为子部分。我该如何解决这个问题?有没有办法在导入之前扩展?

答案1

编辑

我的第一个定义\subimportlevel(见下文)导入组中的子文件以进行保护\mycurrentlevel。在这个新解决方案中,我使用了多个宏(\@currrentlevel0,,\@currentlevel1...),因此不需要组。

\makeatletter
\newcounter{currentimportdepth}
\setcounter{currentimportdepth}{0}
\newcommand{\subimportlevel}[2]{
  \expandafter\edef\csname @currentlevel\thecurrentimportdepth\endcsname{\thecurrentlevel}
  \addtocounter{currentimportdepth}{1}
  \addtocounter{curentlevel}{-1}
  \subimport*{#1}{#2}
  \addtocounter{currentimportdepth}{-1}
  \setcounter{currentlevel}{\csname  @currentlevel\thecurrentimportdepth\endcsname}
}
\makeatother

第一个解决方案

我不确定我是否理解了这个问题。以下解决方案可以满足您的需求...

\documentclass{article}

\usepackage{import}
\usepackage{coseoul}

\newcommand{\subimportlevel}[2]{
  \edef\mycurrentlevel{\thecurrentlevel}
  \bgroup
  \subimport*{#1}{#2}
  \egroup
  \setcounter{currentlevel}{\mycurrentlevel}
}

\begin{document}
\levelstay{A}
\subimportlevel{./}{content}
\levelstay{B}
\end{document}

第1节.tex

\levelstay{Section 1}
This is the first section

\leveldown{A subsection}
This is a subsection

\levelstay{Another subsection}
This is another subsection of the first section.

第2节.tex

\levelstay{Section 2}
This is the second section

\leveldown{Subsection}
This should be a subsection of the second section.

\levelstay{Another subsection}
This is supposed to be another subsection of the second section.

内容.tex

\subimportlevel{./}{section1}
\levelstay{Test}
\subimportlevel{./}{section2}
\leveldown{Test}
\subimportlevel{./}{section2}

相关内容