I propose a solution based on LaTeX3's l3keys package. It is more verbose in your .tex
file than other solutions proposed here, but rather readable once you understand a bit the LaTeX3 programming conventions, and relatively nice on the “user end” (the command line or Makefile, etc., where you pass parameters to your LaTeX document). But really, the main advantages I see compared to other methods given here are:
- very expressive, flexible and extensible;
- the LaTeX3 kernel does all the boring parsing work for you, so end users are provided with easy to understand error messages if they pass unrecognized options or invalid values for an option.
Enough marketing, here is a relatively minimal example. :) In the end, this example just shows how to check the values of recognized options, without actually doing what the option (name, value) pairs suggest. This is in order to keep this first example not too long, despite all the comments I included. Later in this message, I'll include an expanded version that does interesting things with the options passed on the command line. So, the minimal example:
\documentclass{article}
\usepackage{expl3}
% TeX booleans start out as false.
\newif\ifMyScreenOutput
\newif\ifMyFullScreenOutput
% What follows uses LaTeX3 syntax.
\ExplSyntaxOn
% LaTeX3 bools start out as false too.
\bool_new:N \g_MyDocParams_screenOutput_bool
\bool_new:N \g_MyDocParams_fullScreen_bool
% Our LaTeX3 error message(s) for the option list parser (l10n-ready)
\msg_new:nnnn { MyDocParams } { unknown-choice-for-option }
{
Invalid~value~for~option~\exp_not:n {'#1'}:~\exp_not:n {'#3'}~
(valid~choices~are~\exp_not:n {#2})
}
{ You~may~optionally~put~a~more~verbose~message~here. }
% Option definitions for our pseudo-package 'MyDocParams' (this document). See
% l3keys in interface3.pdf as found at [1].
%
% [1] https://ctan.org/pkg/l3kernel
\keys_define:nn { MyDocParams }
{
% First accepted key: 'outputType'. It takes an optional value among a
% fixed, limited number of choices, as defined next.
outputType .choice:,
outputType / paper .code:n = { % The first such value is 'paper'.
\bool_gset_false:N \g_MyDocParams_screenOutput_bool },
outputType / screen .code:n = { % The second one is 'screen'.
\bool_gset_true:N \g_MyDocParams_screenOutput_bool },
outputType .initial:n = { paper }, % Default is 'paper'
outputType / unknown .code:n = { % Run this when passed an invalid value.
\msg_error:nnxxx { MyDocParams } { unknown-choice-for-option }
{ outputType } % name of the choice key
{ 'paper'~and~'screen' } % valid choices
{ \exp_not:n {#1} } % invalid choice given
},
% Second accepted key: 'fullScreen'. It takes a boolean value.
fullScreen .bool_gset:N = \g_MyDocParams_fullScreen_bool,
fullScreen .initial:n = { false }, % the default is false
% Used when the key is passed with no value ('fullScreen' as opposed to
% 'fullScreen=true' or 'fullScreen=false').
fullScreen .default:n = { true }
}
% The option values may be set from the command line by means of the
% \MyDocParams macro, which may be defined this way before \input{}ing this
% file. For the precise option syntax, see l3keys in interface3.pdf[1].
%
% \newcommand{\MyDocParams}{
% outputType = screen,
% fullScreen = false
% }
%
% Since we already set defaults above with \keys_define:nn, no need to set
% any here.
\providecommand{\MyDocParams}{}
% This is where keys are set from the point of view of l3keys, and the action
% associated with each option set is carried out. In order to obtain the
% option list, we expand once ('o') the second argument of \keys_set:no,
% namely the \MyDocParams token.
\keys_set:no { MyDocParams } { \MyDocParams }
% Finally, convert our LaTeX3 booleans to \ifFooBar TeX conditionals. This is
% more or less needed, because control sequences such as
% \g_MyDocParams_screenOutput_bool will be difficult to enter in the main part
% of the document without using \ExplSyntaxOn ... \ExplSyntaxOff every time,
% which would be quite ugly. Of course, instead of the TeX conditionals, one
% could use booleans from the 'ifthen' or 'etoolbox' packages (see below).
\bool_if:NT \g_MyDocParams_screenOutput_bool
{ \MyScreenOutputtrue }
\bool_if:NT \g_MyDocParams_fullScreen_bool
{ \MyFullScreenOutputtrue }
\ExplSyntaxOff
\begin{document}
\ifMyScreenOutput
Screen output selected
\else
Paper output selected
\fi
\ifMyFullScreenOutput
Full screen mode selected
\else
Full screen mode not selected
\fi
\end{document}
% In order to use etoolbox's toggle macros instead of TeX's
% \ifFooBar ... \else ... \fi conditionals, one would use syntax like this:
% \usepackage{etoolbox}
%
% [...]
%
% \ExplSyntaxOn
%
% \newtoggle { myScreenOutput }
% \newtoggle { myFullScreenOutput }
% \bool_if:NT \g_MyDocParams_screenOutput_bool
% { \toggletrue { myScreenOutput } }
% \bool_if:NT \g_MyDocParams_fullScreen_bool
% { \toggletrue { myFullScreenOutput } }
%
% \ExplSyntaxOff
%
% [...] % What follows could be in the document body
%
% \iftoggle{myScreenOutput}{<code for true>}{<code for false>}
% \iftoggle{myFullScreenOutput}{<code for true>}{<code for false>}
Sample output for the print, screen and fullscreen variants

So, this document accepts two parameters:
outputType=paper
or outputType=screen
(defaults to paper
);
fullScreen=true
or fullScreen=false
(defaults to false
).
and you can pass them this way (I'll assume you saved the TeX file under the name parametrized_doc.tex):
pdflatex '\newcommand{\MyDocParams}{outputType=screen,fullScreen=false}' \
'\input{parametrized_doc.tex}'
It's also possible to use \def
instead of \newcommand
, to put spaces around parameters (see l3keys in interface3.pdf), to use PGF-style hierarchical option names, to gather all the \newcommand{\MyDocParams}{...}\input{parametrized_doc.tex}
as one argument to the latex
|pdflatex
|lualatex
|xelatex
program called, etc.
With the following Makefile, you may call make print
, make screen
or make fullscreen
in order to build parametrized_doc.tex with either of the three meaningful combinations of our two options, and just make
to build all three documents with one command. This Makefile uses the --jobname
option mentioned above (thanks Harald) in order to produce parametrized_doc-{print,screen,fullscreen}.pdf from the same parametrized_doc.tex file, depending on the chosen variant as passed to make
(no copying, renaming nor symlinking of the .tex
file).
Beware: simply copying and pasting the following code block won't work, because the Markdown engine used on TeX.SE destroys tab characters, which are very important in Makefiles. It seems the easiest way to get a correct Makefile from this answer (i.e., what I posted) is to click on the edit link, select the whole Makefile code block, click on the {}
button to unindent the block, copy/paste to the place you want and finally cancel your edit.
VARIANTS := screen fullscreen print
all: $(VARIANTS) # ps
LATEX := pdflatex -output-format dvi
PDFLATEX := pdflatex
LATEX_ARGS := -interaction=nonstopmode -halt-on-error
PDFLATEX_ARGS := $(LATEX_ARGS)
TEX_RUNS := 2
SRC_BASE_NAME := parametrized_doc
SRC := $(SRC_BASE_NAME).tex
# cf. GNU Make Manual (“Syntax of Functions”) and
# <https://stackoverflow.com/questions/28615974/wildcard-to-variable-to-comma-joined-string>
space :=
space += # $(space) is a space
comma := ,
# Function that converts a space-separated list into a comma-separated list
comma-separate = $(subst ${space},${comma},$(strip $(1)))
# Macro that expands to a Make rule for a parametrized document using the
# l3keys LaTeX3 module for parameters and \jobname for the output file name.
#
# $(1): variant name
# $(2): space-separated list of options to pass to l3keys (we can't
# conveniently use the comma separator, because we'll expand this macro
# with Make's $(call ...) function which separates arguments with
# commas, precisely; therefore, we replace spaces with commas for l3keys).
define customPDF =
$(1): $$(SRC_BASE_NAME)-$(1).pdf
$$(SRC_BASE_NAME)-$(1).pdf: $$(SRC)
for i in $$$$(seq 1 $$(TEX_RUNS)); do \
$$(PDFLATEX) --jobname=$$(SRC_BASE_NAME)-$(1) \
$$(PDFLATEX_ARGS) '\newcommand{\MyDocParams}{' \
'$(call comma-separate,$(2)) }' '\input{$$<}'; \
done
endef
$(eval $(call customPDF,screen, outputType=screen fullScreen=false))
$(eval $(call customPDF,fullscreen, outputType=screen fullScreen=true))
$(eval $(call customPDF,print, outputType=paper))
# Write a specific rule for this file (as opposed to a pattern rule starting
# with %.dvi: %.tex), because the suitable $(TEX_RUNS) value depends on the
# document, in general.
$(SRC_BASE_NAME).dvi: $(SRC)
for i in $$(seq 1 $(TEX_RUNS)); do \
$(LATEX) $(LATEX_ARGS) '\input{$<}'; \
done
%.ps: %.dvi
dvips -o '$@' '$<'
dvi: $(SRC_BASE_NAME).dvi
ps: $(SRC_BASE_NAME).ps
clean:
for ext in dvi ps pdf out aux log idx ind ilg toc bbl blg bcf run.xml; \
do rm -f "$(SRC_BASE_NAME).$$ext"; \
\
for variant in $(VARIANTS); do \
rm -f "$(SRC_BASE_NAME)-$$variant.$$ext"; \
done \
done
rm -f missfont.log
# Stuff from preview-latex
for ext in fmt ini log; do \
rm -f "prv_$(SRC_BASE_NAME).$$ext"; \
done
rm -rf auctex-auto '$(SRC_BASE_NAME).prv' _region_.prv
for ext in tex pdf log; do \
rm -f "_region_.$$ext"; \
done
.PHONY: all clean screen fullscreen print dvi ps
Finally, here is an expanded version of the same .tex
file that actually adapts the layout based on the options passed using the mechanism just described. It uses the KOMA-Script scrartcl
class, but obviously this has nothing to do with the parameters handling discussed here. I have removed most of the comments that were already in the “minimal example”, so if you find something unclear, look at the above LaTeX code and you should find what you are looking for. :-)
\documentclass[12pt]{scrartcl}
\usepackage{lmodern}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{textcomp}
\usepackage{expl3}
\usepackage{xparse}
\usepackage{blindtext}
\usepackage[english]{babel}
\usepackage[final,babel]{microtype}
\usepackage{scrlayer-scrpage} % used to customize headers and footers
\pagestyle{scrheadings}
\newif\ifMyScreenOutput
\newif\ifMyFullScreenOutput
\ExplSyntaxOn
\bool_new:N \g_MyDocParams_screenOutput_bool
\bool_new:N \g_MyDocParams_fullScreen_bool
\msg_new:nnnn { MyDocParams } { unknown-choice-for-option }
{
Invalid~value~for~option~\exp_not:n {'#1'}:~\exp_not:n {'#3'}~
(valid~choices~are~\exp_not:n {#2})
}
{ You~may~optionally~put~a~more~verbose~message~here. }
\keys_define:nn { MyDocParams }
{
outputType .choice:,
outputType / paper .code:n = {
\bool_gset_false:N \g_MyDocParams_screenOutput_bool },
outputType / screen .code:n = {
\bool_gset_true:N \g_MyDocParams_screenOutput_bool },
outputType .initial:n = { paper },
outputType / unknown .code:n = {
\msg_error:nnxxx { MyDocParams } { unknown-choice-for-option }
{ outputType } % name of the choice key
{ 'paper'~and~'screen' } % valid choices
{ \exp_not:n {#1} } % invalid choice given
},
fullScreen .bool_gset:N = \g_MyDocParams_fullScreen_bool,
fullScreen .initial:n = { false },
% Used when the key is passed with no value
fullScreen .default:n = { true }
}
% The option values may be set from the command line by means of the
% \MyDocParams macro. If nothing is passed this way, the defaults come from
% the 'outputType .initial:n' and 'fullScreen .initial:n' settings above,
% but they could also be set here in the definition of \MyDocParams.
\providecommand{\MyDocParams}{}
% This is where keys are set from the point of view of l3keys.
\keys_set:no { MyDocParams } { \MyDocParams }
% Finally, convert our LaTeX3 booleans to \ifFooBar TeX conditionals.
\bool_if:NT \g_MyDocParams_screenOutput_bool
{ \MyScreenOutputtrue }
\bool_if:NT \g_MyDocParams_fullScreen_bool
{ \MyFullScreenOutputtrue }
\ExplSyntaxOff
% Customize the layout and colors depending on the selected output type.
\ifMyScreenOutput
% Useful if you choose a two-sided layout for paper output (e.g., with the
% scrbook class) but want to override it here in order to have a one-sided
% layout for screen output.
\KOMAoptions{twoside=false}
\usepackage[svgnames]{xcolor}
\pagecolor{yellow!9!white}
% Let's choose a \textwidth containing a suitable number of characters for
% convenient reading, and a \textheight such that if a page is filled with
% “normal text” in the document font without any space between paragraphs,
% then no vertical stretching nor shrinking is needed to fill the type area
% (technique explained in the typearea/KOMA-Script documentation).
\newlength{\MyTextWidthGoal}
\newlength{\MyTextHeightGoal}
\settowidth{\MyTextWidthGoal}{% 67 characters, incl. spaces and punctuation
{\normalfont % (recommended range is between 60 and 70)
In this document, we'll show that in spite of its original syntax, }}
\setlength{\MyTextHeightGoal}{\topskip}
\ifMyFullScreenOutput
\addtolength{\MyTextHeightGoal}{14\baselineskip} % 15 lines
% Aspect ratio is 16:9 in this case
\usepackage[papersize={17cm,9.5625cm},
width=\MyTextWidthGoal,height=\MyTextHeightGoal]{geometry}
\else
% 55 lines (very tall!). I want this for screen reading as in a web
% browser---without being disturbed by page separations.
\addtolength{\MyTextHeightGoal}{54\baselineskip}
\usepackage[papersize={17cm,31.5cm},
width=\MyTextWidthGoal,height=\MyTextHeightGoal]{geometry}
\fi
% I want empty headers and footers for screen output (these are commands
% from KOMA-Script's scrlayer-scrpage package).
\ohead*{} \chead*{} \ihead*{}
\ofoot*{} \cfoot*{} \ifoot*{}
\else
% Paper output: just use typearea's automatic calculations, they work great!
\KOMAoptions{paper=A4,BCOR=0mm,DIV=calc}
\fi
\usepackage[colorlinks=true]{hyperref}
\ifMyScreenOutput
% Also available: filecolor, menucolor, runcolor
\hypersetup{anchorcolor=Lime,linkcolor=DarkRed,urlcolor=RoyalBlue,
citecolor=DarkRed}
\ifMyFullScreenOutput
\hypersetup{pdfpagemode=FullScreen}
\fi
\else
\hypersetup{allcolors=black} % for print; other possibility: 'hidelinks'
\fi
% Define a few convenient document-level commands using the LaTeX3 framework.
\ExplSyntaxOn
% Insert a URL with optional link text. In print mode, if the link text is
% provided, then the URL is put inside a footnote tied to the link text.
%
% #1: URL (prefix any '%' or '#' characters with a backaslash)
% #2: link text (optional)
\NewDocumentCommand \myHref { m o }
{
\IfValueTF {#2}
{ % The link text was provided (#2)
\bool_if:nTF { \g_MyDocParams_screenOutput_bool }
{ \href {#1} {#2} }
{ #2 \footnote { \url {#1} } }
}
{ % No link text provided
\url {#1}
}
}
% Typeset a LaTeX3 package name
\NewDocumentCommand \liiiPkg { m }
{
\texttt {#1}
}
\ExplSyntaxOff
\begin{document}
\title{Gnus, gnats and armadillos}%
\subtitle{Their life in relation to the universe}%
\author{Joe R.~User}%
\date{}%
\maketitle
In this article, we are going to make a reference to
\autoref{sec:test-section} just to show the link color. And also add a pointer
to the very useful
\myHref{https://ctan.org/pkg/l3kernel}[\liiiPkg{l3kernel} documentation]
for people interested in \LaTeX3 programming. The \LaTeX3 source code
repository can be found on GitHub: \myHref{https://github.com/latex3/latex3}.
\section{This is a test section\label{sec:test-section}}
\blindtext % text that belongs to the section
\Blinddocument
\end{document}
Sample outputs for the print, screen and fullscreen variants
Print

Screen

Fullscreen

Detail on the differing handling of hyperlinks implemented in \myHref
:
Print

Screen

Fullscreen
For this part of the document, it is identical to the screen variant, except that the page is shorter and thus the first paragraph doesn't entirely fit on the first page. Thus, I'm not including the screenshot in order to spare some bandwidth.
Notes:
- I used LaTeX3 to parse the key/value pairs, but of course one could do something similar with
xkeyval
in pure LaTeX2e;
- I implemented the fullscreen variant mainly to see what the result would look like with
\hypersetup{pdfpagemode=FullScreen}
; however, for real presentations, specialized packages such as beamer
and pdfscreen
should be considered too;
Since I'm using the outputType and fullScreen logic in several documents of mine, to avoid redundancy I've moved all this logic to a little package I called parmoutput.sty
(for “parametrizable output”). In this setup, options can be passed in several ways:
- with
\PassOptionsToPackage{outputType=screen,...}{parmoutput}
, which is convenient from the Makefile or any batch file controlling the compilation (this works because I use \ProcessKeysOptions
from l3keys2e
in parmoutput.sty
, see here for explanations);
- with
\usepackage[outputType=screen,...]{parmoutput}
if I want the format choice to be written in the document itself;
- with
\ParmOutputSetup{outputType=screen,...}
: the same, but allows one to select these options later in the document, possibly in several steps (conceptually similar to hyperref's \hypersetup
command).
Currently, parmoutput.sty
can be found here, but I can't guarantee the URL will remain stable (I don't guarantee its API will be stable either, yet).
I'm just starting with LaTeX3, so please forgive any mistakes in this area. :-)
make
is not available it is quite easy to do that by hand.