Colorir ou negrito várias linhas na integração do fancyvrb com listagens

Colorir ou negrito várias linhas na integração do fancyvrb com listagens

Eu gostaria de aplicar comandos latex em um monte de linhas em um ambiente Verbatim com listagens, especialmente colocar em negrito ou colorir um bloco de código.

Consigo fazer isso para uma única linha, mas não para várias linhas.

\documentclass{beamer}

\usepackage[T1]{fontenc}
\usepackage[scaled=0.85]{beramono}%% monotype with bold variant 
\usetheme{bars}

\usepackage{xcolor}
\usepackage{hyperref}
\usepackage{listings}
\usepackage{setspace}
\usepackage{graphicx}
\usepackage{alltt}
\usepackage{mathtools}
\usepackage{fancyvrb}
\usepackage[normalem]{ulem}

\lstdefinestyle{Java}{ %
basicstyle=\scriptsize\ttfamily, % the size of the fonts that are used for the code
language=Java,                % choose the language of the code
numbers=left,                   % where to put the line-numbers
numberstyle=\tiny,      % the size of the fonts that are used for the line-numbers
stepnumber=1,                   % the step between two line-numbers. If it is 1 each line will be numbered
numbersep=5pt,                  % how far the line-numbers are from the code
backgroundcolor=\color{white},  % choose the background color. You must add \usepackage{color}
showspaces=false,               % show spaces adding particular underscores
showstringspaces=false,         % underline spaces within strings
showtabs=false,                 % show tabs within strings adding particular underscores
frame=single,           % adds a frame around the code
tabsize=2,          % sets default tabsize to 2 spaces
captionpos=b,           % sets the caption-position to bottom
breaklines=true,        % sets automatic line breaking
breakatwhitespace=false,    % sets if automatic breaks should only happen at whitespace
keywordstyle=\color{red}, %keywordstyle=\color{red}\bf
commentstyle=\color{green},
variablestyle=\color{blue},
fancyvrb=true,
}


\newcommand\Red[1]{\textcolor{red}{#1}}
\newcommand\Blue[1]{\textcolor{blue}{#1}}
\newcommand\Green[1]{\textcolor{green}{#1}}

\newcommand\RB[1]{\textcolor{red}{\textbf{#1}}}
\newcommand\BB[1]{\textcolor{blue}{\textbf{#1}}}
\newcommand\GB[1]{\textcolor{green}{\textbf{#1}}}

\newenvironment{JavaCode}[1][]
  { \VerbatimEnvironment%
    \lstset{style=Java}
    \begin{Verbatim}[#1]}
  { \end{Verbatim}  }



\begin{document}

\begin{frame}[fragile]
 \frametitle{MyActionListener}
 \begin{JavaCode}[commandchars=\\!|,frame=single,numbers=left,numbersep=2pt] 

  public void perform() {
    //Doesn't work for multiple lines
    \textbf!
    class MyActionListener implements ActionListener {
      public void actionPerformed(ActionEvent event)
      {
        System.out.print("Action Performed");
      }
    }
    |

   //works for individual lines
   \textbf! ActionListener listener = new MyActionListener();|
    button.addActionListener(listener);
  }

 \end{JavaCode}
\end{frame}

\end{document}

Responder1

Existem vários problemas com seu código:

  1. Você usa uma chave chamada variablestyleque não é definida listingsnem no seu código.
  2. Você tenta definir um ambiente com conteúdo literal usando \newenvironment, o que não é possível. Ambos fancyvrb(veja 4.2.4. no documento) e listings(veja 4.16 no documento) possuem mecanismos para criar ambientes personalizados com conteúdo literal.
  3. Seu código não é mínimo (não há necessidade de hyperref, mathtools, etc. aqui)

Além disso, não sei por que você não está simplesmente usando um lstlistingambiente. Você pode definir facilmente delimitadores que acionam negrito em seu código, usando a tecla listings' moredelim, assim:

moredelim=**[is][\bfseries]{<openingdelimiter>}{<closingdelimiter>}

Veja abaixo.

insira a descrição da imagem aqui

\documentclass{beamer}

\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[scaled=0.85]{beramono}

\usetheme{bars}

\usepackage{xcolor}
\usepackage{fancyvrb}
\usepackage{listings}

\lstdefinestyle{Java}%
{%
    basicstyle          = \scriptsize\ttfamily,
    language            = Java,
    numbers             = left,
    numberstyle         = \tiny,
    stepnumber          = 1,
    numbersep           = 5pt,
    backgroundcolor     = \color{white},
    showspaces          = false,
    showstringspaces    = false,
    showtabs            = false,
    frame               = single,
    tabsize             = 2,
    captionpos          = b,
    breaklines          = true,
    breakatwhitespace   = false,
    morestring          = [b]",
    stringstyle         = \color{magenta},
    keywordstyle        = \color{red},
    commentstyle        = \color{green},
    identifierstyle     = \color{blue},
    moredelim           = **[is][\bfseries]{`}{`},
    fancyvrb            = true,
}

\begin{document}

\begin{frame}[fragile]
\frametitle{MyActionListener}
\begin{lstlisting}[style=Java]
public void perform() {
  //Doesn't work for multiple lines    
  `
  class MyActionListener implements ActionListener {
    public void actionPerformed(ActionEvent event)
    {
      System.out.print("Action Performed");
    }
  }
  `

  `ActionListener listener = new MyActionListener();`
  button.addActionListener(listener);
}
 \end{lstlisting}
\end{frame}

\end{document}

informação relacionada