learn latex – Terminally Incoherent http://www.terminally-incoherent.com/blog I will not fix your computer. Wed, 05 Jan 2022 03:54:09 +0000 en-US hourly 1 https://wordpress.org/?v=4.7.26 Let’s Learn LaTex: Part 7 http://www.terminally-incoherent.com/blog/2014/03/26/lets-learn-latex-part-7/ http://www.terminally-incoherent.com/blog/2014/03/26/lets-learn-latex-part-7/#comments Wed, 26 Mar 2014 14:02:50 +0000 http://www.terminally-incoherent.com/blog/?p=16618 Continue reading ]]> Let’s talk about embedding code snippets in your LaTex documents. All of us here are programmers (except for those who aren’t) so this is a natural thing we might want to do. Despite being built by programmers for programmers, LaTex doesn’t really have a code mode. Knuth spent around a lot of time on making sure that Tex is the best tool around for typesetting math equations, which was probably a good choice. After all, math is the universal language of science and formulas are the “meat” of any serious research paper. This goes double for Computer Science papers which should be liberally sprinkled with it. Snippets of code are “implementation details” and thus of little importance in the grand scheme of things.

Still, embedding code in documents is something we may want to do. The traditional method is using the verbatim environment which respect white space and creates a nice, preformated, mono-spaced code blocks. For example, lets take the following snippet:

\noindent Here is a code snippet in Python:

\begin{verbatim}
# Hello world
def Hello():
    foo = 10
    print "Hello World!"
\end{verbatim}

Upon compiling, it will look like this:

Verbatim Environment

Verbatim Environment

While this is not terribly impressive, it is good enough for most research papers. That said, if you are using LaTex for writing manuals, homeworks or school papers you might want your code blocks to be a little bit more flashy. Perhaps they could include line numbers, and some color. How do you do that?

With a package of course. There are a number of different packages that offer this kind of functionality, but my favorite is probably the one named lstlistings. It is not the most powerful or flexible one, but it does not have any dependencies (except maybe the color package), does not rely on external tools and it is easy to use.

You include it in your preamble like this:

\usepackage{listings}
\usepackage{color}

Then you put your code snippet inside the lstlisting environment instead of verbatim:

\noindent Here is a code snippet in Python:

\begin{lstlisting}
# Hello world
def Hello():
    foo = 10
	print "Hello World!"
\end{lstlisting}

The result is rather unimpressive:

Listings Package

Listings package without any configuration.

Yes, it does actually look worse than the verbatim environment, but that’s only because we have never configured it. You see, the lstlistings package is old school, and like many LaTex packages it adheres to the fuck reasonable defaults philosophy. The idea behind this attitude is simple: the user should know what they are doing, or else go die in a fire. Yes, I know – it’s charming. But what are you gonna do? Go back to using Microsoft Word? I didn’t think so.

Configuring our code environment is actually not a major pain in the ass. You basically need to include a short lstset block somewhere in the preamble. It can be as brief or as detailed as you want. I typically go with something like this:

\lstset{ %
	language=python,
	numbers=left,
	frame=single,
	showstringspaces=true,
        basicstyle=\ttfamily,
       	keywordstyle=\color{blue}\ttfamily\textbf,
	identifierstyle=\color{magenta}\ttfamily,
	stringstyle=\color{red}\ttfamily,
	commentstyle=\color{cyan}\ttfamily\textit
}

The above will set the default language for all the code blocks in the document to be python (don’t worry, this can be overriden), toggles on line numbers, puts a border (frame) around the code and sets up some basic font and color formatting. You should remember commands like \textbf from Part 2. The color related commands are provided by the color package.

The resulting code block will look like this:

Listings Package

Listings package with config.

The lstlistings package makes up for having no useful defaults by being very configurable. You can control just about any aspect of the way your code is displayed. You not only have control over fonts and colors, but you can mess around with the line numbers, visual indicators for whitespace characters, and change which words are treated as keywords. Here is a nearly complete list of config options you may find useful:

\lstset{ %
  language=python,                 % the language of the code
  basicstyle=\ttfamily,        	   % style for all of the code
  keywordstyle=\color{blue},       % keyword style
  identifierstyle=\color{magenta}, % style for variables and identifiers
  commentstyle=\color{green},      % comment style
  stringstyle=\color{mymauve},     % style for string literals

  tabsize=2,                       % sets default tabsize (in spaces)
  backgroundcolor=\color{white},   % requires the color package
  frame=single,                    % put a border around the code

  numbers=left,                    % line numbers (none, left, right)
  numberstyle=\tiny\color{red},    % the style that is used for line numbers
  numbersep=5pt,                   % how far the line-numbers are from the code 
  
  showspaces=false,                % visibly indicate spaces everywhere
  showstringspaces=false,          % visibly indicate spaces within strings only
  showtabs=false,                  % visibly indicate tabs within strings
  
  breaklines=true,                 % toggle automated line wrapping
  breakatwhitespace=false,         % if wrapping is on, enable to break on whitespace only

  deletekeywords={...},            % exclude keywords from chosen language
  morekeywords={*,...},            % add words to be treated as keywords
      
  captionpos=b                     % sets the caption-position (bottom)
}

The package supports a good number of languages out of the box. All the popular ones are represented, alongside some rather obscure ones (like Motorola assembler). Here is a table of languages ripped straight out of the manual:

Supported Languages

Supported Languages. Dialects are listed in parentheses with defaults underlined. If there is no default, dialect must be specified.

Dialects are listed in parentheses, with the defaults being underlined. As you probably noticed, not all languages that have dialects include a default (because fuck defaults, remember?). For those languages you must specify one in the declaration. The method of doing it is rather awkward:

\lstset{
	language={[x86masm]Assembler}
}

It doesn’t look pretty, but it works.

I mentioned before that you can override the language setting. You can also skip it from the preamble declaration, but putting it there is usually a good idea. In most documents you will be posting snippets in the same language over and over again, so this saves you typing. If you want to use a different language, or you did not specify one in preamble, you will need to include it as an optional argument when you open the lstlisting environment like this:

\begin{lstlisting}[language=ruby]
	puts "Hello World!"
\end{lstlisting}

You can also override any of the other options this way. Just list them after the language declaration.

If you are super lazy, and can’t be bothered to copy and paste a code snippet into your paper, you can include it using the \lstinputlisting command. It has one mandatory argument which is the file name:

\lstinputlisting[language=python, firstline=7, lastline=18]{filename.py}

You can specify any regular \lstset settings as optiononal arguments. The firstline and lastline arguments can be used to import only a part of the file. If you skip them, the entire file will be embedded.

Let’s Learn LaTex
<< Prev Next >>
]]>
http://www.terminally-incoherent.com/blog/2014/03/26/lets-learn-latex-part-7/feed/ 2
Let’s Learn LaTex: Part 6 http://www.terminally-incoherent.com/blog/2013/09/09/lets-learn-latex-part-6/ http://www.terminally-incoherent.com/blog/2013/09/09/lets-learn-latex-part-6/#respond Mon, 09 Sep 2013 14:05:52 +0000 http://www.terminally-incoherent.com/blog/?p=15511 Continue reading ]]> In Part 4 we talked about the tabular environment which, as I mentioned, is more or less equivalent to tables in HTML. There is another popular way to typeset tabulated data in LaTex which emulates a feature that simply does not exist in HTML but is commonly seen in word processors. I’m talking about tab stops.

There is a funny feature in Microsoft Word, known as the tab ruler. It is typically located on a little strip at the top of the editing window. It is funny because I have yet to meet a MS Office user who actually knew what it was for and how to use it. Pretty much all Word users assume that hitting the Tab key simply advances the cursor a fix amount of space to the right, except for when it does not. They figure it is one of those eternally unresolved computer mysteries. Word of course tells you exactly where it will place the cursor when you tab over. It places it at the nearest tab stop to the righgt. By default these tab stops are visible on the ruler – I highlighted them for you in the screen shot below:

Tab Stops in MS Word

Tab Stops in MS Word

Default tab stops are evenly spaced half an inch apart which would be kinda limiting if you couldn’t override them. But you can, by simply clicking on the ruler and leaving these L shaped marks which override default tab stops. This feature allows you to properly line up your variable with font text without leaving too much hassle. Until you realize that like most features in word, depending on cursor location and context the setting may be global, per paragraph or per line leading to all kinds of hilarious formatting mishaps.

In LaTex you can achieve a similar effect using the tabbig environment. Except it is much clearer, and it gives you much better control as to where the tab stops are placed. Basically you set them by example like this:

\begin{tabbing}
   This is a long line: 	\= 1254 \\
   Another line:		\> 5785 \\
   Short line:			\> 5747 \\
\end{tabbing}

The \= sequence sets a tab stop at the current position and the \> advances the text that follows to the next tab stop position. The result looks like this:

Tabbing Output

Tabbing Output

As with most LaTex environments, the white space in tabbing is meaningless and the actual length of the line defines the position of the tab stop. So in the example above everything aligns to the length of the first line. This can sometimes be problematic, seeing how the first line in your list does not always have to be the longest one:

\begin{tabbing}
   This is a long line: 		\= 1254 \\
   Another line:			\> 5785 \\
   Short line:				\> 5747 \\
   This one is even longer:		\> 1457 \\
\end{tabbing}

This code will produce an ugly, overlapping effect:

Tab Overlap

Tab Overlap

If you run into this sort of an issue you can often resolve it by applying some padding to the first line using the \hspace command. In case you haven’t guessed it, the command is short for horizontal space and int inserts exactly that into your document. It takes one parameter as a required argument, and it must be a number with a unit of measurement indicator (ie 1in, 2cm, 3em, etc..):

\begin{tabbing}
   This is a long line: \hspace{3em}	\= 1254 \\
   Another line:			\> 5785 \\
   Short line:				\> 5747 \\
   This one is even longer:		\> 1457 \\
\end{tabbing}

The 3em padding before the tab stop will provide adequate spacing for all the lines now:

Using Padding

Using Padding

Inserting a \hspace command into the first line is convenient, but not always ideal. The downside is that it “pollutes” the actual data with irrelevant positioning and formatting code. Frequently you will want your actual data to be de-coupled with the formatting markup that surrounds it.

If you know the approximate width of you longest line, you can make an invisible heading line that will set the tab stops without being displayed by ending it with the \kill command. It works the same as \\ but suppresses printing of the line while maintaining the tab stops it sets:

\begin{tabbing}
   \hspace{12em} 	 	\= \kill
   This is a long line: 	\> 1254 \\
   Another line:		\> 5785 \\
   Short line:			\> 5747 \\
   This one is even longer:	\> 1457 \\
\end{tabbing}

There are also \+ and \- commands that indent and un-indent all following lines by a tab stop. The former is equivalent of starting each line that follows it with a single \>. As an example of how to use these two operators, take this snippet of code taken directly from my syllabus:

\begin{tabbing}

   \textbf{Class Schedule:} \= \\
   \+\kill % indent everything

	\hspace{3em}	\= \hspace{8em}		\=	\hspace{5em}	\= \kill
	Thu. 		\> 8:15PM-9:30PM 	\>	(RI108) 	\> Lab Session \\ 
	Thu. 		\> 9:30PM-10:45PM 	\> 	(RI118) 	\> Lecture Session \\

   \< \textbf{Office Hours:} \\
     	Thu. 		\> 7:00PM-8:00PM 	\> RI320\\

\end{tabbing}

The above will produce output that looks something like this:

Tabbing with Indents

Tabbing with Indents

Note how in line 4 I use the \+ indent operator, and then everything below automatically start one tab stop to the right. This actually saves me a lot of typing (and potential formatting issues later) since I no longer have to preface every other line with \>. Instead I just stick \< in front of line 10 (the office hours heading) to shift it back one tab stop to the left so that it is in the same position as line 3.

Note that I could have easily put the \+ on line 3, immediately after the tab stop and it would have worked just as well. However since this command affects everything below it, I like to put it on it’s own suppressed line just so that it is painfully obvious what is happening. Otherwise it is easy to miss, and if I come back and start shifting things around later I might be in for a nasty surprise when stuff breaks unexpectedly.

Let’s Learn LaTeX
<< Prev Next >>
]]>
http://www.terminally-incoherent.com/blog/2013/09/09/lets-learn-latex-part-6/feed/ 0
Let’s Learn Latex: Part 5 http://www.terminally-incoherent.com/blog/2012/12/14/lets-learn-latex-part-5/ http://www.terminally-incoherent.com/blog/2012/12/14/lets-learn-latex-part-5/#comments Fri, 14 Dec 2012 15:03:24 +0000 http://www.terminally-incoherent.com/blog/?p=13230 Continue reading ]]> LaTeX is fully extensible. Just about every command you can think of can be overloaded and redefined in your document. Or the document class definition. Or a custom made package file. This is the beauty of this system. You can start creating great looking documents just using the base system, and if you need to do something fancy you can start pulling in third party modules and code that adds more and more functionality. At the same time, if you ever figure out how to do something very unorthodox and difficult, you can abstract that code into a package you can reuse at a later time.

What is a LaTeX package? Well, it is a file with the extension *.sty which contains some code that either defines new commands, redefines existing ones or provides some other new functionality to the base system. You drop this file in the same directory as your document and then add a single line anywhere in your preamble:

\usepackage{my_package}

Here my_package refers to some file that will need to be named my_package.sty. Once you declare that you are using package, you can start adding the custom commands it defines immediately below. In some cases, declaring the package this way is all you need to do. For example the helvet package changes the default font to Helvetica as soon as you include it:

\documentclass{article}
\usepackage{helvet}
\begin{document}
   ...
\end{document}

There is nothing else that needs to be done after this. Other packages may require you to include some setup commands in the preamble, or trigger commands in the body. In most cases, the documentation provided with the package ought to explain these matters as there is no standard that would apply to all the diverse add-ins you can find out there online.

Once you start messing with the packages, you will probably notice that a single package is usually not enough. On average, you will likely be pulling in two to three packages per document. Sometimes more, sometimes less. If you find yourself importing the same bundle of packages time and time again, you can easily roll them into a single command like this:

\usepackage{helvet, color, graphics}

That said, it is usually beneficial to import each package separately. This way you can quickly comment out packages you don’t need while debugging or re-formatting the document. Keeping declarations on their own lines is especially important for packages which take optional arguments. For example, the geometry package can be declared like this:

\usepackage[margin=1in]{geometry}

This will immediately alter the left and right margins of the document to be exactly 1 inch in size. As you can probably guess, declaring more packages after geometry this way will actually cause an error.

What happens if you issue the \usepackage command without having downloaded it first? Well, it depends. Chances are your LaTeX installation came bundled with a dozen or so useful packages. All of the above mentioned packages for example, should be included by default in your ProText Distribution for Windows. You can find the appropriate *.sty files in their own separate directories in your default LaTeX installation path:

  • On windows usually under c:\Progam Files\MiKTeX\tex\latex\
  • On unix systems usually in /usr/share/texmf/tex/latex/

If you include a package and it is not in the document’s directory, LaTeX will check if it is located in it’s installation bundle. Unfortunately, it is not as simple as a quick look-up in one of these directories. There is actually a hash table which maps the exact locations of all the installed packages. So installing a new package globally is not as easy as just dropping it in the right directory. The good news is, your system will know right away that the package you are trying to include is neither installed, nor available and will be able to do something about it.

If you are running one of the nice all-bells-and-whistles LaTeX distributions (like MiKTeX which ships with ProTeXt) there is an automated package fetch application built into the system. So chances are that first time you \uspackage something that was not included in the default installation bundle, you will see a pop-up like this:

LaTeX package installer on windows

LaTeX package installer on windows

This also works for document classes which are sort of like packages in their own right. Either way, MiKTeX will check online repositories and download the package for you if it exists. If it cannot find it online, or if your distribution simply does not have a fancy installer your compilation will simply bug out.

