I am creating a code/strategy reference document for my student organization to be built on by groups of students into the future, and trying to make it simple and readable for those who will be adding to it and updating it later. I've been representing code in the following way, which is fine, but a long message and I wanted to make it something shorter.
\begin{minted}[mathescape, linenos, fontsize=\footnotesize]{python}
class MyClass:
def my_function():
# my code
\end{minted}
This produces the display shown in the image
I know that minted is a verbatim environment, so the regular \newenvironment{codeblock}{...}{...} command would not really work. When I tried to use it, it seemed to work okay but the \end{codeblock} would not be recognized, causing the whole rest of the document to be in the code style.
I found this post, which shows a way to use minted with the \newtcblisting command in the tcolorbox package, and it certainly looks better, but has a couple problems as well. I define the environment:
\usepackage{minted} \usepackage{tcolorbox} \tcbuselibrary{minted}
\newtcblisting{codeblock}[2][]{
minted options={mathescape, linenos,fontsize=\footnotesize},
minted language=#2,
#1
}
And I then use it,
\begin{codeblock}{python}
class MyClass:
def my_function():
# my code
\end{codeblock}
This looks good, and I like the box, but I can't figure out how to solve two problems:
- The line numbers are overlapping the left edge of the box. Is there a way to shift all the code text (including the line numbers) to the right?
- The raw code is displayed as text in the lower half (and seems to switch into math mode after the underscore), which did not happen in the post I referenced and linked above. How can I prevent this from displaying, and have only the nice-looking code in the box?
Any help would be appreciated with solving these specific issues, or even just a way to define a custom environment that works with minted. I've found a few posts on here but nothing that's worked.



newtcblisting), addlisting onlyto output source code only (otherwise it will try to compile the code as LaTeX); addleft=2mm(or any other length you like) to adjust left margin. – Alan Xiang Dec 14 '20 at 02:18