4

I am loading the gitver package based on the expl3 solution accepted for my question here.

However, I need to use some commands depending on whether the package has actually been loaded. For instance, using a combination of hyperxmp, hyperref and gitver, one can provide an option pdfversionid = \gitVer to the hypersetup command (see code below).

The question is, how do I conditionally detect the presence of a package loaded (gitver in my example) and set up this conditional compilation?

Minimal conceptual example:

\documentclass{article}
\usepackage{expl3}
\csname sys_if_shell_unrestricted:T\endcsname{\usepackage{gitver}}
\usepackage{hyperxmp}
\usepackage{hyperref}


% this commented paragraph is conceptual & needs fixing through a solution from this forum
% \hypersetup{%
% pdfversionid = {detect if gitver has been loaded & set to \gitVer if so; otherwise set to empty {}}
% }%

\begin{document}
Hello world!

% The following again describes my intended requirements in words
% detect if gitver has been loaded & print \versionBox{} if so; otherwise print "gitver not loaded"

\end{document}
5

Normally you would just use \@ifpackageloaded, but the command is limited to the preamble. To use it in the document body you need \ltx@ifpackageloaded from the ltxcmds package. Since the macro has an @ in the name, you need to wrap it in \makeatletter and \makeatother.

\documentclass{article}
\usepackage{expl3}
\usepackage{ltxcmds}
%\csname sys_if_shell_unrestricted:T\endcsname{\usepackage{gitver}}
\usepackage{hyperxmp}
\usepackage{hyperref}

\makeatletter
% this commented paragraph is conceptual & needs fixing through a solution from this forum
\@ifpackageloaded{gitver}{
  \hypersetup{pdfversionid = \gitVer}
}{
  \hypersetup{pdfversionid = {}}
}
\makeatother

\begin{document}
Hello world!

\meaning\gitVer
% The following again describes my intended requirements in words
% detect if gitver has been loaded & print \versionBox{} if so; otherwise print "gitver not loaded"
\makeatletter
\ltx@ifpackageloaded{gitver}{\versionBox{}}{gitver not loaded}
\makeatother

\end{document}
6

Assuming that \gitVer and \VersionBox are defined by gitver, just add

\providecommand{\gitVer}{}
\providecommand{\VersionBox}[1]{gitver not loaded}

after the conditional loading.

This exploits the fact that \providecommand does nothing if the command is already defined.

  • thank you. It worked for me. However, I think the ltxcmds package is a bit more flexible, and hence I'd like to accept that answer. However, yours is a valid solution and I am upvoting this. – Krishna Sep 19 at 16:25
  • @Krishna I disagree about the flexibility and you're fill your document with extraneous bits of code. – egreg Sep 19 at 16:27

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.