Search code examples
latexlistings

Changing how the LaTeX listings package renders the tilde


I am working on a book which has a lot of code in the JAGS modelling language. In JAGS, the user can specify the distribution the data are supposed to have originated from, and priors for the parameters. The operator used to do this is the tilde ~. For example

model{
  for(i in 1:n){
    speed[i] ~ dnorm(mu, tau)
  }

  mu ~ dnorm(0, 0.000001)
}

I am formatting the code in the book using the listings package which is pretty awesome. However, I would like the tilde character to be formatted in the same way as it is on this page - centered in the "height" of the text. This is what I get from listings

JAGS code rendered using the <code>listings</code> package in LaTeX

I am assuming there is a section for operators, but I have not been able to find one.


Solution

  • You could use another font for the tilde:

    \documentclass{article}
    
    \usepackage[T1]{fontenc}
    \usepackage{listings}
    \lstset{
            basicstyle=\ttfamily,
            literate={~}{{\fontfamily{ptm}\selectfont \textasciitilde}}1
    }
    
    
    \begin{document}
    
    \begin{lstlisting}
    model{
      for(i in 1:n){
        speed[i] ~ dnorm(mu, tau)
      }
    
      mu ~ dnorm(0, 0.000001)
    }
    \end{lstlisting}
    
    
    \end{document}
    

    enter image description here