I wish to create a "library" of commands that I often use, say lib.tex, so that every time I wish to use them, I write \input{lib} and get on with life. The problem, however, arises when my library relies on third-party packages, like \usepackage{expl3}, \usepackage{tabto} and so on. I'm paranoid that, at some point, if I include my library, the document won't compile due to collision of these \usepackage{} statements, e.g. \input{lib}\usepackage{X}, where X is already included inside lib.tex. In C, we have header guards, is there anything LaTeX could offer to mimic this behaviour or make up for it with certain internal mechanisms? Is there anything I could do, so I could care-free \usepackage{} in lib.tex?
Asked
Active
Viewed 60 times
1
1 Answers
1
There is \@ifpackageloaded
\documentclass{article}
% \usepackage{color}
\makeatletter
\@ifpackageloaded{color}{\AtBeginDocument{%
{\color{red}Package color already used}\end{document}}}%
{\usepackage{color}}
\makeatother
\begin{document}
Some \color{blue} blue color
\end{document}
You can also test the options of the package with
\@ifpackagewithand the date of the package with \@ifpackagelater. See Test if a package (or package option) is loaded.
Edit:
To avoid commands collisions, you can use \@ifundefined:
\documentclass{article}
\makeatletter
\def\foo{default foo}
\@ifundefined{foo}{\def\foo{my foo}}{\relax}
\makeatother
\begin{document}
\foo
\end{document}
But as stated in the comments, \def is a risky command. It is better to use \newcommand or \renewcommand to define or redefine commands.
Fran
- 80,769
-
Thank you for taking your time to answer!
If time permits, I'd appreciate if you could address the following complementary issue: how should one (would you recommend to) deal with the collusion of
– Piotr Tarasov Jul 10 '20 at 08:52\def{}and\newcommand[n]{...}statements? As the library grows, the\input{}tree becomes more complex, and the risk of defining something multiple times becomes relevant. -
1@PiotrTarasov @ifundefined (see edit answer) but better use
\newcommand, and\renewcommandthat\def, than can overwrite any command without warning you. – Fran Jul 10 '20 at 09:40 -
\usepackagerelatively care-free. The fact that LaTeX allows multiple\usepackagestatements for the same package without giving a warning is actually a feature, see https://tex.stackexchange.com/questions/148250/using-usepackage-twice-with-the-same-package-name. – Marijn Jul 10 '20 at 08:44\defand\newcommand[n]{...}statements? – Piotr Tarasov Jul 10 '20 at 08:55\@ifundefinedis not a primitive command either). – Ulrike Fischer Jul 10 '20 at 11:50\defsufficiently to use it (enable its power), which my paper so far demonstrates. – Piotr Tarasov Jul 13 '20 at 04:59