# Only \usepackage if the package can be found [duplicate]

Possible Duplicate:
Conditional “if a package is available”

I'm using a package "mcode.sty" that enhances/colors listings output; typesetting will work perfectly without it. However, I'm often typesetting in an environment where I can't include the package file anywhere LaTeX can find it except the current directory. I'd like to include the \usepackage statement in my default preamble (I'm using LyX), but often the file won't be there, and LaTeX will quit with an error, even though I have no need for the functionality in my current project. In effect, I'd like to include the package only if the .sty file is in the current directory, or somewhere on the LaTeX path, and not exit if it can't be found. Something like \begin{ignore_errors} \usepackage{mcode} \end{ignore_errors}. Is there a way to do this?

-

## marked as duplicate by Seamus, Martin Scharrer♦Apr 15 '11 at 11:27

I think this is a duplicate –  Seamus Apr 15 '11 at 10:26
Thanks, Seamus! I think I searched for every combination of terms except that one :) –  btown Apr 16 '11 at 0:59

If you don't need the package, you shouldn't be including it. That said, this does what you want.

\IfFileExists{foo.sty}{\usepackage{foo}}{}


If you want a macro for this, then you can use something like the following.

\newcommand*\usepackageifpresent[2][]{%
\IfFileExists{#2.sty}{\usepackage[#1]{#2}}{}%
}


It supports optional arguments,

\usepackageifpresent[margin=3in]{geometry}


for example.

-