hckr.fyi // thoughts

Creating an Index in LaTeX for PDF Output

by Michael Szul on

One of the major reasons Bill and I started Codepunk was for the distillation of information. If I learn something that I think others could benefit from, I'll drop it here.

That's been the reason for the last few LaTeX posts. In writing my book, I had to learn some formatting/processing of text, and that involved a decent amount of research.

Many moons ago, I experimented with self-publishing, and had no idea what I was doing. When it came time to write the index, I did it by hand, figuring out which pages had which words, and what should be cataloged. It was a beast.

In working on the chatbot book, I used several tools and processors to get the exact layout, style, and format that I wanted. I started it in Markdown, and then used Pandoc to convert it to LaTeX. It was in LaTeX that all the hard work was done--specifically with formatting. Luckily, with a few packages, creating the index was pretty easy.

A couple of things worth noting: My Windows installation for LaTeX is the MikTeX flavor, and I used the LaTeX Workshop in the Visual Studio Code Marketplace. I then had to install Perl to get the latexmk recipe to run. For that, I used Strawberry Perl.

To start, we include the package at the top of our LaTeX file:

\usepackage{makeidx}
    

Then, before the end of our document, we need to print the index:

\printindex
    

Inside of your document, you just have to add \index commands after the words you want indexed:

Much like Skype\index{Skype}, if you want your bot to appear in the Facebook Messenger\index{Facebook Messenger}
    application directory, it'll have to go through a review process.
    

In the example above, the text passed to the index command matches the word that's being indexed, but you could just as easily do Facebook Messenger\index{Messenger} or something similar. The text passed to the command is what shows up in the index with the page number.

When you process your document, it needs to run once to build the index file, and then again to actually insert the index. This is why we went with the latexmk recipe, which will process everything for you without you having to know which commands to run and at what point.

With these few commands, you can then LaTeX build your index for you without having to worry about your page numbers and formatting.