Typesetting Code in LaTeX

Since I recently pulled a few all-nighters to prepare code slides to teach my students R and they were less than enthusiastic, I thought I’d use the opportunity to at least write up a post on how to display code in LaTeX for you guys. It focuses on displaying the code for teaching, writing tutorials and so on. So the integration of code in beamer will be dominant, or at least the example on which I demonstrate things. Of course, you can also use the tips to just display it in a ‘normal’ document.

When I thought about it, I realized there are actually so many ways of displaying code using LaTeX packages. So I’ll start with the most basic and then go on to the more advanced ones 😉  You can find the example document here on Overleaf. It uses the beautiful metropolis beamer theme, which is worth looking into as well.

code-listings1
Be sure to check out the template on Overleaf.

The \texttt{} command

This one isn’t a verbatim way to express code, but it will change the font to typewriter, so it ‘looks like code’. However, in these short bits of code, you will have to use escape sequences for reserved characters. Furthermore, it (shockingly!) is not natively included in beamer, so you have to add it yourself in the preamble if you want it (as demonstrated in the template). How can one write about code without over-using \texttt{}?

I make massive use of \texttt{} when ‘talking’ about code or, you know, writing explanatory text sequences. It is especially useful for bits of code where there is no excessive (or none at all) use of escape sequences. Then it is a really handy way to quickly typeset code. Once you have lots of reserved characters, you might be better of just using this next one.

The verbatim environment

This one really is a staple and pretty failsafe, but also doesn’t have code highlighting which you might want in most cases, apart from very short bits of code where highlighting isn’t important.

You can use verbatim as an environment for multiple lines of code which appear like a quote as a separate block in your text. In other cases, where you just want \texttt{} but without having to escape reserved characters, you might want to use the \verb|some code| command. You can use any characters as delimiters to denote beginng and end of code. To be more precise, a quote from the Overleaf site: “Any character, except letters and *, can be used as delimiter. ” So it can also be \verb+test+. The idea is that you can choose one which you will not need inside the code, as not to ‘confuse’ the enviroment.

A note about code in beamer

When you use code in beamer, make sure to always use the fragile option for the frames in question. This is necessary due to the way how beamer handles verbatim, apparently.

Also, beamer and code can generally can wreck quite some havoc. I have had problems with lots of KnitR where it would stop working for no reason, then the exact same code would work again later, etc. And there are lots of conflicts and bugs you need to know about. So if you run into problems here, don’t blame yourself. It might easily be beamer which is ‘responsible’ for some of the problems.

The lstlisting package

You can just use the lstlisting environment without configuring anything but then again, it will not have code highlighting which is kind of the point in typesetting code (most times at least).

However, I find that without setting your own colours for the listings, it still looks quite boring with the black and white hightlighting (bold vs. non-bold). You can configure it any way you like, can even define yourself which elements are to be hightlighted and how. But it is quite a lot of work if there isn’t something you like out of the box. I personally prefer minted and especially tcblisting – that is minted with tcolorbox (as far as I know, even though it’s called listing). It has these cute little boxes. I like boxes.

Using KnitR

When using knitr to run R in LaTeX, don’t forget to change the file extension from .tex to .Rtex so LaTeX gets a heads up that you want to use KnitR. Otherwise you’ll end up with jumbled code and might spend hours trying to find the mistake, since it isn’t actually in your code. (Just so you know, I speak from experience here 😉 It’s just so easy to forget to do this. Basically happens to me all the time…)

You can use KnitR out of the box on Overleaf. Note, however, that they might not have all the packages you might want. But if, like me, you just want to display code to teach coding, you can eval=FALSE the results (which will be error messages due to lacking packages) and let the students run the code themselves. Since my elaborated fancy didactical plan was not to share the code as a file but rather have them type it themselves from the presentations, to increase the learning effect. Disclaimer: It did not work out the way I had hoped it would 😉

The minted package

If you like fancy, minted probably is for you. It’s kind of like lstlisting but with more beautiful colours and preset options. Give it a try. It’s probably the go-to solution.

Minted and tcblistings

tcblistings use minted and tcolorbox to create highlighted code listings in cute boxes. For me, that’s just too good to be true 😉 Note, however, that Beamer, tcblisting and enumitem are not compatible with each other. There is a bug I haven’t yet found a way around. So you can’t use customized enumerates oder itemize in the same presentation as these code listings! Sad, but true. But maybe there is a not-all-that-inconveniant way for you to keep presentation and code parts in separate sets of slides anyway. Here, it’s on you to get creative 😉

Generally, with the beamer package, there are actually quite a few things which don’t work once you want to use some less common features. So in case you encounter a bug and really can’t see how it’s your fault, web search if it’s a common error or known bug. Maybe there will be a way around it, maybe there won’t.

A workaround for this specific case would be to use beamer with lstlisting.

Wrapup

So, I hope this helped you and provided you with  an overview of possible ways of typesetting code in LaTeX, with a focus on presentations.

Best, the Ninja

Resources

Buy me coffee!

If my content has helped you, donate 3€ to buy me coffee. Thanks a lot, I appreciate it!

€3.00

Advertisements

LaTeX for PhD students

Today, I decided to finally publish some thoughts on why I think PhD students can profit from using LaTeX. In this post, I try to avoid common not-all-that-creative reasons and point you to some aspects you might not yet have thought about like the fact that your PhD thesis will yield two PDF outputs with (more or less) the same content but very distinct different formatting requirements. Enter LaTeX.

1 PhD = 2 (!) print outputs, i.e. thesis print and printed book publication

Typesetting your PhD in LaTeX is a good idea because of the citation management, for formulars and for images. You probably already know that. But another aspect a lot of people tend to forget while writing their PhD thesis is that a thesis will usually result in two different output PDFs with different typesetting needs: The thesis to be handed in at your university and the print publication which follows. But these two usually have some important differences in requirements. Like a thesis print will probably be a4 or letter paper, a font size of 12pt, etc. A print publication almost always has a smaller paper size and thus, a smaller font size. In my case, this was: paperwidth=170mm, paperheight=240mm and 11pt. Where as a4paper is 210:270, as far as I remember. If you take this into account beforehand, you can save yourself a lot of work and trouble. Also, it’s not like you will suddenly have tons of free time in the time after the PhD writing, probably the opposite. You don’t want to make that even harder by placing another unnecessary burden on yourself.

Already here, LaTeX really pays of. Just change two settings. That’s basically less than 10 characters (!) in your main.tex. If you don’t have to make other changes, that is. Well, you get what I mean. Whereas in MS Word, this can be a lot of effort since quotes probably have a different text size and unless you use the “Standard” predefined templates which you can then change, this can take you a while. Also, it probably often happens to people who don’t reflect on the typesetting while writing (which, after all, will occur long after the writing, so we don’t yet give it a lot of thought) that you don’t consistently use those templates and thus, will have to change or at least check everything manually. With LaTeX, you don’t. Isn’t this enough of a point for LaTeX already? But behold, we have more.

 

Typesetting concerns like orphans and widow lines

Another thing for producing nice typesetting: A (respectable) publisher will usually ask you to take care of orphans and widow lines. In a 300 page MS Word document, you will probably end up having to do this all manually which usually entails all sorts of horrible consequences you hadn’t even dreamt about this far. While this problem cannot be fully automated in LaTeX, you have the possibility of adding this simple statement to your preamble:

\setlength{\emergencystretch}{.25em} % avoid line overflow
\clubpenalty10000\widowpenalty10000\displaywidowpenalty=10000% avoid widow lines and orphans

This, supposing that you have included all the languages you use with \usepackage[ngerman,english]{babel} (for example, last one is the one active), will avoid most line overflows.

A problem that you, admittedly don’t have in MS Word but do have in LaTeX. But more important is the following line. There, we add to the internal ‘penalties’ which LaTeX has, thus preventing orphans and widow lines quite effectively. Maybe you’ll still have to correct one or two things. But one or two things in the whole document, speaking of a document wihch basically handles itself, is not that much of a big deal. In MS Word, calculate to sit down for a few hours. Thus, yet another plus for LaTeX: less grey hair and more time for work-life-balance. Isn’t it amazing?

 

Another plus: Relative and absolute positioning

It’s always better to use relative positioning and values and also, leave litterally everything up to LaTeX. Thank me later. For some info on relative and absolute sizing, consult the upcoming post LaTeX for Archaeologists: Typeset your PhD catalogue in LaTeX post.

 

The (lack of) comment function: A workaround

A possible down-side for LaTeX is that advisors often like to use the comment function in MS Word to correct and comment your work in progress. This, I personally have solved by converting it to MS Word using Pandoc and then uploading it to GoogleDocs for my advisor to make corrections. These have to be put back into the original by hand, of course. But you need to proof-read multiple times anyway, so I reckon it doesn’t make much of a difference. It’s a wee bit inconveniant, is all.

But… LaTeX is scary?! On common concerns

If the prospect of first “having to learn complicated LaTeX” sacres you, you might want to check my article on The power of simplicity, or: Why LaTeX needn’t be scarily complicated. If you think LaTeX will slow you down, you might want to check my post on typing fast in LaTeX. But then again, when writing highly qualitative work (like your dissertation should be), it might even be better if your writing slows you down a little. Pause to reflect!

Transition to LaTeX and get a life. A manifesto

“Well, at some point, LaTeX really had more features than Word but nowadays, I don’t see why you should bother using it anymore.” That’s a typical counter-argument, a justification why people don’t use LaTeX and don’t see why it’s worth the effort to learn it and finally make the transition. To this, I want to say: Well, can it do this? Hint: no. I rather suggest you don’t even try. Well at least, don’t hold me accountable if you should try and fail.

If you don’t see why using LaTeX would benefit you, maybe you just haven’t heard the facts yet? And well, probably you aren’t an archaeologist with 1 million images in a 500-page PhD thesis. If you are, don’t commit suicide just yet. There are other ways than Word. If your thesis document won’t even open anymore, don’t despair. Just convert it to LaTeX! And, thank me later.

Citation styles

LaTeX offers citation support. It’s basically a lot like Citavi or Zotero, only less complicated. Not that I have a lot experience with those, I do admit it. But the principle is the same. LaTeX and Bibtex seem complicated at first. But you’re most certainly just so conditioned and accustomed to MS Word workflows that you don’t remember anything else. And what we don’t know, we fear. But you need not fear, LaTeX is here for you.

A tutorial and more info on this will follow in a separate post.

Yes, LaTeX will throw warnings and errors. It’s not a big deal, really.

People are put off by the fact that you can get warnings or fatal compilation errors. Well yeah, it’s inconvienent to have to debug your own bullshit but well, sorry to have to break it to you, that’s life. Would you rather have a program that doesn’t complain there is a mistake, subsequently hide the problem from you entirely but just stop working for inexplicable reasons and you have no way of escaping? Wait, yes, maybe you do. It’s called MS Word.

You’re not a qualified typesetter

LaTeX is an art. It’s supposed to be an art. Typesetting is an art. And if you haven’t learned to be a typesetter, you probably are not and thus, should not act as a professional typesetter. But MS Word, one hell of a program (and I mean this litterally), makes you believe that you are or you could. It even suggests you should. Hint: You shouldn’t. And in your heart, you really know that’s true.

How to transition from an existing MS Word document or LaTeX-ify your workflow

  1. Migrate your document. (Oxgarage, Pandoc, you name it. Read how to do this in my post on who to quit MS Word).
  2. Continue writing in Word and transform your stuff to LaTeX before adding the images and thus, killing Word for good. Why the hell would anyone want to continue using MS Word? But hey, my opinion isn’t the truth. It’s just my opinion. Do what works for you. If it contains LaTeX, all the better. The LaTeX Noob uses this workflow and it seeems to work for her. Kind of like a “the best of the two worlds” compromise. You get the parts where MS Word is conveniant (letting your advisor use the comment function, etc.), but the typesetting and image handeling is done in LaTeX.
  3.  Just write it in LaTeX. It’s just a question of getting used to it. Using it exclusively will give you just that. Even though I had been using LaTeX for years, transitioning completely made me quite a bit better still. I now also write quick notes in LaTeX without batting an eyelash. Sometimes I still use a GoogleDoc to write things down that are just meant for note-taking, not for creating PDF output.

I will follow up with a post on citation styles and how to import your Citavi to BibTeX, etc. Until then, consider looking up some of my already existing posts which might be of interest, like Jumpstarting: Learn LaTeX in 3 minutes  or A Humanities’ seminar paper with LaTeX – in 10 minutes or How to quit MS Word for good.

Best,

your Ninja

Further resources

The not-so-short intro, also available in German. Tobias Oetiker, Hubert Partl, Irene Hyna & Elisabeth Schlegl: The Not So Short Introduction to LATEX 2ε. Or LATEX 2ε in 139 minutes. Version 6.2, February 28, 2018

https://www.latex-tutorial.com/tutorials/

https://learnxinyminutes.com/docs/latex/

https://en.wikibooks.org/wiki/LaTeX

A Survival Guide for a PhD: http://karpathy.github.io/2016/09/07/phd/

https://www.quora.com/I-wrote-my-PhD-dissertation-in-LaTeX-but-my-advisor-told-me-it-needs-to-be-in-a-format-other-than-PDF-to-send-to-my-committee-members-He-says-it-is-too-difficult-to-make-comments-or-corrections-on-PDF-What-is-the-best-format-for-a-dissertation Quote: “And I’ll even print out the occasional paper and use a red pen. ” yep, good idea. I thought that was actually very sensible advice 😉

https://tex.stackexchange.com/questions/1756/why-should-i-use-latex

https://www.overleaf.com/project/5c42fa03a343e77a02003def (The Scientific Paper: A Template with Tips for Working with LaTeX)

 

Buy me coffee!

If my content has helped you, donate 3€ to buy me coffee. Thanks a lot, I appreciate it!

€3.00