Babel package causes Missing \endcsname error when minted is used

babelminted

On the tex file below, if I use the babel package along with the minted package, it gives this error:

! Missing \endcsname inserted.
<to be read again>
                   \protect
l.1 \begin{Verbatim}[commandchars=\\\{\}]

My system is Tex Live 2020 on macOS 10.7.5 and the command is:

xelatex --shell-escape minted-tryin.tex

If I comment out all the minted related lines, it compiles fine when the babel is included.

How to use these both packages together?

\documentclass[a4paper,12pt]{book}

\usepackage[british, turkish]{babel}
\selectlanguage{turkish}

\usepackage{minted}
\usepackage[left=1.5cm]{geometry}

\begin{document}
Ok let's start...

\begin{minted}{python}
import sys, math
if (len(sys.argv)>1) :
    print (math.factorial(int(sys.argv[1])))
\end{minted}

\end{document}

Best Answer

The turkish language will (under at least pdflatex) make !:= into active characters. You'll probably need to disable them around minted as it probably affect the key=value interface minted uses internally and because of the : in your example.

Adding this to the preamble seems to work

\usepackage{etoolbox}
\AtBeginEnvironment{minted}{
  \shorthandoff{=}
  \shorthandoff{:}
}

I did not add ! in my tests.