4

How could I design a macro (if possible using \NewDocumentCommand) to add in a tikz matrix (created via tikzcd) something like |[stylename]| content? For now I can do:

\newcommand\zxZ[1]{|[Z]| #1}

but with NewDocumentCommand, this fails:

\NewDocumentCommand{\zxZ}{m}{|[Z]| #1}

Here is what I get for now:

enter image description here

MWE:

\documentclass{article}

\usepackage{tikz} \usetikzlibrary{cd} \usetikzlibrary{backgrounds,positioning} \usetikzlibrary{shapes,shapes.geometric,shapes.misc} \usepackage{xparse} \begin{document}

\tikzstyle{Z}=[fill=green]

% Works %\newcommand\zxZ[1]{|[Z]| #1} % Works (but I'd prefer the above |[Z]| since it seems to handle \arr and https://tex.stackexchange.com/a/21167/116348 better) %\newcommand\zxZ[1]{\node[Z]{#1};} % Fails %\NewDocumentCommand{\zxZ}{m}{\node[Z]{#1};} % Fails %\NewDocumentCommand{\zxZ}{m}{|[Z]| #1}

\begin{tikzcd} \node[Z]{\alpha}; & \zxZ{\beta} \end{tikzcd}

\end{document}

tobiasBora
  • 8,684

1 Answers1

4

Not sure why \NewDocumentCommand is deemed necessary. Anyway, you need to use \NewExpandableDocumentCommand, because of the inner workings of tikz.

\documentclass{article}

\usepackage{tikz} \usetikzlibrary{cd} %\usepackage{xparse} % only for LaTeX prior to 2020-10-01

\begin{document}

\tikzset{ Z/.style={fill=green}, }

% Works %\newcommand\zxZ[1]{|[Z]| #1} % Works (but I'd prefer the above |[Z]| %\newcommand\zxZ[1]{\node[Z]{#1};} % Works %\NewExpandableDocumentCommand{\zxZ}{m}{\node[Z]{#1};} % Works \NewExpandableDocumentCommand{\zxZ}{m}{|[Z]| #1}

\begin{tikzcd} \node[Z]{\alpha}; & \zxZ{\beta} \end{tikzcd}

\end{document}

Note that \tikzstyle has been deprecated for several years.

egreg
  • 1,121,712
  • Amazing, thanks a lot! Concerning \tikzstyle, it's just that tikzit produces style files with that syntax, but thanks for mentionning. – tobiasBora Oct 05 '21 at 15:15
  • Concerning \NewDocumentCommand, it's just that I like the way I can specify arguments a lot better (I mean compared to \def and \newcommand, I don't care to use \NewExpandableDocumentCommand). And I guess it's consider more solid compared to \newcommand no? – tobiasBora Oct 05 '21 at 15:16
  • @tobiasBora The usual problem: packing many optional arguments is not a recommended way to define interfaces. – egreg Oct 05 '21 at 15:21
  • I've two remarks/questions: first, I tried your method but adding this time some conditions and/or macros... and now it fails again. Any idea what I did wrong? (see my edit) Secondly, I agree with your remark (well especially in LaTeX since you can't define second optional argument without defining the first one), even if I like adding one or two optional arguments. That said, interfaces like pgfkeys are extremely useful, and I like to use the optional argument together with pgfkeys. – tobiasBora Oct 06 '21 at 18:04