[Tex/LaTex] Making a multiline code environment

environments

I want to create an environment which makes some text look like code. Namely, I want the font to be monospace, with a light grey background (precisely, \definecolor{mygray}{gray}{0.9}). I also need it to have proper indentation. However, I do not want to use either the listings or minted packages for other reasons, and I do not need automatic highlighting of code in fancy colours (I want to do these manually—using \textbf and other LaTeX commands should still be possible within this environment, instead of it being displayed as code). In essence, within this environment everything works precisely the same as normal text, except the font, the background colour, the font-size which I want to be \scriptsize, and automatic indenting (similar to listings). Properties like text wrap should be conserved.

Here's where I got so far:

\documentclass{article}
\usepackage[scaled=0.85]{beramono}

\newenvironment{monospace}{\ttfamily}{\par}
\newenvironment{code}{\begin{monospace}\begin{tabbing}}{\end{tabbing}\end{monospace}}

\begin{document}

\begin{code}
\textbf{def} \=weird(x,y):\\
    \>  a = math.sin(x)\\
    \>  b = math.cos(y)\\
    \>  c = math.tan(x+y)\\
    \>  s = (a+b+c)/3\\
    \>  \textbf{def} \=tant(n):\\
    \>  \>  \textbf{return} math.tan((n+x+y)/3)\\
    \>  \textbf{return} \=math.cos(math.sin(tant(s)*\\
    \>  \>       tant(a)*tant(b)*tant(c)))
\end{code}

\end{document}

The problem with this, is of course that creating the correct indentation is extremely tedious, and text wrap has to be done manually (the last statement is broken up into two lines, because I'm using twocolumn mode and without the manual line break, the code exceeds the margin). Also, I have no clue how to add the background colour. Any help is appreciated!
enter image description here

Best Answer

It will probably be simplest to use fancyvrb, with fvextra if you want automatic line breaking. You might start with something like this:

\documentclass[twocolumn]{article}
\usepackage[T1]{fontenc}
\usepackage[scaled=0.85]{beramono}
\usepackage{xcolor}
\definecolor{mygray}{gray}{0.9}
\usepackage{fvextra}
\usepackage{tcolorbox}

\newenvironment{code}%
 {\VerbatimEnvironment
  \begin{tcolorbox}[colback=mygray, boxsep=0pt, arc=0pt, boxrule=0pt]
  \begin{Verbatim}[fontsize=\scriptsize, commandchars=\\\{\},
    breaklines, breakafter=*, breaksymbolsep=0.5em,
    breakaftersymbolpre={\,\tiny\ensuremath{\rfloor}}]}%
 {\end{Verbatim}%
  \end{tcolorbox}}

\begin{document}

\begin{code}
\textbf{def} weird(x,y):
    a = math.sin(x)
    b = math.cos(y)
    c = math.tan(x+y)
    s = (a+b+c)/3
    \textbf{def} tant(n):
        \textbf{return} math.tan((n+x+y)/3)
    \textbf{return} math.cos(math.sin(tant(s)*tant(a)*tant(b)*tant(c)))
\end{code}

\end{document}

enter image description here

Related Question