24 Apr 2012

LaTeX is More Powerful than you Think - Computing the Fibonacci Numbers and Turing Completeness

LaTeX is a powerful tool. So powerful in fact, that it can be used for much more than document markup. LaTeX is Turing complete; that is, it can be programmed to compute just about anything.

To demonstrate the general purpose programming abilities of LaTeX, we'll look at an example that calculates the first Fibonacci numbers. While this isn't a proof of Turing completeness, it is a good example of a complete algorithm implemented in LaTeX.

The Fibonacci Numbers

Each number in the Fibonacci sequence is the sum of the previous two terms in the sequence, with the first two terms defined as 1 to provide a starting point.

We can write a new command that will compute these numbers. Let's begin by deciding how a call to our yet-to-be-built command should look.

\fibonacci{10}

When this command is called from our LaTeX document, it should produce a list of n Fibonacci numbers (where n=10 in the example call here). Here is the code for the \fibonacci function. Let's take a look at how it works.



\newcount \temp \newcount \fone \newcount \ftwo \newcount \counter

\newcommand{\fibonacci}[1]{
\counter=#1
\fone=1
\ftwo=1
\temp=0
\the\fone, \the\ftwo
\fibloop
}

\newcommand{\fibloop}{, 
\let\next= \fibloop
\temp=\fone
\fone=\ftwo
\advance \ftwo by  \temp
\ifnum \counter \let\next=\relax \else \advance \counter by -1  \fi
\the\ftwo
\next
}


First, we set up a few variables that we'll use later. The \newcount command gives us a variable we can use to hold an integer, here we create four: \counter \fone \ftwo and \temp. It's worth mentioning that these are not actually new variables, they are more like aliases for counters that already exist. These can be used directly as \count0, \count1, etc. Assigning names prevents us from writing to a counter that is already is use. If you're curious, replace one of the variables in this code with \count0, and the page numbers will be wrong for the rest of the document.

We next have the \fibonacci command. We create it with \newcommand, which we provide with the name, number of arguments, and TeX code to process as arguments. For this program, we accept a single argument, the number of Fibonacci numbers to output. The content of this command is simple: we set default values for our variables, print the first two Fibonacci numbers (since they don't need to be calculated), and then call \fibloop, which will do the heavy lifting for our calculations.

The command \fibloop is declared in the same way. A key part of the program is the way in which it loops. We use a function called next, and you'll see that the first command within \fibloop sets this, and the last line calls it. We set \next to \fibloop, so the function will repeat until \next is changed by code within the \fibloop command. We only want to loop n times, so we use an if statement that checks the value of our counter, and then if it hasn't reached the threshold, decrements the counter value each time through the loop. If the condition is met, we set \next to \relax, which will prevent \fibloop from repeating again.

The other commands in this block calculate the next Fibonacci number in the sequence, and update the values of the variables so they're ready for the next pass. The command \the\ftwo prints the value of the current number to the document, you'll also notice a comma and a space at the top of the command to separate each value.

The Result

The simplest way to see this example in action is to copy the code above into the top of your .tex document, then add the line 

\fibonacci{n}

to the body of your document, replacing n with a number. The Fibonacci sequence grows quickly, so any n>46 will result in an integer overflow in this particular implementation. If you're using ScribTeX, you can use the example main.tex as a starting point, and add this code to it.

Where to go from Here?

This was an example of the programming capabilities of LaTeX. As an informal proof that LaTeX is Turing complete, I present the following code: 

\newcommand{\nand}[2]{
 \count0=#1
 \count1=#2
 \ifnum \count0=\count1 \ifnum \count0 0 \else 1 \fi \else 1 \fi
 } 

which is a quick and dirty implementation of a NAND gate. NAND (and also NOR) logic gates have the interesting property that any other logic gate can be formed with just this single type of gate. From the basic logic gates latches, flip-flops, and memory can be created. Those are the ingredients for a general-purpose computer. You can test this NAND gate for each of its four possible inputs with the following code.



\nand{0}{0}
\nand{0}{1}
\nand{1}{0}
\nand{1}{1}


Knowing that LaTeX is Turing complete opens up a world of possibilities. Code like this is common in the back-end of LaTeX, for things like keeping track of page and figure numbers, and making decisions about where to place floats. It's a tool that you can use to your advantage to simplify complex document layouts.

To end this post, I'll leave you with some further reading on examples of programming in LaTeX and Turing machines in general.

LaTeX Programming Examples:

The Mandlebrot Set in LaTeX [http://warp.povusers.org/MandScripts/latex.html]. Special thanks to this one, this code was a helpful example while writing my Fibonacci command.

Turing Machine Simulator in LaTeX [http://en.literateprograms.org/Turing_machine_simulator_(LaTeX)]. This is a Turing machine that creates a description of its state as it runs the 3-state busy beaver problem.

Wikibook on TeX commands [http://en.wikibooks.org/wiki/Category:TeX]. 

LaTeX in a programming contest [http://sdh33b.blogspot.com/2008/07/icfp-contest-2008.html]. A mars rover controller in LaTeX beat out entries in several more common programming languages.

Turing Machines in Unexpected Places:

Conway's Game of Life is turing complete [http://rendell-attic.org/gol/utm/index.htm]. Here is an implementation of a Turing machine.

Rule 110 [http://en.wikipedia.org/wiki/Rule_110] is a 1-D cellular automata which is Turing complete.

Minecraft (the video game) is Turing complete [http://www.youtube.com/results?search_query=minecraft+turing+machine]. Several examples have been built, so this link is simply to a page of relevant youtube search results.

 

31 Jan 2012

Goals for 2012

We're now about half way between the beginning of 2012 and the 2nd aniversary of ScribTeX being reincarnated into the website it is today. So this seems like as good a time as any to lay out our plans for the future.

In 2011 most of my focus was on developing the new editor which is rolling out as we speak. Other exciting things included a doubling of our team size (from 1 to 2, welcome Josh!) and a doubling of our traffic.

Here's our manifesto for 2012:

  1. A desktop-like experience. A huge advantage of ScribTeX is the ease and portability that it brings to getting set up with LaTeX. However, we're aware that the editing experience doesn't match up with that available on the desktop. Expect to see features like autocompletion, templates, tex/PDF syncing, code-folding coming to the new editor throughout the year as well as some general usability improvements.
  2. Scaling our infrastructure. Our servers have been coping with the demand on them well so far. However, as our traffic increases we're going to need to start to think about how we can continue to grow the service. This is an exciting challenge which I look forward to keeping you updated on.
  3. Increased support for API access, starting with the CLSI (http://clsi.scribtex.com) for remotely compiling LaTeX documents. We want to make ScribTeX a platform that others can build on to make the web more exciting and useful. The CLSI is open source (http://github.com/jpallen/clsi) and we hope to release more code under an open source license this year, so get your bug fixing hat on a dig in!

Of course, there are hundreds of other smaller goals that we'll be working away on as well, but these three points best outline the direction that we'll be taking ScribTeX in the future.

31 Jan 2012

Keep track of your labels with showlabels

Whenever I'm writing long LaTeX documents I always find myself jumping backwards and forwards in the code trying to remember what I named a \label. To save me losing my place in the code I use the showlabels package which displays the name of the label next to the corresponding equation. Then I can look in the PDF where it's easier the find the equation I'm looking for and I don't need to jump around in my code. It works on nearly everything you can assign a \label to. Marvelous!

Usage

In your preamble put:

\usepackage{showlabels}

Example Output

Screen_shot_2012-01-31_at_21
(This example has the inline option enabled)

Options

You can provide an option to showlabels to tell it where to place the labels: 

\usepackage[inline]{showlabels}

Availabe options are (taken from the documentation):

  • outer [default] - all notes are placed in the text's outer margin
  • inner - inner margin
  • left - left margin
  • right - right margin
  • marginal [default] - put notes in the margin
  • inline - put notes inline, as much as possible, and ignore any of the margin-placement options above
  • nolabel - do not insert a marginal note for \label commands
  • draft [default] - does nothing, partner of...
  • final - turns o ff all the package's functionality

Note that showlabels should be included after the packages amsmath and hyperref to work correctly with them. See the official documentation for more details.

 

28 Jan 2012

The first round of beta testing of the new editor begins!

It's been a long time since we announced that we were developing a new editor for ScribTeX. We've had plenty of false starts, changes of plan and last minute realisations, but I'm pleased to announce that as of today we are starting to roll it out to a limited number of users to beta test. If all goes well, we'll keep expanding who it is available to until everyone can use it.

Pictures can say far more than words, so here are a few screenshots:

(download)

If you'd like to get early access and help us with feedback and bug hunting, please let us know. Tell us your ScribTeX username either in the comments below, or via an email to team@scribtex.com. We'll try our best to let everyone use it as quickly as possible.

27 Mar 2011

How to write a LaTeX class file and design your own CV (Part 1)

Everyone wants a professional looking CV and there are no shortage of LaTeX templates that will give you one. If you're like me though you'll want to own your CV and make it your own. That means you need to be able to customise the look and feel yourself which can be notoriously difficult in LaTeX. In this series of blog posts I hope to guide you through creating your own custom class file and show you that it can be easy to format your CV exactly how you want. We'll focus on a CV style but the methods will be identical for any sort of document.

What is a class file?

When you write \documentclass{article} in your LaTeX file, you are including the class file article.cls. This defines all the commands like \section and \title which go into structuring your document. It also configures how these commands affect the format and layout of the page.

Setting up your own class file

The neatest way to customise the format of a document is to keep all that information in a personal class file. This keeps the structure of your document cleanly separated from the formatting and allows for easy reuse. It's easy to set this up so create a document called cv.tex with the following content:

This is trying to load your custom class file my_cv.cls, which doesn't exist yet. Create my_cv.cls in the same directory as cv.tex and write the following line in it:

If you compile your document now you should see the headers in the default article style.

So what has happened here? Class files need to contain a lot of formatting information and internal setup to make LaTeX work properly, but we don't want to have to enter it all manually. Instead we can base our new class file on article.cls. We use \LoadClass to include article.cls and load all of the commands and styles defined in it. Note that we don't use the usual \documentclass command to include article.cls because \documentclass should only ever be called once at the very beginning of your LaTeX document.

Telling LaTeX about your class

All class files should start with two lines similar to the following, which you should add in at the top of my_cv.cls now:

The \NeedsTeXFormat commands tells the compiler which version of LaTeX the package is for. The current version of LaTeX is LaTeX2e and almost all distributions use this.

The \ProvidesClass command gives the compiler some information about your package. The first argument should match the filename of your class file and tells LaTeX what your package is called. The second argument is optional and provides a description of your class which will appear in the log and other places. The description must begin with a date in exactly the format above and it should be the date the package was last modified. This can be used when including the class to check that you have a recent enough version of it. For example if you include it via \documentclass{my_cv}[2012/01/01] with a date which is newer than the date in the class description then a warning will be shown saying that the class is outdated.

Modifying the section headers

The standard article section headings don't really suit a CV so we'd like to replace them with something neater. To do this, we can redefine the \section command to output a custom header. 

Fortunately there is already an excellent package called titlesec which provides an easy way to to customise our header styles. Include this in your class file with

Notice that we should use \RequirePackage rather than the usual \usepackage command because we are in a class file. The \RequirePackage command makes sure that each package is only loaded once, even if called multiple times from different style and class files.

The titlesec package provides the command \titleformat which lets us customise our section headings. Add the following at the end of my_cv.cls to customise the format of the heading:

If we compile cv.tex now we will see that we have some main headers more appropriate for a CV:

Screenshot1

We can customise the \subsection headers as well:

The sub-sections are now in the same style:

Screenshot

You should try out some of the formatting options available to see what you like:

  • \bf, \it - make the heading bold or italic,
  • \scshape - small capitals,
  • \small, \normalsize, \large, \Large, \LARGE, \huge, \Huge - set the font size,
  • \rmfamily, \sffamily, \ttfamily - set the font type to serifed, san serifed or typewriter respectively.

Adding dates to section headers

We can define some new commands which let us include dates in our section headings. Include the following in your class file:

This defines two new commands \datedsection and \datedsubsection which take two arguments: the section name as before, and a date which will be typeset on the right hand side of the page. The \hfill command tells LaTeX to fill as much space as possible and so pushes the second argument (#2) to the right of the page. Modify cv.tex to use these commands:

Our CV now contains dates:

Screenshot-1

Conclusions

That's all for part one of this guide, but hopefully I've covered enough for you to go away and start making useful class files. It hasn't taken many commands to create what already looks like a reasonable CV template and we've only scratched the surface of what else we could customise. In the next few parts of this guide I will talk about passing options to your class to configure it, creating a nice title and how to set some general layout options.

Thanks for reading!

(I am relatively new to creating class files myself, so if anyone can point out better ways to do the things I have mentioned here, please let me know.)

 

22 Mar 2011

Updated compile interface

A few users have been experiencing problems compiling large documents, but thanks to a new compling interface and some backend infrastucture changes these documents shouldn't pose any problems now. For most users this will be a minor user interface update, although the mobile view has been significantly improved. These are the first components of the new editor which will be rolled out slowly in small chunks like this over the next few months.

Technical Details

Previously when a document was compiled, a request would be sent to the ScribTeX servers which would send a request to the compile server. Both of these connections would be left open while the compile was processed and eventually returned via the ScribTeX server back to your browser. This was fine for small documents, but larger compiles would take long enough that the server would timeout and close its connection. The user would be returned an error, despite the fact that the compile would still succeed after the connection was dropped.

Now the compile happens behind the scenes without needing to keep a connection open. The ScribTeX server sends a request to the compile server and then immediately returns a page to your browser. Your browser will then keep asking the compile server if it is finished and when it has the PDF and log are downloaded. This way nothing will timeout even if the compile takes a long time. 

8 Feb 2011

Have a sneak peak at the new editor

Here are some in-progress screenshots of the new editor I am developing for ScribTeX:

(download)

Some of the most important new features are:

  • Line numbers
  • Better information about where LaTeX errors occured, and the ability to jump to the line
  • Open multiple files in tabs
  • Based on the Ace editor which is fast and responsive

Please let me know what you think so far and what you are looking for in the ScribTeX editor.

1 Feb 2011

Git access enabled for all users

ScribTeX is flourishing as an online LaTeX editor and can now become your main collaborative hub with access to your project's git repositories. Git is a powerful version control system which helps to keep two or more copies of a project up to date with each other. With ScribTeX it will make it easy to keep a local copy of your project synchronized with your online files. Git takes care of tracking changes and merging any differences that arise between the copies. Unfortunately git has quite a steep learning curve, but if you are new to it and looking to learn more then the Git Community Book is a great place to start.

To access your project's git repository you must have an SSH key pair set up. This is a secure way of authenticating your computer with the ScribTeX server. If you aren't familiar with SSH keys, the documentation at GitHub provides an excellent guide for setting them up. Most of the guide will apply equally well to ScribTeX and the GitHub specific steps can easily be adapted.

Once you have your SSH keys configured you need to upload your public key to ScribTeX. This can be done through your preferences:

Screenshot-edit_your_account__scribtex_-_mozilla_firefox

Click on 'Edit Preferences' in the Account details section of your dashboard. From here, click on 'SSH Keys' and you will be prompted to upload your public key. You should give the key a descriptive name such as the computer it corresponds to.

You will now be able to access your projects via git. To find the url for a project, go to its settings page and click on 'Git Access':

Screenshot-scribtex_demo_settings__scribtex_-_mozilla_firefox

You can use git to checkout and maintain your projects offline:

$ git clone git@git.scribtex.com/bob/my-project.git

Make some local changes, commit them to git, and push them back to ScribTeX:

$ git commit -a -m 'Updated my files on my own computer'
$ git push origin master

Enjoy!

Please note that ScribTeX is not a full git hosting solution and has a few restrictions. ScribTeX is very fussy about preserving its history and so you will not be able to rebase or change any commits that already exist on the ScribTeX server. Hopefully this restriction will eventually be lifted, but for now it keeps things sane on the ScribTeX server. You should also note that only the master branch is available for editing via the ScribTeX web interface.

22 Jan 2011

Choose your compiler: pdflatex, latex or xelatex

I know I'm a bit late, but Happy New year to all the ScribTeX users out there. I hope 2011 is a good year for you. I know this blog sees a lack of regular updates so I've made one of my New Year's resolutions to post regular updates on how ScribTeX is getting on, and what I'm working on to improve it. This time I'm going to talk a bit about how you can now choose between different compilers for each project.

There are three different compilers you can choose for each project: pdflatex, latex, xelatex. These are the programs that convert your .tex files into a nicely formatted pdf document. Previously, ScribTeX only used pdflatex to compile your documents. This is the best choice for the majority of users, but there are certain things that pdflatex can't do which latex and xelatex can.

For example, a big difference is that latex compiles natively to a postscript file but pdflatex compiles directly to a pdf. Some packages like pstricks make use of commands that only make sense to postscript files and so can't be used with pdflatex. If you want to use packages like pstricks you can now use them with the latex compiler instead.

xelatex is a more recent compiler and has better support for modern fonts and Unicode encodings. A lot of the power of XeLaTeX comes from the ability to use almost any font with LaTeX, but ScribTeX only has the standard fonts installed at the moment. If you would like to add some extra ones that you need, please open a support ticket, or drop me an email at team@scribtex.com. Please consider that the font must have an appropriate license for use by ScribTeX though.

To choose the compiler for your project, goto 'Settings' on the project page, and then 'Compiler Settings'. You should see a drop down box where you can choose between pdflatex, latex and xelatex as the default compiler:

Screenshot

8 Aug 2010

Carrying Forward the Academic Collaboration Banner

It will come as a blow to many academics that Google have recently decided to discontinue support for Google Wave, their real-time collaboration and communication tool. When Google originally announced Wave there were many in the academic community who were looking forward to having a platform for a mix of real-time communication and joint editing. With the addition of LaTeX widgets things looked really promising. Sadly, Wave didn't live up to it's promised potential. It did the job, but it didn't become the perfect tool academics were hoping for. None the less, I'm sure it will be missed.

There have been plenty of blog posts dissecting Google's decision and most seem to have reached the same conclusion. Google Wave tried to be all things for all people and instead ended up being confusing and hard to use. Waves are neither document nor chat, and they certainly aren't up to handling large amounts of LaTeX. When you're trying to write a paper or some other document you need an environment that will handle not just snippets of mathematics but the full typesetting power of LaTeX. For this niche use, Wave is little better than a wiki with support for inline equations.

Wave could be useful as a communication tool or, in less generous terms, a glorified instant messenger. It's real-time nature certainly makes this a possibility, but whenever I tried to use it like this I ended up overwriting things I shouldn't have. Sometimes being able to edit anything that has gone before isn't good idea. A conversation has a distinct linear evolution and this needs to be respected if communication is going to be clear.

So Google Wave is on it's way out, but I'm sure that it has pushed us further towards a good solution. There are similar products that are coming out of the woodwork now that Wave won't overshadow them. Hopefully people will take all the things that Google Wave tried to be and separate them into niche products that do their specific job well.

In the case of collaborating on a LaTeX document, I'd like to think ScribTeX has got that one covered.

ScribTeX is far from perfect and I have a hundred and one features I would like to add, but I'm very aware of making sure it doesn't become a tool for all possible uses. If it does, it will stop being focused on the one task it should do well - editing a LaTeX document. ScribTeX will never become a multitool for academics, but I'm sure it kicks Wave's ass at writing papers collaboratively.

I look forward to seeing which other niche uses can be extracted from Wave. The more focused tools there are, the less we need tools like Wave.

ScribTeX's Space

Welcome to the blog of the ScribTeX, the online LaTeX editor. We try to focus on making LaTeX easy to use and fun to collaborate with. Try it out at http://www.scribtex.com

Contributors

ScribTeX James Allen rmurrish