Latex学习

本文最后更新于:8 个月前

这里是Latex相关的学习。近日进研究生组,需要使用Latex去做很多paper work,

Latex Introduction

  • a tool for typesetting professional-looking documents
  • TeX engine uses the commands embedded in your text file to guide and control the typesetting process, converting the LaTeX commands and document text into a professionally typeset PDF file.

Reasons for Learning Latex

  • Arguments in favour of LATEX include:

    • support for typesetting extremely complex mathematics, tables and technical content for the physical sciences;

    • facilities for footnotes, cross-referencing and management of bibliographies;

    • ease of producing complicated, or tedious, document elements such as indexes, glossaries, table of contents, lists of figures;

    • being highly customizable for bespoke document production due to its intrinsic programmability and extensibility through thousands of free add-on packages.

  • 总结:好用、功能多、可复用模版、免费,可以多人协作编辑

An Example

  • Latex代码例子:
1
2
3
4
5
\documentclass{article}
\begin{document}
First document. This is a simple example, with no
extra parameters or packages included.
\end{document}
  • Latex代码效果:

img

多种Topic: https://www.ctan.org/topic/class,Different types of documents require different classes; i.e., a CV/resume will require a different class than a scientific paper which might use the standard LATEX article class. Other types of documents you may be working on may require different classes such as book or report. 不同类型的需求,可以使用不同的topic昂!

Document’s Preamable

  • 按照惯例latex文件后缀为:.tex,main.tex是默认的主文件。

  • .tex文件中出现在\begin之前的所有内容都称为序言,它充当文档的“设置”部分。可以定义文档类别(类型)以及诸如编写文档时要使用的语言等细节,加载您想要使用的包等

  • 一个小例子:

1
2
\documentclass [12pt, letterpaper]{article}
\usepackage { Graphicx }

Including title, author and date information

  • \title{My first LaTeX document}: the document title

  • \author{Hubert Farnsworth}: here you write the name of the author(s) and, optionally, the \thanks command within the curly braces:

    • \thanks{Funded by the Overleaf team.}: can be added after the name of the author, inside the braces of the author command. It will add a superscript and a footnote with the text inside the braces. Useful if you need to thank an institution in your article.
  • \date{August 2022}: you can enter the date manually or use the command \today to typeset the current date every time the document is compiled

  • maletitle and show:

1
2
3
4
5
6
7
8
\documentclass[12pt, letterpaper]{article}
\title{My first LaTeX document}
\author{Hubert Farnsworth\thanks{Funded by the Overleaf team.}}
\date{August 2022}
\begin{document}
\maketitle
We have now added a title, author and date to our first \LaTeX{} document!
\end{document}

Image of a simple document produced in LaTeX

Adding Comments

A LATEX comment is a section of text that will not be typeset or affect the document in any way—often used to add “to do” notes; include explanatory notes; provide in-line explanations of tricky macros or comment-out lines/sections of LaTeX code when debugging.

  • An example
1
% This line here is a comment. It will not be typeset in the document.

Bold, italics and underlining

  • Bold: bold text in LaTeX is typeset using the \textbf{...} command.
  • Italics: italicised text is produced using the \textit{...} command.
  • Underline: to underline text use the \underline{...} command.
  • emph: to emphasize content depending on the context. Inside normal text, the emphasized text is italicized, but this behaviour is reversed if used inside an italicized text.
1
2
3
4
5
6
7
8
Some of the greatest \emph{discoveries} in science 
were made by accident.

\textit{Some of the greatest \emph{discoveries}
in science were made by accident.}

\textbf{Some of the greatest \emph{discoveries}
in science were made by accident.}

效果:

Image demonstrating use of the LaTeX \emph command

  • Note: some packages, such as Beamer, change the behaviour of the \emph command.

Adding images

