- Document Structure and Sections
- Text Formatting
- Math Expression
- Creating Tables
- Including Images and Figures
- List Environments
- Footnotes
- Customizing Document Layout
- Code Snippet
- Setting PDF Metadata
- Managing Sources and Citations with Zotero
- Miscellaneous
- Managing Complex LaTeX Projects with Multiple Files
A LaTeX document typically starts with a document class declaration, followed by the inclusion of packages, and then the document content within \begin{document}
and \end{document}
:
\documentclass{article}
\usepackage{package_name} % Add required packages
\begin{document}
% Document content goes here
\end{document}
-
Section: Use
\section{Section Title}
to create a new section. Sections are numbered automatically. -
Subsection: Use
\subsection{Subsection Title}
within a section to create a subsection. -
Subsubsection: Use
\subsubsection{Subsubsection Title}
within a subsection for more detailed division. -
Unnumbered Sections: Add an asterisk (*) to create an unnumbered section or subsection, like
\section*{Title}
. The section also won't be visible in the table of content
Example:
\section{Introduction}
This is the introduction text.
\subsection{Background}
Details about the background.
\subsubsection{Detailed Topic}
More specific details.
\section*{Acknowledgments}
Unnumbered section for acknowledgments.
- Automatically generate a table of contents based on sections and subsections using
\tableofcontents
.
Example:
\tableofcontents
\section{Introduction}
...
To create a clickable Table of Contents in LaTeX, use the hyperref
package. Simply add \usepackage{hyperref}
to your document's preamble, and then use \tableofcontents
where you want the ToC to appear. The hyperref
package automatically turns all entries in the ToC into clickable links.
- Italic:
\textit{text}
- Bold:
\textbf{text}
- Underline:
\underline{text}
- Double Underline: Use
\underline{\underline{text}}
or define a new command in the preamble with\def\doubleunderline#1{\underline{\underline{#1}}}
and then use\doubleunderline{text}
LaTeX reserves several characters for formatting and commands, which cannot be used directly in the text. Here's how to include these special characters in your document:
- Backslash
\
: Use\textbackslash
for backslash, as it is used to start commands. - Tilde
~
: Use\textasciitilde
or\~{}
for a tilde, often used for non-breaking spaces. - Dollar
$
: Use\$
for dollar signs, as$
is used for entering math mode. - Percent
%
: Use\%
for percent signs, as%
is used for comments. - Ampersand
&
: Use\&
for ampersands, as&
is used for tabular alignment. - Underscore
_
: Use\_
for underscores, as_
is used for subscripts in math mode. - Hash
#
: Use\#
for hash symbols, as#
is used for macro parameters. - Curly Braces
{}
: Use\{
and\}
for curly braces, as{}
are used for grouping. - Caret
^
: Use\textasciicircum
or\^{}
for caret symbols, as^
is used for superscripts in math mode. - Pipe
|
: Use\textbar
for pipe symbols, as|
can be used in tabular and math environments.
Example usage in a LaTeX document:
This is a special character example: \% \$ \& \# \{ \} \_ \textasciitilde \textasciicircum \textbar
-
Paragraphs: Start a new paragraph by leaving an empty line in the LaTeX code. Avoid using
\\
for breaking paragraphs.-
Incorrect method:
This is my first paragraph. \\ This is my second paragraph.
-
Correct method:
This is my first paragraph. This is my second paragraph.
In this correct method, the second paragraph will start with an indent. If you prefer to not have this indent, you can use the
parskip
package.
-
-
Removing Indentation: To remove the indentation at the beginning of paragraphs and add a bit of vertical space between paragraphs, include
\usepackage{parskip}
in your document's preamble. -
Line Breaks: Use
\\
or\newline
for a new line within the same paragraph when necessary, though it's generally best to let LaTeX handle line breaks automatically.
Coloring in LaTeX can enhance the visual appeal and clarity of your document. This can be achieved using the xcolor
package, which provides a wide range of color options and functionalities.
First, include the xcolor
package in your document's preamble:
\usepackage{xcolor}
You can specify options when loading xcolor
to access more color models or predefined colors, like so:
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
To change the color of text:
\textcolor{color_name}{text}
For example:
\textcolor{blue}{This text will be blue.}
\textcolor{red}{This text will be red.}
You can define your own colors:
\definecolor{mycolor}{RGB}{0,123,255} % RGB model
\definecolor{anothercolor}{HTML}{00FF00} % HTML color codes
And use them like this:
\textcolor{mycolor}{Custom colored text.}
To set the background color of a text block:
\colorbox{color_name}{text}
For a frame around the text with a background color:
\fcolorbox{frame_color}{background_color}{text}
-
Paragraphs: You can apply color to entire paragraphs or larger text blocks using the
\color
command at the beginning of the paragraph. -
Custom Environments: Combine color commands with custom environments to colorize specific sections or elements consistently.
-
Math Mode: Colors can also be applied within math mode to highlight equations or parts of equations.
In LaTeX, you have the flexibility to adjust the text size and spacing to meet your specific formatting needs. This section covers how to change the text size and control vertical spacing.
LaTeX provides several commands for adjusting the text size. These commands affect the text size within their scope (enclosed within curly braces {}
or within a LaTeX group/environment).
Here are the most common text size commands, listed from smallest to largest (The font size in pt is only approximately and based on the default article
class):
\tiny % 5pt
\scriptsize % 7pt
\footnotesize % 8pt
\small % 9pt
\normalsize % 10pt
\large % 12pt
\Large % 14.4pt
\LARGE % 17.28pt
\huge % 20.74pt
\Huge % 24.88pt
Example of usage:
This is {\small small text} and this is {\Large large text}.
For more specific text size requirements, you can use the \fontsize{size}{baselineskip}
command, followed by \selectfont
.
Example:
\fontsize{12pt}{14pt}\selectfont
Vertical spacing can be controlled using commands like \vspace
and \vfill
.
\vspace{length}
: Adds vertical space of the specified length. Can be negative.\vfill
: Adds a variable amount of vertical space that expands as much as possible.
Example:
Text before space.
\vspace{10mm}
Text after space.
To adjust the line spacing for a portion of the document, use the setspace
package and its commands:
\usepackage{setspace}
\singlespacing % Single line spacing
\onehalfspacing % One and a half line spacing
\doublespacing % Double line spacing
For a specific section:
\begin{spacing}{2.5}
Your text here.
\end{spacing}
- Customizing Paragraph Indent: Use
\setlength{\parindent}{length}
to set the paragraph indent. - Customizing Paragraph Skip: Use
\setlength{\parskip}{length}
to set the space between paragraphs.
Example:
\setlength{\parindent}{0em}
\setlength{\parskip}{1em}
- Centered Math: Use
\[ ... \]
for equations that you want to appear centered on a new line. - Inline Math: Use
\( ... \)
for equations that appear inline with the text.
Example:
Here is an inline equation \( x^2 + y^2 = z^2 \) and here is a centered equation:
\[ E = mc^2 \]
In LaTeX, it's recommended to use \(...\)
for inline math and \[...\]
for display math instead of $...$
and $$...$$
because:
\(...\)
and\[...\]
ensure proper spacing and formatting.- They are compatible with the
amsmath
package, which is widely used for advanced math typesetting. $...$
and$$...$$
can cause issues in formatting and are not recommended in LaTeX, though they are originally from plain TeX.
- Use different environments for matrices, depending on the brackets you want:
\begin{bmatrix} % for square brackets []
1 & 2 \\
3 & 4
\end{bmatrix}
\begin{pmatrix} % for parentheses ()
1 & 2 \\
3 & 4
\end{pmatrix}
Other types:
matrix
: without brackets.Bmatrix
:{}
curly brackets.vmatrix
:| |
single vertical lines.Vmatrix
:|| ||
double vertical lines.
Here's a section about creating tables in LaTeX that you can add to your Markdown instruction:
-
Begin with the
table
Environment:- Use for floating placement, captions, and labels.
- Placement specifiers:
htbp
(here, top, bottom, page of floats). - Example:
\begin{table}[htbp] ... \end{table}
-
Use the
tabular
Environment Withintable
:- Define table format and structure.
- Specify columns and alignments (
l
= left,c
= center,r
= right). - Separate rows with
\\
and columns with&
. - Add horizontal lines with
\hline
.
-
table
Environment Specifiers:h
: Place the table approximately at the same point it occurs in the text.t
: Position the table at the top of a page.b
: Place the table at the bottom of a page.p
: Place the table on a separate page of floats.!
: Override internal parameters for float placement.
-
tabular
Environment Specifiers:l
,c
,r
: Align columns left, center, or right.p{width}
,m{width}
,b{width}
: Paragraph columns with specified width and vertical alignment.|
: Add vertical lines between columns.
\begin{table}[htbp]
\centering
\begin{tabular}{lcr}
\hline
Left & Center & Right \\
\hline
Text1 & Text2 & Text3 \\
Text4 & Text5 & Text6 \\
\hline
\end{tabular}
\caption{Example of a simple table}
\label{table:example}
\end{table}
- Column Separators: Use
|
for vertical lines between columns. - Row Spacing: Adjusstomize using
@{...}
. - Enhanced Lines: For professional tables, use
\toprule
,\midrule
,\bottomrule
from thebooktabs
package.
- It's often best to keep tables as simple and uncluttered as possible.
- For complex tables, consider using pat with
\vspace{...}
. - Column Spacing: Cuckages like
booktabs
for better visual quality. - Remember that large tables may need to be scaled or adjusted to fit the page width.
Use the \ref
command within the text:
... as shown in Figure \ref{fig:that-figure}.
- Use the
figure
environment with placement specifiers. Only use specifiers if necessary; otherwise, LaTeX's default placement is often sufficient.
\begin{figure}[htbp] % h: here, t: top, b: bottom, p: separate page, !: force location.
\centering
\includegraphics[width=0.5\textwidth]{path/to/your/image.png}
\caption{Meaningful description}
\label{fig:that-figure}
\end{figure}
- Reference the figure in your text as shown above.
- Specify relative or absolute path if the figure is not in the same directory:
\includegraphics{../Images/your_image.png}
- Use
\graphicspath
in the preamble (globally) for multiple directories:
\graphicspath{{./images/}{./photos/}}
LaTeX provides various list environments which can be customized to fit different needs. Here are the common list types and ways to customize them:
- Basic Usage:
\begin{itemize} \item First item \item Second item \end{itemize}
- Changing Bullet Styles:
Customize bullet points by redefining
\labelitemi
(first level),\labelitemii
(second level), etc.\renewcommand{\labelitemi}{$\star$} \renewcommand{\labelitemii}{$\cdot$}
- Basic Usage:
\begin{enumerate} \item First item \item Second item \end{enumerate}
- Changing Numbering Style:
Redefine
\labelenumi
,\labelenumii
, etc., for different levels.\renewcommand{\labelenumi}{\Roman{enumi}.} \renewcommand{\labelenumii}{(\alph{enumii})}
- Basic Usage:
\begin{description} \item[Term] Definition of the term. \item[Concept] Explanation of the concept. \end{description}
- Adjust spacing between items and paragraphs in lists using
\itemsep
and\parsep
.\begin{itemize} \setlength{\itemsep}{5pt} \setlength{\parsep}{3pt} \item Item 1 \item Item 2 \end{itemize}
- Lists can be nested within each other for more complex structures.
\begin{enumerate} \item First item \begin{itemize} \item Nested item \item Another nested item \end{itemize} \item Second item \end{enumerate}
- Adding a footnote:
This is some text with a footnote.\footnote{This is the footnote text.}
- Changing margins and customizing header/footer:
\usepackage[margin=2.1cm]{geometry} % Change margins
\usepackage{fancyhdr} % Customize header and footer
\pagestyle{fancy}
\fancyhead[L]{Left Header}
\fancyhead[C]{Center Header}
\fancyhead[R]{Right Header}
\fancyfoot[L]{Left Footer}
\fancyfoot[C]{Center Footer}
\fancyfoot[R]{Page \thepage}
If you're tired of Latex's default font, you can change it with the fontspec
package.
Define a new font with \setmainfont{Calibri}
If you're on Linux and want to use a MS office font, you can download the fonts somewhere on github and copy them to /usr/share/fonts
you can create a new folder inside /fonts
e.g. sudo mkdir /usr/share/fonts/win
- Import the package:
\usepackage{listings}
- Example for Java code:
\begin{lstlisting}[language=Java, caption=Java Example]
// This is a comment
public class HelloWorld {
public static void main(String[] args) {
// Prints Hello, World!
System.out.println("Hello, World!");
}
}
\end{lstlisting}
- Create custom syntax highlighting with
\lstdefinestyle{name}
and use it with\lstset{style=name}
.
In LaTeX, you can use the \hypersetup
command from the hyperref
package to set metadata for the compiled PDF file. This metadata includes the title, author, subject, and other properties that can be viewed in PDF readers, which helps in organizing and finding documents, especially in digital libraries or personal archives.
First, ensure that the hyperref
package is included in your preamble:
\usepackage{hyperref}
Then, use the \hypersetup
command to set your PDF metadata:
\hypersetup{
pdftitle={Your Document Title},
pdfauthor={Your Name},
pdfsubject={The Subject of Your Document},
pdfkeywords={Keyword1, Keyword2, Keyword3},
% other settings like colorlinks, linkcolor, etc.
}
- Install Zotero: Download and install.
- Install Better BibTeX (BBT): Add-on for Zotero. Automates BibTeX export. Installation guide.
- Auto-Export with BBT: Set up BBT to auto-export your Zotero library to a
.bib
file. Configure this in Zotero's BBT settings.
- Bib File: Place
.bib
file in LaTeX project directory. - Bibliography Command: Add
\bibliography{filename}
to your LaTeX file (replacefilename
with your.bib
file name, without extension). - Bibliography Style: Define style with
\bibliographystyle{stylename}
(e.g.,plain
,IEEEtran
).
- Cite Command: Use
\cite{key}
in the document, wherekey
is the citation key from the.bib
file.
\documentclass{article}
\usepackage{hyperref}
\begin{document}
\section{Introduction}
As discussed in \cite{Smith2020}, the results...
% (normally) at the end of the document insert:
\bibliographystyle{IEEEtran}
\bibliography{myreferences} % Assumes a file named 'myreferences.bib'
\end{document}
- Compile Sequence: Run LaTeX, BibTeX, LaTeX, and LaTeX again to process citations and update the bibliography.
LaTeX is very weird at first, because on one hand it feels like a programming language where indentation should be mandatory, but on the other hand it kinda isn't. Here I have some (opinionated) suggestions to make indentation in your LaTeX sources consistent.
-
Use an indentation of 2 spaces. This is because you can get many nested expressions. You could go with 4, but keep in mind that you will need a wider screen.
-
Indent only
\begin{...} \end{...}
blocks and open parenthesis()
brackets[]
or braces{}
. Example:\begin{table} \begin{tabular}{l l} \toprule % ... \end{tabular} \caption{ A decently indented table. \label{tab:another-table} } \end{table}
Another example for maths:
\[ % yes these count as brackets y = \bar{y} \pm \sigma_y \approx f(\bar{\vec{x}}) \pm \sqrt{\sum_{i=1}^m \left( % and these as well \partial_{x_i} f(\bar{\vec{x}}) \sigma_{x_i} \right)^2} \]
-
The only exception is
\begin{document}
and\end{document}
, which should not be indented. This is the only exception. The reasoning behind this is that (unless you use\include
) everything will be be indented which is not very useful. -
Section headings etc. do not cause indentation. You should think of these macros as just putting there the title, not as a block.
\section[VHSIC Hardware Description Language (VHDL)]{ VHDL: Very high-speed integrated circuits program Hardware Description Language } \subsection{Basic syntax and identifiers} In VHDL an identifier is a case insensitive string composed of \texttt{A-Z a-z 0-9 \_} that \begin{itemize} \item is not a keyword, \item does not start with a number or \texttt{\_}, \item does not have two or more \texttt{\_} in a row. \end{itemize}
-
Align tables to the
&
, if the content is short. For example\begin{table} \centering \begin{tabularx}{\linewidth}{>{\ttfamily}c l X} \toprule \textrm{Value} & Meaning & Usage \\ \midrule U & Uninitialized & In the simulator \\ X & Undefined & Simulator sees a bus conflict \\ 0 & Force to 0 & Low state of outputs \\ 1 & Force to 1 & High state of outputs \\ Z & High Impedance & Three state ports \\ W & Weak Unknown & Simulator sees weak a bus conflict \\ L & Weak Low & Open source outputs with pull-down resistor \\ H & Weak High & Open drain output with pull-up resistor \\ - & Don't care & Allow minimization \\ \bottomrule \end{tabularx} \caption{ Possible values for \vhdl{std_logic} signals. \label{tab:std-logic-1164-types} } \end{table}
If you're currently using pdfLaTeX, consider switching to XeLaTeX or LuaLaTeX. These modern compilers provide several advantages, including:
-
Advanced Font Handling: Easily use any font on your computer (with the
fontspec
package), including OpenType and TrueType, unlike the limited font options in pdfLaTeX. -
Robust Unicode Support: Ideal for multilingual documents and special characters, offering seamless support for Unicode, a feature where pdfLaTeX often falls short.
-
Modern Features and Flexibility: LuaLaTeX integrates Lua scripting for advanced programmable capabilities within your documents.
-
Enhanced Micro-typography: LuaLaTeX enhances the appearance and readability of your document with advanced typesetting features.
-
Reduced Package Conflicts: Both compilers are aligned with current LaTeX development, ensuring better compatibility with new packages and fewer conflicts.
When working on large LaTeX projects, such as a thesis or a book, it's beneficial to split the content into multiple files for better organization and manageability. Here's a guide to setting up a structured folder system for such projects:
A well-organized folder structure is crucial for managing complex documents. Here's an example of an effective structure:
myproject/
│
├── main.tex # Main document file
│
├── chapters/ # Folder for chapter files
│ ├── chapter1.tex
│ ├── chapter2.tex
│ └── ...
│
├── images/ # Folder for images
│ ├── img1.png
│ ├── img2.jpg
│ └── ...
│
├── styles/ # Folder for custom style files
│ ├── mystyle.sty
│ └── ...
│
├── bib/ # Folder for bibliography files
│ ├── references.bib
│ └── ...
│
└── appendices/ # Folder for appendices
├── appendixA.tex
└── ...
The main.tex
file serves as the root document that integrates all other parts. Use \input
or \include
commands to add chapters and appendices.
Example:
\documentclass{book}
\usepackage{...} % Import necessary packages
% Document settings go here
\begin{document}
\tableofcontents
\include{chapters/chapter1}
\include{chapters/chapter2}
% Include other chapters as needed
\appendix
\include{appendices/appendixA}
% Include other appendices as needed
\bibliographystyle{plain}
\bibliography{bib/references}
\end{document}
In LaTeX, the commands \input
and \include
are used to incorporate external files into a main document, but they serve different purposes and have distinct behaviors that suit particular use cases. The \input{file}
command is like a text copy-paste operation; it takes the content of file.tex
and inserts it at the point where the command is used, with no added spacing or new pages. It is ideal for pulling in sections of text, preambles, or LaTeX configurations, allowing for modular document organization without affecting the document's flow.
On the other hand, \include{file}
is more suitable for adding whole chapters or sections that should begin on new pages in larger documents such as books or theses. This command inserts the content of file.tex
starting on a new page, and importantly, it can be used with the \includeonly{}
command. This feature can be leveraged during the drafting phase to compile only specific sections of the document, thereby speeding up the compilation process—a particularly handy tool when working with lengthy texts.
One must note that \include
cannot be nested, and it automatically adds a page break, which would be undesirable for smaller inclusions like figures, tables, or code snippets. In summary, use \input
for seamless, continuous inclusions, and reserve \include
for structuring larger documents into separately compiled units, each beginning on a new page.
- Consistency: Maintain consistent formatting across all files.
- Modularity: Keep each chapter or section in its own file for easy editing and organization.
- Version Control: Use a version control system like Git to manage changes, especially when collaborating.
- Regular Backups: Regularly backup your project folder.
- Compilation: Compile the
main.tex
file, not the individual chapter files. - Relative Paths: Use relative paths for including files and images.
- Comments and Documentation: Comment your code for clarity, especially when working in teams.
With a multi-file structure, compilation remains straightforward. Compile main.tex
, and LaTeX will automatically include the other files as specified.