Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
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 at 11:19
    
@Manuel --- Good point. –  Ian Thompson Jul 29 at 20:49

1 Answer 1

up vote 8 down vote accepted

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.

share|improve this answer
    
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 at 10:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.