0

Consider this MWE:

\documentclass{article}

\usepackage{tikz}

% \gdef\myset{  %*
\tikzset{ %
  mystyle/.style={rectangle},
  mycode/.code n args={2}{%
    \typeout{YEAH! #1 #2} %
  },
} % end tikzset
% } % end gdef  %*


\begin{document}

\begin{tikzpicture}
% \myset        %*

\node[mystyle,mycode={trying}{out}] (origin) at (0,0) {};
\end{tikzpicture}

\end{document}

If you compile it as is, it will print "YEAH! trying out" to stdout. However, if you uncomment the lines marked with %*, then compilation fails with:

! Illegal parameter number in definition of \myset.
<to be read again> 
                   1
l.9     \typeout{YEAH! #1
                          #2} %
? 

... clearly, because Latex thinks the #1 is for the \gdef\myset, while I intend it to be for the \tikzset{ command inside it!

So, after checking out How to get the catcode of a token?, and doing texdef -t latex \makeatletter and texdef -t latex \makeatother, and \typeout{catcode of #: \the\catcode`#}, I came up with the following analog to \makeatletter, called \makehashletter:

\documentclass{article}

\usepackage{tikz}

\typeout{catcode of #: \the\catcode`#} %catcode of ##: 6
\def\makehashletter{\catcode`\#11\relax}
\def\makehashother{\catcode`\#6\relax}

\makehashletter
\gdef\myset{  %*
\tikzset{ %
  mystyle/.style={rectangle},
  mycode/.code n args={2}{%
    \typeout{YEAH! #1 #2} %
  },
} % end tikzset
} % end gdef  %*
\makehashother

\begin{document}

\begin{tikzpicture}
\myset        %*

\node[mystyle,mycode={trying}{out}] (origin) at (0,0) {};
\end{tikzpicture}

\end{document}

... and this does compile - but it dumps YEAH! #1 #2 to stdout, which is not what I intended.

So my question is - is there a way to protect the # in a macro like the above, such that when the macro is ran and calls tikzset, the tikzset will see the previously protected #s as arguments?

Would it also be possible to somehow use that protection only on certain arguments (e.g. \myset could itself accept #1, which I would use "unprotected"; and I'd protect/escape the tikzset specific ones )?

(Note that I've tried:

\edef\hashmark{\string#}

... as in Match number sign inside plain TeX loop, and then using \hashmark1 instead of #1 where I want them "escaped", but that didn't work)

2

0

Browse other questions tagged .