[Tex/LaTex] Preamble anywhere


If I want to use a set of macros in my tex document, I have to obviously include the appropriate packages IN THE PREAMBLE. So now, i write a 100 page document, with 55 packages already included (in a separate tex file or everything inline) and I want to include a new package, I would need to go to the preamble, and include my package and then return back to my work. Is it possible in LaTeX, where in the \usepackage{} commands can be written anywhere in the file and not only the preamble something similar to C++ or Java where in the declaration of a variable need not be always after main immediately rather anywhere in the program(the main disadvantage of C)

Best Answer

Short answer: no.

There are two reasons for this: a 'LaTeX' one and a 'TeX' one. The 'LaTeX' reason is that the mechanisms for loading packages are deliberately disabled at the start of the document, so for example \usepackage gives an error. The decision to do this is done is partly based on a desire for 'logical structure' but mainly due to the underlying 'TeX reason'. TeX reads files sequentially and processes as it goes. As such, there is no 'first see what packages are loaded' phase to running (La)TeX: package features can only be used after they have been loaded. As LaTeX can't know what any particular package does, this means they all need to come in the preamble before 'stuff' is typeset: the outcomes might otherwise be altered.

Note that you can \input a file anywhere, so you can for example define commands in a secondary file then load it part-way through a document. That's not encouraged: experience suggests that commands should be defined for all of a document, not just part of it.