I want to emphasize some lines in a listing environment by applying a special style on them (for example, a different background color).

All custom styling seem to be content-based. I would like to be able to do something like:


If it is not possible with the plain listings package, what do you suggest to get this effect?

My goal is to highlight different lines in different slides of a beamer presentation, so if there is a simple way to do this, I will be very thankful.

Edit: I came up with this solution after Ulrike's idea. I'm satisfied with the result, and the redundancy is bearable for my taste. It'd be very nice if someone more knowledgeable in TeX scripting suggests some improvements.

  • In case you're displaying line numbers, it's useful to add a firstnumber=last option, so that numbering sequentiality is preserved. Jul 27, 2012 at 9:27

3 Answers 3


The only way I know is to reinput the file with different firstline/lastline settings. Not difficult but a bit tedious:

  • Maybe this can be made less tedious by using TikZ' foreach macro. I'll give it a try, thanks! Aug 24, 2010 at 17:42

The simplest way is to use the semiverbatim environment from beamer, see Section 3.13 (Verbatim Text) of the manual. The disadvantage of this method is that you don’t get highlighting.

In order to have all the functionality of the listings package, you could use its fancyvrb interface with commandchars:



|alert[for i:=maxint to 0 do]
{ do nothing }


The symbols in commandchars are replacement characters for \, { and }, properly escaped with backslashes.

I don’t know however how to get overlay specifications (like <1>) to work.

  • I didn't know about semiverbatim. I'll take a look to the manual, thanks! Aug 24, 2010 at 17:51

You could save some arguments in your \emphline-command if you let LaTeX do some of calculations. linerange doesn't seem to like numexpr, but lastline and firstline works fine. E.g in your example you could use


and then

 \only<1> {\emphline{6} {potencia.f95}}             
  • I didn't know about \numexpr either. This opens a world of possibilities! Aug 25, 2010 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.