Don’t fret though – you can still manually install the package by dumping it into one of the above mentioned paths and then running a magic command called texhash which will re-index said folder and add any new packages to the global hash file, making them available from that point on. On windows you can probably find it under c:\Program Files\MiKTeX\miktex\bin\texhash.exe. On unixes it ought to be in your path, just like all the other tex related commands. It is probably important to mention that you should usually run this command as root/admin because it will likely need to update files that are typically not write accessible to regular users both on Widnows and unix-like systems.

I guess your next question might be “how do I figure out how to use package XYZ?”. Unfortunately, the best answer I can give you is RTFM. And I don’t mean it in an offensive way. I’m just stating a fact here – there are thousands of packages out there, and their functionality and complexity is beyond the scope of this humble guide. While I’m intending to talk about some of the useful or important packages in the next few entries, it is important to know how to be able to find the documentation for all the packages you may have to use on your own.

This should not be a problem for random things you will download from the internet, as the same page where you found the *.sty file will likely also include explanations and examples of how to use said file. For pre-installed packages it may not be as straightforward. Fortunately, there is another magical command that will help you out here: texdoc. This is pretty much man for LaTeX packages. For example running:

texdoc geometry

Should display the documentation for the geometry package. Depending on the whimsy of the package creator, this documentation may be stored a PDF, a text file, or sometimes in a PostScript or DVI format. Linux/Unix users should be able to open all of these with no problems. Windows users may need to download some software to open the last two formats – but fortunately bundles like ProTeXt ship with GhostScript and/or Yap viewers that ought to just work with the texdoc command.

If for some reason you don’t want to use the command line tool, you can always manually browse to the default documentation directory for your package and try to find relevant docs there. Each package usually keeps it’s manuals and sample files in it’s own directory in your LaTeX installation path:

  • On windows its: c:\Program Files\MiKTeX\doc\latex\
  • On unixes its: /usr/share/texmf-tetex/doc/latex/

Just find the appropriate directory, open it, and view the docs inside.

How to find new/useful LaTeX packages? Well, for one you can Google for them. Pretty much every time you type in something along the lines of “how do I XYZ in LaTeX” the answer is likely to require you to use at least one \usepackage command. But if you just feel like browsing, you can start with the CTAN Catalog. This list by no means all inclusive, but it is a good place to start, and also the primary resource against which your automatic installer is going to check your documents.

Let’s Learn LaTeX
<< Prev Next >>
]]>
http://www.terminally-incoherent.com/blog/2012/12/14/lets-learn-latex-part-5/feed/ 1
Let’s Learn LaTex: Part 4 http://www.terminally-incoherent.com/blog/2010/12/01/lets-learn-latex-part-4/ http://www.terminally-incoherent.com/blog/2010/12/01/lets-learn-latex-part-4/#comments Wed, 01 Dec 2010 15:48:59 +0000 http://www.terminally-incoherent.com/blog/?p=6943 Continue reading ]]> I sort of neglected my Let’s Learn LaTex series for a while now. The last LaTex related post I made was in April and now it is already November. I figured I might as well get back to it, and hopefully if you were following along you can refresh yourselves using the link above.

Last time I promised to explain tables, but then I realized that tables are quite a big topic so I will split this lesson into two parts. Today I will talk about basic table structure, and next time I’ll outline some more advanced table tricks.

How do you make a table in LaTex? How do you make a list? If you recall from the last post, lists were LaTex environments. So are tables. Instead of using enumerate or itemize environment, you use tabular instead. The \begin{tabular} and \end{tabular} keywords set it up up just like lists. Let me show you a simple one:

\begin{tabular}{ l c r }
  foo1 & bar1 & baz1 \\
  foo2 & bar2 & baz2 \\
  foo3 & bar3 & baz3 \\
\end{tabular}

It will make this fine looking table:

Basic table

It is spartan and simplistic but we can fix that in a few seconds. Let’s talk about the basics. The tabular environment takes an argument which is a textual string that “describes” the columns, and it accepts following literals:

  • l – Left aligned column
  • c – Centered column
  • r – Right aligned column
  • | – A vertical line / column divider

It does not really matter which character you use in the example above, because all the columns are of equal width and LaTex will do auto-kerning and alignment on them as usual.

Once you define the columns, you just start typing your data in, and place the & character when you want to skip to the next column and you end the row with the \\. Naturally if you want to use the & symbol in your table you will need to escape it as \&

Now let’s add some lines. You can use the | (pipe character) to add vertical lines in the column definition string and \hline command to add vertical lines in the body of the table like this:

\begin{tabular}{| l | c || r |}
\hline
  foo1 & bar1 & baz1 \\
\hline
  foo2 & bar2 & baz2 \\
\hline
  foo3 & bar3 & baz3 \\
\hline
\end{tabular}

The result will look like this:

Table with some lines

Much nicer, eh? You should note that LaTex does not have the equivalent of the <th> html tag that would automatically style a row as a column header. You have to do this sort of thing manually either by using multiple \hline commands or by using \textbf or other formatting on individual table cells.

Similarly to HTML tables, the tabular environment won’t wrap long text lines around. This behavior is by design, but it often catches new LaTex users by surprise when their table slides right off the page. Let’s test it and create a nice table with some long sentences. To make it more fun lets use everyone’s favorite panagram featuring that pesky brown fox:

\begin{tabular}{| l | l |}
\hline
  Incorrect version & The quick brown fox jumped over the lazy dog. \\
\hline
  Correct version & The quick brown fox jumps over the lazy dog. \\
\hline
\end{tabular}