note that you need to upload images to your Overleaf project first.

  • needs an add-on package which provides the commands and features required to include external graphics files.
  • \includegraphics{...} to import graphics and \graphicspath{...} to advise LATEX where the graphics are located.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
\documentclass{article}
\usepackage{graphicx}% LaTeX package to import graphics
\graphicspath{{images/}} % configuring the graphicx package

\begin{document}
The universe is immense and it seems to be homogeneous,
on a large scale, everywhere we look.

% The \includegraphcs command is
% provided (implemented) by the
% graphicx package
\includegraphics{universe}

There's a picture of a galaxy above.
\end{document}

Image showing LaTeX accessing images stored in a folder

The \includegraphics{universe} command does the actual work of inserting the image in the document. Here, universe is the name of the image file but without its extension.

Note:

  • Although the full file name, including its extension, is allowed in the \includegraphics command, it’s considered best practice to omit the file extension because it will prompt LATEX to search for all the supported formats.
  • Generally, the graphic’s file name should not contain white spaces or multiple dots; it is also recommended to use lowercase letters for the file extension when uploading image files to Overleaf.

Captions, labels and references

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
\documentclass{article}
\usepackage{graphicx}
\graphicspath{{images/}}

\begin{document}

\begin{figure}[h]
\centering
\includegraphics[width=0.75\textwidth]{mesh}
\caption{A nice plot.}
\label{fig:mesh1}
\end{figure}

As you can see in figure \ref{fig:mesh1}, the function grows near the origin. This example is on page \pageref{fig:mesh1}.

\end{document}

Graphic showing use of figure captions in LaTeX

  • \includegraphics[width=0.75\textwidth]{mesh}: This form of \includegraphics instructs LATEX to set the figure’s width to 75% of the text width—whose value is stored in the \textwidth command.

  • \caption{A nice plot.}: As its name suggests, this command sets the figure caption which can be placed above or below the figure. If you create a list of figures this caption will be used in that list.

  • \label{fig:mesh1}: To reference this image within your document you give it a label using the \label command. The label is used to generate a number for the image and, combined with the next command, will allow you to reference it.

  • \ref{fig:mesh1}: This code will be substituted by the number corresponding to the referenced figure.

Creating lists in LATEX

You can create different types of list using environments, which are used to encapsulate the LATEX code required to implement a specific typesetting feature. An environment starts with \begin{*environment-name*} and ends with \end{*environment-name*} where *environment-name* might be figure, tabular or one of the list types: itemize for unordered lists or enumerate for ordered lists.

Unordered lists

1
2
3
4
5
6
7
\documentclass{article}
\begin{document}
\begin{itemize}
\item The individual entries are indicated with a black dot, a so-called bullet.
\item The text in the entries may be of any length.
\end{itemize}
\end{document}

Ordered lists

1
2
3
4
5
6
7
\documentclass{article}
\begin{document}
\begin{enumerate}
\item This is the first entry in our list.
\item The list numbers increase with each entry we add.
\end{enumerate}
\end{document}

Adding math to LATEX

  • LATEX provides two writing modes for typesetting mathematics:

    • inline math mode used for writing formulas that are part of a paragraph

    • display math mode used to write expressions that are not part of a text or paragraph and are typeset on separate lines

Inline math mode

  • To typeset inline-mode math you can use one of these delimiter pairs: \( ... \), $ ... $ or \begin{math} ... \end{math},Examples:
1
2
3
4
5
\documentclass[12pt, letterpaper]{article}
\begin{document}
In physics, the mass-energy equivalence is stated
by the equation $E=mc^2$, discovered in 1905 by Albert Einstein.
\end{document}
1
2
3
4
5
6
\documentclass[12pt, letterpaper]{article}
\begin{document}
\begin{math}
E=mc^2
\end{math} is typeset in a paragraph using inline math mode---as is $E=mc^2$, and so too is \(E=mc^2\).
\end{document}

Display math mode

  • Equations typeset in display mode can be numbered or unnumbered:
1
2
3
4
5
6
7
8
9
10
\documentclass[12pt, letterpaper]{article}
\begin{document}
The mass-energy equivalence is described by the famous equation
\[ E=mc^2 \] discovered in 1905 by Albert Einstein.

In natural units ($c = 1$), the formula expresses the identity
\begin{equation}
E=m
\end{equation}
\end{document}
  • To typeset display-mode math you can use one of these delimiter pairs: \[ ... \], \begin{displaymath} ... \end{displaymath} or \begin{equation} ... \end{equation}. Historically, typesetting display-mode math required use of $$ characters delimiters, as in $$ *... display math here ...*$$, but this method is no longer recommended: use LaTeX’s delimiters \[ ... \] instead.

More complete examples

  • Complex Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
\documentclass{article}
\begin{document}
Subscripts in math mode are written as $a_b$ and superscripts are written as $a^b$. These can be combined and nested to write expressions such as

\[ T^{i_1 i_2 \dots i_p}_{j_1 j_2 \dots j_q} = T(x^{i_1},\dots,x^{i_p},e_{j_1},\dots,e_{j_q}) \]

We write integrals using $\int$ and fractions using $\frac{a}{b}$. Limits are placed on integrals using superscripts and subscripts:

\[ \int_0^1 \frac{dx}{e^x} = \frac{e-1}{e} \]

Lower case Greek letters are written as $\omega$ $\delta$ etc. while upper case Greek letters are written as $\Omega$ $\Delta$.

Mathematical operators are prefixed with a backslash as $\sin(\beta)$, $\cos(\alpha)$, $\log(x)$ etc.
\end{document}

