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 LaTex: Continous Background Compilation http://www.terminally-incoherent.com/blog/2014/06/09/latex-continous-background-compilation/ http://www.terminally-incoherent.com/blog/2014/06/09/latex-continous-background-compilation/#comments Mon, 09 Jun 2014 14:07:08 +0000 http://www.terminally-incoherent.com/blog/?p=17224 Continue reading ]]> What I’m about to propose here is a bit unconventional, but it really works for me. I’ve been doing a lot of front and back end web stuff lately and as a result every machine I own or work with has Node installed by default. Not that I do much in node itself, but because it gives me access to some amazing front-end tools and utilities such as Bower, Yeoman and Grunt. That last one especially has become my go-to build tool as of late. Not necessarily because I love it’s syntax (it’s not great) but because of how it works.

It is a build tool unlike any other: instead of providing users with a monolithic set of build tasks and commands it is completely modularized, allowing you to mix and match both official and community made plugins. And it has a vibrant community that builds plugins for just about everything. Including LaTex.

Combining Latex and Grunt

Combining Latex and Grunt

One of my favorite features of Grunt is the ability to set up watch tasks that monitor your project files for changes and will continuously build and test your code while you work. You can combine it with a live-reload functionality which automatically refreshes your browser. When I work on web projects these days I can automatically see my changes taking effect on the second monitor. I can’t emphasize enough how much does this improve your productivity, and how cool it feels.

I decided I want that kind of setup when I work in LaTex, and it turns out that it can be accomplished using the same tools I use for web development. This is perhaps not a pure LaTex environment, and I am probably committing some horrible transgression here by altering the “proper” Tex workflow. This is definitely not how St. Knuth and St. Lamport intended their tools to be used. But it works really well.

The basic idea is to use Grunt to set up a watch task that will re-compile your document every time you save it. Web-developers probably already know where I’m going with this, but since this is a LaTex post, I’m going to assume you are not familiar with these very web-specific tools. So if you never used Grunt I’m going to explain it step by step.

First, you need to install Node, and then use the built in package manager known as npm to install the Grunt command line tool:

npm install -g grunt-cli

The -g parameter means “global”. By default npm installs packages into node_modules folder in the current directory, but the command line client must be installed globally. While npm is working and spewing all kinds of information into the console, you might go ahead and put that node_modules directory into your .gitignore file.

Now, that you are done with that, go into your project directory and install Grunt proper. Yes, you install it twice. The tool used for issuing build commands is installed globally, whereas the actual meat of the build engine along with all the plugins is installed locally in your project folder. If you think about it, it is a brilliant move as it ensures that every project gets it’s own self-contained environment. Not only that, but you can simultaneously work on two different projects: one which requires a bleeding edge version of the build tool, and one which uses deprecated logic tied to a very old version and they will never conflict with each other.

npm install grunt

It will be installed to the aforementioned local directory:

Installing Grunt

Installing Grunt

Next, you will need to install at least two plugins. One of them is the official watch plugin which will monitor files and trigger build tasks when they are changed. The other one is an excellent LaTex wrapper written by Tim von Oldenburg:

npm install grunt-contrib-watch grunt-latex

You can specify both plugins on the same line. In fact, you can install both grunt and the associated plugins in one command.

Installing Plugins

Installing Plugins

The nice thing about Tim von Oldenburg’s package is that it is configured to work with all the popular LaTex distributions so it should work on any platform. I tested it both on Windows and Linux and it was working flawlessly.

Once you have all the components of your build system in place, you can set up your “make” file, here known as a Gruntfile. In most circumstances these build files are written in Javascript and saved as Gruntfile.js in the root of your project directory. But I highly recommend using CoffeeScript instead, because it results in much smaller and readable files. Grunt does not care which of the two languages you use.

Don’t worry if you have never used CoffeeScript – the basic syntax needed to make a Gruntfile is no more complex than that of Make. Here is a very basic Gruntfile.coffee you can use for your project:

# Grunt boilerplate
module.exports = ->
    
    # Set up individual tasks
    @initConfig
        latex:
            src: ['main.tex']
        watch:
            files: 'main.tex'
            tasks: ['latex']

    # Specify tasks you want to use
    @loadNpmTasks 'grunt-latex'
    @loadNpmTasks 'grunt-contrib-watch'

    # Tell grunt what to do if no arguments are specified
    @registerTask 'default', ['latex', 'watch']

Let me explain. Lines 2 and 5 are just standard boilerplate that has to be there in every Gruntfile. In a CoffeeScript they are just two trow-away lines, whereas in the Javascript version they would be two nested closures which are about seven times as scary to someone who is not used to the “sideways x-mas tree” shape that language usually ends up with. CoffeeScript flattens it out a bit and makes it quite more readable.

Lines 13 and 14 declare the plugins that you will be using. We then set up specific option for each plugin in the @initConfig block (lines 6-10). By default the name for each plugin based task is the unique part of the plugin name. So it is latex for grunt-latex and watch for grunt-contrib-watch (all the “official” plugins have the contrib prefix). You use that name to refer to them in the initialization block.

For example the latex plugin requires only one option, which is src and it is used to specify your main .tex file. The watch plugin needs to options. First specifies which files to watch, and second is which tasks to run (which in our case is the latex task).

Finally, the last line defines the “default” taks – which is the one to be run if no tasks are specified on the command line. Normally, you can run a specific task by supplying it to grunt as an argument. For example:

grunt latex

Will run the latex task. If no arguments are specified the task default is run, if it exist. So it is always a good idea to register it in your Gruntfile. I set it to compile the document once, and then watch for changes from that point on. Running grun then throws it into an infinite loop, where it waits for file changes and re-compiles my document on the fly. Observe:

Using Grunt to Live Compile Latex

Using Grunt to Live Compile Latex (click to enlarge)

To stop Grunt from it’s active watch-loop you simply hit Ctrl+C.

Most PDF readers will auto-refresh your document when it changes, so as long as you keep it open on the side, or on the second monitor you will see the changes as they stream in. Adobe Reader for some reason locks any file it has open, and prevents LaTex from overwriting it, so you cannot use it with this setup. Pretty much anything else will work fine. In the screenshot above I’m using Evince which is the default PDF viewer on Ubuntu which has a perfectly serviceable Windows version.

You should keep in mind that this method is not perfect. For example, while the grunt-latex plugin is very robust and set up to work in just about every environment, it is not very versatile. It does have some configuration options, but it does not run external commands. This means that if you are using BibTex or a similar package which requires an additional binary to be run before or after latex, the plugin won’t help you.

The good news is that Grunt is incredibly flexible, so it is easy to work around such limitations. For example, in the document I was working on I needed to build a word index. This requires you to run the makeindex command each time you compile. I figured how to make this happen using the grunt-shell plugin which lets you configure a task that will run an arbitrary shell command for you. My Gruntfile ended up looking like this:

module.exports = ->
    
    @initConfig
        latex:
            src: ['main.tex']
        watch:
            files: 'main.tex'
            tasks: ['latex', 'shell', 'latex']
        shell:
            makeIndex:
                command: 'makeindex main.idx'

    @loadNpmTasks 'grunt-latex'
    @loadNpmTasks 'grunt-contrib-watch'
    @loadNpmTasks 'grunt-shell'

    @registerTask 'build', ['latex', 'shell', 'latex']
    @registerTask 'default', ['build', 'watch']

If I needed to add BibTex support I could just another entry under shell and then whenever that task was invoked both the indexing and BibTex tasks would run. Or, I could run them individually by specifying their name after the colon (shell:makeIndex instead of just shell).

What do you think of this setup? How do you compile your LaTex documents? Do you use a makefile of any sort, or do you rely on an IDE to run all the build tasks for you? And if you use an IDE, then which one? Let me know in the comments.

]]>
http://www.terminally-incoherent.com/blog/2014/06/09/latex-continous-background-compilation/feed/ 7
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
LaTex: Automating Repetition http://www.terminally-incoherent.com/blog/2012/07/11/latex-automating-repetition/ http://www.terminally-incoherent.com/blog/2012/07/11/latex-automating-repetition/#comments Wed, 11 Jul 2012 14:17:50 +0000 http://www.terminally-incoherent.com/blog/?p=12339 Continue reading ]]> Few days ago, a buddy of mine contacted me with a problem. He was tasked with creating about a thousand form letters (for snail mail distribution). Being an awesome dude, he turned to open source solutions – and specifically LaTex rather than braving the evils of Mail Merge in Microsoft Word. He correctly guessed that this tool could easily take a delimited list of addresses and generate the right number of letters without much hassle. He however was a bit at a loss on how to actually implement it.

Being a bit of a problem solver I decided to jump in and help him out. His letter went a little bit like this:

\documentclass{letter}
\begin{document}
\clearpage 

\signature{John Smith}
\address{
Bouncing Shuttlecocks Incorporated \\ 
1234 Squiggly Bottom Court \\ 
Hoffenpuff, AL 12348\\ 
contact@bouncingshuttlecocks.us}

\begin{letter}{Mr. Poop McGee \\ Some Address \\ Some City, NJ, 07586}
\opening{Dear Sir or Madam:}

We would like to send you a sample of our terrific product for free, 
so that you can see that our shuttlecocks bounce the best. 

If you are not satisfied with bounciness of our shuttlecocks we are 
prepared to send you another sample for free just so you can re-evaluate 
it. And then another one if that one is not bouncy to your liking either. 
In fact, we will just keep sending you free samples until you agree that 
the bounciness factor of our shuttlecocks is satisfactory. We will drown 
you in free shuttlecocks! Don't even try returning them to sender - we 
know people at UPS.

So please evaluate our sample and let us know how much you enjoyed the 
bounciness of our shuttlecocks.

\closing{We look forward to hearing from you,}
\end{letter}
\clearpage 
\end{document}

There would be only one line in this letter that would change – the Poop McGee line. That’s ideally where he would want to plug different addresses from a list. But how?

Well, I did a little bit of research and found out that the easiest way to accomplish this is by using a nice package called forarray. It ships with a ForEach command which has the following syntax:

\ForEach
{;}                % delimiter
{ \thislevelitem } % function
{ foo; bar; baz }  % list

The delimiter is exactly what it sounds – a character (or series of characters) that will separate items on your list. As you can see, the list I used in the third bracket uses the semicolon delimiter defined in the first one. This command will iterate over that list and output whatever it is you put in the middle bracket. In this particular case the only thing I’m outputting is \thislevelitem which is the “current” list item. So the output of this particular code would simply be: foo bar baz. Of course you can put whatever you want in that middle bracket. For example, the text of our letter.

Here is how you would apply this to generate bunch of form letters like the one above:

\documentclass{letter}
\usepackage{forarray}
\begin{document}

\ForEach {;}
{

\clearpage 
\signature{John Smith}
\address {
Bouncing Shuttlecocks Incorporated \\ 
1234 Squiggly Bottom Court \\ 
Hoffenpuff, AL 12348\\ 
contact@bouncingshuttlecocks.us}

\begin{letter}{\thislevelitem}
\opening{Dear Sir or Madam:}

We would like to send you a sample of our terrific product for free, 
so that you can see that our shuttlecocks bounce the best. 

If you are not satisfied with bounciness of our shuttlecocks we are 
prepared to send you another sample for free just so you can re-evaluate 
it. And then another one if that one is not bouncy to your liking either. 
In fact, we will just keep sending you free samples until you agree that 
the bounciness factor of our shuttlecocks is satisfactory. We will drown 
you in free shuttlecocks! And don't even try returning them to sender - 
we know people at UPS.

So please evaluate our sample and let us know how much you enjoyed the 
bounciness of our shuttlecocks.

\closing{We look forward to hearing from you,}
\end{letter}
\clearpage 

}
{
Ms. Jane Smith \\ Foobar Incorporated\\ Foo Street \\ Foo City, GA 44559; 
Mr. Poop McGee \\ Some Company \\ Some Street \\ Some City, IL 112547; 
Mr. Nobody \\ No Company \\ No Street \\ No Town TX, 586235
}

\end{document}

And there you go. It is a clear, easy and elegant solution to a non-trivial problem and another proof that LaTex is ridiculously powerful. What other typesetting system lets you do conditionals, loops and arrays? Pretty much none. Once again LaTex saves the day.

]]>
http://www.terminally-incoherent.com/blog/2012/07/11/latex-automating-repetition/feed/ 6
ScribTex – Learn LaTex in the Clouds http://www.terminally-incoherent.com/blog/2011/10/24/scribtex-learn-latex-in-the-clouds/ http://www.terminally-incoherent.com/blog/2011/10/24/scribtex-learn-latex-in-the-clouds/#comments Mon, 24 Oct 2011 14:04:21 +0000 http://www.terminally-incoherent.com/blog/?p=10295 Continue reading ]]> As you know, I am a big fan of LaTex. If you did not know that then you must be new here. Welcome to the blog! I have actually written a fairly large number of posts about this lovely markup language. If you never read any of my LaTex stuff, this should be a good starting point.

I always try to encourage people to try their hand at creating simple LaTex documents just to see how it works. Making your first few steps is actually quite easy. All you need is two or three lines of boilerplate code, and you are ready to go. There is a bit of a learning curve later on, but you will start seeing the benefits of your move right away. For example, if you are a student, expect to be complimented on how nice and neat your assignments look compared to the work your peers.

Alas, getting LaTex to work on Windows might be a bit daunting to the un-initiated. For example, the simplest installation method requires you to download a 1GB self-extracting package that includes everything and the kitchen sink. There are smaller packages, but they tend to be more labor intensive. So just to try LaTex you need to invest a lot of time upfront – you need to download a big file, wait for it to install, familiarize yourself with a new IDE, etc… It is not something most people will do on an impulse. You almost have to set aside about an hour of two for setup before you even write a single line of code.

Are you one of these people who was a bit curious about LaTex after reading my posts about it, but never bothered to install and configure it on your windows machine? Well, I have good news for you – now you can jump right into it, without any setup or preparation. How?

Via ScribTex.

ScribTex is essentially a Google Docs for LaTex. Well, not exactly but I think this is the best way to describe it. The service lets you create new Tex documents directly in your browser or upload existing files and then compiles them for you on the server side. You push a single button and you get a PDF file that you can download and store locally.

The editor window looks like this:

ScribTex Editor Window

The approach is minimalistic – you don’t get any frilly buttons or code-assist tools. Most IDE’s (like TeXnicCenter or TexMaker) will actually give you a much richer interface but in ScribTex all you get is a plain text box, with code highlighting, and two buttons labeled Save and Compile. That’s about it. But I actually don’t mind that. It is plain, simple and it works. More importantly, it makes it a better learning tool.

When you are just starting with a new language you don’t necessarily want the IDE to do all the work for you. It is usually a good idea to do things the hard way first – look up how to do things, use trial and error, explore and etc. Later on the little buttons may be helpful shortcuts, but initially it may be tempting to use them as a crutch. ScribTex removes this temptation.

It gives you something else though. Like most cloud services, ScribTex keeps track of your document’s history and lets you revert to previous versions at will:

The History Page in ScribTex

You know what this is, right? It is poor man’s version control and you get it for free. I mentioned this in my Anti-Word Processor rant – most people don’t actually use any version control. Even when using a LaTex specific IDE you will not get this sort of feature unless you set it up yourself (for example by using DropBox). With ScribTex, you get it for free. This illustrates that the creators have their priorities in order: frills and UI gadgets are nowhere to be found, but robust versioning is built into the core of the service. I like this.

Another feature you won’t find on your desktop is the collaborative editing which seems analogous to similar feature in Google Docs. I haven’t really had a chance to test it so I can’t tell you how well it works, but I know that it is there. Combined with the version tracking, it seems to provide a very decent platform for document sharing and colab-editing.

When you hit the compile button, a preview page will open in a new browser tab:

The PDF Preview Page

I’m not sure what setup do they have for this service, but ScribTex actually compiles documents faster than my computer. And by my computer, I mean the beefy gaming machine, with a fast dual core CPU and ridiculous amount of memory. The compilation takes mere seconds – about as much time as it takes you to load any other page in their service, which is quite impressive.

If your file has errors or warnings they will show up in the log tab on the same screen:

The Log Tab

The quality of the output is decent. The syllabus I used in the screenshots usually compiles to a two page PDF document on my desktop. With ScribTex it got stretched a bit onto the third page. I’m not exactly sure why this happened. I looked through my log and all the packages were found and activated properly, and there were no warnings or weird messages. Perhaps the font scaling is not as granular as in the desktop version?

I guess my point is that the output is not 100% perfect. In certain circumstances your document may be a bit off and not exactly the same as when you compile it with LaTex proper. But whatever failed, failed gracefully. The document wasn’t broken, it wasn’t unreadable and it wasn’t ugly. I guess the slight discrepancies (which only become apparent when you compare two documents side by side) are a fair price to pay for the convenience of compiling your Tex code in the cloud.

ScribTex is a three tier service structure. The basic plan gives you 3 projects, limited number of collaborators per project and up to 50MB of storage space. I do realize that the storage capacity looks like the size of your hotmail inbox in the 90’s (times ten) but it is actually quite reasonable. Roughly 90% of the data you will be storing on their server is going to be plain text, and maybe a few jpeg images for charts. Most documents you will produce probably won’t break 1MB barrier (compare that to Word – an empty .doc file takes up around 300KB of space for some strange reason). So I’d say the storage is fair. It would be much nicer if they started you with 1GB and went from there, but I guess they realize no one would ever upgrade then. Filling up 1GB with pure LaTex data is actually quite difficult.

Here is their price structure:

ScribTex Pricing

The paid plans look a bit pricey to me. While I would like more disk space, $5.99 per month seems a bit too much. I just don’t see myself using this service enough to warrant that kind of expense. But your millage might vary. I almost wish they offered cheep incremental upgrades – like buy additional 50MB of space and an extra collaborator for $1/mo or something like that. A free plan user running low on space would surely be tempted by such an offering much more than by the $5.99 plan.

Best part of the service is probably their free sandbox environment in which you can start experimenting with LaTex without the need to signing up. You can mess around with the sample documents on that page, change them, upload your own files and see how they compile. Your changes won’t be preserved, but it is great for learning and experimenting.

If you ever had an itch to work through some of the examples in my Let’s Learn LaTex series, this is a tool for you. Simply go to the sandbox, hit the “New File” button and start messing around.

All in all, it is a very nifty service. I highly recommend it as a learning tool. I have used it in the last few weeks to quickly tweak documents from computers that did not have any LaTex software. Like a boss. The output is a bit off, the pricing is a bit steep – those two areas could use some improvement. Other than that, I like it.

Oh, and of course it is a cloud application, meaning you don’t actually know who will be reading your documents. Don’t put anything confidential there, and always have a local copy in case a sudden bankrupcy (of the cloud company, not you) or some random ban for obscure terms of service violation. But I guess that goes without saying.

]]>
http://www.terminally-incoherent.com/blog/2011/10/24/scribtex-learn-latex-in-the-clouds/feed/ 4
Re: All Word Processors Suck http://www.terminally-incoherent.com/blog/2011/06/01/all-word-processors-suck/ http://www.terminally-incoherent.com/blog/2011/06/01/all-word-processors-suck/#comments Wed, 01 Jun 2011 14:39:19 +0000 http://www.terminally-incoherent.com/blog/?p=8396 Continue reading ]]> Shamus Young, the guy who brought us the DM of the Rings, the Spoiler Warning Series and Stolen Pixels is currently writing a book. Like a real, dead tree novel type thing. I’m totally stoked to read it, but it seems that he has run into word processing issues recently. This entry is, more or less, a long form response to his blog post. I hope Shamus will read it and that it will help him choose the right tool for the job. I decided to put it here, rather than in his comments section because this stuff might be beneficial to you guys as well.

You see, the issues Shamus just discovered are something I have learned to route around back in grad school. Granted, I have never written a novel, but my Masters thesis was a few hundred pages long. So, you can say that I do have some experience with editing huge documents. Here are some of my pointers. This is the stuff that I had learned the hard way in grad school.

Ditch WYSIWYG

Ditch it! My regular readers are probably familiar with this mantra. I keep going on about this all the time, but there is a reason for it. In my honest opinion WYSIWYG is the root of all evil. Most of the problems that Shamus described in his post stem from the use of a WYSIWYG editor. Not MS Word mind you – any WYSIWYG editor will do this to you. Shamus, for example, was using Libre Office (an open source office suite) which was developed independently from Microsoft Office. And yet, as he described it “duplicated” all the worst flaws and “bugs” of Microsoft Word. How can that be though?

Libre Office team didn’t just copy these flaws from Microsoft. They have never even seen Microsoft Office code (no one outside from Microsoft Employees and contractors does – it is a closed source application). They developed their product independently simply following the conventions established long before Micrsoft was the dominant force in the word processing market.

So what does it tell you when two products developed absolutely independently share a number of identical flaws? It means the problem lies with the design, and not the implementation. To put it simply, What You See is What You Get is a blatant lie. Internally all WYSIWYG editors use invisible markup elements that build up in your document – they basically insert their custom HTML tag like constructs all over your text to indicate where to start paragraphs, what should be bold and etc. The problem is that you cannot see that markup. The last major Office Suite that offered that feature was Corel Word Perfect, but alas, they were run out of business completely marginalized by good old Uncle Microsoft.

The problem with invisible markup is that you never know whether or not you just deleted some formatting tag, section break, paragraph break, or whatever. Every once in a while you apply some formatting to your entire document, and it cocks everything up. The first 6 pages look fine, but page 7 looks like something has chewed and barfed it up all over page 8. Why? Because somewhere in the middle of page 6 there is a major clusterfuck of improperly nested tags. You could fix it, but since you can’t see the problem you are forced to work blind. Most of the time, the more you try to fix it, the worse it gets. Sometimes the only way to rescue your document quickly is to copy it, paste it into notepad (to remove all the invisible formatting) and then re-paste the plain text version into a new document.

I can guarantee you that you will experience these issues sooner or later with every single WYSIWYG tool.

Use Plain Text

The best advice I can give you is to put off formatting till you are done. If you are not ready to wean yourself away from WYSIWYG editors, then don’t but do not give into the urge to start formatting your work. Just type text. Don’t bold chapter names, don’t put page numbers, don’t do anything. Concentrate on content. You can add all that other stuff later. Pretend it’s a plain text editor with a built in spell check…

Can you do that? Ok, good. Now that you are pretending Word is a plain text editor, ask yourself why do you need that bloated piece of software anyway? Both Microsoft Word and Open/Libre Office editors take up lots of memory, and have tons, upon tons of features you will never ever use. On top of that, they are unstable and prone to crashing. Their proprietary file formats are prone to corruption. You don’t need to format your work as you go – you can do that at the end right? So why not ditch these editors.

The only useful feature these tools have going for them is the inline spell checking. You know, the stuff that makes squiggly lines under your words when you misspell them. Well, guess what? These days almost every single text editor which is not Notepad has that feature built in by default. Personally, I prefer Vim but, I admit – it is not for everyone. If you do end up using it, I created this nifty cheat-sheet that hangs over my desk now. Of course the fact that you need a cheat-sheet to use an editor may be a deal breaker to some people. Of course then there is Cream – vim for dummies which strips down some of the raw power, in exchange for convenience and familiar conventions (ctrl+s to save, etc…). It could be worth checking out.

Picking the right text editor is a deeply personal choice. It is a tool that you will be spending a lot of time in, so finding one that does everything you want, and does not get in your way may take you a while. But once you find the right one, you will be much happier and you will never want to look back. There is a lot you can learn about a man just by looking at his preferred text editor.

So this is what you do: you try bunch of them. Save your work as a plain .txt file, and then the editor no longer matters. You can switch it to a different one at a moments notice. There is no converting, no copying and pasting, no hassle. You just can’t go wrong with that format, and most importantly it is almost impossible to corrupt it. Binary Word documents go bad if you as much as sneeze at them, but text simple and robust.

If your publisher, proofreading buddy or thesis adviser insists on Word, you can always just copy, paste and save a copy of your work in their preferred program. It will take you an additional minute or two, to get it formatted the way they like it, but in the long run you will save many, many hours of productivity because you won’t have to deal with WYSIWYG issues.

Shamus, if you want a no frills, stripped down writing experience, have you checked out Q10 or Dark Room. They are full screen editors that remove all the toolbars and menus and allow you to immerse yourself in your work without any distractions. Creative writing types swear by these things.

Use Version Control

When I was writing my thesis, I was extremely paranoid of losing work. Even if technology cooperates with you, shit happens. I cannot tell you know many time I have lost hours of work because I accidentally deleted a chunk of text/code and did not notice it until like the next day at which point there was no way to undo the change. Over the years, I have learned my lesson – never embark on a big project without version control.

This is a big hurdle for non-programmers. Version Control is something we techies learn to use at an early stage in our careers, but creative writing types never, ever actually see it. It is a tool for programmers, but there is no reason why you can’t use it for prose. Fortunately, Shamus is a programmer too, so I hope he will get this.

You don’t need anything fancy. A local Subversion or Git repository is perfect. Just set one up, check your work in, and then at the end of your work cycle, commit your work. The repository will basically take a snapshot of your document at every commit, and you will be able to pull up those snapshots at any time later. So if you suddenly decide that deleting that one chapter was a bad idea, you can easily get it back.

The advantage of a repository is that it hides all these redundant copies from you. It only stores incremental changes, so it takes up far less space, and it avoids the clutter, and the hassle of keeping redundant copies of your work by hand.

If you are a programmer (like me and Shamus) chances are you are already familiar with at least one version control tool, and have at least one repository for your code. So it should be trivial to just start using it for your creative writing and/or academic papers.

If you are not a programmer, and you never used version control tool, don’t fret. I got you covered: use Dropbox. It is dead simple. You sign up, you install a client and assign a single folder on your computer to be the “dropbox folder”. The client will then monitor that folder for changes. Every time you edit a file inside that folder, it will upload your changes into the cloud. Every time you hit save, it makes a copy, and you can later log into the web interface and revert your file to a previous state.

Granted, it is not as powerful as a real repository, but it will do in a pinch.

Make Backups

There is a common trope in movies and TV shows. A struggling writer is shown writing his latest novel on his trusty laptop. This novel is going to either make or break his career. He finishes the first draft the night before deadline, and then BAM – somehow he manages to destroy the laptop which contained the only copy of his work. It is lost in a fire, it falls out the window, he drops it into the tub, etc…

Don’t be that guy! Have redundant backups. Backing up your work is not just for geeks. I should not have to say it, but you would be amazed how many people don’t grasp this concept. If you created a document that can’t be easily reproduced from scratch in a day or two, then having only a single copy of it on a single machine is just stupid.

Especially, since I already gave you a link to Dropbox. In addition to being a poor-mans version control, Dropbox is also a great backup tool. All your changes are automatically uploaded into their web portal. They give you 2GB of free space, but you can buy more if you need too. The free allowances is more than enough space for text though.

It gets even better though – if you install the dropbox client on more than one computer, it will keep all your machines in synch. All of them will have the latest version of the file pushed to them, as soon as you hit the save button. So you can start writing a document on your desktop, then grab your laptop, drive to your local coffee shop, and continue editing like nothing happened. It’s like using Google docs, but you never have to log in, and all your files are stored locally and mirrored across all your computers in addition to being held in the cloud.

LaTex is not Hard

No, seriously. It is not. If you follow my tip, and ween yourself from WYSIWYG and start writing your documents in plain text, then you are only a step away from working in LaTex. You are basically 80% there.

You see, the thing about LaTex is that it is plain text. If you have a .txt document you can convert it to a fully functional LaTex document by:

  1. Changing the extension to .tex
  2. Sticking these two lines at the begging of your document:
    \documentclass[letterpaper, 10pt]{article}
    \begin{document}
    
  3. Appending this line to the end of your document:
    \end{document}

That’s it. That’s all there is to it. Just three lines, and you are using Tex. The rest is just fine tuning, and formatting. But, like I said, you don’t need to worry about that stuff until your done and ready to mess with the formatting.

In case your curious, I have a running series of posts in which I introduce total beginners to the ins and outs of this wonderful technology. Oh, and windows users: here is a list of links that will get you started.

The huge advantage of LaTex over WYSIWYG is that it is just like coding. If you mess up the formatting, the compiler will tell you that you did, and point at a line where you fucked up. There is no guess work, no bizarre undocumented behavior or quirks. If you run into a problem, you can just google the error message, and more often than not, you will find useful information relevant to your problem. As a programmer I find this much, much easier to deal with than seemingly random quirks of WYSIWYG engines. But if you are still not convinced, please go and read my article on why LaTex is superior to Office.

Shamus, good luck on your book. I hope some of this advice will help you. Everyone works differently, personally but I would never trust anything longer than a 1-2 page letter to a WYSIWYG editor.

]]>
http://www.terminally-incoherent.com/blog/2011/06/01/all-word-processors-suck/feed/ 17
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