Yes, despite the popular belief the brown fox jumps over the dog all the time – like right now for example. If he had jumped over him once at some point in the past and never did it again he would ruin the panagram by ommiting the letter ‘s’. But I digress. For our purpose let’s say we have a rather narrow page. In such case the table above could easily end up looking like this:

Table too wide for the page

Fortunately this is easily fixable by using p{w}, m{w} or b{w} instead of l, c and r where w is some width attribute:

  • p{w} – top aligned wrapped paragraph column
  • m{w} – middle aligned wrapped paragraph column
  • b{w} – bottom aligned wrapped paragraph column

The value of w must be a number followed by measurement unit such as in (inches), cm (cemtimeters) or em (internal LaTex measure which defaults to the width of letter ‘m’ in the current font). Let’s try this with our example:

\begin{tabular}{| l | p{10em} |}
\hline
  Incorrect version & The quick brown fox jumped over the lazy dog. \\
\hline
  Correct version & The quick brown fox jumps over the lazy dog. \\
\hline
\end{tabular}

Here I set the width of the second column to be approximately ten widths of the letter m, which resulted in this output:

Table with restricted width

As you can see, the result is much better.

One of the lovely things about LaTex is that it was written by programmers for programmers. Programmers are lazy beasts, so anything that requires lots of typing or copying and pasting will usually get lumped into some sort of a function. This is true for tables. For example, if you need to define several identical columns, you can use the * (star/asterisk) notation in your column definition. It usually takes the form of:

*{howmany}{columndef}

The value of howmany is a number and the value of columndef is actual column definition (for example c or a p which can be accompanied by some pipe characters to create column border). Let me give you a quick example:

\begin{tabular}{ l | *{4}{c|} }
  Student Name	& HW 1 & HW 2 & HW 3 & HW 4 \\
\hline
  John Smith	& A & B & A & F \\
  Jane Smith	& C & C & F & F \\
  Bob Johnson	& A & F & A & B \\
\end{tabular}

It will look like this:

Table created using the star notation

The last thing I want to show you today is spanning. Sometimes you want to have rows that span more than one column. In HTML tables you can achieve that by sticking an attribute on a <td> tag. Since LaTex uses a much simpler table structure, and the column definition attribute is already overloaded as it is, things get hairier here – but only a little bit.

Essentially instead of typing the columns or rows that need to span, you use a special command such as:

\multicolumn{howmany}{columndef}{content}

Let me give you a quick example:

\begin{tabular}{| l | *{4}{c|} }
\hline
  \multicolumn{5}{|c|}{Homework Grades} \\
\hline
  Student Name	& HW 1 & HW 2 & HW 3 & HW 4 \\
\hline
  John Smith	& A & B & A & F \\
  Jane Smith	& C & C & F & F \\
  Bob Johnson	& A & F & A & B \\
\hline
\end{tabular}

I’m sure you can see the \multicolumn statement replaces an entire row here, but if it didn’t you could still use & characters to the left and right of it. Here is the output:

Table with multicolumn

If you want spanning rows, you will need to use a package called multirow which is something I did not explain yet. Which is why I think the next lesson will be about importing packages and then I will swing back to tables.

Let’s Learn LaTex
<< Prev Next >>
]]>
http://www.terminally-incoherent.com/blog/2010/12/01/lets-learn-latex-part-4/feed/ 8
Let’s Learn LaTex: Part 3 http://www.terminally-incoherent.com/blog/2010/04/22/lets-learn-latex-part-3/ http://www.terminally-incoherent.com/blog/2010/04/22/lets-learn-latex-part-3/#comments Thu, 22 Apr 2010 14:39:55 +0000 http://www.terminally-incoherent.com/blog/?p=5124 Continue reading ]]> Welcome back to my Let’s Lern LaTex series. I haven’t done any of these posts in a while, but that doesn’t mean i gave up on the idea. Today I want to show you lists which interestingly enough work very much like their corresponding structures in HTML.

For example, LaTex has 3 basic list environments: enumerated list, itemized list and description list. Sounds familiar? It should because these correspond to the ordered list (<ol>), unordered list (<ul>) and definition list (<dl>) in HTML. Let me show you some quick examples – these should be self explanatory.

First let’s do the enumerated list:

\begin{enumerate}
	\item First item
	\item Second item
	\item Third item
\end{enumerate}

As you can see it is a standard environment just like the ones I have shown you before. The only difference is that you preface each item on the list with an \item command. Here is a sample output:

Enumerated list

Itemized list is identical in syntax:

\begin{itemize}
	\item First item
	\item Second item
	\item Third item
\end{itemize}

Here is the output:

Itemized list

Description list is actually even easier to make than in HTML because you don’t need two sets of tags. In the description environment the item command takes an argument which is the word/phrase that is to be used as the word to be defined/described:

\begin{description}
	\item[Foo] Some long description that will probably wrap to the next line, because that's what we want to show. Note how the wrap around works in this case, indenting the second line 
	\item[Bar] And even longer description that will probably wrap to the next line, because that's what we want to show. Actually, this one may not be as long. Whatever.
\end{description}

Note that Foo an Bar are user defined values – you can put whatever you want in there. Here is how it looks once compiled:

Description List

If you want to make lists with multiple indentation levels, you do the same exact thing you would do in HTML: you nest two or three lists like this:

\begin{enumerate}
	\item First item
	\item Second item	
		\begin{enumerate}
			\item First Sub item
				\begin{enumerate}
				    \item First sub sub item
				    \item Second sub sub item
				\end{enumerate}				
			\item Second Sub item
			\item Third Sub item
		\end{enumerate}
	\item Third item
\end{enumerate}

Here is how it would look – note that the counter type changes automatically so that the first level is numbers, second level is characters, third level is roman numerals and etc:

Nested list

First thing people ask after they learn how to use lists is how to change their appearance. For example, how to make enumerated list start with upper case roman numerals instead of numbers. Well, it is not the most straightforward thing to do conceptually. I mean, it can be accomplished in one line, but understanding what is a whole other thing.

You see, in LaTex you can redefine every single command and change what it does. Yep, it is one of those languages where almost nothing is holly and even the most basic operators can be tampered with. This is one of the features that makes LaTex so flexible. To change the way lists work, you basically go in, and you alter the command that LaTex uses internally to display list labels and counters.

By default LaTex recognizes following counter styles:

\arabic	% 1, 2, 3 ...
\alph 	% a, b, c ...
\Alph 	% A, B, C ...
\roman	% i, ii, iii ...
\Roman	% I, II, III ...

You use them like this:

\renewcommand{\labelenumi}{\Roman{enumi}.}

This may seem a bit difficult to grasp but basically in plain english we would say that \renewcommand command redefines the \labelenumi command (which prints out the first level list label) by applying the \Roman style to the first level counter. Does that make sense? If you want to change second and third level, you follow the same pattern:

\renewcommand{\labelenumii}{\roman{enumii}--}
\renewcommand{\labelenumiii}{\{\alph{enumiii}\}}

As you can see, the last argument can be formatted any way you like. You can add dots, parentheses, dashes and etc.. These settings will affect the rest of the document from the point where you first specify them, so if you want to mix and match styles you will need to do this several times in your document. Here is a sample output:

Modified list

Itemized lists can be modified as well using the following command:

\renewcommand{\labelitemi}{\textgreater}

This will change the default bullet to \textgreater which prints out the greater-than symbol like this:

Modified itemized list

There are many symbols you can use as bullets. There is a wide range of them you can find here for example. In general, just google “LaTex Symbols” and you should be all set. If you use a symbol command and you get compilation errors just surround it in $ marks like this:

\renewcommand{\labelitemi}{$\clubsuit$}

This will give you nice club symbols for bullets:

Modified itemized list with math mode

The dollar sign symbols enter LaTex math mode – but you don’t have to worry about that yet. I will talk about it at length in one of the next posts. For now just keep in mind that some symbols are only accessible after you surround them with dollar signs.

I wanted to talk about tables in the same post, but I realized that this post is already getting long so I will stop here. Next week: tables. And maybe something else if we have space.

Let’s Learn LaTex
<< Prev Next >>
]]>
http://www.terminally-incoherent.com/blog/2010/04/22/lets-learn-latex-part-3/feed/ 10
Let’s Learn LaTex: Part 2 http://www.terminally-incoherent.com/blog/2010/02/22/lets-learn-latex-part-2/ http://www.terminally-incoherent.com/blog/2010/02/22/lets-learn-latex-part-2/#comments Mon, 22 Feb 2010 15:31:23 +0000 http://www.terminally-incoherent.com/blog/?p=5032 Continue reading ]]> Last week I have shown you the bare bone basics of LaTeX. We learned how to create a simple hello world document, and the usual boilerplate code that goes into the preamble. Lets move on to slightly more complex ideas.

I want to start with the meta-information you can add to your document. Each paper you create will likely have a title, author and creation date. Latex has special commands you can use to insert that info into the preamble:

\title{My Document}
\author{Lukasz Grzegorz Maciak}
\date{\today{}}

Note that the date command will accept anything as an argument – you don’t have to format your input in some special way. In the sample above I am using a latex command \today{} in order to add the current date to the document. This means that your work will have the date of the day when it was last compiled. If you go back to your work, make changes and re-compile it, the date will be adjusted automatically.

This information will now be used throughout the document for things like headers and footers and etc. It won’t be displayed at the top of your document unless you actually want to though. If you do just put \maketitle somewhere below the \begin{document} like this:

\documentclass[10pt, letterpaper]{article}

\title{My Document}
\author{Lukasz Grzegorz Maciak}
\date{\today{}}

\begin{document}
\maketitle

Lorem ipsum dolor sit amet ...
\end{document}

This should produce something like this:

Use \maketitle to display title information above the document

By the way, notice how each paragraph in the sample above is indented. This is automatic. In my source code I simply leave a blank line between paragraphs (a bit like in this blog) and LaTeX does the rest. If you don’t like the indentation, you can always suppress it by adding \noident at the begging of a paragraph.

Starting documents this way is nice, but there are cases where it is appropriate to have the title, author and date on a separate page (for the sake of this tutorial let’s call that special page a “title page”. Also for the sake of this tutorial imagine me saying “title page” in Dr. Evil’s voice why making air-quotes gesture why Seth Green rolls his eyes in the background). Let me show you how it’s done:

\documentclass[10pt, letterpaper, titlepage]{article}

Yep, it’s that easy. Just pass a single optional argument to your \documentclass{} and you are done.

Our next step would be to add some structure to our document – for example, lets say you want to break it up into sections and subsections like this:

\section{This is a section}
\subsection{This is a subsection}
\subsubsection{This is a subsubsection}

