3

I would like to determine whether a line inside a verbatim environment starts with 3 spaces.

I'm using pdflatex and the \pdfmatch primitive. I see that the verbatim environment sets the category code of space to \active, so I do not know how to represent a space character in the test at the time it is reached (from within the verbatim environment).

If I perform the test below using a 'normal' character instead of a space, it works as expected.

\documentclass{article}
\usepackage{verbatim}
\begin{document}
  \makeatletter
  \def\verbatim@addtoline#1{
    \ifnum\pdfmatch{^   myline}{#1}=1
       #1 matched
    \else
       #1 did not match
    \fi}
    \makeatother

\begin{verbatim}
  myline1
   myline2
    myline3
     myline4
\end{verbatim}
\end{document}

1 Answer 1

4

It's a problem with the expansion. Because of this #1 should not be expanded and the spaces have to be preserved:

\documentclass{article}
\usepackage{verbatim}
\begin{document}
\makeatletter
\def\verbatim@addtoline#1{%
  \ifnum\pdfmatch{^\space\space\space myline}{\detokenize{#1}}=1
    #1 matched
  \else
    #1 did not match
  \fi}
\makeatother

\begin{verbatim}
  myline1
   myline2
    myline3
     myline4
\end{verbatim}
\end{document}
3
  • Thanks. I thought it would be related to expansion but I didn't know how to make it work. So \detokenize takes the arguments and treats it like a string, correct? and when \space\space\space is expanded in the \edef it is a string of three real spaces; so the match can work.
    – Tim A
    Nov 22, 2011 at 19:30
  • After playing around a bit with this solution, it appears that the following macro will also work and is simpler to understand. I'm not an expansion expert, so this may be a naive solution. However it does work in this example. Hmmm, I see I can't add a code block in a comment, so I've added my simpler macro as another answer. I'd appreciate confirmation if this is wrong!
    – Tim A
    Nov 23, 2011 at 15:14
  • @Tim: Ok, I've forget to test elimination of \@tempa after my experiment. May be changed but is not a drama. Nov 23, 2011 at 16:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .