0

I am frequently using the \input{} command in my master.tex file to import text from other files, e.g.

\input{./texts/myText.tex}

for inserting the text file "myText.tex", from the folder "texts" into my master.

However, if Latex cannot find the file "./texts/myText.tex" the compilation process stops and I have to search the log file for an explanation. To circumvent this I use the package etoolbox in the preamble, and the following code where I want to insert the file content:

\usepackage{etoolbox}
-----
\newcommand{\filename}{./texts/myText.tex}

\IfFileExists{\filename}%
    {\input{\filename}}%
    {\color{red} Latex cannot find this file: \filename}

When using this code Latex will input the file if it finds it, and if not Latex will insert a warning message into the compiled output instead of stopping the compilation process.

This functions great, except for the fact that the new code takes four lines of space compared to one line for the initial code.

My question is, how can I put the four lines of code into a latex function like

\inputMsg{./texts/myText.tex}

where the new function "inputMsg" contains the functionality of four lines of code. How will the code for this new "inputMsg" look like ?

Thanks in advance for any helpful suggestions : )

2

You can use \InputIfFileExists from the LaTeX kernel.

It will \input the file in its first argument and will execute the code in its second argument before that. The third argument is executed if the file does not exist.

\newcommand*{\inputMsg}[1]{%
  \InputIfFileExists{#1}
    {}
    {\color{red} Latex cannot find this file: #1}}

and then

\inputMsg{./texts/myText.tex}

But of course it is also possible to pack up your code into a macro

\newcommand*{\inputMsg}[1]{%
  \IfFileExists{#1}
    {\input{#1}}
    {\color{red} Latex cannot find this file: #1}}

You shouldn't even need etoolbox for those suggestions.

| improve this answer | |
  • Thanks a lot! It really helps me keep my master neat and tidy. How would your code look like for \includegraphics[width=160mm]{./figures/myFigure}? In this case there are two different inputs to the function, one in [] brackets and one in {} brackets. How could I make a version \includegraphicsMsg that similarly writes an errormessage in the compiled file if the file "myFile" is not found? – myotis Mar 21 '19 at 17:45
  • @myotis I guess \includegraphics is more complicated due to the different file types it handles. I suggest you ask a new question about that. – moewe Mar 21 '19 at 18:22

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.