All the answers given so far capture an argument, fixing the category codes of the argument tokens forever. That will not work if you want verbatim text mixed with your emphasized text. They are also not \protected
, so they won't work in a caption or footnote.
The below uses |+
...text... +|
to delimit emphasized text and works in the cases I just described (as well as meeting your original requirements). I find it better to use a shortcut like "|+
" and "+|
" because it allows you to insert "|
" into your document easily. Otherwise, you need to make up some control sequence representing the original meaning of "|
".
\documentclass{article}
%% Justin Bailey
%% [email protected]
%% January, 2012
\newtoks\toinsert %% scratch token register
\makeatletter
%% Capture meaning of | and +
\let\emphbar=| \let\emphplus=+
\catcode`\|=\active \catcode`\+=\active
\protected\def\startEmphA{\futurelet\next\startEmphB}
%% See if | is followed by +, indicating we are starting empahsized
%% text. If so, begina new group and run \startEmphC. If not, put |
%% back back into stream.
\def\startEmphB{\toinsert={\emphbar}%%
\ifx\next+\toinsert={\bgroup\startEmphC}\fi
\the\toinsert} %%
\def\startEmphC{\ifmmode%%
\let \math@bgroup \relax%%
\def \math@egroup {\let \math@bgroup \@@math@bgroup%%
\let \math@egroup \@@math@egroup}%%
\mathit\relax%%
\else%%
\itshape\fi\@gobble}%%
\protected\def\stopEmphA{\futurelet\next\stopEmphB}
%% See if + is followd by a |, indicating the end of emphasized
%% text. If it is, end the group and gobble the | token. Otherwise,
%% put a + back into the stream.
\def\stopEmphB{\toinsert={\emphplus}%%
\ifx\next|\toinsert={\egroup\@gobble}\fi%%
\the\toinsert}
%% Associate | and + with startEmphA and stopEmphA. A more
%% robust implementation would put these in a macro so
%% we could turn the definitions of | and + on or off.
\protected\def|{\startEmphA} \protected\def+{\stopEmphA}
\makeatother
\usepackage[paperheight=3in,paperwidth=3in]{geometry}
\begin{document}
\pagestyle{empty}
%% Basic test
\tracingmacros=2\tracingcommands=2This is an |+important+| test.
%% Use special characters inside emphasize environment. Note
%% that | becomes an em-dash in this font.
This is an |+important (+x|y+)+| test.
%% Test in math mode
This is an $|+important+|$ test.
%% Test in a caption
\begin{figure}
This is an |+important+| test.
\caption{This is an |+important+| test.}
\end{figure}
%% With verbatim text.
This is an |+important \verb=$test$=+|.
%% Nested emphasis
This is an |+important, |+important+|+| test.
\end{document}
The above produces the following document:
