5

So, shortvrb is a neat little package that allows you to do \MakeShortVerb{\|} which then has |foo| behave like \verb|foo|.

Now, I like listings. Is there a \MakeShortListings that makes |bar| act like \lstinline|bar|?

6
\documentclass{article}
\usepackage{listings}
\lstMakeShortInline[basicstyle=\small\ttfamily]{|}

\begin{document}

foo |bar| baz

\lstDeleteShortInline{|}
foo |bar| baz
\end{document} 
3

You can define the character in question to be active and define it to \lstinline[<options>]<char> where <char> stands for the character.

\documentclass{article}
\usepackage{listings}

\catcode`|=\active
\def|{\lstinline[language=C]|}

\begin{document}

|\relax|


|int main();|

\end{document}

A \MakeShortListings based on this can be defined the following way:

\documentclass{article}
\usepackage{listings}

\newcommand*\MakeShortListings[2][]{%
    \catcode`#2=\active
    \begingroup
    \def\@tempa{\lstinline[#1]}%
    \lccode`~=`#2%
    \lowercase{\expandafter\endgroup\expandafter\def\expandafter~\expandafter{\@tempa~}}%
}

\MakeShortListings{\|}

\begin{document}

|\relax|

\MakeShortListings[language=C]{\|}

|int main();|

\end{document}

If you also want to be able to delete the special meaning of this char again, like \DeleteShortVerb allows it for \MakeShortVerb, you can use these to save and restore its catcode and definition. This already make the character active.

\documentclass{article}
\usepackage{listings}
\usepackage{shortvrb}

\newcommand*\MakeShortListings[2][]{%
    \MakeShortVerb{#2}%
    \begingroup
    \def\@tempa{\lstinline[#1]}%
    \lccode`~=`#2%
    \lowercase{\expandafter\endgroup\expandafter\def\expandafter~\expandafter{\@tempa~}}%
}

\MakeShortListings{\"}

\begin{document}

"\relax"

\MakeShortListings[language=C]{\"}

"int main();"

\DeleteShortVerb{\"}

``test"


\end{document}
  • I've accepted Herbert's answer since it seems to be the "canonical" one. But I think I have learned something about catcodes from this answer. Thanks! – Seamus Jul 15 '11 at 12:24
  • @Seamus: Sure, no problem. Herbert's answer should be accepted. I didn't know that listings provides such a macro already. (There was however not much reason that it got down-voted by two people. The solution is sound IMHO.) – Martin Scharrer Jul 15 '11 at 12:29
  • 1
    I hadn't noticed you'd got downvoted! That does seem harsh. Just because there's a "better" solution doesn't mean this isn't a good solution – Seamus Jul 15 '11 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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