如何使用主文件和标签结合其他两个文件?

如何使用主文件和标签结合其他两个文件?
\begin{filecontents}{a.tex}
\tag{1.1}{this is 1.1 from file a.}
\tag{1.2}{this is 1.2 from file a.}
\end{filecontents}

\begin{filecontents}{b.tex}
\tag{0.1}{this is 0.1 from file b.}
\tag{1.1}{this is 1.1 from file b.}
\tag{1.2}{this is 1.2 from file b.}
\end{filecontents}

\documentclass{article}

\makeatletter
\newcommand{\print}[2][]{%
  \if\relax\detokenize{#1}\relax
    \print@all{#2}%
  \else
    \print@one{#1}{#2}%
  \fi
}

\newcommand{\taginput}[1]{%
  \ifx\taginput@files\@empty
    \gdef\taginput@files{#1}%
  \else
    \g@addto@macro\taginput@files{,#1}%
  \fi
  \def\taginput@current{#1}%
  \input{#1}%
}
\let\taginput@files\@empty

\newcommand{\tag}[2]{%
  \global\@namedef{taginput@\taginput@current @#1}{#2}%
}

\newcommand{\print@all}[1]{%
  \begingroup\edef\x{\endgroup
    \noexpand\@for\noexpand\next:=\taginput@files\noexpand\do
  }\x{\print@one{\next}{#1}}%
}
\newcommand{\print@one}[2]{%
  \@nameuse{taginput@#1@#2}\par
}
\makeatother

\begin{document}

\tag{0.1}{this is 0.1 from file main.}
\taginput{a}
\tag{1.1}{this is 1.1 from file main.}
\taginput{b}
\tag{0.1}{this is 0.1-2 from file main.}

\print[a]{1.1}   % result 1 line (1.1 from a)

\print[b]{1.2}   % result 1 line (1.2 from b)

\bigskip

\print{1.1}    % result 3 lines (1.1 from a, 1.1 from main, 1.1 from b)

\bigskip

\print{1.2}    % result 2 lines (1.2 from a,  1.2 from b)

\bigskip

\print{0.1} % result 3 line (0.1 from main, 0.1 from b, 0.1-2 from main)

\end{document}

相关内容