5

The tikzpicture environment allows to define styles in square brackets that are available within the picture. I would like to share the styles between multiple pictures to edit them in a single place. I know that this is possible with global variables, but I'd like to avoid making the styles available to all pictures. Is there a way to selectively include styles only into the picture environments where I want to use them?

1
  • 1
    What about newcommands?
    – koleygr
    Commented Sep 1, 2018 at 19:09

1 Answer 1

8

You can define a style that 'installs' more styles. For example, in the following MWE I define a style b that is globally available, that in turn installs/sets style c to be available. Similarly, I defined a style a that is globally available, but is overwritten by b. And finally, I defined a style e that only adjusts style a, without completely redefining it.

\documentclass{article}

\usepackage{tikz}

\tikzset{
    a/.style={ % 'a' is globally available 
        draw=green,
        line width=2pt,
        dashed,
    },
    b/.style={ % 'b' installs 'c' and overwrites 'a'
        c/.style={
            draw=red,
            fill=blue,
            text=white,
        },
        a/.style={
            draw=blue,
            line width=1pt,
        },
    },
    e/.style={ % The 'e' style will only change 'a' a bit, but will not overwrite
        a/.append style={
            fill=gray,
        }
    }
}

\begin{document}
    \begin{tikzpicture}
        \node[a] {Text}; % 'a' is globally available
    \end{tikzpicture}

    \begin{tikzpicture}[b]
        \node[a] {Text}; % Having called 'b', 'a' is redefined
        \node[c] at (1,0) {Text}; % And 'c' is available only in this picture
    \end{tikzpicture}

    \begin{tikzpicture}
        \node[a] {Text};
        %\node[c] at (2,0) {Text}; % This will not compile, 'c' is unknown here
        \begin{scope}[b]
            \node[a] at (1,0) {Text}; % In this scope, 'a' is redefined by 'b'
            \node[c] at (2,0) {Text}; % Again 'c' is available due to 'b'
        \end{scope}
    \end{tikzpicture}

    \begin{tikzpicture}[b,e]
        \node[a] {Text}; % Now 'a' is not completely redefined, but is changed due to 'e'
    \end{tikzpicture}
\end{document}

The code above results in:

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .