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)


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.

  • 5
    Note that the usual way to handle long docs is to have a 'main' file then one or more 'content' files. Done this way, adding a package only requires switching to the main file then back to the content: not really too much work. – Joseph Wright Apr 23 '14 at 8:13
  • Also see latex.ltx: \@onlypreamble\usepackage. – Ruben Apr 23 '14 at 8:15
  • Does LaTeX3 support this feature? – subham soni Apr 23 '14 at 8:22
  • @subhamsoni Currently, the only part of LaTeX3 that is anything like 'done' is the programming layer (expl3), thus talking about other parts is speculative. That said, I think it's very unlikely a change to this restriction will be made: the idea that packages add functionality to the entire document works well, and as I said there are technical reasons for therefore requiring all package loading in the preamble. – Joseph Wright Apr 23 '14 at 9:00

\usepackage{} can be used only in the preamble.

What you can do is make other file and concatenate them in another document (for exemple using \includepdf if you use pdftex or equivalent)

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.