1

Suppose first.tex contains \input{second.tex} and second.tex contains \input{third.tex}.

I would like to have an automated input depth counter whose value is 0 when used inside first.tex, 1 inside second.tex , and 2 inside third.tex. It should increase when \input is used and decreased on completion of the input.

How can I implement it?

1

Try like this:

\documentclass{article}
\usepackage{mathtools}
\usepackage{pifont} 
\usepackage{bbding}
\usepackage{wasysym}
\newcounter{InputDepth}

\let\oldinput\input
\def\input#1{\stepcounter{InputDepth}\oldinput{#1}\addtocounter{InputDepth}{-1}}
\begin{document}
\theInputDepth

\input{first}

\theInputDepth

\input{second}

\theInputDepth

\end{document}

first.tex:

\theInputDepth

second.tex:

\theInputDepth

\input{third}

third.tex:

\theInputDepth

Output:

enter image description here

2

If you have a recent (after 2020-10-01) release of LaTeX, you can use the new hook mechanism.

\begin{filecontents*}{\jobname-first}
This is first: \theinputdepth

\input{\jobname-second}

Again: \theinputdepth
\end{filecontents*}

\begin{filecontents*}{\jobname-second}
This is second: \theinputdepth

\input{\jobname-third}

Again: \theinputdepth
\end{filecontents*}

\begin{filecontents*}{\jobname-third}
This is third: \theinputdepth
\end{filecontents*}

\documentclass{article}

\newcounter{inputdepth}

\AtBeginDocument{%
  \AddToHook{file/before}{\addtocounter{inputdepth}{1}}%
  \AddToHook{file/after}{\addtocounter{inputdepth}{-1}}%
}

\begin{document}

This is main: \theinputdepth

\input{\jobname-first}

Again: \theinputdepth

\end{document}

enter image description here

The hooks are set at begin document in order to avoid spurious settings of the counter. Not a big deal, though, you can just set the hooks in the preamble; there will be other settings to the counter, but the state will be 0 at the beginning of the document.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.