2

Why does this not work in common?

\newcommand{\test}[2][]{ \node[draw, #1] {#2}; } 

Only if I say

\newcommand{\test}[2][]{ \begin{tikzpicture} \node[draw, #1] {#2}; \end{tikzpicture} } 

it works sometimes - but everytime a complete tikzpicture...?

Hint: I want so set a more complex command (contains foreach) several times into a TikZ-matrix, so the following MWE contains a TikZ-matrix.

\documentclass{article} \usepackage{tikz} \usetikzlibrary{matrix} \begin{document} \newcommand{\test}[2][]{ \node[draw, #1] {#2}; } \test{aaa} % Does not work! ================== \begin{tikzpicture} \matrix (m) [matrix of nodes, nodes in empty cells]{ a & b \\ \test{aaa} & \test[red]{bbb} \\ % Does not work! ================== }; \end{tikzpicture} \end{document} 

1 Answer 1

2

The code did not work with \newcommand because then the command is not expandable, as illustrated in the example below: \testA is defined with \newcommand but can not be used in \edef. Whereas \testC is defined with \NewExpandableDocumentCommand and \testC can be used in \edef.

\documentclass[border=6pt]{standalone} \newcommand{\testA}[2][]{A} \def\testB{\testA{B}}%works with \def but not with \edef \NewExpandableDocumentCommand\testC{O{}m}{C} \edef\testD{\testC{D}}%works with \def and \edef \begin{document} \testB ; \testD \end{document} 

enter image description here

If the command \test is defined with \NewExpandableDocumentCommand then \test can be used inside the \matrix.

\documentclass[border=6pt]{standalone} \usepackage{tikz} \usetikzlibrary{matrix} \NewExpandableDocumentCommand\test{O{}m}{\node[draw, #1] {#2};} \begin{document} \begin{tikzpicture} \matrix (m) [matrix of nodes, nodes in empty cells]{ a & b \\ \test{aaa} & \test[red]{bbb} \\ %Does work }; \end{tikzpicture} \end{document} 

enter image description here

1
  • 1
    Ahhh..... TYVM! Commented Apr 5, 2024 at 11:51

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.