27

How do I insert a nice tilde that is centered in the middle in a lstlisting? I found another thread about tildes but I can't apply it because the method described there only works outside of lstlisting as lstlisting displays all the text literally. Any ideas?

Here is how the tilde looks in my document at the moment - it's at the very top of the font and I would like it to be in the middle (like ~ this).

enter image description here

Here is the LaTeX for this fragment:

\section{Remove duplicate, consecutive lines (emulate "uniq")}

\begin{lstlisting}
awk 'a !~ $0; { a = $0 }'
\end{lstlisting}

Variables in Awk don't need to be initialized or declared before they are being used.

3 Answers3

30
\documentclass{minimal}
\usepackage{listings}
\lstset{
    literate={~} {$\sim$}{1}
}
\begin{document}

\begin{lstlisting}
awk 'a !~ $0; { a = $0 }'
\end{lstlisting}

Variables in Awk don't need to be initialized or declared before they are being used.
\end{document}

enter image description here

Thorsten
  • 12,872
  • 3
    If $\sim$ is too wide or prominent, then \texttildelow may be better. Source: https://tex.stackexchange.com/a/9365/120598 – goodmami Sep 23 '19 at 07:32
  • And, personally, an even better option is to do \lstset{ literate={~}{{\raisebox{0.5ex}{\texttildelow}}}{1} }, which raises \texttildelow. Source: https://tex.stackexchange.com/a/377/141755 – Breno Jan 18 '22 at 21:00
  • I get TeX capacity exceeded, sorry [grouping levels=255] after a substantial number of occurrences of ~ in a listing. Is there a remedy for that? – AstroFloyd Apr 13 '22 at 10:18
12
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[scaled=0.85]{beramono}
\usepackage{listings}
\begin{document}

\begin{lstlisting}[basicstyle=\ttfamily]
awk 'a !~ $0; { a = $0 }'
\end{lstlisting}

\end{document} 

enter image description here

  • @Peteris Krumins Have a look at this answer: http://tex.stackexchange.com/questions/664/why-should-i-use-usepackaget1fontenc/677#677 – Thorsten May 03 '11 at 14:01
  • 1
    @Peteris It uses a better fontencoding. But it is not the main point of Herbert's example. With beramono he changes to another typewriter font with a better looking tilde. – Ulrike Fischer May 03 '11 at 14:03
  • This looks awesome Herbert! No more $\sim$ substitution for me---I wish I could upvote this answer twice! – Sharpie May 05 '11 at 23:20
  • I get TeX capacity exceeded, sorry [grouping levels=255] after a substantial number of occurrences. Is there a remedy for that? – AstroFloyd Apr 13 '22 at 10:19
10

The above tip also works with T1 encoding and the courier package:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{courier}
\usepackage{listings}
\begin{document}

\begin{lstlisting}[basicstyle=\ttfamily]
awk 'a !~ $0; { a = $0 }'
\end{lstlisting}

\end{document} 
Thorsten
  • 12,872
kolesarm
  • 101
  • 1
  • 3