Load a package by command line

Yes, that's true: the first input file is used for the name.

How to fix it?

latex -jobname=myfile '\RequirePackage{xcolor}\input{myfile.tex}'

On your system, double quotes may work, on mine they don't.


Why does that happen? When a TeX engine starts with

engine <options> <argument>

(in your case engine is latex)

it looks at what it is fed with. If the <argument> does not start with a backslash, it is considered a file name and essentially the engine executes \input <argument>. Otherwise the engine waits for the first \input instruction and the name of the input file will determine the job name, used for the log file and the output (dvi or PDF).

Note: the \input command is the primitive one.

Since \RequirePackage eventually does \input xcolor.sty, we have that the jobname is set to xcolor because of the rules.

The option -jobname fixes it by disabling the above feature and establishing the jobname at the outset.

There is a big difference between the command line call above and when the input file starts with \RequirePackage. In the latter case, \RequirePackage is seen when a file has already been \input and the jobname decided upon.


Driver mismatch

The file myfile.tex is broken:

tmp$ latex

latex is initialized to generate DVI as output format.

(/usr/local/texlive/2015/texmf-dist/tex/latex/xcolor/xcolor.sty
...
(/usr/local/texlive/2015/texmf-dist/tex/latex/graphics/dvips.def))

Package xcolor is loaded with DVI driver dvips. Fine.

But then:

Non-PDF special ignored!
{/usr/local/texlive/2015/texmf-var/fonts/map/pdftex/upd

map/pdftex.map} ... Output written on xcolor.pdf

The mode switches to PDF and a PDF file is generated. Color specials for DVI have no effect.

The LaTeX document should never change the output mode. Many, many packages relay on a stable output mode. Check the code for changes of \pdfoutput. It may be read (better is the use of package ifpdf), but should not be changed.

Loading a package on the command line

There are packages, that can be loaded before \documentclass using \RequirePackage, see egreg's answer.

Other package require to be loaded after the class. Some of them, can be loaded even quite late in \AtBeginDocument, then the command line would become:

$ pdflatex '\AtBeginDocument{\RequirePackage{xcolor}\pagecolor{yellow}}\input{myfile}'

An alternative is providing a hook in the file myfile.tex. For example, at the right place in the preamble:

\ifx\WithPageColor Y
  \usepackage{xcolor}
  \pagecolor{yellow}
\fi

If \WithPageColor is undefined, the page color setting is ignored. But, it can be defined on the command line:

$ pdflatex '\let\WithPageColor=Y\input{myfile}'

Another variant for the hook in the preamble:

\documentclass{...}
...
\providecommand{\PageColorHook}{}
\PageColorHook
...
\begin{document}
\end{document}

Then on the command line:

$ pdflatex '\newcommand{\PageColorHook}{\usepackage{xcolor}{\pagecolor{yellow}}\input{myfile}'

Tags:

Compiling