包含 \addcontentsline 和 fancyhdr 包的宏,具有唯一标识号

包含 \addcontentsline 和 fancyhdr 包的宏,具有唯一标识号

我有几个文档,其中的标识号输入在用户定义的宏中。宏使用包将标识号放在文档页面的顶部fancyhdr。我想在主文档中添加一个目录,以便轻松浏览所有子文档(每个子文档都有多个页面和唯一的标识号)。此外,每个标识号有三个子文档。我目前有以下代码来定义这些宏:

\documentclass{report}
\usepackage[margin=1in]{geometry}
\usepackage{fancyhdr}
\usepackage{titlesec}
\usepackage[hidelinks]{hyperref}

%Users enter \pid{NUMBERS}
%I want the command to place the NUMBERS on the top left of each page and to add a contents line the first (and only the first) time it is called for each subject
\newcommand{\pid}[1]{%
    \renewcommand{\pid}[1]{\lhead{\texttt{Participant ID: }##1}}%
    \lhead{\texttt{Participant ID: }#1}%
    \addcontentsline{toc}{section}{#1}%
}

%User types \scneario{NAME} here
%I want this to display the scenario as a subsection the first (and only the first) time it is called *for each unique identification number*
\newcommand{\scenario}[1]{%
    \rhead{\texttt{Scenario: }#1}%
    \addcontentsline{toc}{subsection}{#1}%
}

\begin{document}

\pid{111}
\scenario{Scen1}
Some text.\\
Some more text.\\

\pid{111}
\scenario{Scen2}
Some text.\\
Some more text.\\

\newpage

\pid{222}
\scenario{Scen1}
Some text.\\
Some more text.\\

\newpage

\pid{222}
\scenario{Scen2}
Some text.\\
Some more text.\\

\end{document}

在我的文档中,每个命令实际上都是\input{document.tex}。目前这两个命令都不起作用。

答案1

这是您想要的行为吗?

\documentclass{report}
\usepackage[margin=1in]{geometry}
\usepackage{fancyhdr}
\usepackage{titlesec}
\usepackage[hidelinks]{hyperref}
\usepackage{lipsum}

\pagestyle{fancy}

\makeatletter
\newcommand{\pid}[1]{%
    \lhead{\texttt{Participant ID: }#1}% Set the head anyway
    \ifcsname pid#1\endcsname% check existence of a macro called 'pid#1'
    \else% if there is none
    \expandafter\gdef\csname pid#1\endcsname{}% define a macro with that name
    \addcontentsline{toc}{section}{#1}% add the contentsline
    \fi%
    \gdef\cur@pid{#1}% define a global macro containing the current pid
}
\newcommand{\scenario}[1]{%
    \rhead{\texttt{Scenario: }#1}%
    \ifcsname\cur@pid @scenario#1\endcsname% I added a #1 here so the scenario name is also considered in the check
    \else%
    \expandafter\gdef\csname\cur@pid @scenario#1\endcsname{}% I added a #1 here
    \addcontentsline{toc}{subsection}{#1}%
    \fi%
}
\makeatother

\begin{document}
\tableofcontents
\clearpage
\pid{111}
\scenario{Scen1}
\scenario{Scen1}
\lipsum[1]

\pid{111}
\scenario{Scen2}
\scenario{Scen2}
\lipsum[1]

\newpage
\pid{222}
\scenario{Scen1}
\scenario{Scen1}
\lipsum[1]

\pid{222}
\scenario{Scen2}
\scenario{Scen2}
\lipsum[1]
\end{document}

由此得出以下目录: 在此处输入图片描述

\scenario请注意,如果在第一次使用之前使用,则此操作会失败\pid

编辑:改变了的行为\scenario,现在它将场景放入目录中,除非已经遇到\pid和-name 的相同组合。\scenario

相关内容