6

I would like to define a macro \mynode (to be used inside TikZ) whose behavior depends on the last symbol of its argument as follows:

\mynode{text!} should produce

\node[fill=red] at (0,0) {text};

while \mynode{text} should produce just

\node at (0,0) {text};

In other words, the definition of \mynode should be something like

\newcommand{\mynode}[1]{
  \node[fill=red] at (0,0) {#1};
}

where the fill=red parameter is supplied only when #1 ends with ! (if this is the case, the actual node content in the curly braces should be stripped off the exclamation mark).

Māris Ozols
  • 1,095
  • Is ! supposed to appear in other places? However, wouldn't it be easier to have \mynode{text} for the non filled version and \mynode*{text} for the filled version? – egreg Dec 20 '16 at 23:48
  • The exclamation mark can be forgotten once it's removed. A starred version is not an option because I want to use this to draw a Young diagram using a command like this: \young{{{1,1,1},{2,2,3!},{3}}} and I want the ! node to become red. – Māris Ozols Dec 20 '16 at 23:52

3 Answers3

7

If ! is not supposed to appear anywhere else in the argument to \mynode, it's quite easy:

\documentclass{article}
\usepackage{tikz}

\makeatletter
\newcommand\mynode[1]{\mynodeaux#1!\@nil}
\def\mynodeaux#1!#2\@nil{%
  \if\relax\detokenize{#2}\relax
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
  {\node at (0,0) {#1};}%
  {\node[fill=red] at (0,0) {#1};}%
}
\makeatother

\begin{document}

\begin{tikzpicture}
\mynode{text}
\end{tikzpicture}

\bigskip

\begin{tikzpicture}
\mynode{text!}
\end{tikzpicture}

\end{document}

enter image description here

However, I'd suggest a different strategy, more in line with standard LaTeX syntax.

\documentclass{article}
\usepackage{tikz}
\usepackage{xparse}

\NewDocumentCommand{\mynode}{sm}{%
  \IfBooleanTF{#1}
   {\node[fill=red] at (0,0) {#2};}%
   {\node at (0,0) {#2};}%
}

\begin{document}

\begin{tikzpicture}
\mynode{text}
\end{tikzpicture}

\bigskip

\begin{tikzpicture}
\mynode*{text}
\end{tikzpicture}

\end{document}
egreg
  • 1,121,712
5

How about this:

\documentclass{article}
\usepackage{tikz}
\makeatletter
\def\mynode{\@ifnextchar[{\mynode@}{\mynode@[]}}%]
\def\mynode@[#1]#2{\mynode@@{#1}#2\empty!\empty\relax}
\def\mynode@@#1#2!\empty#3\relax{
    \def\temp{#3}
    \node[#1,/utils/exec=\ifx\temp\empty\else\pgfkeysalso{fill=red}\fi] at (0,0) {#2};
}


\makeatother


\begin{document}
\begin{tikzpicture}
\mynode{hi!}

\mynode[xshift=1cm]{the!re}
\end{tikzpicture}

\end{document} 

(I stole David Carlisle's code to check whether the argument ends in an exclamation point.)

enter image description here

Hood Chatham
  • 5,467
2

enter image description here

\def\remshriek#1{\xremshriek#1\empty!\empty\relax}
\def\xremshriek#1!\empty#2\relax{%
\def\tmp{#2}
\ifx\tmp\empty\else[fill]\fi
#1}

\remshriek{text}

\remshriek{text! text}

\remshriek{text!}
David Carlisle
  • 757,742