0

I wonder if there are methods to test if a file(or files) has been input by \input before to avoid multiple inputting which may cause LaTeX Error: Command ... already defined.

Example

    \documentclass{article}
    \input{a.tex}
    \input{b.tex}
    
    %#1-files 
    \newcommand\inputfiles[1]{
    %if a certain file in #1 has been input before, then doing noting; else if the file exists then \input this file manually like \iffileexist \input{...}\else warning message and program breaks down\fi.
    }
    % I'd like the macro \inputfiles can work both in preambel and in main document, just like \input.    
    
    \begin{document}
    \inputfiles{a.tex,b.tex,c.tex}
    %Since a.tex and b.tex have been input in preamble, here only c.tex will be input if c.tex exists.
    \end{document}
20
  • 2
    rename to .sty and use \usepackage{a,b,a,c,b} would cover most use cases Jul 13, 2022 at 6:54
  • 2
    @lyl I gave a complete example in my comment. files of definitions should normally be in .sty not .tex then \usepackage{a}\usepackage{a}\usepackage{a}\usepackage{a} will only input a.sty once. Jul 13, 2022 at 8:15
  • 1
    if there are \makeatletter/\makeatother commands in your files you should better remove them. This is automatic in a package. Jul 13, 2022 at 8:21
  • 1
    @UlrikeFischer even those don't hurt, they are just not needed. (Major improvement in 2e over 2.09, where a \makeatletter at the end of a .sty would break all following ones.) Jul 13, 2022 at 8:25
  • 1
    @lyl Read texdoc docstrip etc.. Long story short, you can "compile" a dtx file for it to generate a sty file, either by running [pdf][la]tex file.dtx or tex file.ins (depends on the package)
    – user202729
    Jul 13, 2022 at 10:30

1 Answer 1

1

I don't really see the use case, so won't bother expanding the code below to handle comma separated lists of tex files.

\documentclass{article}
\usepackage{etoolbox}

\makeatletter
\newcommand\inputonce[1]{\ifcsdef{prior@input@check#1}{\typeout{#1 already loaded}}{\input{#1}\expandafter\newcommand\csname prior@input@check#1\endcsname{}}}
\makeatother

\begin{document}
\input{a}

\input{a}

\inputonce{a}

\inputonce{a}
\end{document}

The above code will load a.tex a total of three times: the first two times from the \input{a}. The third time from the first occurrence of \inputonce{a}. The second time \inputonce{a} is called the file is not loaded, and a message is shown on the console indicating that the file a.tex is already loaded.

Note: this is based on the filename provided to \input. So doing \inputonce{a} followed by \inputonce{a.tex} will not detect the collision.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .