Highlighting inline code snippets with the latex listings package - latex

In my latex document I am using the listings package extensively.
I have many short inline code snippets that I like to give a proper highlighting in the text, and I am using the \lstMakeShortInline construct. Now I am interested in highlighting (background coloring) at least some of those code inserts for clarity, and was trying the following:
\lstMakeShortInline[language=Python,basicstyle=\ttfamily, backgroundcolor=\color{lightgray}]!
hoping that usage like:
some text some text !read_csv()! some more text
Will result in read_csv() appearing on a light-gray background, but it does not seem to work. The \ttfamily format works well in this situation.
(Thanks to samcarter_is_at_topanswers.xyz)
Here is a minimal example:
\documentclass{book}
\usepackage{listings}
\usepackage{color}
\lstset{language=Python}
\begin{document}
\lstMakeShortInline[language=Python, keywordstyle={\bfseries \color{blue}}, backgroundcolor=\color{yellow}]!
Here is the keyword !for!, showing that the \textbf{keywordstyle} setting takes effect, but the \textbf{backgroundcolor} setting does not.
\textbf{backgroundcolor} fails to take effect also when applied to a non-keyword !df.read_csv()! code snippet.
\end{document}
Is this possible with the listings package?
Thanks
Michael

Based on https://tex.stackexchange.com/a/357239/36296 you could do something like (make sure that ! does not occur in the normal text or use a different character):
% !TeX program = lualatex
\documentclass{article}
\usepackage{xcolor,listings,realboxes,fancyvrb} % fancyvrb for '\Verb' macro
\definecolor{mygray}{rgb}{0.8,0.8,0.8}
\lstset{basicstyle=\ttfamily, breaklines = true, backgroundcolor=\color{mygray}}
\usepackage[doublespacing]{setspace} % just for this example
\usepackage{luacode} % for 'luacode' environment
\begin{luacode}
-- the following code employs Lua's powerful "string.gsub" function
function color_lstinline ( s )
s = string.gsub ( s , "%b!!", "\\Colorbox{mygray}{%0}" )
return s
end
\end{luacode}
%% Define 2 LaTeX macros to switch operation of Lua function on and off
\newcommand{\ColorLstinlineOn}{\directlua{
luatexbase.add_to_callback ( "process_input_buffer" ,
color_lstinline, "color_lstinline" )}}
\newcommand{\ColorLstinlineOff}{\directlua{
luatexbase.remove_from_callback ( "process_input_buffer" ,
"color_lstinline" )}}
\AtBeginDocument{\ColorLstinlineOn} % Default: activate the Lua function
\lstMakeShortInline[language=Python, keywordstyle={\bfseries \color{blue}}, backgroundcolor=\color{yellow}]!
\begin{document}
!for!
\end{document}

Related

How do I send the result of \pgfkeys to Lua?

