LaTeX frequent snippets

Basic elements

Section numbering

Alphabetical numbering:

\renewcommand{\thesection}{\Alph{section}}
\setcounter{section}{0} % reset counter to start from A

Math

Matrix:

\begin{bmatrix}
    x_{11} & x_{12} & x_{13} & \dots & x_{1n} \\
    x_{21} & x_{22} & x_{23} & \dots & x_{2n} \\
    x_{d1} & x_{d2} & x_{d3} & \dots & x_{dn} \\
\end{bmatrix}

Matrix bolding:

\mathbf

Transpose:

^\top

x^,x~,x\hat x, \tilde x, \overline x:

\hat x, \tilde x, \overline x

Argmin with centered subscript:

\underset{\Theta_p, \Theta_s, \Theta_a}{\operatorname{argmin}}

Additional symbols:

List of LaTeX mathematical symbols - OeisWiki

Listing

\begin{itemize}
    \item 
\end{itemize}
\begin{enumerate}
    \item 
\end{enumerate}

Algorithm

\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{algorithm}
\caption{Functional Map Refinement}
\label{alg:fmap_refinement}
\begin{algorithmic}[1]
    \State Set $C_\text{refined} \gets C_{\mathcal Y\mathcal X}$
    \For{$t = 1, \ldots, n_\text{iter}$}
        \State ...
        \State ...
        \State ...
    \EndFor
    \State ...
    \State \Return $\Pi_\text{refined}$
\end{algorithmic}
\end{algorithm}

Table

\begin{table}[h]
	\centering
	\caption{<>}
	\label{tab:<>}
	\vskip5pt
	\begin{tabular}{lcc}
		\toprule
		& & \\
		\midrule
		& & \\
		\bottomrule
	\end{tabular}
\end{table}

P.S. booktabs package needed.

P.S. Snippets for marking 1st, 2nd, and 3rd best methods. \usepackage[dvipsnames, table]{xcolor} needed:

% marking 1st, 2nd, and 3rd best methods in table
\colorlet{bestclr}{teal!60}
\colorlet{secondclr}{teal!40}
\colorlet{thirdclr}{teal!20}
\newcommand{\firstplace}{\cellcolor{bestclr}\bfseries}
\newcommand{\secondplace}{\cellcolor{secondclr}}
\newcommand{\thirdplace}{\cellcolor{thirdclr}}
\def\tabclrscheme{The \colorbox{bestclr}{\textbf{first}}/\colorbox{secondclr}{second}/\colorbox{thirdclr}{third} best results are highlighted, respectively.}

Figure

\centering\includegraphics[width=\textwidth]{figures/}
\centering\animategraphics[loop, autoplay, every=1, width=\textwidth]{5}{figures/<folder>/<name>-}{0}{<end>}

P.S. Additional options: palindrome playback.

\begin{figure}[h]
	\centering
	\includegraphics[width=\linewidth]{figures/<>}
	\caption{<>}
	\label{fig:<>}
\end{figure}

P.S. graphicx package is needed.

\begin{figure}[h]
\centering
	\begin{subfigure}{\linewidth}
		\centering\includegraphics[width=\linewidth]{figures/<>}
		\caption{<>}
	\end{subfigure}
	\caption{<>}
	\label{fig:<>}
\end{figure}

P.S. graphicx and subcaption package is needed.

Emoji

Inserting emojis in LaTeX documents on Overleaf - Overleaf, Online LaTeX Editor

\usepackage{emoji}
...
\emoji{<code>}

Emoji code reference:

The emoji package documentation

P.S. To include emojis, luatex is needed to be used for typesetting.

Code block

\begin{lstlisting}[language=Python]

\end{lstlisting}

P.S. listings package is needed.

\begin{frame}[fragile]{}
\begin{lstlisting}[language=Python]

\end{lstlisting}
\end{frame}

P.S. When used within a beamer frame, the frame need to be set as [fragile] to use lstlisting:

Example code block styling:

% code block style
\definecolor{codegreen}{RGB}{101,218,120}
\definecolor{darkgreen}{RGB}{93,158,82}
\definecolor{darkyellow}{RGB}{245,194,105}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}

\lstdefinestyle{mystyle}{
    commentstyle=\color{airforceblue},
    keywordstyle=\color{magenta},
    numberstyle=\tiny\color{codegray},
    stringstyle=\color{codepurple},
    basicstyle=\ttfamily\scriptsize,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    keepspaces=true,
    numbers=left,
    numbersep=5pt,
    showspaces=false,
    showstringspaces=false,
    showtabs=false,
    tabsize=4,
    xleftmargin=10pt,
    xrightmargin=10pt,
}

\lstset{style=mystyle}

Bibliography

\usepackage[style=ieee]{biblatex}
\addbibresource{../../contents/biblio.bib}

Then inside the \begin{document} ... \end{document}:

% bibliography
\printbibliography

Reference

\usepackage{hyperref}
\hypersetup{
    colorlinks,
    linkcolor={black},
    citecolor={black},
    urlcolor={black}
}

