For the verbatim material I want to show two other solutions:
The first one is the package fancyvrb
, where you can set an option for active characters (commandchars) and in this way let execute macros inside of the Verbatim
environment, and you can define custom verbatim environments with \DefineVerbatimEnvironment
.
The second does not only work in verbatim environments, but is a general one: The package etoolbox
provides hooks for environments, see below in the example for \BeforeBeginEnvironment
and \AfterEndEnvironment
. I used fancyvrb’s Verbatim environment for that:
\documentclass{article}
\usepackage[english]{babel} % needed for "blindtext"
\usepackage[pangram]{blindtext}
\usepackage{xcolor}
\usepackage{fancyvrb}
\DefineVerbatimEnvironment{ColorVerbatim}{Verbatim}%
{formatcom=\color{purple},commandchars=\\\{\}}
\usepackage{etoolbox}
\BeforeBeginEnvironment{Verbatim}{\begingroup\color{green}}%
\AfterEndEnvironment{Verbatim}{\endgroup}%
\begin{document}
\blindtext[1]
\begin{Verbatim}
Verbatim text with by hook predefined colour:
This blindtext is no pangram.
\end{Verbatim}
\begin{Verbatim}[commandchars=\\\{\}]
Verbatim text with individual colour settings:
{\color{red}\blindtext[1]}
\textcolor{blue}{\blindtext[1]}
\end{Verbatim}
\begin{ColorVerbatim}
Custom verbatim environment with predefined colour:
\blindtext[1]
... and with individual colour settings:
\textcolor{orange}{\blindtext[1]}
{\color{teal}\blindtext[1]}
\end{ColorVerbatim}
\blindtext[1]
\end{document}

beamer
references in your question because I'm pretty sure what you want to achieve can be done inbeamer
just like in any other document. Hence, the question could be made more widely applicable, which is desirable on tex.sx.