Formatting Text and Creating Macros
local graph
Chapter 2 — Formatting Text and Creating Macros
Section titled “Chapter 2 — Formatting Text and Creating Macros”In the last chapter, we installed LaTeX and wrote our first document using both the TeXworks editor and Overleaf. Now, we’ll take a closer look at the structure of text, focusing on formatting and fine-tuning details.
In this chapter, we’ll cover the following:
- Using logical formatting
- Understanding how LaTeX processes your input
- Modifying text fonts
- Using color
- Limiting paragraph width
- Breaking lines and paragraphs
- Changing text alignment
- Displaying quotations
- Creating commands
- Creating environments
- Using an alternative syntax
Through hands-on examples and trying the features, you’ll learn some essential LaTeX concepts. By the end of this chapter, you’ll be comfortable working with commands and environments and be able to define custom commands.
Remember that you can edit and compile all the examples online on the book’s web page. This chapter’s code can be found at https://latexguide.org/chapter-02 and in the book’s GitHub project.
As you begin working more extensively, you may occasionally encounter error messages. If that happens, refer to Chapter 14, Troubleshooting, for guidance and possible solutions.
Using logical formatting
Section titled “Using logical formatting”Within a LaTeX document, we should avoid applying physical formatting, such as making words bold or italicized or choosing different font sizes. Instead, we should use logical formatting, such as declaring a title and the author, and then assigning a section heading. LaTeX takes care of the visual appearance, such as printing the title in a large font size and displaying section headings in bold.
In some examples later in this chapter, we will use physical formatting commands, such as making words bold or italic. However, that’s for practicing font commands. The ultimate goal is to define our own logical commands using font commands.
In a good LaTeX document, physical formatting would only be used inside the definition of logical formatting commands. If you need a specific style, such as for highlighting keywords, you can define a logical command for it in the document preamble. Then, throughout the body of your document, you only use that logical command. This ensures consistent formatting throughout your text. Whenever you change your mind about formatting details, you can modify the logical commands in the preamble; no need to go through the entire document.
To get started, let’s examine a brief example that illustrates the typical document structure.
Creating a document with a title and heading
Section titled “Creating a document with a title and heading”Let’s build a short example that uses some basic formatting. The document will include a title, the author’s name, the date, a section heading, and some regular text.
Follow these steps:
- Type the following code into your editor to start a small document:
\documentclass[a4paper,11pt]{article}
- Specify the title, author, and date:
\title{Example 2}\author{My name}\date{May 5, 2021}
- Begin the document:
\begin{document}
- Let LaTeX print the full title, which will include the author and date:
\maketitle
- Add a section heading and write some text, then end the document:
\section{What's this?}This is our second document. It contains a title and a section with text.\end{document}
- Save the document by clicking the Save button (or pressing Ctrl + S). Give it a name, such as
example2.tex. - Compile the document by clicking the Typeset button (or pressing Ctrl + T); this converts your code into a PDF file.
- View the output:

Figure 2.1 – Text with a heading
Figure 2.1 – Text with a heading
In the TeXworks editor, the PDF preview appears automatically after you press the Typeset button. At the same time, a PDF file is created. In this case, it’s called example2.pdf and stored in the same folder as your original code file, example2.tex.
In the first chapter, we talked about logical formatting; let’s now look at this example with that in mind. Here’s what we told LaTeX:
- The document type is
article, and it is to be printed on A4 paper with a base font size of 11 points - The document title is Example 2
- The document shows the author’s name
- The document’s date is set to May 5, 2021
Concerning the content of the document, we stated the following:
- The document begins with a title
- The first section is titled What’s this?
- The section contains the following text: This is our second document. It contains a title and a section with text
.
Notice that we didn’t choose the font size of the title or section heading, or make anything bold or centered. LaTeX handles all of that formatting. Nevertheless, you’re free to customize the way things look.
Once you’ve saved a document, there’s no need to press the Save button again. TeXworks automatically saves it whenever you click the Typeset button.
Exploring the document structure
Section titled “Exploring the document structure”Let’s take a closer look at the example we just created. A LaTeX document doesn’t exist in isolation—typically, it’s based on a reusable template called a class. A class provides an overall structure, along with customizable features, typically tailored to a specific purpose. There are classes for various types of materials, including books, journal articles, letters, presentations, and posters. You’ll find hundreds of reliable classes in online archives and even on your computer after you’ve installed TeX Live. In our example, we chose the article class, a standard LaTeX class well suited for shorter documents.
The first line starts with \documentclass. This word begins with a backslash; such a word is called a command or a macro. We’ve already used a few such commands to specify the class and to state the document’s metadata in our first example in this chapter: \title, \author, and \date. These commands store the properties; they don’t produce visible output.
The first part of the document is called the preamble. This is where we choose the class, specify properties, and, in general, make document-wide definitions.
\begin{document} marks the end of the preamble and the beginning of the actual document. \end{document} marks the end of the document. Anything that follows would be ignored by LaTeX. Generally, such a piece of code framed by a \begin and \end command pair is called an environment.
Within the document environment, we used the \maketitle command to print the title, author, and date in a nicely formatted layout. With the \section command, we produced a heading, bigger and bolder than standard text. Finally, we added a short paragraph. To be clear: the preamble will never produce any output. Only what’s in the document environment will be printed.
Now that you’ve seen how commands work, let’s take a closer look at LaTeX’s command syntax.
Using LaTeX commands
Section titled “Using LaTeX commands”LaTeX commands begin with a backslash, followed by letters, usually lowercase, sometimes mixed with uppercase. They are usually named descriptively, with exceptions, though: later on, you will encounter commands consisting of just a backslash and a single special character.
Commands can take parameters. These are options that determine how the command performs its work. The values of parameters passed to commands are referred to as arguments. Arguments appear in curly braces when they are mandatory, or in square brackets when they are optional.
So, you’ll see commands used in various ways, typically like one of these:
\command\command{argument}\command[optional argument]\command[optional argument]{argument}\command{argument}{another argument}You see that some commands can take multiple arguments, with each of them enclosed in braces or brackets. Let’s look closer at how it works.
If a command requires an argument by definition, that argument has to be provided; it’s mandatory, denoted by curly braces. For example, calling \documentclass without specifying a class name would be pointless.
Commands can support arguments without strictly requiring them, so they are called optional. You may specify them, but it’s not a must. If an optional argument isn’t provided, the command will use a default one. Enclose such arguments in square brackets.
Let’s look at the first example in Chapter 1, Getting Started with LaTeX. We wrote \documentclass{article} to choose the article class. Since we omitted an optional argument, this document was typeset with a base font size of 10 points because this is the class’s default base font size. In the second document, we wrote \documentclass[a4paper,11pt]{article}; here, we overrode the default values, so now the document will be adjusted for A4 paper with a base font size of 11 points.
Most LaTeX commands, including those we define ourselves, consist of other commands. That’s why LaTeX commands are also called macros, and the terms macro and command are used interchangeably. A command or macro that doesn’t print something but just changes current settings, such as the font shape or text alignment, is also called a declaration.
There’s a kind of command that applies changes only within a limited scope, such as a few lines or a code block. That’s called an environment. Let’s look at their syntax.
Using LaTeX environments
Section titled “Using LaTeX environments”LaTeX environments are code blocks that start with \begin and end with \end. Both commands require the name of the environment as their argument.
A simple environment can look like this:
\begin{name} …\end{name}Such environments can also be used for an existing declaration called \name, limiting the effect of the \name command.
Just like commands, environments can take arguments. Again, mandatory arguments go in curly braces while optional arguments go in square brackets. So, you may encounter an environment written like this:
\begin{name}{argument} …\end{name}Or, you might see an additional optional argument:
\begin{name}[optional argument]{argument} …\end{name}You can think of environments as declarations with a built-in scope. When \begin is called, the environment changes something particular, such as the layout, font, or other properties. That change stays in effect until an \end command is reached, at which point the change is canceled. The impact of the environment name is limited to the piece of code between \begin{name} and \end{name}.
Furthermore, the effect of all local declarations for formatting commands used within an environment will also end when the surrounding environment ends.
Now that we’ve covered the syntax of LaTeX commands and environments, let’s look at how LaTeX understands our code.
Understanding how LaTeX processes your input
Section titled “Understanding how LaTeX processes your input”Before we continue writing, let’s look at how LaTeX understands what we type:
- In addition to basic letters from the Latin alphabet, you can directly type (or copy and paste) accented characters, such as ä, ü, and ö, as well as characters from other languages, such as Greek or Cyrillic
- A single space in the input code appears as a space in the output document, while several consecutive spaces are treated as just one space
- A line break in the source code is treated like a space
- An empty line in the source code is treated as a paragraph break
Some characters have special meanings, like you saw before:
- A backslash,
\, starts a LaTeX command or a LaTeX macro - Curly braces and square brackets are used for command arguments
- A dollar sign,
$, begins and ends math mode, which we’ll explore in Chapter 9, Writing Math Formulas - A percent sign,
%, tells LaTeX to ignore the rest of the line
Let’s expand on that last point: the percent sign begins a comment. Everything following a percent sign up to the end of the line will be ignored by LaTeX and won’t be printed out. This allows you to insert notes into your document. It’s often used in LaTeX templates to inform the user of what the template does or requires the user to do at a certain point. Note that the end of the line, normally behaving as a space, will also be ignored after a percent sign. That’s the reason why you can often see a % sign at the end of lines in other people’s code: to prevent the end of the line from acting like a space.
If you want to disable a command or a line of code temporarily, it’s often better to insert a percent sign instead of deleting the command. That way, you’re able to undo this change easily by just removing the percent sign.
If that is how the percent sign works, what should we do if we want to write something like 100% in our text? And what about the other special symbols? Let’s figure out how to handle such cases in the next section.
Printing special symbols
Section titled “Printing special symbols”Most of the time, you can simply type letters, digits, and punctuation directly into your LaTeX document. However, some characters are reserved for LaTeX commands and can’t be used as is in your text. We’ve already seen such characters, such as the percent sign and curly braces. To include these characters in your output, LaTeX provides special commands to print such symbols.
Let’s write a very short example printing out a dollar amount, a percentage, and a few other special symbols:
- Create a new document and enter the following lines:
\documentclass{article}\begin{document}Statement \#1:50\% of \$100 equals \$50.More special symbols are \&, \_, \{ and \}.\end{document}
- Click the Typeset button to compile the document.
- Check out the output:

Figure 2.2 – Special symbols
Figure 2.2 – Special symbols
By placing a backslash in front of a special character, we turned it into a LaTeX command. The only purpose of this command is to print out that symbol.
You may be wondering how to print a backslash. To do this, use the \textbackslash command. Two consecutive backslashes, \\, are used as a shortcut for a line break. That might seem a bit unintuitive, but line breaks occur frequently, whereas backslashes are rarely printed in the output, so this shortcut has been chosen.
There’s a huge range of additional symbols that we can use for math formulas, chess notation, zodiac signs, music scores, and more. We won’t need to deal with those symbols for now, but we shall return to that subject in Chapter 9, Writing Math Formulas, when we’ll need symbols to typeset math formulas.
Now that we know how to enter plain text, let’s move on to formatting our text.
Modifying text fonts
Section titled “Modifying text fonts”LaTeX applies some formatting automatically; for example, we’ve seen that section headings are bigger than regular text and bold-faced. Now we will learn how to change the appearance of the text ourselves.
Adjusting the font shape
Section titled “Adjusting the font shape”In this example, we’ll emphasize an important word in our text, and we will see how to make words appear in bold, italics, or slanted. We’ll also figure out how to highlight words inside a section of text that’s already emphasized.
Let’s take a look:
- Create a new document containing the following code:
\documentclass{article}\begin{document}Text can be \emph{emphasized}.Besides from \textit{italics}, words can be\textbf{bold}, \textsl{slanted}, or typesetin \textsc {Small Caps}.Such commands can be \textit{\textbf{nested}}.\emph{See how \emph{emphasizing} looks when nested.}\end{document}
- Click Typeset and have a look at the output:

Figure 2.3 – Emphasizing phrases
Figure 2.3 – Emphasizing phrases
At first, we used the \emph command, passing a word as its argument. This word will be typeset in italics because LaTeX uses italics to emphasize text.
Most text-formatting command names follow the pattern \text**{argument}, where ** stands for a two-letter abbreviation, such as bf for bold face, it for italics, and sl for slanted. The argument text will then be formatted accordingly. After the command, LaTeX continues typesetting subsequent text in the previously used style.
We nested the \textit and \textbf commands to combine styles, so the text appears in both italics and bold.
It’s worth noting that most font commands will show the same effect if they are applied repeatedly, such as \textbf{\textbf{words}}. Here, the words will still be in the same bold style as with \textbf{words}, not bolder.
However, the \emph command behaves differently. We’ve seen that \emph changes text to italics, but if we use \emph on a piece of text that is already in italics, it will switch back from italic to upright font. Imagine a vital theorem completely typeset in italic, and you would like to highlight a word within this theorem. That word should not be in italics because it should be distinguishable from the surrounding text, so it’s formatted in an upright font again. In other words, the \emph command toggles between upright and italics.
Use font changes with care. Combining font shapes, such as big, bold, and italic, at the same time, can be visually overwhelming and may be perceived as poor style. Use available font styles thoughtfully and apply them consistently throughout your document.
Choosing the font family
Section titled “Choosing the font family”By default, LaTeX uses a serif font, also called a Roman font. Such fonts have small lines or strokes attached to letters, called serifs. Fonts without such serifs are sans-serif fonts, using the French word sans, meaning without.
Compare the two lines in Figure 2.4. Look closely at the first letter T; you’ll clearly notice the difference between serif and sans-serif fonts:

Figure 2.4 – Serif versus sans-serif font
Figure 2.4 – Serif versus sans-serif font
These different kinds of fonts are referred to as font families or typefaces.
Another available typeface is monospaced, where all letters have the same width. Such fonts are also called typewriter fonts.
Let’s switch font families in a short example document. We’ll begin with bold text, but using bold text with serif can look very heavy. So, we will use sans-serif bold text instead. The following text will contain an internet address, and we will choose a typewriter font to set it apart.
Follow these instructions:
- Create a LaTeX document with the following code:
\documentclass{article}\begin{document}\textsf{\textbf{Get help on the Internet}}\texttt{https://latex.org} is a support forum for \LaTeX.\end{document}
- Click on Typeset and look at the result:

Figure 2.5 – Text with a URL
Figure 2.5 – Text with a URL
Here, we encountered further font commands. Using \textsf, we’ve chosen a sans-serif font in the heading line, and we applied the \texttt command to get a typewriter font for the internet address. These commands work just like the font commands we’ve seen earlier.
Serifs, those small decorative details at the ends of a letter’s strokes, improve readability by guiding the reader’s eyes along the line. That’s why they are often preferred in printed books and newspapers.
Headings, however, are often set without serifs. Sans-serif fonts are also a good choice for screen text due to their better readability on lower-resolution displays or smaller screens, such as mobile phones. For this reason, sans-serif fonts are often preferred for text in e-books, on internet pages, and often for technical texts.
Monospaced (typewriter) fonts are ideal for displaying source code of computer programs, in printed documents as well as in text editors. As in our previous example, this book generally uses a typewriter font to distinguish internet addresses and source code from the surrounding text.
So far, we’ve seen commands that apply formatting to the text in the argument in curly braces. LaTeX also offers commands that don’t take arguments and work like switches.
Using the following instructions, we’ll modify the previous example, this time using font family switching commands:
- Edit the previous example to get the following code:
\documentclass{article}\begin{document}\sffamily\bfseries Get help on the Internet\normalfont\ttfamily https://latex.org\normalfont\ isa support forum for \LaTeX.\end{document}
- Click on Typeset to compile.
- Compare the output to the previous example; it looks the same.
We switched to the sans-serif typeface using the \sffamily command. The \bfseries command additionally switched the text to bold. We used the \normalfont command to return to the default LaTeX font, and then we applied the \ttfamily command to switch to a typewriter font. After the internet address, we used \normalfont again to switch back to the default font.
Such switching commands don’t produce any visible output on their own. They just change how the following text is rendered. That’s why they are also called declarations.
Let’s summarize the font commands and their corresponding declarations along with their meanings:

Figure 2.6 – Font commands
Figure 2.6 – Font commands
The corresponding declaration to the \emph command is \em.
Limiting the effect of commands
Section titled “Limiting the effect of commands”In the previous example, we wrote \normalfont to switch the font back to LaTeX’s default, but there’s another way. We can use curly braces to tell LaTeX where to apply a command and where to stop it:
- Shorten and modify our font shape example that produced Figure 2.3 to get this code:
\documentclass{article}\begin{document}Besides from {\itshape italics}, words can be{\bfseries bold}, {\slshape slanted}, or typesetin {\scshape Small Caps}.\end{document}
- Click the Typeset button and check out the output:
Figure 2.7 – Using declarations to change the font weight and shape
When we wanted to apply a declaration to change the font, we started with an opening curly brace, {, and let the font declaration command follow. The effect of that command lasts until it’s stopped by the corresponding closing brace, }.
An opening curly brace tells LaTeX to begin a group. The following commands are valid for the subsequent text until a closing curly brace ends the group. Groups can also be nested. Here’s an example:
Normal text, {\sffamily sans serif text {\bfseries and bold}}.The area where a command is valid is referred to as its scope. We have to be careful to complete each group. For every opening brace, there has to be a matching closing brace; otherwise, LaTeX will produce an error.
So, in short, groups are defined by curly braces and they contain and confine the effect of local commands.
Exploring font sizes
Section titled “Exploring font sizes”Let’s try out all the font sizes available through LaTeX’s built-in font size commands:
- Create a document with the following code:
\documentclass{article}\begin{document}\tiny We \scriptsize start \footnotesize very\smallsmall, \normalsize get \large big \Largeand \LARGE bigger, \huge huge, \Huge gigantic!\end{document}
- Click Typeset and observe the output:

Figure 2.8 – Font sizes
Figure 2.8 – Font sizes
We used all 10 available font size declarations, starting small with \tiny and ending with \Huge. There are no corresponding commands that take arguments, so if you want to limit their scope, you would have to use curly braces, just as we learned earlier.
The actual font size scales with the base font size of your document. So, if your document has a base font size of 12 points, then \tiny would result in text bigger than with a base font of 10 points.
Use the \footnotesize command if you want the same font size as LaTeX uses for footnotes; use \scriptsize for a size that matches LaTeX’s subscripts and superscripts. Document classes provide carefully selected and well-suited font size steps, so you usually don’t need to set a specific physical size.
If you want fine-grained control or advanced tweaks, these are covered in Chapter 3, Adjusting Fonts, in the LaTeX Cookbook, published by Packt Publishing.
Using color
Section titled “Using color”While the font style can help differentiate text, a bit of color can make content stand out more clearly, for emphasis, highlights, or getting attention. LaTeX provides the basic color package, but we will use the more versatile xcolor package right away.
We begin with a brief example, highlighting a short line of text in bold red to emphasize its importance. Follow these instructions:
- Create a document with the following code:
\documentclass{article}\usepackage{xcolor}\begin{document}\textcolor{red}{\textbf{Important:}}Always keep backup copies of your documents.\end{document}
- Click Typeset and look at the result:
Figure 2.9 – Text with color
The \textcolor command takes two mandatory arguments: the color name and the text to be colored. In our example, we wrote \textcolor{red}{...} to color the word Important: in red. We also made the word bold using \textbf, showing how to combine two formatting commands. You can use standard colors such as red, blue, green, yellow, black, and even white. The xcolor package provides hundreds of predefined named colors, such as LimeGreen or DarkCyan, with huge tables in its manual. You can open that manual by running texdoc xcolor at the command line, or visit https://texdoc.org/pkg/xcolor.
As with font-switching commands, LaTeX also provides a declaration-style version for setting the text color across larger portions of text: the \color command acts as a switch; once issued, it affects all subsequent text until the end of the current group or environment. This code would result in the same output as the previous figure:
{\color{red}\bfseries Important:}The xcolor package lets you easily mix colors using a simple syntax:
name1!percent1!name2!percent2!...This means: take percent1 of name1, percent2 of name2, and so on. The total should ideally sum to 100%, but if the last percentage is missing, xcolor just fills in the rest. Here are a few examples to show how it works:
- For a light gray, you can write
\color{black!20}to get 20% blackness - To blend 30% red with 70% yellow, use
\color{red!30!yellow} - To combine 50% red, 20% green, and the remaining 30% of the mix shall be blue, write
\color{red!50!green!20!blue}
I usually take this easy way to mix the base colors until it looks how I want. You can define your own color names, and you can use different color models for specifying numeric values such as RGB, CMYK, or even HTML codes, which is explained in the manual over 60 pages; but we’ll keep it at this.
Now that we have seen how to format words and phrases, let’s move on to formatting entire paragraphs.
Limiting paragraph width
Section titled “Limiting paragraph width”In most cases, we write text just from left to right across the entire text area. But sometimes you may want to narrow the width of a paragraph, for instance, when placing text beside a picture.
In the following sections, we’ll look at how to work with paragraph boxes in LaTeX.
Creating a narrow text box
Section titled “Creating a narrow text box”In this example, we’ll explain the acronym TUG in a text column that’s only 3 cm wide. Here’s how:
- Create a new document containing these four lines:
\documentclass{article}\begin{document}\parbox{3cm}{TUG is an acronym. It means\TeX\ Users Group.}\end{document}
- Click Typeset and review the output. It works, but we get loose lines:

Figure 2.10 – A narrow justified paragraph with big gaps
Figure 2.10 – A narrow justified paragraph with big gaps
In this example, we used the \parbox command to create a column of fixed width. The first argument specifies the width, and the second argument contains the text.
\parbox formats the argument text to fit the specified width. By default, the text is fully justified; however, our example shows an obvious problem: keeping full justification could lead to awkward gaps in the text. There are a few options to improve the appearance:
- Introduce hyphenation, for example, breaking long words such as acronym
- Improve general justification behavior
- Disable full justification and switch to ragged-right alignment
We’ll examine these techniques in the Breaking lines and paragraphs and Changing text alignment sections later in this chapter.
But first, let’s take a closer look at how \parbox actually works.
Producing paragraph boxes
Section titled “Producing paragraph boxes”In most cases, we simply need a text box with a certain width. However, sometimes, we also want to control how it aligns with the surrounding text. The \parbox command supports an optional argument for alignment. The general form of the \parbox command looks like this:
\parbox[alignment]{width}{text}These are the meanings of the parameters:
alignmentis the optional argument for vertical alignment with the surrounding text:taligns at the baseline of the top line of the box.baligns at the baseline of its bottom line.caligns its vertical center with the center of the adjacent text line. That’s the default so that you can omit it.
widthsets the width of the box. You can use standard length units without spaces, such as3cm, 44mm, or 2in.textis the content you want to put in that box. It should be a short paragraph or phrase. For more complex or multi-paragraph content, consider using theminipageenvironment instead. We will look at this in the next section.
Here’s a demonstration of the effect of the alignment parameters:
\documentclass{article}\begin{document}Text line\quad\parbox[b]{1.8cm}{this parbox is aligned at its bottom line}\quad\parbox{1.5cm}{center-aligned parbox}\quad\parbox[t]{2cm}{another parbox aligned at its top line}\end{document}The \quad command produces some space; we used it to separate the boxes a bit. Here’s the output:

Figure 2.11 – Aligned paragraph boxes
Figure 2.11 – Aligned paragraph boxes
Figure 2.11 shows how the alignment arguments work. Using the preceding text as the baseline, the following boxes are aligned, respectively, at the bottom line, the top line, or the center.
Exploring further paragraph box features
Section titled “Exploring further paragraph box features”The \parbox command offers even more control. If you need advanced positioning, here’s the complete syntax:
\parbox[alignment][height][inner alignment]{width}{text}The meanings of the new arguments are as follows:
height: By default, the box will have just the natural height of the text inside. Use this argument if you want to change the height of the box to make it bigger or smaller than the content.inner alignment: If the height of the box is different from the natural height of the contained text, you might want to adjust the text position. You can specify the following values:c: Center the text in the box verticallyt: Align text to the top of the boxb: Align text to the bottoms: Stretch the text vertically to fill the box (if possible)
If you omit this argument, the alignment argument will be used here as the default value.
Take our previous demonstration example and try the effect of the optional arguments. To better see the effect, use the \fbox command: if you write \fbox{\parbox[...]{...}{text}}, the entire parbox will get a frame.
Using minipages
Section titled “Using minipages”While \parbox works well for small amounts of text, it’s hard to manage longer content. A closing brace could easily be forgotten or overlooked. The minipage environment would then be a better choice. A minipage is a small area on your main page that LaTeX keeps together without breaking across pages.
In this example, we will use the minipage environment instead of \parbox to get a sample of text with a width of just 3 cm:
- Modify the
parboxexample to get the following code:\documentclass{article}\begin{document}\begin{minipage}{3cm}TUG is an acronym. It means \TeX\ Users Group.\end{minipage}\end{document} - Click on Typeset and look at the output:

Figure 2.12 – A minipage example
Figure 2.12 – A minipage example
By using \begin{minipage}, we started a “page within a page.” We specified the width of 3 cm as a mandatory argument. From that point onward, LaTeX will wrap text lines to fit within the 3 cm width; they will be automatically wrapped and fully justified. We ended this restriction with \end{minipage}. Any following text would run over the complete body text width.
A minipage environment will never have a page break within, so that’s a way to prevent page breaks for content that you want to keep together. If the content of a minipage environment doesn’t fit on the current page, LaTeX will move it entirely to the next page.
The minipage environment accepts the same arguments as \parbox with the same meanings.
When text is wrapped in a box or simply on a regular line, LaTeX will automatically fit it to the page layout reasonably well. However, we may still want to fine-tune line breaking and justification. Let’s see how to do that in the following sections.
Breaking lines and paragraphs
Section titled “Breaking lines and paragraphs”In most cases, you don’t need to worry about how lines break while you’re writing. Simply type your text in your editor, and LaTeX will format it to fit the line and handle the justification. To start a new paragraph, simply insert an empty line before you continue with your text for the following paragraph.
Now, we will discuss how to control line wrapping. First, we’ll examine ways to improve automatic hyphenation, and second, we’ll learn commands to insert breaks directly.
Improving hyphenation
Section titled “Improving hyphenation”If you look at longer documents, you’ll often notice how impressively LaTeX justifies paragraphs and distributes spacing between words evenly. If necessary, LaTeX will break words with hyphens at the end of the line to improve alignment.
LaTeX already uses excellent and very sophisticated algorithms for hyphenation, but in rare cases it can’t find an acceptable way to break a word. The previous example pointed out this problem: breaking the word acronym would improve the output, but LaTeX does not know where to divide it. We shall find out how to solve that.
No matter how reasonable the justification is, text in very narrow columns is extremely hard to justify. To achieve full justification, LaTeX may insert significant gaps between the words, but we want to avoid that.
In the following example, we’ll tell LaTeX how a word could be divided, to give LaTeX more flexibility for paragraph justification:
- Insert the following line into the preamble of the previous example:
\hyphenation{acro-nym}
- Click on Typeset and look at the output:

Figure 2.13 – A paragraph with improved hyphenation
Figure 2.13 – A paragraph with improved hyphenation
We’ve instructed LaTeX that the word acronym may be split between acro and nym. That allows LaTeX to insert a hyphen after acro at the end of the line and move nym down to the next line.
The \hyphenation command tells LaTeX where a word may be divided if needed. Its argument can contain several words separated by spaces. For each word, we can indicate multiple hyphenation points. For instance, we could extend the argument by more hyphenation points and more word variants, like this:
\hyphenation{ac-ro-nym ac-ro-nym-ic a-cro-nym-i-cal-ly}You could also indicate division points within the body text by inserting a backslash followed by a hyphen, such as ac\-ro\-nym. However, by using the \hyphenation command in the preamble, you can collect all rules there, ensuring they are used consistently. Therefore, use it mainly in rare cases where LaTeX’s automation fails.
Preventing hyphenation
Section titled “Preventing hyphenation”Sometimes, you may want to prevent LaTeX from hyphenating a particular word. There are a few ways:
- Declare it in the preamble using it in the
\hyphenationargument without any hyphenation points, such as\hyphenation{indivisible} - Wrap the word in an
\mboxcommand, which keeps the entire word together, like this:The following word is \mbox{indivisible}
Loading the hyphenat package gives us more control:
\usepackage[none]{hyphenat}disables hyphenation entirely\usepackage[htt]{hyphenat}enables hyphenation for typewriter text; otherwise, such monospaced words won’t be hyphenated by default, as it makes sense for URLs and code keywords
These optional arguments to \usepackage are called package options. They configure the behavior of a package. The mentioned options may be combined, separated by commas, like in \usepackage[htt,none]{hyphenat}. Even if you don’t use the none option, you can disable hyphenation for short pieces of text using the \nohyphens{text} command. Try out these features if you want to benefit from them. The package documentation at https://texdoc.org/pkg/hyphenat provides more information on additional features that you may need, such as hyphenation after special characters such as numerals and punctuation.
Improving the justification
Section titled “Improving the justification”Today’s most popular TeX compiler is pdfTeX, which outputs documents directly as a PDF. When Hàn Thế Thành developed pdfTeX, he added micro-typographic enhancements, subtle adjustments that improve the overall appearance. We can take advantage of these new features by using the microtype package.
Let’s improve our previous example using the microtype package:
- Insert the following line into the preamble of the previous example:
\usepackage{microtype}
- Click on Typeset and look at the output:

Figure 2.14 – A paragraph with better justification
Figure 2.14 – A paragraph with better justification
What happened? By simply loading the microtype package without any options, we activated its default features. It introduces font expansion to tweak the justification and uses hanging punctuation to improve the visual appearance of the margins. This may reduce the need for hyphenation and avoid getting awkward gaps between words to achieve full justification. You’ve seen its effect on a narrow column, so imagine the improvement on wide text—keep that in mind and try it out later!
Though microtype provides powerful features and options for the advanced typesetter, we usually won’t need to do more than just load it to benefit from it. There’s extensive package documentation if you want to study it in depth: run the texdoc microtype command at the command line or open it at https://texdoc.org/pkg/microtype. microtype does nice tweaking, but it’s not a cure-all; we should still take care of proper hyphenation when necessary.
Breaking lines manually
Section titled “Breaking lines manually”We can decide to end a line ourselves, overriding the automation. Now, we will learn about several commands with different effects for ending a line.
Let’s typeset the opening of the famous poem Annabel Lee by Edgar Allan Poe. Since the poet determined exactly where each line has to end, we’ll insert breaks manually.
So, let’s write up the beginning of the poem:
- Create a document containing these lines:
\documentclass{article}\begin{document}\noindent\emph{Annabel Lee}\\It was many and many a year ago,\\In a kingdom by the sea,\\That a maiden there lived whom you may know\\By the name of Annabel Lee\end{document}
- Click Typeset and review the output:

Figure 2.15 – Manually broken lines
Figure 2.15 – Manually broken lines
The very short \\ command ended the current line, and the following text was moved to the next line. However, it’s different from a paragraph break as we’re staying in the same paragraph. The \newline command is an alternative and has the same effect.
By default, LaTeX indents the first line in the paragraph, which is a useful convention for visually separating paragraphs. We used the \noindent command to suppress the paragraph indentation. You won’t need it often because, after headings, there’s no paragraph indentation by default. For removing paragraph indentation for the entire document, and using vertical inter-paragraph spacing instead, load the parskip package. You can see this in Figure 2.23 and the corresponding code.
Note that although we inserted line endings, the text remained a single paragraph. Therefore, our line breaks didn’t cause a paragraph indentation, as it’s logically still part of the same paragraph.
Exploring line-breaking options
Section titled “Exploring line-breaking options”The \\ command supports the following optional arguments for fine-tuning:
\\[value]inserts additional vertical space after the break with the requestedvalue, such as\\[3mm]\\*[value]does the same but prevents a page break from occurring immediately afterward
Try, for example, changing the opening of our poem example to the following:
\emph{Annabel Lee}\\[3mm]That inserts an additional 3 mm space between this line and the poem fragment, separating it as a heading.
There’s another command called \linebreak that tells LaTeX to end the line while maintaining full justification. If needed, LaTeX will stretch the space between words to reach the right margin. This could cause unpleasant gaps—that’s why that command is rarely used, or at least with an optional argument; \linebreak[number] can be used to tweak the line break. If the number is 0, a line break is allowed; 1 means it’s desired; 2 and 3 mark more insistent requests; and 4 will enforce it. The latter is the default behavior if no number is given.
Preventing line breaks
Section titled “Preventing line breaks”The \linebreak command has a direct opposite: \nolinebreak. This command prevents a line break at the current position.
Like its counterpart, it takes an optional argument to control the strength of the request. If you write \nolinebreak[0], you merely suggest not to break the line here. Using 1, 2, or even 3 insists more and \nolinebreak[4] strictly forbids it. LaTeX presumes the latter option if you don’t provide an argument.
The already-mentioned \mbox{text} command not only disables the hyphenation of a word, but you can also use it to prevent a line break within the enclosed text.
Instead of \nolinebreak, you can use the ~ shortcut, which stands for an inter-word space where no line break is allowed. For example, if you wrote Dr.~Watson, LaTeX would never let the title Dr. dangle lonely at the end of a line.
By default, LaTeX fully justifies the text, stretching lines to align with the right margin. LaTeX has an excellent method to adjust spacing for whole paragraphs, but sometimes it may result in undesirable big gaps between words on a justified line. Let’s see how to disable this if we want to.
Changing text alignment
Section titled “Changing text alignment”While your text will usually look well aligned if full justification is used, there may be occasions when it’s not ideal. For instance, full justification could be displeasing when text lines are short; in such a case, it could be sufficient to align only at the left side. Let’s see how to put this into practice, as well as how to right-align and create centered lines.
Creating ragged-right text
Section titled “Creating ragged-right text”Recall our first parbox example, where full justification led to noticeable gaps between words. This time, we’ll turn off right-margin justification to avoid such gaps:
- Create a new document with the following lines:
\documentclass{article}\begin{document}\parbox{3cm}{\raggedrightTUG is an acronym. It means \TeX\ Users Group.}\end{document}
- Click on Typeset and observe the result:

Figure 2.16 – Left-justified text
Figure 2.16 – Left-justified text
We inserted the \raggedright declaration. From this point onward, the text will be ragged-right. In other words, the text will be moved to the left margin—”flushed-left”—leaving the right edge uneven. There won’t be hyphenation.
Since we used this declaration inside a box, it only affects the contents within, like inside environments. After the box, the text will be fully justified again.
If you want the whole document to be ragged-right, you can use \raggedright in the preamble.
Creating ragged-left text
Section titled “Creating ragged-left text”In some cases, we may want to achieve the opposite effect: flushing the text to the right margin instead. We can do this similarly by inserting the \raggedleft declaration. You can control line breaks using the \\ shortcut.
Centering text
Section titled “Centering text”To align text horizontally in the center of the page, we can use the \centering declaration. Let’s do this with a few example lines.
We’ll manually create a nice-looking title for our document; it should contain the title, the author, and the date, all of which will be centered:
- Write a document containing this code:
\documentclass{article}\pagestyle{empty}\begin{document}{\centering\huge\bfseries Centered text \\\Large\normalfont written by me \\\normalsize\today}\end{document}
- Click Typeset to see the output:

Figure 2.17 – Centered text
Figure 2.17 – Centered text
Because only the title should be centered, we used a group to restrict the effect of the \centering declaration. All text within the group will be horizontally aligned to the center. We also inserted a paragraph break with an empty line; it’s recommended to do this before ending the group to apply our centering to the full paragraph. By using the closing brace, we ended the group. Any text placed after the closing brace will revert to the default alignment, not centered.
\centering is often used for pictures and tables, and on title pages.
Using environments for justification
Section titled “Using environments for justification”LaTeX provides the center environment that centers text and adds vertical space around it.
Let’s test it. We will reuse the excerpt of the Edgar Allan Poe poem again. This time, we’ll center all lines:
- Start a new document:
\documentclass{article}
- Now, load the
urlpackage so that we can also print a hyperlink at the end:\usepackage{url} - Start the document with an introductory line:
\begin{document}\noindent This is the beginning of a poemby Edgar Allan Poe:
- Now, write text in a
centerenvironment:\begin{center}\emph{Annabel Lee}\end{center} - Again, write text for the body of the poem:
\begin{center}It was many and many a year ago,\\In a kingdom by the sea,\\That a maiden there lived whom you may know\\By the name of Annabel Lee\end{center}
- Add some text, including a URL pointing to the poem on the internet, and finish:
The complete poem can be read on\url{http://www.online-literature.com/poe/576/}.\end{document}
- Click Typeset and see the result:

Figure 2.18 – A centered poem within text
Figure 2.18 – A centered poem within text
We began with \noindent again, avoiding the paragraph indentation. \begin{center} started the center environment, which begins a new paragraph, with added vertical spacing. \end{center} ended this environment. We used the center environment a second time, where we inserted \\ to end the verses. After the center environment ends, some space follows, and the next paragraph begins at the left margin.
The corresponding environment for ragged-right text is called flushleft; here, LaTeX pushes everything within the environment to the left and leaves the right side ragged, and, similarly, for ragged-left text, it’s the flushright environment.
Centering is a popular technique for emphasizing text. Another way is to indent it a bit and to add some vertical space before and after the text. It’s commonly used to display a quotation. Let’s see how to do that next.
Displaying quotations
Section titled “Displaying quotations”When including a quotation from another author, it might be hard to see that it’s a quote when it’s directly embedded within the text. A common and effective practice to improve readability is to visually set off the quotation by indenting it on both the left and right sides. Let’s illustrate this with quotes from famous physicists in the following example:
- Create a new document with some introductory text:
\documentclass{article}\begin{document}\noindent Niels Bohr said: \`\`An expert is a personwho has made all the mistakes that can be made ina very narrow field.''Albert Einstein said:
- Display the quotation using the
quoteenvironment:\begin{quote}Anyone who has never made a mistake has nevertried anything new.\end{quote} - Add a concluding sentence, and finish:
Errors are inevitable. So, let's be bravetrying something new.\end{document}
- Click Typeset to compile and view the result:

Figure 2.19 – Quotes
Figure 2.19 – Quotes
Firstly, we quoted inline, which is within the text flow of the paragraph. The ` shortcut produces a left quotation mark, also called a backtick, and the ' shortcut gives a right quotation mark. To get double quotes, we just typed two such characters. We call this inline quoting.
Then, we used the quote environment to display a quotation separated from the surrounding text. We did not begin a new paragraph for it, because the quotation is already set off in its own paragraph. That’s called displayed quoting.
Quoting longer text
Section titled “Quoting longer text”For short quotations, the quote environment works well. However, when you’re quoting a more extended text passage that spans multiple paragraphs, you may prefer to keep the default paragraph indentation like in your surrounding text. The quotation environment will do this for you.
Let’s quote a few benefits of using TeX and LaTeX, as described on a web page on CTAN:
- Start a new document with this text:
\documentclass{article}\usepackage{url}\begin{document}The authors of the CTAN team listed ten good reasonsfor using \TeX. Among them are:\begin{quotation}\TeX\ has the best output. What you end with,the symbols on the page, is as useable, and beautiful,as a non-professional can produce.\TeX\ knows typesetting. As those plain text samplesshow, TeX's has more sophisticated typographicalalgorithms such as those for making paragraphsand for hyphenating.\TeX\ is fast. On today's machines \TeX\ is very fast.It is easy on memory and disk space, too.\TeX\ is stable. It is in wide use, with a longhistory. It has been tested by millions of users,on demanding input.It will never eat your document. Never.\end{quotation}The original text can be found on\url{https://www.ctan.org/what_is_tex.html}.\end{document}
- Click Typeset and look at the output:

Figure 2.20 – A long section of quoted text
Figure 2.20 – A long section of quoted text
This time, we used the quotation environment to display multiple paragraphs. Like in regular text, blank lines separate the paragraphs; they are left-indented at their beginning just like in all our body text.
But what if we prefer not to use that paragraph indentation? Let’s check out an alternative.
In this example, we’ll avoid paragraph indentation and instead separate the paragraphs with some vertical spacing. As filler text, we will use a few sentences of the previous example about quoting, as follows:
- Create a small document with the following code:
\documentclass{article}\usepackage{parskip}\usepackage{url}\begin{document}The authors of the CTAN team listed ten good reasonsfor using \TeX. Among them are:\TeX\ has the best output. What you end with,the symbols on the page, is as useable, and beautiful,as a non-professional can produce\ldotsThe original text can be found on\url{https://www.ctan.org/what_is_tex.html}.\end{document}
- Click Typeset and see the effect:

Figure 2.21 – Vertical spacing between paragraphs
Figure 2.21 – Vertical spacing between paragraphs
Here, we loaded the parskip package to remove the paragraph indentation completely. Instead, this package adds vertical space between paragraphs. However, this package doesn’t alter the behavior of the quotation environment; you can still use the quote environment.
There are two common ways to distinguish paragraphs. One is to indent the first line of each paragraph, which is LaTeX’s default behavior. The other is to insert vertical space between paragraphs without indentation. This is often preferred for narrow columns, where indenting would occupy valuable space.
So far, we’ve practiced using many predefined physical commands to customize text and paragraphs. The next step is to create our own logical formatting commands, and use those within the document body text instead.
Creating commands
Section titled “Creating commands”If you find yourself using the same term repeatedly in your document, it can get tedious to type it out each time. What if you later decide to change that term or its formatting? To avoid searching for and replacing the term in the entire document, LaTeX allows you to define your own custom commands in your preamble. That saves time and ensures consistency.
Remember: A command that’s made up of other commands or text is called a macro, and that’s what we’ll define now. Basically, we choose a new macro name and define the sequence of text or commands to be used in that macro. Then, any time we want to reuse that content or formatting, we just need to call the macro by its name.
We’ll begin with basic macros that work like abbreviations.
Using macros for simple text
Section titled “Using macros for simple text”Macros are great for avoiding repeating long words or phrases and can also act as placeholders, such as for person or company names or anything that can change in a different context. We can modify the macro’s content to update the entire document with a different version of that phrase.
In the following example, we’ll define a short command to represent the name of the TeX Users Group (TUG):
- Enter the following code into a new document:
\documentclass{article}\newcommand{\TUG}{\TeX\ Users Group}\begin{document}\section{The \TUG}The \TUG\ is an organization for people who use\TeX\ or \LaTeX.\end{document}
- Click Typeset and look at the result:

Figure 2.22 – Using our first macro
Figure 2.22 – Using our first macro
We called \newcommand in the highlighted line to define our command. The first argument is the command’s name we’ve chosen, and the second argument is the text it should expand to whenever we use that command in the document.
Now, every time we write \TUG in our document, LaTeX will print the complete name TeX Users Group. If we later decide to change the name or its formatting, we just need to change this \newcommand line. Then, the change of that macro will be applied to the entire document.
You may use formatting commands inside your command definition. Let’s say you would like to change the formatting of all occurrences of this name to be typeset in small caps; just change the definition to the following:
\newcommand{\TUG}{\textsc{TeX Users Group}}Notice that we’ve used the \TeX command. This abbreviation command just prints out the name of the typesetting system, formatted in the same way as its logo. The built-in \LaTeX command works similarly.
Note that we used a backslash after \TeX. The following space itself would just separate the command from the following text; it wouldn’t produce a space in the output. Using the backslash followed by a space forces the output of a space that would otherwise be ignored. That also applies to the command we just created.
Now we will see how to avoid that manual spacing.
Improving spacing after commands
Section titled “Improving spacing after commands”It’s easy to forget the extra backslash needed to insert a space after a macro. Can we automate that? Tasks such as this, which aren’t handled directly by LaTeX, can often be solved by using packages, which are collections of styles and commands.
In this case, we will use the xspace package; its only purpose is to adjust the spacing after a macro output automatically:
- Insert this line into your preamble, before
\begin{document}:\usepackage{xspace} - Add the
\xspacecommand to the end of your macro definition:\newcommand{\TUG}{\TeX\ Users Group\xspace}
The \usepackage{xspace} line tells LaTeX to load the xspace package and to import its definitions. After \usepackage, we can use all commands contained in that package.
This package provides the \xspace command, which inserts a space depending on what the following character is:
- If a normal letter follows, then it will insert a space after the macro content
- If punctuation such as a dot, a comma, an exclamation mark, or a quotation mark follows, it won’t insert a space
This simple automated solution works well in normal text; it always inserts a space if a letter follows and skips it when it detects punctuation. In a rare case that it’s followed by something else, such as a macro that xspace cannot interpret, and inserts a space, you can prevent that by adding {} right after the \xspace command. The package manual explains it clearly; you can find it at https://texdoc.org/pkg/xspace.
Creating flexible commands with arguments
Section titled “Creating flexible commands with arguments”Suppose your document contains a lot of keywords that you want to be displayed in bold. If you use the \textbf command every time, what will happen if you later decide to use an italic shape instead, or a typewriter font? You’d have to update that formatting for every instance of that keyword, which is tedious and error-prone.
There’s a better way: define a custom macro that uses \textbf internally.
Defining a macro with arguments
Section titled “Defining a macro with arguments”In this section, we’ll use \newcommand again, but this time, we’ll give it an argument that shall contain our keyword. For our example, we’ll apply it to some terms that we learned about earlier in this chapter.
Let’s get started:
- Enter the following code in your editor. Our command will be called
\keyword:\documentclass{article}\newcommand{\keyword}[1]{\textbf{#1}}\begin{document}\keyword{Grouping} by curly braces limits the\keyword{scope} of \keyword{declarations}.\end{document} - Click Typeset and observe how the keywords appear in the output:
Figure 2.23 – Formatting keywords
Let’s look at the \newcommand line in the code. The number 1 in the square brackets marks the number of arguments that we want to use in the command. #1 is a placeholder and will be replaced by the value of the first argument; #2 would be replaced by the value of the second argument, and so on. Now, if you decide to change the appearance of all keywords to be italics instead, just modify the definition of \keyword to use \textit{#1}, and the change will be global.
The first time we used \newcommand, in the Using macros for simple text section, we used it with two arguments: the macro name and its definition. In the previous example, there were three arguments; the additional argument is enclosed in square brackets, which indicates that it is an optional argument, so that it may be provided or omitted. If omitted, it would have a default value.
Previously, we’ve already worked with the \documentclass command and optional arguments, but how can we define a command with optional arguments ourselves? Let’s find out.
Defining a macro with optional arguments
Section titled “Defining a macro with optional arguments”Let’s revisit \newcommand, but this time we’ll give it an optional formatting argument along with a mandatory keyword argument:
- Update the previous example to the following code:
\documentclass{article}\newcommand{\keyword}[2][\bfseries]{{#1#2}}\begin{document}\keyword{Grouping} by curly braces limits the\keyword{scope} of \keyword[\itshape]{declarations}.\end{document}
- Click on Typeset and check out the result:
Figure 2.24 – Optional arguments
Let’s look again at the \newcommand line in the code. By using [\bfseries] in square brackets, we introduced an optional parameter; we refer to it by #1, and its default value is set to \bfseries. Since we used a declaration this time, we added a pair of braces to ensure that only the keyword is affected by the declaration. Later in the document, we passed [\itshape] to the \keyword command, changing the default formatting to italics.
Here’s the general form of \newcommand:
\newcommand{command}[arguments][optional]{definition}These are the meanings of the parameters to \newcommand:
command: The new command’s name, starting with a backslash followed by lowercase and/or uppercase letters, or a backslash followed by a single non-letter symbol. The name must not be already defined and is not allowed to begin with\end.arguments: A number from 1 to 9 that tells LaTeX how many arguments the new command accepts. If omitted, the command takes no arguments.optional: If present, the first of the arguments would be optional with a default value given here. Otherwise, all arguments are mandatory.definition: Every occurrence ofcommandwill be replaced bydefinitionand every occurrence of the form#nwill then be replaced by the nth argument.
Use \newcommand to define reusable styles for keywords, code snippets, web addresses, names, notes, information boxes, or differently emphasized text. That’s how we achieved the consistent structure of this book, by defining and using styles. We should use font commands within our macro definitions rather than scattering them throughout the document body text.
Whenever possible, define your own macros to achieve a logical structure. You’ll benefit from consistent formatting, easier global changes, and more maintainable code. By defining and using macros, you can ensure that the formatting remains consistent throughout your entire document.
Redefining commands
Section titled “Redefining commands”You can change existing LaTeX macros using \renewcommand in a very similar way:
\renewcommand{command}[arguments][optional]{definition}You may rarely need it as a beginner, though it’s a common way to change, for example, LaTeX’s default values. Here are some examples you may encounter later:
\renewcommand{\familydefault}{\sfdefault}makes the default font family the default sans-serif family, so that it is not a serif font by default anymore.\renewcommand{\arraystretch}{1.5}stretches the default row height in tables by a factor of 1.5.\renewcommand{\thepage}{\Roman{page}}switches the page number display to uppercase Roman numbers.\romanwould mean lowercase.
This command is particularly useful if you want to customize an existing macro or command.
Creating environments
Section titled “Creating environments”Just like \newcommand lets us define new commands, LaTeX has a command for defining blocks of content: \newenvironment. This is useful when we want to mark up larger sections of text, such as notes, boxes, examples, or other repeated layout patterns, with consistent formatting and structure.
Let’s immediately jump to the general form:
\newenvironment{name}[arguments][optional]{begin-code}{end-code}These are the meanings of the parameters to \newenvironment:
name: The environment’s name, used later as\begin{name}and\end{name}.arguments: An optional number from 1 to 9 indicating how many arguments the environment accepts;0by default when omitted.optional: If given, this assigns a default value to the first optional argument.begin-code: LaTeX will execute this code at the start of the environment. Use#1,#2, and so on to refer to the arguments.end-code: LaTeX runs this code when the environment ends.
For a very thorough specification of this and all macro definition commands, please refer to the reference at https://latex2e.org/Definitions.html.
Here’s an example to illustrate it in practice:
\documentclass{article}\newenvironment{note}[1][Note] {\begin{quote}\textbf{#1}\itshape} {\end{quote}}\begin{document}\begin{note}[Hint] Use high-contrast colors for readability.\end{note}\end{document}This code does the following:
- It defines a
noteenvironment that takes an optional argument. - It is based on the
quoteenvironment. - If no argument is given, it prints Note at the beginning. Otherwise, it starts with the optional argument, such as Hint here.
- It continues with italic font for the remaining text in the environment.
Similar to \renewcommand, you can use \renewenvironment with exactly the same syntax to redefine an existing environment. That’s something you’ll rarely need, and you can also find it at https://latex2e.org, so we’ll wrap it up at this.
Using an alternative syntax
Section titled “Using an alternative syntax”LaTeX now provides additional ways to define commands and environments. You can continue to use the classic commands from the previous sections and skip this section for now. If you want, let’s take a quick look at the newer approach. You can now define commands in this way:
\NewDocumentCommand{<command name>}{<argument types>}{code}Argument types can be m for a mandatory argument, a lowercase o for an optional argument, or a capital O{text} for an optional argument with default text when the argument is omitted. But let’s see how it looks in practice.
The definition for the macro in Figure 2.22 would now be as follows:
\NewDocumentCommand{\TUG}{}{\TeX\ Users Group}In the macro for Figure 2.23, we had one mandatory argument. It translates to the following:
\NewDocumentCommand{\keyword}{m}{\textbf{#1}}For Figure 2.24, we added an optional argument with a default value. The same macro can also be written like this:
\NewDocumentCommand{\keyword}{O{\bfseries}m}{{#1#2}}If you’re curious about how the o option can be used to achieve the same, it looks as follows:
\NewDocumentCommand{\keyword}{om}{{% \IfNoValueTF{#1}% {\bfseries#2}% {#1#2}%}}Here, we used this command to handle both cases—when the optional argument is given and when it’s not:
\IfNoValueTF{#1}% {Do stuff with argument #2 only}% {Do stuff with arguments #1 and #2}%Note that I used the percent sign (%) at the end of lines to avoid accidentally introducing white space, since line breaks are treated as spaces. That’s why I commented out the line breaks.
TF stands for true and false. There are also shorter variants for single cases. To just cover the case that no argument #1 was given (frue), the following is used:
\IfNoValueT{#1}{Do stuff with argument #2 only}%If an argument #1 was given (false), the following is used:
\IfNoValueF{#1}{Do stuff with arguments #1 and #2}%It might look a bit complex at first, but this system gives you much more flexibility. You can even define multiple optional arguments. For example, here’s a more advanced definition with five mandatory and three optional ones:
\NewDocumentCommand{\name}{ m m m m m O{#3} O{#4} O{#5} }{ ... }You see that you can have spaces between the specifiers for clarity, and you can use #n for a default value with a given nth argument. There are more argument types, and you can add delimiters for arguments, and you even have more similar commands, such as \RenewDocumentCommand, \NewDocumentEnvironment, and \RenewDocumentEnvironment, as replacements for the respective commands in the previous sections.
If you consider taking this new approach, have a look at these links:
- https://www.texdev.net/2010/05/23/from-newcommand-to-newdocumentcommand/ – a blog article by LaTeX developer Joseph Wright with clear examples
- https://texdoc.org/pkg/xparse – the complete documentation
- https://www.latex-project.org/publications/2021-JAW-TUB-tb130wright-newdoccmd.pdf – a detailed comparison with other syntaxes and packages, for advanced users
Why might you want to use this approach?
- The LaTeX project team recommends it
- While it’s easy to use for simple cases, you can define more complex macros
- Most importantly, in contrast to
\newcommand, your new macros are robust, also referred to as protected; they aren’t expanded to their definition immediately when LaTeX processes your code, but at a later stage
So, for example, if you use such a macro in a section title, the macro name would be written into the .toc (table of contents) file, while a \newcommand defined macro would be expanded immediately and its expanded content would go into the .toc file. Or, let’s just say, robust commands often save you from subtle issues. It’s a rather advanced topic; you may read about it at https://texfaq.org/FAQ-protect.
Personally, I’m fine with the original \newcommand and its companions, but I want you to know about the modern alternatives you will also see in newer LaTeX code on the internet.
Summary
Section titled “Summary”In this chapter, we explored the fundamentals of editing, arranging, and formatting text. Specifically, we covered modifying fonts and styles, using commands and declarations with mandatory and optional arguments, and defining custom commands and environments. We also learned how to format paragraphs with different alignments, such as left, right, or fully justified, and how to include quotations.
Keep in mind that even though we used formatting commands directly in the text for practicing, it’s better to use them in command definitions in the preamble to have styles consistently across a document. As we progress through this book, you’ll discover further useful commands and packages to refine and extend your formatting setup.
Now that you’ve mastered detailed text formatting, you’re ready to move on to the next chapter, which focuses on the formatting and layout of entire pages, including margins, headers, and footers.