As others have pointed out, this is because minted only activates mathescape
inside comments.
FWIW, the same is true for the t-vim module in ConTeXt. It is similar to the minted
package for LaTeX, but uses vim
instead of pygments
for syntax highlighting.
t-vim
provides an option to load an arbitrary vim file before the source code is parsed. So, it is possible to change the parser on the fly. For example, to identify docstrings as comments, you can use the vim file given in this thread in the vim mailing list.
\usemodule[vim]
\startvimrc[name=python-docstring]
syn match pythonBlock ":$" nextgroup=pythonDocString skipempty skipwhite
syn region pythonDocString matchgroup=Normal start=+[uU]\='+ end=+'+ skip=+\\\\\|\\'+ contains=pythonEscape,@Spell contained
syn region pythonDocString matchgroup=Normal start=+[uU]\="+ end=+"+ skip=+\\\\\|\\"+ contains=pythonEscape,@Spell contained
syn region pythonDocString matchgroup=Normal start=+[uU]\="""+ end=+"""+ contains=pythonEscape,@Spell contained
syn region pythonDocString matchgroup=Normal start=+[uU]\='''+ end=+'''+ contains=pythonEscape,@Spell contained
hi def link pythonDocString Comment
\stopvimrc
\definevimtyping[PYTHON][syntax=python, extras=python-docstring]
\starttext
\startPYTHON[escape=on]
def naive(a,x):
"""
lorem ipsum....
this code will be escaped (note no spaces)
\math{a=\{a_0,a_1,a_2,a_3,\dots,a_n\}}
"""
# this code will be escaped
p = a[0] # \math{p=\sqrt{\frac{1}{3}}}
y = x
for ai in a[1:]:
p = p + ai*y
y = y*x
return p
\stopPYTHON
\stoptext
which gives:
One difference in t-vim is that you need to use \math{...}
(or \m{...}
) to enable math mode rather than $...$
. As with minted
and listings
do not use spaces in math mode.
To do something similar in minted
, you will need to change the python parser so that it identifies docstrings as comments.
mathescape
.mathescape
only for comments. pygments.org/docs/formatters