\renewcommand{\sectionautorefname}{Section}
\renewcommand{\subsectionautorefname}{Section}
\renewcommand{\subsubsectionautorefname}{Section}
\renewcommand{\figureautorefname}{Fig.}
\renewcommand{\tableautorefname}{Table}

Then you can just \autoref{} sections, figures, and tables without having to manually type prefix like Fig.~\ref{}.

However, for equation, use \eqref{}.

Footnote

Footnotes | Overleaf

\footnote<[id]>{...}
\footnotemark<[id]>
\footnotetext<[id]>{...}

Changing footnote mark:

  • \arabic{_counter variable_}: typeset _counter variable_ in Arabic numerals.
  • \roman{_counter variable_}: typeset _counter variable_ in lowercase Roman numerals.
  • \Roman{_counter variable_}: typeset _counter variable_ in uppercase Roman numerals.
  • \alph{_counter variable_}: typeset _counter variable_ in lowercase Alphabetic characters.
  • \Alph{_counter variable_}: typeset _counter variable_ in uppercase Alphabetic characters.
  • \fnsymbol{_counter variable_}: typeset _counter variable_ using a set of 9 special symbols.
\renewcommand{\thefootnote}{<\style>{footnote}}

P.S. This can be used inside the document to change style for various times.

P.S. In the min page environment, use mpfootnote variable instead of footnoe:

\renewcommand{\thempfootnote}{<\style>{mpfootnote}}

Beamer

Beamer - Overleaf, Online LaTeX Editor

Partition

\begin{frame}{}
    
\end{frame}
\begin{columns}
    \begin{column}{0.5\textwidth}
        
    \end{column}
    \begin{column}{0.5\textwidth}
        
    \end{column}
\end{columns}
\begin{block}{}
    
\end{block}
\begin{block}{}
    \begin{lstlisting}[language=Python]
        
    \end{lstlisting}
\end{block}

Visibility

In Beamers, the following commands can be used to control the visibility of the elements:

\only<>{}
\visbile<>{}

In itemize and enumerate environments, you don't need to manually write these commands for 1-by-1 roll out. Just use <+-> or <+>:

  • Appears one by one:
\begin{itemize}[<+->]
    \item First
    \item Second
    \item Third
\end{itemize}
  • Appears one by one with the previous one disappears:
\begin{itemize}[<+>]
    \item First
    \item Second
    \item Third
\end{itemize}

Tikz

Writing in Tikz could be painful if we don't follow a good structure/pattern. The most important principles are:

  • Define the styles in a separate place and reuse them in the diagram.
  • Use scope to group a series of related elements and give the scope a name, so that its position can be referenced like a node. For example, <scope>.center, <scope>.south, etc.
  • Always align two elements relatively as long as possible, rather than hard coding their absolute positions.
    • Use chains for aligning a chain of nodes (within a scope or tikzpicture) to avoid specifying alignment direction & distance in every node.
    • Use calc for programmatically assign position to a node.
  • Use \for loop and \newcommand to draw repeated elements.

Following these principles can make the Tikz diagram human-readable, maintainable, and, most importantly, elegant.

Include packages

\documentclass[10pt, border=5mm]{standalone}
\usepackage{amstext}  % for text in math mode
\usepackage[dvipsnames]{xcolor} % for color names
\usepackage{tikz}  % for drawing
\usepackage{pgf}  % for key=value style command variables
\usepackage{pgfplots}  % for plotting

\usetikzlibrary{
    chains,
    positioning,
    calc,
    fit,
    arrows.meta,
    shapes.geometric,
}

Define styles

\tikzset{
    basicnode/.style = {
        rectangle, rounded corners, minimum width=1.5cm, minimum height=0.5cm, text centered, align=center, draw=black, fill=blue!20
    },
    boundingbox/.style = {draw=black, dashed},
    inputnode/.style = {draw=black, rounded corners, dashed, align=center},
    postblc/.style = {basicnode, fill=yellow!20, minimum width=1cm},
    clsblc/.style = {basicnode, fill=lightgray, minimum width=1cm},
    connect/.style = {thick},
    arrow/.style = {connect, ->, >=stealth},
    joint/.style = {circle, thin, fill=lightgray, draw, minimum size=0.25cm, inner sep=0pt, outer sep=0pt, label=center:+},
}

Body

\begin{document}
\begin{tikzpicture} [node distance=0cm]

\end{tikzpicture}
\end{document}

Scope

\begin{scope} [local bounding box=<id>, xshift=<>cm, yshift=<>cm]
	...
\end{scope}

P.S. xshift and yshift shift the whole bounding box, making location adjustment much easier.

Alignment

Relative alignment

\node (<id>) [<style>, below=of <id>] {}
\node (<id>) [<style>, above=of <id>] {}
\node (<id>) [<style>, left=of <id>] {}
\node (<id>) [<style>, right=of <id>] {}

P.S. xshift & yshift for fine-grained adjustment.

P.S. Use label=<direction>:<text> to add label to a node. If multi-line is needed, use label=<direction>:{\parabox{<size>}{<text>}.

Chain

Chains - PGF/TikZ Manual

\begin{tikzpicture}[
    start chain=1 going right,
    start chain=2 going below,
    node distance=5mm,
    every node/.style=draw,
    every on chain/.style={join=by arrow},
    ]
  \node [on chain=1] {A};
  \node [on chain=1] {B};
  \node [on chain=1] {C};

  \node [on chain=2] at (0.5,-.5) {0};
  \node [on chain=2] {1};
  \node [on chain=2] {2};

  \node [on chain=1] {D};
\end{tikzpicture}

Calc

\node (A) at (0,0) {A};
\node (B) at ($(A) + (2,1)$) {B};
\node (C) at ($(C |- B)$) {D};  % (C_x, B_y)
\node (D) at ($(C -| B)$) {D};  % (C_y, B_x)

Fit

\node (<id>) [<style>, fit={(<id>) (<coord>) <...>}] {};

e.g.

\node [draw, dashed, fit={(vertex) (padded_vertex)}, label=above:Vertex Input] {};

Reusable stuff

\newcommand{\tikzdashbox}[1]{%
    \tikz[baseline=(X.base)]{%
        \node[draw, dashed, rounded corners, inner sep=5pt] (X) {#1};%
    }%
}

New command & for loop

\documentclass{article}
\usepackage{tikz}

\newcommand{\mycircle}[3]{
    \node[circle, draw, fill=#1, minimum size=1cm] at (#2, #3) {};
}

\begin{document}
\begin{tikzpicture}
    \foreach \x in {0, 1, 2, 3} {
	    \foreach \y in {0, 1, 2} {
            \mycircle{blue}{\x}{\y};
	    }
	}
\end{tikzpicture}
\end{document}

Typesetting engine selection in VS Code plugin

luatex

To use luatex in VS Code LaTeX plugin:

luatex - LuaLaTeX not recognised as a VS Code tool - TeX - LaTeX Stack Exchange

# .vscode/settings.json
"latex-workshop.latex.recipe.default": "latexmk (lualatex)",

xelatex

P.S. To use xelatex in VS Code LaTeX plugin:

xetex - How to use visual studio code LaTex Workshop with xelatex - TeX - LaTeX Stack Exchange

# .vscode/settings.json
"latex-workshop.latex.recipe.default": "latexmk (xelatex)",

.gitignore

# gitignore
.DS_Store
.idea/
log/

build/
*.aux
*.log
*.nav
*.out
*.snm
*.toc
*.synctex.gz
*.toc.vrb
*.vrb
*.bbl
*.bcf
*.run.xml
*.blg
*.pdf
*.sav
*.fdb_latexmk
*.fls
*.brf

*.docx

# ignore pdf files except for those in the figures/ folder
*.pdf
!figures/**/*.pdf

PDF postprocessing

Reducing PDF size

Downsize PDF files without image quality loss using Ghostscript:

gs \
  -sDEVICE=pdfwrite \
  -dCompatibilityLevel=1.6 \
  -dNOPAUSE \
  -dQUIET \
  -dBATCH \
  -dDetectDuplicateImages=true \
  -dCompressFonts=true \
  -dSubsetFonts=true \
  -dDownsampleColorImages=false \
  -dDownsampleGrayImages=false \
  -dDownsampleMonoImages=false \
  -sOutputFile=compressed.pdf \
  main.pdf

If image compression is necessary:

gs \
  -sDEVICE=pdfwrite \
  -dCompatibilityLevel=1.6 \
  -dNOPAUSE \
  -dQUIET \
  -dBATCH \
  -dDetectDuplicateImages=true \
  -dCompressFonts=true \
  -dSubsetFonts=true \
  -dDownsampleColorImages=true \
  -dColorImageResolution=300 \
  -dDownsampleGrayImages=true \
  -dGrayImageResolution=300 \
  -dDownsampleMonoImages=true \
  -dMonoImageResolution=300 \
  -sOutputFile=compressed.pdf \
  main.pdf

P.S. gs is usually shipped with an Ubuntu Desktop system. On macOS, it is installed when you install MacTeX.

PDF page trimming

gs \
  -sDEVICE=pdfwrite \
  -dNOPAUSE \
  -dQUIET \
  -dBATCH \
  -dFirstPage=1 \
  -dLastPage=9 \
  -sOutputFile=main.trimmed.pdf \
  main.pdf

Example:

  • Keep the main text (to page 9)
  • Keep the appendix (from page 10)
gs \
  -sDEVICE=pdfwrite \
  -dNOPAUSE \
  -dQUIET \
  -dBATCH \
  -dLastPage=9 \
  -sOutputFile=main-paper.pdf \
  main.pdf

gs \
  -sDEVICE=pdfwrite \
  -dNOPAUSE \
  -dQUIET \
  -dBATCH \
  -dFirstPage=10 \
  -sOutputFile=main-appendix.pdf \
  main.pdf
Lastly updated: 2025-04-23

Do you have any ideas or comments? Please join the discussion on X👇