7. Customising LaTeX

7. Customising LaTeX #

Customisation works best when it supports the document’s structure. Define a command for a concept, change the settings in one place, and check a representative page before applying the result throughout a long document.

7.1 New Commands, Environments, and Packages #

New commands #

The modern interface is:

\NewDocumentCommand{\commandname}{argument specification}{definition}

References to arguments inside the definition use #1, #2, and so on.

Specification Argument
m Required argument.
o Optional argument in square brackets; may be absent.
O{default} Optional argument with a default value.
s An optional star.
+m A required argument that can contain paragraphs.

For example:

% Preamble
\NewDocumentCommand{\person}{mm}{#1~\textsc{#2}}
\NewDocumentCommand{\notice}{O{Note}m}{\textbf{#1:} #2}

% Body
\person{Alex}{Writer}

\notice{Keep the source files.}

\notice[Warning]{This example needs XeLaTeX.}

Use \IfValueTF{#1}{present}{absent} for an o argument:

\NewDocumentCommand{\result}{om}{%
  \IfValueTF{#1}{\textbf{Result #1:}}{\textbf{Result:}} #2%
}

The tests \IfValueT and \IfValueF handle only one branch. \IfNoValueTF reverses the branches. For an s argument, use \IfBooleanTF:

\NewDocumentCommand{\term}{sm}{%
  \IfBooleanTF{#1}{\textbf{#2}}{\emph{#2}}%
}

\term{sample} uses emphasis; \term*{sample} uses bold.

\NewDocumentCommand refuses to overwrite a definition. \RenewDocumentCommand requires one to exist. \ProvideDocumentCommand defines it only if absent, and \DeclareDocumentCommand defines it regardless. Choose the variant intentionally.

New environments #

An environment has begin and end code:

% Preamble
\NewDocumentEnvironment{important}{O{Important}}{%
  \begin{quote}
  \textbf{#1.}\space
}{%
  \end{quote}
}

% Body
\begin{important}[Remember]
Keep content and appearance separate.

A named environment makes later design changes easier.
\end{important}

\NewDocumentEnvironment{name}{specification}{begin code}{end code} uses the same argument specifications as commands. Arguments follow \begin{name}.

A final +b argument captures the body, including paragraphs. Use it when the body must be processed as an argument, not as the default for every environment: it changes what content is allowed, especially verbatim material. A starred name such as important* is a separate environment; an s argument alone does not create it.

Copying commands #

A wrapper around a command is not a frozen copy of its definition. When redefining something while retaining the original behaviour, make a real copy first:

\NewCommandCopy{\originalemph}{\emph}
\NewDocumentCommand{\markedemph}{m}{%
  \originalemph{#1}%
}

If you redefine \emph and call \emph inside its new definition, the command calls itself indefinitely. \NewCommandCopy avoids this when an actual saved definition is needed.

Command-line LaTeX #

A local build can inject a definition before reading the source:

xelatex '\NewCommandCopy{\monochrome}{\BooleanTrue}\input{main.tex}'

In main.tex, this fallback and test allow the same source to be compiled normally or with the command above:

% Preamble, after \documentclass
\ifdefined\monochrome\else
  \NewCommandCopy{\monochrome}{\BooleanFalse}
\fi
\usepackage{xcolor}
\IfBooleanTF{\monochrome}
  {\definecolor{accent}{gray}{0}}
  {\definecolor{accent}{RGB}{0,90,150}}

The fallback copies the boolean only when \monochrome is not already defined. Use an actual copy of \BooleanTrue or \BooleanFalse: \IfBooleanTF checks that value, not a wrapper command that expands to it.

The shell quoting shown is for Unix-like shells. For a shared online project, a small configuration file may be easier to manage than command-line definitions.

Your own package #

When definitions become reusable, put them in projectstyle.sty:

\ProvidesExplPackage
  {projectstyle}{2026-09-18}{1.0}{Shared document commands}

\NewDocumentCommand{\projecttitle}{}{
  A~Reproducible~Experiment
}
\NewDocumentEnvironment{projectnote}{}{
  \begin{quote}
}{
  \end{quote}
}

Load the uploaded file with \usepackage{projectstyle}. Here, \ProvidesExplPackage enables LaTeX3 syntax: ordinary input spaces are ignored, and ~ represents an explicit space. Use \nobreakspace if you need a non-breaking space in that syntax.

A package should contain reusable definitions, not a second document environment. If it depends on another package, load that dependency with \RequirePackage.

7.2 Fonts and Sizes #

Font-changing commands #

Property Command with an argument Declaration
Serif \textrm{text} \rmfamily
Sans serif \textsf{text} \sffamily
Monospaced \texttt{text} \ttfamily
Bold \textbf{text} \bfseries
Italic \textit{text} \itshape
Slanted \textsl{text} \slshape
Small capitals \textsc{text} \scshape

These properties can combine, for example \textbf{\textit{important}}, if the font provides the requested shape. Use \emph for semantic emphasis. A missing shape may produce a substitution warning.

Prefer the argument form for a short passage. Restrict declarations with a group or environment:

Normal text. {\sffamily A short sans-serif passage.} Normal text.

Font sizes #

Relative size commands run from \tiny, \scriptsize, \footnotesize, and \small through \normalsize, \large, \Large, \LARGE, \huge, and \Huge. Their absolute sizes depend on the class and its base size.

For a paragraph, end the paragraph while the size setting is still active so LaTeX uses the correct line spacing:

{\Large
This paragraph uses a larger font and the corresponding line spacing.
\par}

For an explicit size and baseline distance:

{\fontsize{12pt}{15pt}\selectfont
A paragraph in twelve-point type with a fifteen-point baseline distance.
\par}

Avoid using arbitrary font changes as substitutes for section headings. A small number of consistent styles usually makes a document easier to read.

7.3 Custom Fonts with fontspec #

Use XeLaTeX or LuaLaTeX. Set the main, sans-serif, and monospaced families in the preamble:

\usepackage{fontspec}
\setmainfont{Latin Modern Roman}
\setsansfont{Latin Modern Sans}
\setmonofont{Latin Modern Mono}

The font must exist in the compilation environment. In an online project, selecting a font installed only on your own computer is not sufficient.

OpenType options depend on the font. Examples include Numbers=OldStyle, Numbers=Lining, Ligatures=TeX, and Language=.... A requested feature has no effect if the chosen font does not provide it.

Loading font files #

You can upload font files when their licence permits this. For a family with these exact filenames in fonts/:

\setmainfont{ExampleSerif}[
  Path=fonts/,
  Extension=.otf,
  UprightFont=*-Regular,
  BoldFont=*-Bold,
  ItalicFont=*-Italic,
  BoldItalicFont=*-BoldItalic
]

Replace the placeholder family and filenames with the actual uploaded files. Mapping all the faces prevents LaTeX from guessing an unavailable bold or italic font.

Additional families and math fonts #

\newfontfamily defines a switch for one extra family:

% Preamble, after fontspec
\newfontfamily{\displayfont}{TeX Gyre Pagella}

% Body
{\displayfont A short passage in another family.}

For mathematics, load unicode-math and choose an OpenType math font:

\usepackage{unicode-math}
\setmathfont{Latin Modern Math}

A text font alone is not a complete math font. Set math fonts in the preamble. The range option can replace selected symbol ranges with another font, but check coverage and visual consistency before mixing families.

7.4 Colours #

Load xcolor:

\usepackage{xcolor}
\definecolor{accent}{HTML}{245A81}
\colorlet{lightaccent}{accent!15}

Use a named colour or a mixture:

\textcolor{accent}{An important result.}

{\color{blue!60!black}A darker blue passage.}

\colorbox{lightaccent}{Highlighted text}
\fcolorbox{accent}{white}{A framed label}

blue!60!black means 60% blue mixed with 40% black. If the second colour is omitted, it defaults to white.

Model Values
rgb Three components from 0 to 1.
RGB Three integers from 0 to 255.
HTML A six-digit hexadecimal colour, without #.
gray One value from 0 for black to 1 for white.
cmyk Four components from 0 to 1.
hsb Hue, saturation, and brightness from 0 to 1.

Model names are case-sensitive. \definecolor creates a named colour, \providecolor leaves an existing definition intact, and \colorlet copies a colour or mixture.

\mathcolor{red}{...} colours a mathematical subexpression while preserving its mathematical role. \pagecolor{...} changes the page background and \nopagecolor removes that setting.

Use adequate contrast and retain a way to understand the document when printed in grayscale. Colour should reinforce labels and structure.

7.5 Lengths and Spacing #

Units #

Unit Meaning
mm, cm, in Physical lengths.
pt TeX point: 1/72.27 inch.
bp PDF or desktop-publishing point: 1/72 inch.
em, ex Dimensions relative to the current font.
mu Mathematical spacing unit.
sp Scaled point: 1/65536 TeX point.

em and ex are font metrics, not necessarily the measured width and height of particular letters. Use a relative length when spacing should follow font size.

Horizontal and vertical space #

\hspace{1cm} inserts horizontal space; \vspace{6pt} inserts vertical space. Unstarred spaces can disappear at line or page boundaries; \hspace* and \vspace* retain them there.

Left\hfill Right

\par\smallskip
A slightly separated paragraph.

\par\vspace{6pt}
Another paragraph.

\hfill absorbs available horizontal space. Two equal fills split that space equally. \smallskip, \medskip, and \bigskip provide conventional vertical skips. \vfill absorbs available vertical space.

A flexible length such as 6pt plus 2pt minus 1pt allows stretching and shrinking. \addvspace helps avoid accumulating adjacent vertical skips. These are layout tools, not replacements for paragraphs and headings.

Length variables #

% Preamble
\newlength{\labelwidthcustom}
\settowidth{\labelwidthcustom}{Longest label:}

% Body
\makebox[\labelwidthcustom][l]{Short:} First value.

\makebox[\labelwidthcustom][l]{Longest label:} Second value.

\setlength assigns a length; \addtolength modifies it. \settowidth, \settoheight, and \settodepth measure typeset material. \the\labelwidthcustom prints a length’s value.

Prefer dimensions such as 0.5\linewidth to guessed fixed widths when material must fit the current column or environment.

7.6 The Layout of the Document #

Class options #

Start with the class:

\documentclass[a4paper,11pt,twoside]{article}

Common options include 10pt, 11pt, 12pt; a4paper or letterpaper; oneside or twoside; onecolumn or twocolumn; and titlepage or notitlepage. fleqn aligns displayed mathematics to the left and leqno places equation numbers on the left.

In classes with chapters, openright starts chapters on right-hand pages and openany allows either side. twoside changes the layout for facing pages; it does not instruct a printer to print on both sides.

Page styles and numbering #

\pagestyle{plain} uses a simple page-number style; empty removes headers and footers; headings uses running headings defined by the class. \thispagestyle{empty} affects only the current page.

\pagenumbering{roman} or \pagenumbering{arabic} changes the representation and resets the page counter. In a book, use the class’s front-matter commands when appropriate instead of repeatedly resetting counters yourself.

Line and paragraph spacing #

Use setspace for conventional line-spacing changes:

% Preamble
\usepackage{setspace}
\onehalfspacing

\singlespacing and \doublespacing are alternatives. \linespread{factor} changes the underlying baseline multiplier; it is not necessarily the same as an institutional definition of “double spacing”.

Paragraph indentation and separation are separate lengths:

% Preamble
\setlength{\parindent}{1.5em}
\setlength{\parskip}{0pt}

\noindent suppresses the indentation of one paragraph. If you want unindented paragraphs separated by space, the parskip package also adjusts related list and heading spacing. Avoid combining large indentation and large paragraph gaps without a design reason.

Page geometry #

Use geometry rather than adjusting individual page offsets by trial and error:

\usepackage[
  a4paper,
  inner=3cm,
  outer=2.5cm,
  top=2.5cm,
  bottom=2.5cm,
  includeheadfoot
]{geometry}

inner and outer describe the binding and outside edges in a two-sided document. includeheadfoot includes header and footer areas in the calculated body. showframe is useful while diagnosing a layout.

Check actual PDF dimensions as well as margins. A publisher’s class may manage these settings itself, so follow its instructions before overriding them.

7.7 Fancy Headers #

Load fancyhdr, select its page style, clear the defaults, then assign fields:

% Preamble
\usepackage{fancyhdr}
\setlength{\headheight}{14pt}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[L]{Experiment Notes}
\fancyhead[R]{\nouppercase{\leftmark}}
\fancyfoot[C]{\thepage}
\RenewDocumentCommand{\headrulewidth}{}{0.4pt}
\RenewDocumentCommand{\footrulewidth}{}{0pt}

L, C, and R mean left, centre, and right. With a two-sided class, E and O distinguish even and odd pages. For example, \fancyhead[LE,RO]{\thepage} puts page numbers on the outside.

\leftmark and \rightmark contain running heading information supplied by the class. Their meanings differ between articles and books. \markboth and \markright can supply marks directly. The extramarks package provides first and last marks within a page, useful for dictionary-style headings.

If the log says the header is too tall, increase \headheight to the reported requirement and recheck the page geometry. A fixed value such as 14 pt is suitable only when it accommodates the actual header.

Special pages and advanced controls #

Chapter openings and title pages may switch to plain. Define that style separately if it should match your design:

\fancypagestyle{plain}{
  \fancyhf{}
  \fancyfoot[C]{\thepage}
  \RenewDocumentCommand{\headrulewidth}{}{0pt}
}

\fancyhfoffset adjusts the width of headers or footers. Depending on the installed fancyhdr version, additional interfaces include \fancycenter for balancing left, centre, and right fields, and conditions such as \iftopfloat, \iffloatpage, and \iffootnote for page-specific content. Check the installed fancyhdr manual before relying on these advanced interfaces.

Keep header text short enough to avoid collisions. Use marks for the logical running title instead of copying each section title manually.

7.8 Boxes #

LaTeX lays out material in boxes. A figure, table, or paragraph box can act as a single unbreakable object in the surrounding layout.

Command or environment Behaviour
\mbox{text} A single unbreakable horizontal box.
\makebox[width][position]{text} A horizontal box with specified width and alignment.
\fbox{text}, \framebox Framed horizontal boxes.
\parbox[position]{width}{text} A paragraph box with wrapping text.
minipage A wider range of content in a fixed-width box.
\raisebox{distance}{text} Move a box above or below its normal position.

Put two related paragraphs side by side:

\noindent
\begin{minipage}[t]{0.46\linewidth}
  \textbf{Input}\par
  A short description of the values supplied to the experiment.
\end{minipage}\hfill
\begin{minipage}[t]{0.46\linewidth}
  \textbf{Output}\par
  A short description of the results and how they are interpreted.
\end{minipage}
Two top-aligned text columns headed Input and Output.
Minipages wrap text independently while sharing one row. Download LaTeX source.

The [t] option aligns the top baselines. The combined widths plus any spacing must fit the available line. Inside each minipage, \linewidth refers to that minipage’s width.

A minipage cannot split across pages and cannot contain ordinary floating figures. \fbox adds padding and rules outside its contents, so include \fboxsep and \fboxrule when calculating its total width.

7.9 Rules #

\rule[lift]{width}{height} draws a filled rectangle. A shallow rectangle makes a horizontal rule:

\noindent\rule{\linewidth}{0.4pt}

A zero-width rule, such as \rule{0pt}{2.5ex}, reserves height without drawing a visible line. Such a strut can increase a table row’s minimum height. Use deliberate spacing and package-provided rules where possible rather than adding decorative lines everywhere.

← Graphics · Next: Older Syntax →

Sources and Licence