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.
up vote 22 down vote accepted
\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

\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

  • Can you explain briefly what does \usepackage[T1]{fontenc} do? – Peter Krumins May 3 '11 at 13:55
  • @Peteris Krumins Have a look at this answer: tex.stackexchange.com/questions/664/… – Thorsten May 3 '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 3 '11 at 14:03
  • Thanks! Now I know what it does. :) I also just had the pipe | problem in the text, and I was all confused what was going on and the usage of T1 encoding solved it, too! – Peter Krumins May 3 '11 at 14:05
  • This looks awesome Herbert! No more $\sim$ substitution for me---I wish I could upvote this answer twice! – Sharpie May 5 '11 at 23:20

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} 

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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