Here is an output sample with some lorem ipsum added in between the section headings to make it look more like a real document – just so that you can get the sense of the relative font sizes and spacing:

LaTeX Sections

That’s exactly how you use these. Sections are not environments – you don’t need to open and close them – they are one shot commands. Note the numbering that was added to my document. It is automatic, and inserting new subsection somewhere in the text will automatically re-enumerate everything at compile time so you don’t even have to think about it.

By default LaTeX supports seven levels of document subdivision: part, chapter, section, subsection, subsubsection, paragraph and subparagraph. They all work in the same way, main difference being the formatting. For example, the chapter command (which is only defined in report and book document classes) will force a page break and will make the title take up half the page. Paragraph and subparagraph on the other hand don’t usually get numbered but you can change that if you want.

You can suppress the numbering on any of these elements by adding an asterisk after the command name but before the arguments like so:

\section*{Non numbered section}

Now that we have the whole document broken down into logical parts, the next step would be to generate table of contents no? Once again, all you need is a simple single word command called \tableofcontents. You can put it wherever you want in your document. I usually include it at the beginning like so:

\begin{document}
\maketitle
\tableofcontents
\newpage

Note that I also used \newpage command that I believe should be quite self-explanatory. It forces a page break so that my table of contents is on a page of its own accompanied only by the document title information:

Table of Contents

You now know how to structure your papers in LaTeX. I bet you are dying to find out how to do basic font formatting operations such as making your text bold, italic and etc. It is actually incredibly easy and can usually be accomplished using one of the “text” commands like the ones below:

\textit{This text is italic} \\

\textsl{This text is slanted} \\

\textbf{This text is boldface} \\

\texttt{This text is in typewriter font} \\

\textsc{This text is in small caps} \\

\emph{This text is emphasized}

Note how I used the \\ an a line break at the end of each line. This is basically the LaTeX way of saying <br;> or Shift+Enter (in Word) – a mid paragraph soft line break. Here is a sample output:

The text formating commands

Note that you can nest these commands like this:

\textbf{\textit{\texttt{Boldface. italicized typewriter font}}}

There are also several formatting environments that let you change the size of your font appropriately (think <big> and <small> tags from HTML). They are as follows:

\begin{tiny}This text is tiny\end{tiny} \\

\begin{scriptsize}This text is script size\end{scriptsize} \\

\begin{footnotesize}This text is footnote size\end{footnotesize} \\

\begin{small}This text is small\end{small} \\

\begin{normalsize}This text is normal size\end{normalsize} \\

\begin{large}This text is large\end{large} \\

\begin{Large}This text is upper-case Large\end{Large} \\

\begin{LARGE}This text is all-caps LARGE\end{LARGE} \\

\begin{huge}This text is huge\end{huge} \\

\begin{Huge}This text is all-caps HUGE\end{Huge} \\

And here is some output. Note that the normalsize is the “default” font size as set in your \documentclass:

Font sizing environments

That’s all for now folks. Next time I will show you how to make lists, tables and maybe how to import packages and insert graphics to your documents.

The other day someone asked me how far am I planning to go with these tutorials (ie. how in depth are they going to get). I actually don’t know. I guess I’ll see whether or not people like these. If they do, I can try pushing on definitely even after I am out of my comfort zone. In that case we will be all learning something new each time. On the other hand if the LaTeX posts remain dead (ie. no one ever comments on them) I might wrap them up after I show you guys all the basics and reach some good closing point. We shall see.

Let’s Learn LaTeX
<< Prev Next >>
]]>
http://www.terminally-incoherent.com/blog/2010/02/22/lets-learn-latex-part-2/feed/ 12
Let’s Learn LaTex: Part 1 http://www.terminally-incoherent.com/blog/2010/02/15/lets-learn-latex-part-1/ http://www.terminally-incoherent.com/blog/2010/02/15/lets-learn-latex-part-1/#comments Mon, 15 Feb 2010 15:12:49 +0000 http://www.terminally-incoherent.com/blog/?p=4915 Continue reading ]]> Few days ago Travis gave me an idea for a new series of posts. He mentioned recommending my blog to a friend who was trying to learn LaTex. Unfortunately, my blog is not the best learning resource. It is more like a collection of “hey, look what I found out today” type posts. Some of which have proven to be quite useful to the inhabitants of the interwebs. For example my post on the quirky way in which LaTex processes figure numbers still gets several thank-you comments per month, despite being over 3 years old.

I tend to bring up LaTex in random conversation on this blog all the time. In most cases I assume most of my readers know what the hell am I talking about. But this is often not the case. In fact, I can probably safely guess that majority of my regulars have never really used my favorite typesetting tool. So I figured that I might as well sit down and write a few introductory LaTex posts. Perhaps I can teach bunch of you something new. If not, it may still be an interesting exercise – and perhaps it will bring in some Google juice as well via LaTex related queries.

First off I should probably tell you why you should use LaTex instead of Microsoft Word or other word processing tool. Only I already did that. So I will just refer you to my earlier post in which I illustrate how LaTex is superior to office.

Next I should probably tell you how to install and configure the damn thing. Only I already did that too. Here is one of my posts that shows you how to install a full LaTex suite on windows. The ProTex package I linked to in the article contains Texnic Center – a decent, easy to use IDE that makes compiling tex files into PDF just a matter of pressing a button. I’m fairly confident that since you are reading this blog, you can probably locate the right icon on the toolbar by yourself. So I will not be showing you how to actually run LaTex commands from the CLI or how to use the IDE. I will jump right into teaching you the language itself.