In the example below the macro "\pgfkeysprintvalue" is a variant of "\pgfkeysgetvalue" that sort of sends the value of a key to Lua, and prints it from Lua:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\pgfkeyssetvalue{/p}{PP}
\pgfkeysgetvalue{/p}{\luatmp}
\luatmp % prints a "PP" in the document
\def\pgfkeysprintvalue#1{
\pgfkeysgetvalue{#1}{\luatmp}
\directlua{print("#1: "..(token.get_meaning("luatmp") or ""))}
}
\pgfkeyssetvalue {/q}{QQ}
\pgfkeysprintvalue{/q} % prints "/q: ->QQ" on stdout
\end{document}
In this other example the first three "\pgfkeys"s have interesting side-effects but expand to nothing, and the "\pgfkeys{/c,/d,/e=DD}" expands to "(c)(d:)(c)(d:DD)":
\documentclass{article}
\usepackage{tikz}
\begin{document}
\pgfkeys{/c/.code=(c)}
\pgfkeys{/d/.code=(d:#1)}
\pgfkeys{/e/.style={/c,/d=#1}}
\pgfkeys{/c,/d,/e=DD}
\end{document}
The last "\pgfkeys" above "prints" the "(c)(d:)(c)(d:DD)" into the document, and it appears in the PDF.
How do I write a variant of \pgfkeys - let me call it \pgfkeysprint - that would store the expansion of its argument in a macro called \luatmp? I guess that it would be like this:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\def\pgfkeysprint#1{
<I don't know what to put here>{#1}{\luatmp}
\directlua{print("#1: "..(token.get_meaning("luatmp") or ""))}
}
\pgfkeys{/c/.code=(c)}
\pgfkeys{/d/.code=(d:#1)}
\pgfkeys{/e/.style={/c,/d=#1}}
\pgfkeysprint{/c,/d,/e=DD} % prints "/c,/d,/e=DD: -> (c)(d:)(c)(d:DD)" on stdout
\end{document}
I'm trying to write functions for inspecting PGF keys from a Lua REPL running inside LuaLaTeX, and the part corresponing to the "<I don't know what to put here>" above is the main piece that is still missing...
Obs: I tried to write my macro \pgfkeysprint by adapting the definition of \pgfkeysgetvalue in pgf/utilities/pgfkeys.code.tex, but I couldn't find the right way to use the "\expandafter"s...

C Source Code in Latex document

Can anyone recommend me a good template to include C source code with line numbering
in Latex? For example, taking the classical Hello world program, I would like to make it look as follows:
(1) /* Hello World program */
(2)
(3) #include<stdio.h>
(4)
(5) main()
(6) {
(7) printf("Hello World");
(8) }
Typicall, I always used the verbatim environment, but I am wondering if there is a better and nicer way to do that.
Thanks so much
Richard
As others have said, the listings package will probably do what you want using something like the following:
\lstset{
language=C, % choose the language of the code
numbers=left, % where to put the line-numbers
stepnumber=1, % the step between two line-numbers.
numbersep=5pt, % how far the line-numbers are from the code
backgroundcolor=\color{white}, % choose the background color. You must add \usepackage{color}
showspaces=false, % show spaces adding particular underscores
showstringspaces=false, % underline spaces within strings
showtabs=false, % show tabs within strings adding particular underscores
tabsize=2, % sets default tabsize to 2 spaces
captionpos=b, % sets the caption-position to bottom
breaklines=true, % sets automatic line breaking
breakatwhitespace=true, % sets if automatic breaks should only happen at whitespace
title=\lstname, % show the filename of files included with \lstinputlisting;
}
\lstinputlisting{HelloWorld.c}
A more powerful alternative would be to use the minted package, although this will do much more than what you're currently asking, as it uses/requires pygments to be installed on your system so that it can fully tokenize the code you give it.
You might want to have a look at the listings package. It is very flexible and easy to use.
Take a look at Code listings in LaTeX. You'll find a couple of alternatives there. Some options are:
listings
minted
lgrind
Use lgrind package for latex. It converts your code into a .tex file
CWEB had a nice C formatter.

Inserting code in this LaTeX document with indentation

How do I insert code into a LaTeX document? Is there something like:
\begin{code}## Heading ##
...
\end{code}
The only thing that I really need is indentation and a fixed width font. Syntax highlighting could be nice although it is definitely not required.
Use listings package.
Simple configuration for LaTeX header (before \begin{document}):
\usepackage{listings}
\usepackage{color}
\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\lstset{frame=tb,
language=Java,
aboveskip=3mm,
belowskip=3mm,
showstringspaces=false,
columns=flexible,
basicstyle={\small\ttfamily},
numbers=none,
numberstyle=\tiny\color{gray},
keywordstyle=\color{blue},
commentstyle=\color{dkgreen},
stringstyle=\color{mauve},
breaklines=true,
breakatwhitespace=true,
tabsize=3
}
You can change default language in the middle of document with \lstset{language=Java}.
Example of usage in the document:
\begin{lstlisting}
// Hello.java
import javax.swing.JApplet;
import java.awt.Graphics;
public class Hello extends JApplet {
public void paintComponent(Graphics g) {
g.drawString("Hello, world!", 65, 95);
}
}
\end{lstlisting}
Here's the result:
You could also use the verbatim environment
\begin{verbatim}
your
code
example
\end{verbatim}
Here is how to add inline code:
You can add inline code with {\tt code } or \texttt{ code }. If you want to format the inline code, then it would be best to make your own command
\newcommand{\code}[1]{\texttt{#1}}
Also, note that code blocks can be loaded from other files with
\lstinputlisting[breaklines]{source.c}
breaklines isn't required, but I find it useful. Be aware that you'll have to specify \usepackage{ listings } for this one.
Update: The listings package also includes the \lstinline command, which has the same syntax highlighting features as the \lstlisting and \lstinputlisting commands (see Cloudanger's answer for configuration details). As mentioned in a few other answers, there's also the minted package, which provides the \mintinline command. Like \lstinline, \mintinline provides the same syntax highlighting as a regular minted code block:
\documentclass{article}
\usepackage{minted}
\begin{document}
This is a sentence with \mintinline{python}{def inlineCode(a="ipsum)}
\end{document}
Specialized packages such as minted, which relies on Pygments to do the formatting, offer various advantages over the listings package. To quote from the minted manual,
Pygments provides far superior syntax highlighting compared to conventional packages. For example, listings basically only highlights strings, comments and keywords. Pygments, on the other hand, can be completely customized to highlight any token kind the source language might support. This might include special formatting sequences inside strings, numbers, different kinds of identifiers and exotic constructs such as HTML tags.
Minted, whether from GitHub or CTAN, the Comprehensive TeX Archive Network, works in Overleaf, TeX Live and MiKTeX.
It requires the installation of the Python package Pygments; this is explained in the documentation in either source above. Although Pygments brands itself as a Python syntax highlighter, Minted guarantees the coverage of hundreds of other languages.
Example:
\documentclass{article}
\usepackage{minted}
\begin{document}
\begin{minted}[mathescape, linenos]{python}
# Note: $\pi=\lim_{n\to\infty}\frac{P_n}{d}$
title = "Hello World"
sum = 0
for i in range(10):
sum += i
\end{minted}
\end{document}
Output:
Use Minted.
It's a package that facilitates expressive syntax highlighting in LaTeX using the powerful Pygments library. The package also provides options to customize the highlighted source code output using fancyvrb.
It's much more evolved and customizable than any other package!
A very simple way if your code is in Python, where I didn't have to install a Python package, is the following:
\documentclass[11pt]{article}
\usepackage{pythonhighlight}
\begin{document}
The following is some Python code
\begin{python}
# A comment
x = [5, 7, 10]
y = 0
for num in x:
y += num
print(y)
\end{python}
\end{document}
which looks like:
Unfortunately, this only works for Python.
Since it wasn't yet mentioned here, it may be worth to add one more option, package spverbatim (no syntax highlighting):
\documentclass{article}
\usepackage{spverbatim}
\begin{document}
\begin{spverbatim}
Your code here
\end{spverbatim}
\end{document}
Also, if syntax highlighting is not required, package alltt:
\documentclass{article}
\usepackage{alltt}
\begin{document}
\begin{alltt}
Your code here
\end{alltt}
\end{document}
Use Pygments !

How to create a white-on-black style for LaTeX listings

I've been looking at Philip Bunge's post on how to create a "Tango" style with LaTeX listings, and trying to adapt this to make the default text style white and the background black (this is for slides, not an article!). This is what I added:
\definecolor{Black}{gray}{0.0}
\definecolor{White}{gray}{0.9}
...
\lstset{
basicstyle=\color{White},
backgroundcolor=\color{Black},
...
}
This assumes that basicstyle sets the default style of all text. The listings documentation says this:
basicstyle is selected at the beginning of each listing. You could use \footnotesize,
\small, \itshape, \ttfamily, or something like that. The last token of must not read any following characters.
The output of this still shows "default" text as black. It is possible to set more style directives that cover most tokens in a given programming language, but even doing this some tokens (such as brackets and other punctuation) will be missed. What did I do wrong?
The following code worked for me, but I converted the .dvi file to a .pdf in order to have the text appear as white, so it might have been your viewer? I'm using xdvi and xpdf.
\documentclass[a4paper, 11pt]{article}
\usepackage{listings}
\usepackage{color}
\definecolor{theWhite}{gray}{0.9}
\definecolor{theBlack}{gray}{0.0}
\lstset { basicstyle=\color{theWhite}, backgroundcolor=\color{theBlack} }
\begin{document}
\begin{lstlisting}
((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))
\end{lstlisting}
\end{document}
I hope that helps!

Latex listings-package format option for uppercase keywords

I use the listings package to insert source code. I would like to print all keywords uppercase in the output, regardless of the case in the input.
The manual states that
keywordstyle=[number][*]style
produces just what I want. However the following (almost) minimal example does not work.
if I set keywordstyle to "[1][]{\bfseries}" I end up with "[]" in front of every keyword
and "[*]{\bfseries}" gives me an asterisk in the start of the document.
I also tried "\MakeUppercase" and "{\MakeUppercase}" for keywordstyle which resulted in several errors, the first being:
! Incomplete \iffalse; all text was ignored after line 11
Minimal example:
\documentclass{article}
\usepackage{listings}
\lstdefinelanguage{KA_assembler}
{morekeywords={add,and,or,xor},
keywordstyle=[1][*]{\bfseries},
sensitive=false,
}
\lstset{language=KA_assembler}
\begin{document}
\begin{lstlisting}
and %r1, %r2
xor %r2, %r3
and %r4, %r5
\end{lstlisting}
\end{document}
I use Miktex for compilation of the tex files. So how do I force uppercase for Keywords?
In the manual, the brackets around the * look a bit different then the brackets around number. The reason is that the brackets around * are not meant to be used in the latex code, they just indicate that the presence of the * is optional. So try
keywordstyle=[1]*\bfseries
or
keywordstyle=*\bfseries
- it worked for me.

Resources