Image showing a range of math typeset in LaTeX

  • uses the equation* environment which is provided by the amsmath package, so we need to add the following line to our document preamble:

    1
    \usepackage{amsmath}% For the equation* environment

    https://www.overleaf.com/learn/latex/Aligning_equations_with_amsmath

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
      \documentclass{article}
    \usepackage{amsmath}% For the equation* environment
    \begin{document}
    \section{First example}

    The well-known Pythagorean theorem \(x^2 + y^2 = z^2\) was proved to be invalid for other exponents, meaning the next equation has no integer solutions for \(n>2\):

    \[ x^n + y^n = z^n \]

    \section{Second example}

    This is a simple math expression \(\sqrt{x^2+1}\) inside text.
    And this is also the same:
    \begin{math}
    \sqrt{x^2+1}
    \end{math}
    but by using another command.

    This is a simple math expression without numbering
    \[\sqrt{x^2+1}\]
    separated from text.

    This is also the same:
    \begin{displaymath}
    \sqrt{x^2+1}
    \end{displaymath}

    \ldots and this:
    \begin{equation*}
    \sqrt{x^2+1}
    \end{equation*}
    \end{document}

    ![image-20230721215452982](https://cdn.jsdelivr.net/gh/alexanderliu-creator/blog_img/img/202307212154059.png)

    - 写好数学公式的参考,The possibilities with math in LATEX are endless so be sure to visit our help pages for advice and examples on specific topics:
    - [Mathematical expressions](https://www.overleaf.com/learn/latex/Mathematical_expressions)
    - [Subscripts and superscripts](https://www.overleaf.com/learn/latex/Subscripts_and_superscripts)
    - [Brackets and Parentheses](https://www.overleaf.com/learn/latex/Brackets_and_Parentheses)
    - [Fractions and Binomials](https://www.overleaf.com/learn/latex/Fractions_and_Binomials)
    - [Aligning Equations](https://www.overleaf.com/learn/latex/Aligning_equations_with_amsmath)
    - [Operators](https://www.overleaf.com/learn/latex/Operators)
    - [Spacing in math mode](https://www.overleaf.com/learn/latex/Spacing_in_math_mode)
    - [Integrals, sums and limits](https://www.overleaf.com/learn/latex/Integrals%2C_sums_and_limits)
    - [Display style in math mode](https://www.overleaf.com/learn/latex/Display_style_in_math_mode)
    - [List of Greek letters and math symbols](https://www.overleaf.com/learn/latex/List_of_Greek_letters_and_math_symbols)
    - [Mathematical fonts](https://www.overleaf.com/learn/latex/Mathematical_fonts)





    # Basic document structure

    ## Abstracts

    ```latex
    \documentclass{article}
    \begin{document}
    \begin{abstract}
    This is a simple paragraph at the beginning of the
    document. A brief introduction about the main subject.
    \end{abstract}
    \end{document}

Image showing an abstract typeset in LaTeX

Paragraphs and new lines

  • key problems:
    • how a new paragraph is created by pressing the “enter” key twice, ending the current line and inserting a subsequent blank line;
    • how to start a new line without starting a new paragraph by inserting a manual line break using the \\ command, which is a double backslash; alternatively, use the \newline command.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
\documentclass{article}
\begin{document}

\begin{abstract}
This is a simple paragraph at the beginning of the
document. A brief introduction about the main subject.
\end{abstract}

After our abstract we can begin the first paragraph, then press ``enter'' twice to start the second one.

This line will start a second paragraph.

I will start the third paragraph and then add \\ a manual line break which causes this text to start on a new line but remains part of the same paragraph. Alternatively, I can use the \verb|\newline|\newline command to start a new line, which is also part of the same paragraph.
\end{document}

Chapters and sections

Longer documents, irrespective of authoring software, are usually partitioned into parts, chapters, sections, subsections and so forth. LaTeX also provides document-structuring commands but the available commands, and their implementations (what they do), can depend on the document class being used. By way of example, documents created using the book class can be split into parts, chapters, sections, subsections and so forth but the letter class does not provide (support) any commands to do that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
\documentclass{book}
\begin{document}

\chapter{First Chapter}

\section{Introduction}

This is the first section.

Lorem ipsum dolor sit amet, consectetuer adipiscing
elit. Etiam lobortisfacilisis sem. Nullam nec mi et
neque pharetra sollicitudin. Praesent imperdietmi nec ante.
Donec ullamcorper, felis non sodales...

\section{Second Section}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Etiam lobortis facilisissem. Nullam nec mi et neque pharetra
sollicitudin. Praesent imperdiet mi necante...

\subsection{First Subsection}
Praesent imperdietmi nec ante. Donec ullamcorper, felis non sodales...

\section*{Unnumbered Section}
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Etiam lobortis facilisissem...
\end{document}

image-20230722094811329

  • Tips: Sections can be further divided into \subsection{...} and even \subsubsection{...}. The numbering of sections, subsections etc. is automatic but can be disabled by using the so-called starred version of the appropriate command which has an asterisk (*) at the end, such as \section*{...} and \subsection*{...}.
  • LaTeX document classes provide the following sectioning commands, with specific classes each supporting a relevant subset:
    • \part{part}
    • \chapter{chapter}
    • \section{section}
    • \subsection{subsection}
    • \subsubsection{subsubsection}
    • \paragraph{paragraph}
    • \subparagraph{subparagraph}
  • the \part and \chapter commands are only available in the report and book document classes.
  • article about sections and chapters

Creating tables

  • an example:
1
2
3
4
5
6
7
\begin{center}
\begin{tabular}{c c c}
cell1 & cell2 & cell3 \\
cell4 & cell5 & cell6 \\
cell7 & cell8 & cell9
\end{tabular}
\end{center}

Graphic displaying a table typeset in LaTeX

You must specify a parameter to this environment, in this case {c c c} which advises LATEX that there will be three columns and the text inside each one must be centred. You can also use r to right-align the text and l to left-align it. The alignment symbol & is used to demarcate individual table cells within a table row. To end a table row use the new line command \\. Our table is contained within a center environment to make it centred within the text width of the page.

Adding borders

The tabular environment supports horizontal and vertical lines (rules) as part of the table:

  • to add horizontal rules, above and below rows, use the \hline command
  • to add vertical rules, between columns, use the vertical line parameter |
1
2
3
4
5
6
7
8
9
\begin{center}
\begin{tabular}{|c|c|c|}
\hline
cell1 & cell2 & cell3 \\
cell4 & cell5 & cell6 \\
cell7 & cell8 & cell9 \\
\hline
\end{tabular}
\end{center}

Graphic displaying a table typeset in LaTeX containing horizontal and vertical rules

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
\begin{center}
\begin{tabular}{||c c c c||}
\hline
Col1 & Col2 & Col2 & Col3 \\ [0.5ex]
\hline\hline
1 & 6 & 87837 & 787 \\
\hline
2 & 7 & 78 & 5415 \\
\hline
3 & 545 & 778 & 7507 \\
\hline
4 & 545 & 18744 & 7560 \\
\hline
5 & 88 & 788 & 6344 \\ [1ex]
\hline
\end{tabular}
\end{center}

Graphic displaying a table typeset in LaTeX containing horizontal and vertical rules

Tip!

  • Creating tables in LATEX can be time-consuming so you may want to use the TablesGenerator.com online tool to export LATEX code for tabulars.

Captions, labels and references

  • You can caption and reference tables in much the same way as images. The only difference is that instead of the figure environment, you use the table environment.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Table \ref{table:data} shows how to add a table caption and reference a table.
\begin{table}[h!]
\centering
\begin{tabular}{||c c c c||}
\hline
Col1 & Col2 & Col2 & Col3 \\ [0.5ex]
\hline\hline
1 & 6 & 87837 & 787 \\
2 & 7 & 78 & 5415 \\
3 & 545 & 778 & 7507 \\
4 & 545 & 18744 & 7560 \\
5 & 88 & 788 & 6344 \\ [1ex]
\hline
\end{tabular}
\caption{Table to test captions and labels.}
\label{table:data}
\end{table}

A LaTeX table with a caption

Adding a Table of Contents

Creating a table of contents is straightforward because the command \tableofcontents does almost all the work for you

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
\documentclass{article}
\title{Sections and Chapters}
\author{Gubert Farnsworth}
\date{August 2022}
\begin{document}

\maketitle

\tableofcontents

\section{Introduction}

This is the first section.

Lorem ipsum dolor sit amet, consectetuer adipiscing
elit. Etiam lobortisfacilisis sem. Nullam nec mi et
neque pharetra sollicitudin. Praesent imperdietmi nec ante.
Donec ullamcorper, felis non sodales...

\section*{Unnumbered Section}
\addcontentsline{toc}{section}{Unnumbered Section}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Etiam lobortis facilisissem. Nullam nec mi et neque pharetra
sollicitudin. Praesent imperdiet mi necante...

\section{Second Section}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Etiam lobortis facilisissem. Nullam nec mi et neque pharetra
sollicitudin. Praesent imperdiet mi necante...
\end{document}

Graphic showing a table of contents produced by LaTeX

Sections, subsections and chapters are automatically included in the table of contents. To manually add entries, such as an unnumbered section, use the command \addcontentsline as shown in the example.

Downloading your finished document

On the web page download

Finding and using LaTeX packages

  • LaTeX不仅提供了重要的排版功能,而且还通过使用附加提供了可扩展性的框架

Refer to: Adding images

  • 然后引入这些包:
1
\usepackage{graphicx}

Loading packages

  • packages are loaded in the document preamble via the \usepackage command but because (many) LATEX packages provide a set of options, which can be used to configure their behaviour
1
\usepackage[options]{somepackage}
  • The square brackets “[...]” inform LATEX which set of options should be applied when it loads somepackage. Within the set of options requested by the user, individual options, or settings, are typically separated by a comma; for example, the geometry package provides many options to configure page layout in LATEX, so a typical use of geometry might look like this:
1
2
\usepackage[total={6.5in,8.75in},
top=1.2in, left=0.9in, includefoot]{geometry}
  • If a LATEX package does not provide any options, or the user wants to use the default values of a package’s options, it would be loaded like this:
1
\usepackage{somepackage}
  • When you write \usepackage[...]{somepackage} LATEX looks for a corresponding file called *somepackage*.sty, which it needs to load and process—to make the package commands available and execute any other code provided by that package. If LATEX cannot find *somepackage*.sty it will terminate with an error,
1
2
3
4
5
\documentclass[12pt, letterpaper]{article}
\usepackage{somepackage}% a NON-EXISTENT package
\begin{document}
This will fail!
\end{document}

Finding information about packages: CTAN

  • Packages怎么找,这里有些小妙招!

Packages are distributed through the Comprehensive TeX Archive Network, usually referred to as CTAN, which, at the time of writing, hosts 6287 packages from 2881 contributors. CTAN describes itself as

… a set of Internet sites around the world that offer TEX-related material for download.

Packages available on Overleaf: Introducing TeX Live

  • 发布还需要测试,可能导致CTAN上传的包在Tex Live中不可用。只有经过兼容性测试等工作,在Latex中成熟可用的时候,才会考虑在Tex Live中发布昂!给我的感觉就是:一个是仓库,一个是发行库。

Once per year a (large) subset of packages hosted on CTAN, plus LATEX-related fonts and other software, is collated and distributed as a system called TeX Live, which can be used to install your own (local) LaTeX setup. In fact, Overleaf’s servers also use TeX Live and are updated when a new version of TeX Live is released. Overleaf’s TeX Live updates are not immediate but take place a few months post-release, giving us time to perform compatibility tests of the new TeX Live version with the thousands of templates contained in our gallery. For example, here is our TeX Live 2022 upgrade announcement.

Although TeX Live contains a (large) subset of CTAN packages it is possible to find an interesting package, such as igo for typesetting Go diagrams, which is hosted on CTAN but not included in (distributed by) TeX Live and thus unavailable on Overleaf. Some packages hosted on CTAN are not part of TeX Live due to a variety of reasons: perhaps a package is obsolete, has licensing problems, is extremely new (recently uploaded) or has platform dependencies, such as working on Windows but not Linux.

New packages, and updates to existing ones, are uploaded to CTAN all year round but updates to TeX Live are distributed annually; consequently, packages contained in the current version of TeX Live will not be as up-to-date as those hosted on CTAN. Because Overleaf’s servers use TeX Live it is possible that packages installed on our servers—i.e., ones available to our users—might not be the very latest versions available on CTAN but, generally, this is unlikely to be problematic.

References

  1. Latex Learn: https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes
  2. Latex Website: https://www.latex-project.org/
  3. Latex topics: https://www.ctan.org/topic/class
  4. Page size and margins: https://www.overleaf.com/learn/latex/Page_size_and_margins
  5. Finding and Using Latex packages: https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes#Finding_and_using_LaTeX_packages
  6. Including files in latex: https://www.overleaf.com/learn/how-to/Including_images_on_Overleaf
  7. Positioning of Figures
  8. Inserting Images
  9. Latex help list: https://www.overleaf.com/learn/latex/Lists
  10. amsmath help page: https://www.overleaf.com/learn/latex/Aligning_equations_with_amsmath
  11. The possibilities with math in LATEX are endless so be sure to visit our help pages for advice and examples on specific topics:
  12. new line is important:
  13. article about sections and chapters
  14. TablesGenerator.com helps generating table in latex code
  15. Adding images
  16. geometry package

Latex学习
https://alexanderliu-creator.github.io/2023/07/19/latex-xue-xi/
作者
Alexander Liu
发布于
2023年7月19日
许可协议