LaTex basically works like a markup language. I always compare it to HTML because it is what most people are familiar with. Just like in HTML the text you type out will be rendered as a wall of text. LaTex will ignore most white space, save for spaces that separate words and newlines that tell it to start a new paragraph. Any other formatting or structural organization must be added to the file using specially formatted commands. HTML uses the greater and less then characters as escape sequences. Anything enclosed in them becomes a HTML tag and is not rendered, but rather interpreted as a rendering instruction. In latex our escape character is backslash (“\”). Any word prefixed with this character will be interpreted as a LaTex formatting command. For example:

\newpage

LaTex command can take attributes, which are usually enclosed in curly braces {} like this:

\textbf{this is an attribute}

Om case you were wondering, the “bf” in textbf stands for “bold face”. The command above therefore can be used to make your text bold.

Optional arguments are enclosed in square brackets []. These are usually switches and toggles that modify the commands, while the mandatory argument in curly braces is usually some sort of input that will be processed by the command (but not always). If there are several optional arguments they are written as a comma separated list. The order usually does not matter as LaTex is smart enough to figure to match them up. Here is another example:

\documentclass[letterpaper, 10pt]{article}

First I’d like to show you how a LaTex environment looks like. Environments are a bit like HTML tags – they come in pairs. First command opens the environment, and the other one closes it. Anything you type inside an environment is subject to some special formatting rules. The simplest environment you have to learn is of course:

\begin{document}
    This is where you type your document.
\end{document}

The document environment is essentially the equivalent of the HTML body tag. It denotes where your document starts and where it ends. Anything above it is the preamble – which works a bit like the head section of a HTML document. That’s where you put settings, meta-information, credits, comments and etc.

Speaking of comments – before I forget I should tell you that LaTex uses percent sign % to denote a comment. If you need to use the % sign in your text you will have to escape it with backslash like this:

To escape \% use \\ % and this is a comment

You escape the backslash the same way – with a backslash. There are no multi-line comments – you just have to deal with it.

That’s pretty much it. 99% of time you will not need to use anything beyond these basic constructs. From this point on, it is just a matter of learning bunch of basic commands. The beauty of LaTex is that most of the aesthetic stuff is already preconfigured for you. Unlike a basic HTML page, a basic LaTex document looks good “out of the box” so most of the time you don’t have to do anything beyond some basic tweaking of the standard template.

Similarly to HTML, LaTex tries to separate content from presentation. The presentation is usually controlled by document class files (.cls) which are a little bit like CSS (but don’t look too much into that parallel – it’s a whole different ballgame). These files describe how the text is supposed to flow on the page, default margin settings, how and where the page numbers are displayed, whether or not the pager should be printed as if it was to be bounded in a book and etc. You can override most of these settings via simple latex commands in your document of course. But if you don’t, then changing from one style to the other becomes just a matter of changing a single line in the preamble.

Wen you start an new document, the first thing you need to do is to tell LaTex what document class you want to use. That’s where that line I skipped comes into play:

\documentclass[letterpaper, 10pt]{article}

Here I’m telling LaTex that I want to use article as my class document class. Document classes are basically files with *.cls extension which usually somewhere in the LaTex file hierarchy (along with all the libraries and what not) or in the current folder where you are compiling your document. The \documentclass command takes in several optional arguments. These arguments depend on the class you choose, but most of them relate to default font size (here 10 points), default paper size, page orientation, number of columns and etc. You can usually find the list of those in the documentation for your class file. The standard article class included with your installation accepts the following arguments:

Default Argument Acceptable Arguments
Font Size 10pt 11pt, 12pt
Paper Size letterpaper a4paper, a5paper, b5paper, executivepaper, legalpaper
Column Layout onecolumn twocolumns
Single/Double Sided oneside twoside
Landscape Mode landscape
Draft/Debug Mode draft

Your standard installation comes with 4 basic classes: article, report, book and letter. The optional arguments listed above will actually work in the first three. Letter document class is a little bit different but we’ll cover that later.

As you may imagine, each is geared towards different type of document. Article is for writing short articles destined to be published standalone or in a magazine or journal of some sort. Report is for longer scientific documents that need to be broken down into chapters. Book formats your document in preparation for binding, with alternate styles for even and odd pages, distinctive chapter pages and etc. Letter format on the other hand conforms to the customary rules for official letter writing. If you need something more specific you can usually obtain an appropriate document class file online.

Foe example, if you need to publish your paper in IEEE standard you can grab their class file from their website, put it in the same directory as your document and just use it in your preamble. That said, downloading document classes is not something you are going to be doing very often. The basic classes pretty should cover 90% of the documents you will be generating.

So let’s put all this information together and create a simple hello world file:

\documentclass[10pt, letterpaper]{article}
\begin{document}
	Hello World
\end{document}

Once you type all of that in, simply hit the big PDFLatex button in your IDE (most of them have one) to generate a nice PDF file. It should look something like this:

Hello World Document

That’s it folks. That’s how you start a LaTex document. What? You thought it would be hard? No it is not. It’s easy! Pick a document class, start a document, type your stuff, end document. That’s all! Of course this is merely the tip of the iceberg. Next time I will show you more useful commands and environments, as well as introduce you to packages.

Let’s Learn LaTex
<< Prev Next >>
]]>
http://www.terminally-incoherent.com/blog/2010/02/15/lets-learn-latex-part-1/feed/ 5