7

I have a document which contains example program code in Verbatim environments. The caret symbol produced by typing ^ looks too flat to me, so I defined a macro to produce a sharper version.

\documentclass[12pt]{article}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{fancyvrb}

%A more wedge-like caret for use in code. 
\newcommand\pow{\hspace{-1pt}\raisebox{-1pt}{\scalebox{1.2}{\textsf{\textasciicircum}}}\hspace{-1pt}}

%Set up code environment  
\DefineVerbatimEnvironment{code}{Verbatim}{xleftmargin=12pt,xrightmargin=12pt,commandchars=\\\{\}}

\begin{document}
\begin{code}
y = x^2  
y = x\pow2
\end{code}
\end{document}

caret

Unfortunately, it's easy to forget the necessity to use \pow and not ^ in code examples. Therefore I would like to set things up so that typing ^ in a code environment produces the result of \pow. How can this be achieved?

Ian Thompson
  • 43,767
  • 1
    That definition of \pow doesn't seem “right”, it can have a different width than monospaced fonts. I would use a \makebox to the width of a single character in a monospaced font. – Manuel Jul 29 '14 at 11:19
  • @Manuel --- Good point. – Ian Thompson Jul 29 '14 at 20:49

1 Answers1

7

I'm sure you'll appreciate this devious trick:

\documentclass[12pt]{article}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{fancyvrb}

%A more wedge-like caret for use in code. 
\newcommand\pow{%
  \hspace{-1pt}%
  \raisebox{-1pt}{\scalebox{1.2}{\textsf{\textasciicircum}}}%
  \hspace{-1pt}%
}
\newcommand{\makehatpow}{%
  \begingroup\lccode`~=`^
  \lowercase{\endgroup\let~}\pow
  \catcode`^=\active
}

%Set up code environment  
\DefineVerbatimEnvironment{code}{Verbatim}{
  xleftmargin=12pt,
  xrightmargin=12pt,
  commandchars=\\\{\},
  codes={\makehatpow},
}

\begin{document}
\begin{code}
y = x^2
y = x\pow2
\end{code}
\end{document}

enter image description here

The codes key should contain code that's executed before the usual verbatim category code assignments are performed. Luckily, ^ is not special inside a verbatim environment (like > or `), so we can set it to be active, but before making it active, we (locally) define a meaning for the active ^ with the good old \begingroup\lccode`~=... trick. See this answer or mine for more information.

egreg
  • 1,121,712
  • I knew catcodes would come into it somewhere, but I don't understand the \makehatpow macro definition; can you add an explanation? – Ian Thompson Jul 29 '14 at 10:54