# How to implement a counter of current depth of \input

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?

Try like this:

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

\let\oldinput\input
\begin{document}
\theInputDepth

\input{first}

\theInputDepth

\input{second}

\theInputDepth

\end{document}


first.tex:

\theInputDepth


second.tex:

\theInputDepth

\input{third}


third.tex:

\theInputDepth


Output:

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{%
}

\begin{document}

This is main: \theinputdepth

\input{\jobname-first}

Again: \theinputdepth

\end{document}


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.