In my source code I would like Snap!
to be automatically replaced with Snap\textit{!}
\newcommand{Snap!}{Snap\textit{!}}
Errors with "missing number, treating as zero"
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It only takes a minute to sign up.
Sign up to join this communityI agree with a comment that this is best handled in an editor, rather than in LaTeX. But in the spirit of providing a LaTeX answer...
Pure listofitems
version
Here, a macro \snap
will examine its argument and do the replacement of Snap!
with Snap\textit{!}
. However, unlike the tokcycle
approach shown below, this version will not find Snap!
occurrences inside of arguments, for example, \textbf{blah Snap! blah}
.
\documentclass{article}
\usepackage{tokcycle,listofitems,xcolor}
\setsepchar{Snap!}
\newcommand\snap[1]{%
\readlist\mysnaps{#1}%
\foreachitem\z\in\mysnaps[]{%
\ifnum\zcnt=1\else Snap\textit{!}\fi
\z
}%
}
\begin{document}
\snap{%
There is Snap! and other Snap and snappy *Snap!* words!
}
\end{document}
tokcycle
version
If you can live with !
being considered a "letter" (catcode-11), then there is this tokcycle
environment \snap...\endsnap
that will find exact instances of Snap!
and replace the !
as italic.
\documentclass{article}
\usepackage{tokcycle,listofitems,xcolor}
\catcode`!=11
\setsepchar{Snap!}
\newcommand\testdict{%
\if\relax\detokenize\expandafter{\currentword}\relax\else
{\ignoreemptyitems
\greadlist\dictcompA{\currentword}}%
\readlist\dictcompB{\currentword}%
\ifnum\listlen\dictcompA[]=0\relax
\addcytoks[1]{\autohighlightStyleA}%
\addcytoks[1]{\expandafter{\currentword}}
\else
\ifnum\listlen\dictcompB[]>1\relax
\addcytoks[1]{\autohighlightStyleB}%
\addcytoks[1]{\expandafter{\currentword}}
\else
\addcytoks[1]{\currentword}%
\fi
\fi
\fi
\gdef\currentword{}%
}
\makeatletter
\xtokcycleenvironment\snap
{\tctestifcatnx A##1{\g@addto@macro\currentword{##1}}
{\testdict\addcytoks{##1}}}
{\testdict\groupedcytoks{\processtoks{##1}\testdict}}
{\g@addto@macro\currentword{##1}}
{\testdict\addcytoks{##1}}
{\stripgroupingtrue\def\currentword{}}
{}
\makeatother
\newcommand\autohighlightStyleA{\snapit}
\newcommand\autohighlightStyleB{\snapit}
\newcommand\snapit[1]{Snap\textit{!}}
\begin{document}
\snap
There is Snap! and other Snap and snappy *Snap!* words!
\endsnap
\end{document}
\newcommand{\Snap}{Snap\textit{!}}
? What is the reason you want to get rid of the backslash?\Snap
too, but that deletes spaces directly after itself.\Snap\
puts the space back, there are several answers on this site about that.