Latex: Difference between revisions

From David's Wiki
 
(52 intermediate revisions by the same user not shown)
Line 10: Line 10:
Download [https://miktex.org MikTex].
Download [https://miktex.org MikTex].
It includes the TeXworks editor and will download packages as you use them.
It includes the TeXworks editor and will download packages as you use them.
This will not take up as much disk space as a full install.
This will not take up as much disk space as a full install but will require internet access to download new packages.
===Full Install===
===Full Install===
====Windows====
====Windows====
Download [https://www.tug.org/texlive/ TexLive].
Download [https://www.tug.org/texlive/ TexLive] using the [https://www.tug.org/texlive/acquire-iso.html ISO images].
This is several gigabytes since it includes all the popular LaTex packages and takes a while to install.
This is ~4 gigabytes since it includes all the popular LaTeX packages and takes a while to install.
You'll also need an editor. I recommend installing [[Atom_(text_editor) | Atom]] with the following packages:  
You'll also need an editor. I recommend installing [[Atom_(text_editor) | Atom]] with the following packages:  
* <code>latex</code> for calling the TexLive compiler
* <code>latex</code> for calling the TexLive compiler
* <code>language-latex</code> for syntax highlighting
* <code>language-latex</code> for syntax highlighting
* <code>pdf-view</code> for viewing the compiled pdf.
* <code>pdf-view</code> for viewing the compiled pdf.
<pre>
apm install latex language-latex pdf-view
</pre>


====Linux====
====Linux====
Line 28: Line 31:
pdflatex [mydocument.tex]
pdflatex [mydocument.tex]
</syntaxhighlight>
</syntaxhighlight>
* Note to add bibliography, you need to run <code>pdflatex</code>, <code>bibtex</code>, <code>pdflatex</code> or <code>rubber --pdf</code>.
==Usage==
==Usage==


===Fancy Math Font===
===Fancy Math Font===
See [https://tex.stackexchange.com/questions/58098/what-are-all-the-font-styles-i-can-use-in-math-mode this answer.]


[[File:LatexMathFonts.png|500x500px|right]]
 
See [https://tex.stackexchange.com/questions/58098/what-are-all-the-font-styles-i-can-use-in-math-mode this answer.]
[[File:LatexMathFonts.png|500x500px]]
<syntaxhighlight lang="latex">
<syntaxhighlight lang="latex">
% Use mathbb for the set of reals R or the set of complex numbers C
% Use mathbb for the set of reals R or the set of complex numbers C
Line 41: Line 48:


===Spaces===
===Spaces===
See [https://www.overleaf.com/learn/latex/Spacing_in_math_mode Reference]<br>
See [https://www.overleaf.com/learn/latex/Spacing_in_math_mode Reference]
[[File:SpacingMathEx2.png|250x250px]]
 
<syntaxhighlight lang="latex">
<div style="display: inline-block;vertical-align: top;">
[[File:SpacingMathEx2.png|350px]]
</div>
<syntaxhighlight lang="latex" style="display: inline-block;vertical-align: top; background: none;">
Spaces in mathematical mode.
Spaces in mathematical mode.
   
   
Line 73: Line 83:
\end{minipage}
\end{minipage}
</pre>
</pre>
===Sections===
====Numbering====
To change the section numbering from numbers to letters, add the following:
<syntaxhighlight lang="latex">
% Changes sections to use capital letters
\renewcommand{\thesection}{\Alph{section}}
% Changes subsections to use lowercase letters
\renewcommand{\thesubsection}{\thesection.\alph{subsection}}
</syntaxhighlight>


===Programming===
===Programming===
Line 80: Line 101:
===Custom Commands===
===Custom Commands===
You can define your own commands using <code>\newcommand</code>
You can define your own commands using <code>\newcommand</code>
<syntaxhighlight lang="latex">
\newcommand{\notdone}{{\color{red} Not done!!}}
</syntaxhighlight>


===Custom Operators===
===Custom Operators===
Line 90: Line 114:
\DeclareMathOperator{\sign}{sign}
\DeclareMathOperator{\sign}{sign}
\DeclareMathOperator{\rank}{rank}
\DeclareMathOperator{\rank}{rank}
\DeclareMathOperator{\argmin}{argmin}
\DeclareMathOperator*{\argmin}{argmin}
\DeclareMathOperator{\argmax}{argmax}
\DeclareMathOperator*{\argmax}{argmax}
</syntaxhighlight>
 
;Notes
* Adding <code>*</code> puts subscript elements beneath the operator.
 
==Programming==
===For Each Loops===
<syntaxhighlight lang="latex">
\foreach [count=\i] \j in {A,B,...,H}{
Element \i~is \j\\
}
</syntaxhighlight>
 
==Page Layout==
There are many packages which adjust the page layout.<br>
You can use the package <code>wordlike</code> for a MS Word layout.
===Font===
;Font size
<syntaxhighlight lang="latex">
\documentclass[12pt]{article}
</syntaxhighlight>
 
;Font type
* Times New Roman - <code>\usepackage{mathptmx}</code>
 
==Tables==
===Multirow and Multicolumns===
<syntaxhighlight lang="latex">
\usepackage{multirow}
 
\multirow{3}{4em}{Dataset A}
</syntaxhighlight>
 
===Newlines===
[https://tex.stackexchange.com/questions/2441/how-to-add-a-forced-line-break-inside-a-table-cell stackexchange line break in table cell] 
[https://tex.stackexchange.com/questions/331716/newline-in-multirow-environment linebreak in multirow]
 
To have a newline in a cell, you can use the [https://www.ctan.org/pkg/makecell makecell] package. 
<code>\makecell{Some really \\ longer text}</code>. 
To make this align left: <code>\makecell[l]{Some really \\ longer text}</code>
 
For multirow cells, you can use <code>\multirowcell{5}{Numbers\\from\\ 1 to 5}</code>. 
By default, this will align center. You can make it align left: <code>\multirowcell{2}[0pt][l]{Number\\ Letter}</code>.
 
==Table Generator==
[https://www.tablesgenerator.com/ https://www.tablesgenerator.com/] can generate table code from existing tables.
 
==Figures==
<syntaxhighlight lang="latex">
\begin{figure}[!htbp]
  \includegraphics[width=\linewidth]{/path/to/figure}
  \caption{}
  \label{}
\end{figure}
</syntaxhighlight>
 
Be sure to use vector figures (pdf or pgf) instead of raster ones (png, jpeg).<br>
See [https://timodenk.com/blog/exporting-matplotlib-plots-to-latex/ https://timodenk.com/blog/exporting-matplotlib-plots-to-latex/] on how to export matplotlib to pgf.
 
In the snippet <code>[!htbp]</code> represents the placement preferences.
* <code>!</code> means to ignore some placement limitations
* <code>h</code> mean to place the figure here
* <code>t</code> means top of the page.
* <code>b</code> means bottom of the page.
* <code>p</code> means to place it on a figure only page.
 
If you add the [https://ctan.mirrors.hoobly.com/macros/latex/contrib/float/float.pdf the float package], you can also use <code>[!H]</code> which is a more strict version of <code>[!h]</code>.
 
===Subfigure===
See [https://www.overleaf.com/learn/latex/How_to_Write_a_Thesis_in_LaTeX_(Part_3):_Figures,_Subfigures_and_Tables#Subfigures overleaf reference]
 
<syntaxhighlight lang="latex">
% In the header:
\usepackage{caption}
\usepackage{subcaption}
 
\begin{figure}[!htbp]
  \centering
  \begin{subfigure}[b]{0.45\linewidth}
    \centering
    \includegraphics[width=\linewidth]{graph1}
    \caption{This is graph1.}
    \label{fig:a}
  \end{subfigure}
  \hfill
  \begin{subfigure}[b]{0.45\linewidth}
    \centering
    \includegraphics[width=\linewidth]{graph2}
    \caption{This is graph2.}
    \label{fig:b}
  \end{subfigure}
  \caption{}
  \label{fig:ab}
\end{figure}
</syntaxhighlight>
</syntaxhighlight>


Line 115: Line 233:
</syntaxhighlight>
</syntaxhighlight>
}}
}}
===Other Options===
* <code>font=\bfseries</code> for bold labels
* <code>align=left</code> left align labels


==Useful Commands==
==Useful Commands==
A list of potentially useful commands
A list of potentially useful commands.<br>
You can paste the following an a <code>Macros.tex</code> file and <code>\input{Macros}</code> in your main tex file.


<syntaxhighlight lang="latex">
<syntaxhighlight lang="latex">
\newcommand{\degree}{\ensuremath{^{\circ}} }
\newcommand{\degree}{\ensuremath{^{\circ}} }
\newcommand{\etal}{{\em et al. }}
\newcommand{\etal}{{\em et al.}}
\newcommand{\ceil}[1]{{\lceil #1 \rceil}}
\newcommand{\floor}[1]{{\lfloor #1 \rfloor}}
 
\newcommand{\bmat}[1]{\begin{bmatrix}#1\end{bmatrix}}
\newcommand{\pmat}[1]{\begin{pmatrix}#1\end{pmatrix}}
</syntaxhighlight>
</syntaxhighlight>


==Bibliography==
==Bibliography (Bibtex)==
How to do references in Latex.<br>
How to do references in Latex.<br>
[https://www.verbosus.com/bibtex-style-examples.html Bibtex Examples]
===Citations===
Use <code>\cite</code> or some variant to cite references.<br>
[https://gking.harvard.edu/files/natnotes2.pdf Natbib reference sheet]<br>
<pre>
# Defaults to author-year citations
\usepackage{natbib}
# For numerical citations
\usepackage[numbers]{natbib}
# If using author-year citations
\citet{jon90} ⇒ Jones et al. (1990)
\citep{jon90} ⇒ (Jones et al., 1990)
\citep[see][]{jon90} ⇒ (see Jones et al., 1990)
# If using numerical citations
\citet{jon90} ⇒ Jones et al. [21]
\citep{jon90} ⇒ [21]
\citep[see][]{jon90} ⇒ [see 21]
</pre>


===Case of Titles===
===Case of Titles===
Line 143: Line 292:


==Tikz==
==Tikz==
{{main | PGF/TikZ}}
Tikz is used to draw graphs and other shapes
Tikz is used to draw graphs and other shapes
===Drawing over images===
===Drawing over images===
Line 159: Line 309:
\end{tikzpicture}
\end{tikzpicture}
</syntaxhighlight>
</syntaxhighlight>
==Algorithms==
How to insert pseudocode into your Latex document.
See [https://tex.stackexchange.com/questions/229355/algorithm-algorithmic-algorithmicx-algorithm2e-algpseudocode-confused algorithmc vs algorithmcx vs algorithm2e]<br>
Also [[Wikibooks: LaTeX/Algorithms]] for several examples
===algorithmc===
[http://mirrors.rit.edu/CTAN/macros/latex/contrib/algorithms/algorithms.pdf The algorithms bundle]
===algorithmcx===
[http://mirror.ox.ac.uk/sites/ctan.org/macros/latex/contrib/algorithmicx/algorithmicx.pdf The algorithmicx package]
===algorithm2e===
See [https://en.wikibooks.org/wiki/LaTeX/Algorithms#Typesetting_using_the_algorithm2e_package https://en.wikibooks.org/wiki/LaTeX/Algorithms#Typesetting_using_the_algorithm2e_package]
<syntaxhighlight lang="latex">
\usepackage[linesnumbered,ruled]{algorithm2e}
\begin{algorithm}[!htbp]
\KwData{this text}
\KwResult{how to write algorithm with \LaTeX2e }
initialization\;
\While{not at end of this document}{
  read current\;
  \eIf{understand}{
  go to next section\;
  current section becomes this one\;
  }{
  go back to the beginning of current section\;
  }
}
\caption{How to write algorithms}
\end{algorithm}
</syntaxhighlight>
==Verbatim==
The <code>verbatim</code> package gives you the environment <code>verbatim</code>.
You can use <code>\verbatiminput</code> to embed text files.
===<code>fancyvrb</code>===
The <code>fancyvrb</code> package gives you the environment <code>Verbatim</code> which has more options. 
To embed in a figure, you can use <code>BVerbatim</code>. 
There is also <code>\VerbatimInput</code>, <code>\BVerbatimInput</code>, <code>\LVerbatimInput</code>.
==Document Class==
[https://www.overleaf.com/learn/latex/Writing_your_own_class Overleaf Writing your own class]<br>
Document classes are <code>.cls</code> files which provide a layout for your document.
By writing your own document class, you can ensure a consistent layout across multiple latex documents.
You can also encapsulate commands and macros or package requirements within your document class.<br>
;Notes
See [[Wikibooks: LaTeX/Document Structure]] for a list of common document classes and options.
==Examples==
Below is a basic example of a latex document
{{hidden | Article Example |
<syntaxhighlight lang="latex">
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{datetime}
\usepackage{lipsum} 
\usepackage[numbers]{natbib}
\newdateformat{monthyear}{%
  \monthname[\THEMONTH] \THEYEAR}
\title{My Main Title\\
\large A Subtitle}
\author{My Name}
\date{\monthyear\today}
\begin{document}
\maketitle
\begin{abstract}
    \lipsum[1]
\end{abstract}
\section{Introduction}
\lipsum[2-4]
\bibliographystyle{plain}
\bibliography{thebib}
\end{document}
</syntaxhighlight>
}}
==Exporting==
See [https://en.wikibooks.org/wiki/LaTeX/Export_To_Other_Formats#Convert_to_image_formats https://en.wikibooks.org/wiki/LaTeX/Export_To_Other_Formats#Convert_to_image_formats].
===Images===
On Linux, you can convert PDF files to PNG files using:
<pre>
pdftoppm paper.pdf paper-page -r 300 -png
</pre>
* <code>-r</code> specifies the DPI. Default is 150.
===Latex Cleanup===
If you need to submit the latex, e.g. to Arxiv, you can use this tool to help clean it up:
https://github.com/google-research/arxiv-latex-cleaner


==Resources==
==Resources==
* [http://detexify.kirelabs.org/classify.html Detexify LaTeX handwritten symbol recognition]
* [http://detexify.kirelabs.org/classify.html Detexify LaTeX handwritten symbol recognition]
[[Category:Programming languages]]

Latest revision as of 19:16, 20 September 2023

Typeset all of your papers using latex.


Installation

No Install

Use Overleaf to create latex documents in a web browser.

Partial Install

Download MikTex. It includes the TeXworks editor and will download packages as you use them. This will not take up as much disk space as a full install but will require internet access to download new packages.

Full Install

Windows

Download TexLive using the ISO images.
This is ~4 gigabytes since it includes all the popular LaTeX packages and takes a while to install. You'll also need an editor. I recommend installing Atom with the following packages:

  • latex for calling the TexLive compiler
  • language-latex for syntax highlighting
  • pdf-view for viewing the compiled pdf.
apm install latex language-latex pdf-view

Linux

sudo apt install texlive-full

Compile tex documents with

pdflatex [mydocument.tex]
  • Note to add bibliography, you need to run pdflatex, bibtex, pdflatex or rubber --pdf.

Usage

Fancy Math Font

See this answer.


% Use mathbb for the set of reals R or the set of complex numbers C
% Requires amsfonts
\mathbb{R}

Spaces

See Reference

Spaces in mathematical mode.
 
\begin{align*}
f(x) =& x^2\! +3x\! +2 \\
f(x) =& x^2+3x+2 \\
f(x) =& x^2\, +3x\, +2 \\
f(x) =& x^2\: +3x\: +2 \\
f(x) =& x^2\; +3x\; +2 \\
f(x) =& x^2\ +3x\ +2 \\
f(x) =& x^2\quad +3x\quad +2 \\
f(x) =& x^2\qquad +3x\qquad +2
\end{align*}

Units

For spacing between elements, use \hspace or \vspace.

\hspace[4mm]

Units in Latex
You can specify spacing in pt, mm, cm, ex, em, bp, dd, pc, in

Indents

Section

\hspace*{5mm}\begin{minipage}{\dimexpr\textwidth-5mm}
   Indented Section
\end{minipage}

Sections

Numbering

To change the section numbering from numbers to letters, add the following:

% Changes sections to use capital letters
\renewcommand{\thesection}{\Alph{section}}

% Changes subsections to use lowercase letters
\renewcommand{\thesubsection}{\thesection.\alph{subsection}}

Programming

Latex is a turing complete language.
You can use if statements and for loops in latex.

Custom Commands

You can define your own commands using \newcommand

\newcommand{\notdone}{{\color{red} Not done!!}}

Custom Operators

Latex packages like amsmath come with operators such as \sin and \log.
To get normal text for custom functions like arcsin, use \operatorname{arcsin}.
Below are some potentially useful math operators.

\DeclareMathOperator{\Tr}{Tr}
\DeclareMathOperator{\VCdim}{VCdim}
\DeclareMathOperator{\sign}{sign}
\DeclareMathOperator{\rank}{rank}
\DeclareMathOperator*{\argmin}{argmin}
\DeclareMathOperator*{\argmax}{argmax}
Notes
  • Adding * puts subscript elements beneath the operator.

Programming

For Each Loops

\foreach [count=\i] \j in {A,B,...,H}{
Element \i~is \j\\
}

Page Layout

There are many packages which adjust the page layout.
You can use the package wordlike for a MS Word layout.

Font

Font size
\documentclass[12pt]{article}
Font type
  • Times New Roman - \usepackage{mathptmx}

Tables

Multirow and Multicolumns

\usepackage{multirow}

\multirow{3}{4em}{Dataset A}

Newlines

stackexchange line break in table cell
linebreak in multirow

To have a newline in a cell, you can use the makecell package.
\makecell{Some really \\ longer text}.
To make this align left: \makecell[l]{Some really \\ longer text}

For multirow cells, you can use \multirowcell{5}{Numbers\\from\\ 1 to 5}.
By default, this will align center. You can make it align left: \multirowcell{2}[0pt][l]{Number\\ Letter}.

Table Generator

https://www.tablesgenerator.com/ can generate table code from existing tables.

Figures

\begin{figure}[!htbp]
  \includegraphics[width=\linewidth]{/path/to/figure}
  \caption{}
  \label{}
\end{figure}

Be sure to use vector figures (pdf or pgf) instead of raster ones (png, jpeg).
See https://timodenk.com/blog/exporting-matplotlib-plots-to-latex/ on how to export matplotlib to pgf.

In the snippet [!htbp] represents the placement preferences.

  • ! means to ignore some placement limitations
  • h mean to place the figure here
  • t means top of the page.
  • b means bottom of the page.
  • p means to place it on a figure only page.

If you add the the float package, you can also use [!H] which is a more strict version of [!h].

Subfigure

See overleaf reference

% In the header:
\usepackage{caption}
\usepackage{subcaption}

\begin{figure}[!htbp]
  \centering
  \begin{subfigure}[b]{0.45\linewidth}
    \centering
    \includegraphics[width=\linewidth]{graph1}
    \caption{This is graph1.}
    \label{fig:a}
  \end{subfigure}
  \hfill
  \begin{subfigure}[b]{0.45\linewidth}
    \centering
    \includegraphics[width=\linewidth]{graph2}
    \caption{This is graph2.}
    \label{fig:b}
  \end{subfigure}
  \caption{}
  \label{fig:ab}
\end{figure}

Enumerate

Enumerate is used to make lists

Change the label

Reference
Add the option for the labels:

  • label=(\alph*) for letters
  • label=(\Alph*) for upper-case letters
  • label=(\roman*) for roman numerals.
  • label=(\arabic*) for numbers
Example
\usepackage{enumitem}
#...
\begin{enumerate}[label=(\alph*)]
\item an apple
\item a banana
\item a carrot
\item a durian
\end{enumerate}

Other Options

  • font=\bfseries for bold labels
  • align=left left align labels

Useful Commands

A list of potentially useful commands.
You can paste the following an a Macros.tex file and \input{Macros} in your main tex file.

\newcommand{\degree}{\ensuremath{^{\circ}} }
\newcommand{\etal}{{\em et al.}}
\newcommand{\ceil}[1]{{\lceil #1 \rceil}}
\newcommand{\floor}[1]{{\lfloor #1 \rfloor}}

\newcommand{\bmat}[1]{\begin{bmatrix}#1\end{bmatrix}}
\newcommand{\pmat}[1]{\begin{pmatrix}#1\end{pmatrix}}

Bibliography (Bibtex)

How to do references in Latex.
Bibtex Examples

Citations

Use \cite or some variant to cite references.
Natbib reference sheet

# Defaults to author-year citations
\usepackage{natbib}
# For numerical citations
\usepackage[numbers]{natbib}

# If using author-year citations
\citet{jon90} ⇒ Jones et al. (1990)
\citep{jon90} ⇒ (Jones et al., 1990)
\citep[see][]{jon90} ⇒ (see Jones et al., 1990)

# If using numerical citations
\citet{jon90} ⇒ Jones et al. [21]
\citep{jon90} ⇒ [21]
\citep[see][]{jon90} ⇒ [see 21]

Case of Titles

If you do not want lower case titles, you can change your .bst file by commenting out the portion which alters the case.

FUNCTION {format.title}
{ 
  %title empty$
  %  { "" }
  %  { title "t" change.case$ }
  %if$
  title
  %add.link
}

Tikz

Tikz is used to draw graphs and other shapes

Drawing over images

\begin{tikzpicture}
    \node[anchor=south west,inner sep=0] (image) at (0,0) {
    \includegraphics[width=.9\linewidth]{my_image.png}
    };<br />
    \begin{scope}[x={(image.south east)},y={(image.north west)}]
        \draw[black,ultra thick,rounded corners] (0.0,0.1) rectangle (0.3,0.5);
        \draw[red,ultra thick,rounded corners] (0.5,0.1) rectangle (0.8,0.5);
        % \draw[help lines,xstep=.1,ystep=.1] (0,0) grid (1,1);
        % \foreach \x in {0,1,...,9} { \node [anchor=north] at (\x/10,0) {0.\x}; }
        % \foreach \y in {0,1,...,9} { \node [anchor=east] at (0,\y/10) {0.\y}; }
    \end{scope}
\end{tikzpicture}

Algorithms

How to insert pseudocode into your Latex document.

See algorithmc vs algorithmcx vs algorithm2e
Also Wikibooks: LaTeX/Algorithms for several examples

algorithmc

The algorithms bundle

algorithmcx

The algorithmicx package

algorithm2e

See https://en.wikibooks.org/wiki/LaTeX/Algorithms#Typesetting_using_the_algorithm2e_package

\usepackage[linesnumbered,ruled]{algorithm2e}

\begin{algorithm}[!htbp]
 \KwData{this text}
 \KwResult{how to write algorithm with \LaTeX2e }
 initialization\;
 \While{not at end of this document}{
  read current\;
  \eIf{understand}{
   go to next section\;
   current section becomes this one\;
   }{
   go back to the beginning of current section\;
  }
 }
 \caption{How to write algorithms}
\end{algorithm}

Verbatim

The verbatim package gives you the environment verbatim. You can use \verbatiminput to embed text files.

fancyvrb

The fancyvrb package gives you the environment Verbatim which has more options.
To embed in a figure, you can use BVerbatim.
There is also \VerbatimInput, \BVerbatimInput, \LVerbatimInput.

Document Class

Overleaf Writing your own class
Document classes are .cls files which provide a layout for your document. By writing your own document class, you can ensure a consistent layout across multiple latex documents. You can also encapsulate commands and macros or package requirements within your document class.

Notes

See Wikibooks: LaTeX/Document Structure for a list of common document classes and options.


Examples

Below is a basic example of a latex document

Article Example
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{datetime}
\usepackage{lipsum}<br />
\usepackage[numbers]{natbib}

\newdateformat{monthyear}{%
  \monthname[\THEMONTH] \THEYEAR}

\title{My Main Title\\
\large A Subtitle}
\author{My Name}
\date{\monthyear\today}

\begin{document}

\maketitle

\begin{abstract}
    \lipsum[1]
\end{abstract}

\section{Introduction}
\lipsum[2-4]


\bibliographystyle{plain}
\bibliography{thebib}

\end{document}

Exporting

See https://en.wikibooks.org/wiki/LaTeX/Export_To_Other_Formats#Convert_to_image_formats.

Images

On Linux, you can convert PDF files to PNG files using:

pdftoppm paper.pdf paper-page -r 300 -png
  • -r specifies the DPI. Default is 150.

Latex Cleanup

If you need to submit the latex, e.g. to Arxiv, you can use this tool to help clean it up: https://github.com/google-research/arxiv-latex-cleaner

Resources