How to write latex in latex
How to write latex in latex
How to Write a Thesis in LaTeX (Part 1): Basic Structure
Author: Josh Cassidy (August 2013)
This five-part series of articles uses a combination of video and textual descriptions to teach the basics of writing a thesis using LaTeX. These tutorials were first published on the original ShareLateX blog site during August 2013; consequently, today’s editor interface (Overleaf) has changed considerably due to the development of ShareLaTeX and the subsequent merger of ShareLaTeX and Overleaf. However, much of the content is still relevant and teaches you some basic LaTeX—skills and expertise that will apply across all platforms.
Your thesis could be the longest and most complicated document you’ll ever write, which is why it’s such a good idea to use L a T e X instead of a common word processor. L a T e X makes tasks that are difficult and awkward in word processors, far simpler.
Contents
The preamble
We can also change the font size by adding square brackets into the \documentclass command and specifying the size—we’ll choose 12pt. Let’s also prepare the document for images by loading the graphicx package. We’ll also need to tell L a T e X where to look for the images using the \graphicspath command, as we’re storing them in a separate folder.
The start of our preamble now looks like this:
Now we can finish off the preamble by filling in the title, author and date information. To create the simplest title page we can add the thesis title, institution name and institution logo all into the \title command; for example:
This isn’t the best way to alter the title page so we’ll look at more elaborate ways of customising title pages later on in the series, but this will suffice for now.
This is what the \maketitle command now produces for us:
The frontmatter
After the title page we need to add in an abstract, dedication, declaration and acknowledgements section. We can add each of these in on separate pages using unnumbered chapters. To do this we use the \chapter command and add an asterisk. After these sections we’ll add a table of contents using the \tableofcontents command:
The main body
Then to add these chapters into the document, we use the \input command in the root document. Remember to add in chapters/ before the file name so that L a T e X knows where to find it.
The endmatter
We will now add in an appendix at the end of the document. To do this we use the \appendix command to tell L a T e X that what follows are appendices. Again We’ll write the appendix in a separate file and then input it.
If we now compile the document, all our chapters will be added to the document and the table of contents will be automatically generated.
Now we have a basic structure for a thesis set up. In the next post I will show you how to change the page layout and add headers.
Learn LaTeX in 30 minutes
Contents
L a T e X (pronounced LAY-tek or LAH-tek) is a tool used to create professional-looking documents. It is based on the WYSIWYM (what you see is what you mean) idea, meaning you only have focus on the contents of your document and the computer will take care of the formatting. Instead of spacing out text on a page to control formatting, as with Microsoft Word or LibreOffice Writer, users can enter plain text and let L a T e X take care of the rest.
One of the most important reasons people use L a T e X is that it separates the content of the document from the style. This means that once you have written the content of your document, we can change its appearance with ease. Similarly, you can create one style of document which can be used to standardise the appearance of many different documents. This allows scientific journals to create templates for submissions. These templates have a pre-made layout meaning that only the content needs to be added. In fact there are hundreds of templates available for everything from CVs to slideshows.
Writing your first piece of L a T e X
The first step is to create a new L a T e X project. You can do this on your own computer by creating a new .tex file, or else you can start a new project in Overleaf. Let’s start with the simplest working example:
You can see that L a T e X has already taken care of the first piece of formatting for you, by indenting the first line of the paragraph. Let’s have a close look at what each part of our code does.
After this, you write the content of our document, enclosed inside the \begin and \end tags. This is known as the body of the document. You can start writing here and make changes to the text if you wish. To see the result of these changes in the PDF you have to compile the document. To do this in Overleaf, simply hit Recompile. (You can also set your project to automatically recompile when you edit your files, by clicking on the small arrow next to the ‘Recompile button and set ‘Auto Compile to ‘On.)
If you are using a basic text editor such as gedit, emacs, vim, sublime, notepad etc., you will have to compile the document manually. To do this, simply run pdflatex in your computers terminal/command line. See here for more information on how to do this.
If you are using a dedicated LaTeX editor such as TeXmaker or TeXworks, simply hit the Recompile button. Consult the programs documentation if you are unsure of where this is.
Now that you have learnt how to add content to our document, the next step is to give it a title. To do this, we must talk briefly about the preamble.
The preamble of a document
In the previous example the text was entered after the \begin command. Everything in your .tex file before this point is called the preamble. In the preamble you define the type of document you are writing, the language you are writing in, the packages you would like to use (more on this later) and several other elements. For instance, a normal document preamble would look like this:
Below a detailed description of each line:
Adding a title, author and date
To add a title, author and date to our document, you must add three lines to the preamble (NOT the main body of the document). These lines are
\title
With these lines added, your preamble should look something like this
Now that you have given your document a title, author and date, you can print this information on the document with the \maketitle command. This should be included in the body of the document at the place you want the title to be printed.
Adding comments
Bold, italics and underlining
We will now look at some simple text formatting commands.
An example of each of these in action is shown below:
Moreover, some packages, e.g. Beamer, change the behaviour of \emph command.
Adding images
We will now look at how to add images to a L a T e X document. On Overleaf, you will first have to upload the images.
Below is a example on how to include a picture.
The command \graphicspath <
The \includegraphics command is the one that actually included the image in the document. Here universe is the name of the file containing the image without the extension, then universe.PNG becomes universe. The file name of the image should not contain white spaces nor multiple dots.
Note: The file extension is allowed to be included, but it’s a good idea to omit it. If the file extension is omitted it will prompt LaTeX to search for all the supported formats. It is also usually recommended to use lowercase letters for the file extension when uploading image files. For more details see the section about generating high resolution and low resolution images.
Captions, labels and references
Images can be captioned, labelled and referenced by means of the figure environment as shown below:
There are three important commands in the example:
When placing images in a L a T e X document, we should always put them inside a figure environment or similar so that L a T e X will position the image in a way that fits in with the rest of your text.
Note: If you are using captions and references on your own computer, you will have to compile the document twice for the references to work. Overleaf will do this for you automatically.’
Creating lists in L a T e X
There are two main different types of lists, ordered lists and unordered lists. Each will use a different environment.
Unordered lists
Unordered lists are produced by the itemize environment. Each entry must be preceded by the control sequence \item as shown below.
By default the individual entries are indicated with a black dot, so-called bullet. The text in the entries may be of any length.
Ordered lists
Ordered list have the same syntax inside a different environment. We make ordered lists using the enumerate environment:
Adding math to L a T e X
One of the main advantages of L a T e X is the ease at which mathematical expressions can be written. L a T e X allows two writing modes for mathematical expressions: the inline mode and the display mode. The first one is used to write formulas that are part of a text. The second one is used to write expressions that are not part of a text or paragraph, and are therefore put on separate lines. Let’s see an example of the inline mode:
The displayed mode has two versions: numbered and unnumbered.
Important Note: equation* environment is provided by an external package, consult the amsmath article.
Many math mode commands require the amsmath package, so be sure to include it when writing math. An example is shown below of some basic math mode commands.
The possibilities with math in L a T e X are endless and it is impossible to list them all here. Be sure to check out our other articles on
Basic Formatting
We will now look at how to write abstracts, as well as how to format a L a T e X document into different chapters, sections and paragraphs.
Abstracts
In scientific documents it’s a common practice to include a brief overview of the main subject of the paper. In L a T e X there’s the abstract environment for this. The abstract environment will put the text in a special format at the top of your document.
Paragraphs and newlines
When writing the contents of your document, if you need to start a new paragraph you must hit the «Enter» key twice (to insert a double blank line). Notice that L a T e X automatically indents paragraphs.
To start a new line without actually starting a new paragraph insert a break line point, this can be done by \\ (a double backslash as in the example) or the \newline command.
You can find more information in the Paragraphs and new lines article.
Chapters and Sections
Commands to organize a document vary depending on the document type, the simplest form of organization is the sectioning, available in all formats.
-1 | \part |
0 | \chapter |
1 | \section |
2 | \subsection |
3 | \subsubsection |
4 | \paragraph |
5 | \subparagraph |
Note that \part and \chapter are only available in report and book document classes.
For a more complete discussion about the document structure see the article about sections and chapters.
Creating tables
Creating a simple table in L a T e X
Below you can see the simplest working example of a table
Adding borders
The tabular environment is more flexible, you can put separator lines in between each column.
Below you can see a second example.
Creating tables in L a T e X can be a bit tricky sometimes, so you may want to use the TablesGenerator.com online tool to export L a T e X code for tabulars. The File > Paste table data option lets you copy and paste data from spreadsheet applications.
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.
Note: If you are using captions and references on your own computer, you will have to compile the document twice for the references to work. Overleaf will do this for you automatically.’
Adding a Table of Contents
To create the table of contents is straightforward, the command \tableofcontents does all the work for you:
Sections, subsections and chapters are automatically included in the table of contents. To manually add entries, for example when you want an unnumbered section, use the command \addcontentsline as shown in the example.
Downloading your finished document
You can download your finished PDF from the left hand menu as above by clicking PDF. There is also the quicker option of clicking the Download PDF button on your PDF viewer as shown below.
Осваиваем LaTeX за 30 минут
Что такое LaTeX?
LaTEX (произносится как «лэйтех» или «латех») представляет собой инструмент для создания профессиональных документов. В его основе лежит парадигма редактирования WYSIWYM (что вижу, то и подразумеваю), то есть от пользователя требуется сосредоточиться только на содержимом документа, оставив его форматирование программе. Вместо ручного распределения текста по странице, как это делается в Microsoft Word или LibreOffice Writer, можно просто его вводить, позволив LaTeX заняться остальным.
Зачем нужен LaTeX?
Этот инструмент используется повсеместно для создания научных документов, написания книг, а также многих других форм публикаций. Он позволяет не только создавать красиво оформленные документы, но также дает пользователям возможность очень быстро реализовывать такие сложные элементы печатного набора, как математические выражения, таблицы, ссылки и библиографии, получая согласованную разметку по всем разделам.
Благодаря доступности большого числа открытых библиотек (об этом чуть позже) возможности LaTEX становятся практически безграничны. Эти библиотеки расширяют возможности пользователей еще больше, позволяя добавлять сноски, рисовать схемы и пр.
Одна из наиболее веских причин, по которой многие используют LaTeX, заключается в отделении содержания документа от его стиля. Это означает, что после написания содержимого, можно с легкостью изменять его внешний вид. Аналогичным образом, можно создать один стиль документа и использовать его для стандартизации внешнего вида других.
Это позволяет научным журналам создавать шаблоны для предлагаемых на рассмотрение материалов. Такие шаблоны имеют заданную разметку, в результате чего добавить остается лишь содержание. На деле существуют сотни подобных шаблонов, начиная с различных резюме и заканчивая презентациями слайдов.
Пишем первый документ
Здесь мы видим, что LaTeX уже позаботился о первом элементе форматирования, сделав отступ в начальной строке абзаца. Теперь более подробно рассмотрим, за что отвечает каждая часть кода.
После этого мы пишем содержание документа, заключенное в теги \begin
Чтобы увидеть результат этих изменений в PDF, документ нужно скомпилировать. В Overleaf для этого нужно просто нажать Recompile. (Также можете настроить проект на автоматическую перекомпиляцию в процессе редактирования файлов, нажав на небольшую стрелку рядом с кнопкой Recompile и установив Auto Compile как On).
При использовании специального редактора LaTeX вроде TeXmaker или TeXworks нужно просто нажать кнопку Recompile. Если не знаете, где она находится, обратитесь к документации.
Теперь, когда вы разобрались, как добавлять в документ содержимое, следующим шагом будет его именование. Для этого необходимо вкратце разобрать преамбулу.
Преамбула документа
А вот подробное разъяснение каждой строки:
Эта команда задает кодировку документа. Ее можно опустить либо изменить на другой вариант, но рекомендуется использовать именно utf-8. Если вам не требуется конкретно другая кодировка, либо вы просто не уверены, то добавьте эту строку во вступление.
Добавление заголовка, автора и даты
Для добавления в документ заголовка, автора и даты необходимо внести во вступление три строки (только не в основное тело документа):
Здесь размещается имя автора. При желании можно также добавить в фигурные скобки следующую команду:
После добавления перечисленных строк преамбула должна выглядеть так:
Добавление комментариев
Как и в случае с любым кодом, зачастую будет нелишним добавлять комментарии. Комментарии – это включаемые в документ текстовые элементы, которые в итоге не отображаются и никак не него не влияют. Они помогают организовывать работу, делать пометки или закомментировать (отключать) строки/разделы при отладке. Чтобы создать комментарий в LaTeX, просто наберите символ % в начале строки, как показано ниже:
Жирный, курсив и подчеркивание
А вот еще одна очень простая команда: \emph <. >. Выполняемые ей для аргумента действия определяются контекстом – внутри обычного текста его выделенная часть переводится в курсив, а при использовании команды в курсивном тексте происходит обратное.
Добавление изображений
В Overleaf для добавления изображений их сначала нужно будет загрузить.
Команда \graphicspath <
Примечание: расширение файла включить можно, но лучше его опустить. В этом случае LaTeX будет искать все поддерживаемые форматы. Также при загрузке файлов обычно рекомендуется указывать расширение в нижнем регистре.
Подписи, метки и ссылки
С помощью окружения figure изображения можно подписывать, размечать, а также делать на них ссылки:
В примере выше показаны три важные команды:
Примечание: если вы используете подписи и ссылки на собственном компьютере, то вам потребуется скомпилировать документ дважды, чтобы они сработали. Overleaf делает это автоматически.
Создание списков
Списки в LaTeX создаются очень просто. Делается это с помощью различных окружений списков. Окружения – это разделы, которые требуется представить отличным от остальной части документа образом. Начинаются они с \begin <. >, а завершаются на \end <. >.
Существует два основных типа списков: упорядоченные и неупорядоченные. Каждый из них реализуется в собственном окружении.
Неупорядоченные списки
По умолчанию отдельные записи обозначаются черной точкой, или буллетом. Текст в записях может иметь неограниченную длину.
Упорядоченные списки
Для упорядоченных списков используется тот же синтаксис, но в другом окружении. В данном случае этим окружением выступает enumerate :
Добавление математических выражений
Одно из главных удобств LaTeX состоит в простоте использования математических выражений. Этот инструмент предоставляет два режима их написания: режим inline (встраивание) и режим display (отображение). Первый используется для написания формул, являющихся частью текста. Второй позволяет создавать выражения, не входящие в состав текста или абзаца, а размещаемые на отдельных строках. Вот пример режима встраивания:
Режим отображения предлагает два варианта: без нумерации и с нумерацией.
Важно: окружение equation* предоставляется в виде стороннего пакета. Подробнее об этом рекомендую почитать статью по amsmath.
Для использования многих команд при работе с математикой необходим пакет amsmath, поэтому не забудьте его добавить. Ниже показан пример некоторых его базовых команд:
Возможности использования математики в LaTeX безграничны, и перечислить их все здесь просто нереально. Так что рекомендую дополнительно почитать соответствующие материалы по теме:
Базовое форматирование
Теперь разберем написание аннотаций, а также форматирование документов LaTeX в разных главах, разделах и абзацах.
Аннотации
Абзацы и перевод строки
Когда при написании документа вам требуется начать новый абзац, нужно дважды нажать «Ввод», вставив таким образом двойную пустую строку. Имейте ввиду, что отступ абзацев LaTeX делает автоматически.
Чтобы создать новую строку без создания очередного абзаца нужно вставить точку разрыва строки, для чего используется \\ (двойной обратный слэш, как в примере) или команда \newline.
При этом не следует использовать несколько \\ или \newline для «имитации» абзацев с увеличенными интервалами между ними, так как это приведет к конфликту с внутренними алгоритмами LaTeX. Для подобного эффекта рекомендуется использовать двойные пустые строки, после чего добавлять во вступление \usepackage
Дополнительную информацию по теме можно найти в статье Paragraphs and new lines.
Главы и разделы
Команды для организации документа варьируются в зависимости от его типа. Простейшей формой организации выступает деление на разделы, доступное во всех форматах.
Более подробный разбор структуры документа описан в статье Sections and Chapters.
Создание таблиц
Простые таблицы
Вот простейший пример создания таблицы:
Добавление границ
Окружение tabular достаточно гибкое и позволяет размещать разделяющие строки между каждым столбцом.
Подписи, метки и ссылки
Примечание: если вы используете подписи и ссылки на своем компьютере, то для работоспособности ссылок нужно будет скомпилировать документ дважды. Overleaf делает это автоматически.
Добавление содержания
Процесс создания содержания очень прост и реализуется командой \tableofcontents :
Скачивание готового документа
Завершенный документ в формате PDF можно скачать через расположенное слева меню, кликнув PDF.
Есть и более быстрый способ через нажатие кнопки Download PDF в окне просмотра PDF, как показано ниже:
Mathematical expressions
Contents
Introduction
LaTeX’s features for typesetting mathematics make it a compelling choice for writing technical documents. This article shows the most basic commands needed to get started with writing maths using LaTeX.
Writing basic equations in LaTeX is straightforward, for example:
Mathematical modes
L a T e X allows two writing modes for mathematical expressions: the inline math mode and display math mode:
Inline math mode
You can use any of these «delimiters» to typeset your math in inline mode:
They all work and the choice is a matter of taste, so let’s see some examples.
Display math mode
Use one of these constructions to typeset maths in display mode:
Display math mode has two versions which produce numbered or unnumbered equations. Let’s look at a basic example:
Another example
The following example uses the equation* environment which is provided by the amsmath package—see the amsmath article for more information.
Reference guide
Below is a table with some common maths symbols. For a more complete list see the List of Greek letters and math symbols:
Different classes of mathematical symbols are characterized by different formatting (for example, variables are italicized, but operators are not) and different spacing.
Further reading
The mathematics mode in LaTeX is very flexible and powerful, there is much more that can be done with it:
Basic Code
Special keys
Many script-languages use backslash «\» to denote special commands. In LaTeX backslash is used to generate a special symbol or a command.
Curly brackets are used to group characters.
Hat and underscore are used for superscripts and subscripts.
Superscripts, subscripts and groups of characters
Formula | LaTeX-code |
---|---|
\(x^2\) | x^2 |
\(x^ <2+a>\) | x^ |
\(n_1 \) | n_1 |
\(n_ | n_ |
\(n_ | n_ |
\(e^ | e^ |
Arithmetics
By convention you should either not write a multiplication-sign at all, as in \(y=mx+c\); or you should write it using a vertically centered dot, as in \(3\cdot5=15\). Do not use symbols like «*»! In LaTeX you use the command \cdot to make a multiplication-dot.
Sometimes you can use the symbol \(\times\). A matrix having \(n\) rows and \(m\) columns is a \(m\times n\)-matrix. The code \times is used in LaTeX to make the symbol \(\times\).
The square root symbol is written using the command \sqrt
The square root of a number can never be negative by definition. The root of a quadratic equation however, can be either positive or negative. The solution to the equation \(x^2=4\) is given by \(x = \pm 2\). The symbol \(\pm\) is written using the code \pm in LaTeX.
Formula | LaTeX-code |
---|---|
\(3\cdot5=15 \) | 3\cdot5=15 |
\(n\times m \) | n\times m |
\(\pm 2 \) | \pm 2 |
\(2\div 3 \) | 2\div 3 |
\(\frac<2> <3>\) | \frac |
\(\sqrt <2>\) | \sqrt |
\(\sqrt[3]<8>=8^<\frac<1><3>>=2 \) | \sqrt[3]<8>=8^<\frac<1><3>>=2 |
\(\frac<2> <4>\) | \frac<2> <4> |
\(\frac<\frac<2><3>><\frac<4><5>> \) | \frac<\frac<2><3>><\frac<4><5>> |
\(\frac<\dfrac<2><3>><\dfrac<4><5>> \) | \frac<\dfrac<2><3>><\dfrac<4><5>> |
Standard functions
By convention, variables are written in italics. For that reason all text when writing in math mode is in italics. In some cases however, the text should not be in italics. One such example is the mathematical standard functions.
Formula | LaTeX-code |
---|---|
\(lne^x = x \) (wrong by convention) | lne^x = x |
\(\ln e^x = x \) (correct by convention) | \ln e^x = x (note the space after \ln ) |
There are commands for all standard functions; here are some examples:
\sin \cos \tan \arcsin \arccos \arctan \ln \log
Text in math mode
Sometimes you need text that isn’t written in italics even though it’s written in math mode.
Formula | LaTeX-code |
---|---|
\( 3\text< apples>\times 5\text < apples>\) | 3\text< apples>\times 5\text |
Brackets
Some brackets are written using regular keyboard strokes, such as these: (), [], ||.
| is written by using option + 7 on a Mac, and Alt Gr + on Windows/Linux. How to write various special characters using a Mac, is shown here.
Integrals, series and limits
When writing integrals, series using sigma-notation or limits; you often want to specify boundaries. You use the same characters as are used for subscripts and superscripts when specifying boundaries.
The commands used are \int for integral, \sum for sigma-notation, \lim for limits and \prod products.
Formula | LaTeX-code | ||||
---|---|---|---|---|---|
\( \int_0^2x^2dx \) | \int_0^2x^2dx | ||||
\( \int\limits_ | \int\limits_ | ||||
\( \sum_^ | \sum_^\( \lim_ | \lim_ | \( \prod_^ni=n! \) | \prod_^ni=n! | |
Using display it looks like this:
Spaces
In math mode you don’t get a space when using space bar, white spaces are simply ignored. If you need a space, there are three commands; \, for a short space, \: for a medium space and \; for a long space. If you want to reduce the space between two characters, you use the command \! ; this command is useful for reducing the space between the integral-sign and the integrand.
Formula | LaTeX-code |
---|---|
\( a b \) | a b |
\( a\: b \) | a\: b |
\( \int\limits_ | \int\limits_ |
\( \int\limits_ | \int\limits_ |
by Malin Christersson under a Creative Commons Attribution-Noncommercial-Share Alike 2.5 Sweden License