As mentioned in comments, there is a TeX Live package called
texliveonfly which you can use with
texliveonfly filename.tex, and it will automatically downloaded the right TeX Live packages.
This also works for packages for which the LaTeX package name and the TeX Live package name don't match (for example the LaTeX
rubikrotation package is contained in the
rubik TeX Live package), and it also takes package dependencies into account.
Installing It is a Python script so it requires Python to be installed. You can then install it like usually with
tlmgr install texliveonfly. If you have to use
sudo tlmgr here, you will have to use
sudo texliveonfly later.
Running If you go in your terminal to the directory of your
filename.tex file, you can run it with
Other compilers At the moment it uses
pdflatex by default, but you can configure it to run with other compiler engines by using the
-c) flag, so like
texliveonfly --compiler=lualatex filename.tex.
Compiler flags You can pass flags for the compiler you use to
texliveonfly using the
-a) flag, so for example if you previously used
latexmk -shell-escape -pdf filename.tex then you now use
texliveonfly --compiler=latexmk --arguments='-shell-escape -pdf' filename.tex.
There are some cases of missing packages which fail with a non-standard error message, for example babel when it's missing languages, in which case
texliveonfly doesn't download them.
At the moment the following packages are known to have to be installed manually: (please edit if you find more)
- Babel languages, for example for european languages install the
- Biblatex styles, e.g. for the nature style you need the
- fontenc encodings, e.g. to get
t2aenc.def you need the
cyrillic package, and to get the
ly1enc.def you need the
- Packages involved when using the minted package, which are
minted fvextra upquote lineno xstring framed caption (thanks to pablgonz for testing)
When giving options to texliveonfly, for example for a different compiler, it sometimes hangs for no apparent reason when installing packages. You can most probably work around it by first running texliveonfly without options, so
texliveonfly main.tex (so it will download the packages) and then running whatever you wanted to, for example
Essentially texliveonfly is a build tool like latexmk (which is a Perl script), it wraps the TeX engine. Note however that you can chain them with
texliveonfly --compiler=latexmk filename.tex.
It is a python script which works by trying to run your LaTeX file, and if it fails because a package is missing it will try to install that package.
Besides on ctan.org/pkg/texliveonfly you can view the source at ctan.org/tex-archive/support/texliveonfly or on latex.org/forum
PS I tested this on Arch Linux 4.19.4 and on Travis CI (Ubuntu 14.04).