4

I have lots of C++ code snippets in my article. Just see the following tex content and you'll get what I mean.

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{xspace}

\NewDocumentCommand{\code}{m}{\texttt{{#1}}}

\begin{document}
My code is \code{cout << hello << world;}\\
But I wish it looks like \verb|cout << hello << world;|
\end{document}

The different is « and <<.

How can I avoid ligatures in my \code macro.

enter image description here

  • 1
    Welcome to TeX.SE! – Mensch Nov 23 '20 at 9:01
  • If you use XeLaTeX, you shouldn't load fontenc, but \usepackage{fontspec} and you'll see that there are no ligatures by default. – egreg Nov 23 '20 at 11:18
  • I am wondering, why you are trying to reinvent the wheel. If you want to typeset code use \verb or \lstinline and adjust the style (font, color, etc.) instead of implementing the commands yourself – DG' Nov 23 '20 at 11:40
  • 2
    You can do all of that and more with listings – DG' Nov 23 '20 at 12:00
  • 1
    You can define new sets and aliases and even short versions of macros. Don't get me wrong, I have nothing against wrapping macros for convenience sake, I am just stressing, that it should be the right macros for the job you are intending to do – DG' Nov 23 '20 at 14:40
3

You can use microtype as shown in How do I disable ligatures?:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{xparse}% not needed in recent kernels
\usepackage{xspace}
\usepackage{microtype}
\DisableLigatures{encoding=T1, family=tt*}

\NewDocumentCommand{\code}{m}{\texttt{{#1}}}

\begin{document}
My code is \code{cout << hello << world;}

But I wish it looks like \verb|cout << hello << world;|

Normal ff and ffi ligatures still here.
\end{document}

enter image description here

  • Amazing, I tried \DisableLigatures{encoding = *, family = *} in that webpage but it didn't work at all, why add family=tt* works? And what if I remove encoding=T1? – Qiang Nov 23 '20 at 9:13
  • And it seems failed to compile with xelatex – Qiang Nov 23 '20 at 9:25
  • 1
    @AsyncCode - The microtype package has but very limited capabilities under XeLaTeX. Is switching to LuaLaTeX an option for you? – Mico Nov 23 '20 at 9:49
  • Yes, I found I works under LuaLaTeX – Qiang Nov 23 '20 at 10:45

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.