TransWikia.com

Custom environment with options for tikz

TeX - LaTeX Asked on May 9, 2021

I wanted to create a custom environment and I am currently facing the following problem:

  • I want to pass an Option to my environment which scales the tikzpicture but the first example does not work and returns the following error -> ! Missing number, treated as zero.
  • The second one seems to work but I do not understand why the first one does not if it is similar to the second one.
  • The error is caused by the following code:
    -> scale = scalevalue
documentclass{article}

usepackage{l3keys2e}
usepackage{tikz}

ExplSyntaxOn
keys_define:nn{test} {
    scale .tl_set:N = l_test_scale_tl,
    scale .default:n = 1,
    scale .initial:n  = 1
}
ExplSyntaxOff

NewDocumentEnvironment{myenv}{o}
    {
        % Options
        ExplSyntaxOn
        IfNoValueF{#1}{keys_set:nn {test}{#1}}
        ExplSyntaxOff
        
        ExplSyntaxOn
        newcommand*{scalevalue}{thenumexprl_test_scale_tlrelax}
        
        ExplSyntaxOff
        begin{tikzpicture}[scale = scalevalue, transform shape]
    }
    {
        end{tikzpicture}
    }

begin{document}
% Example 1: Error
%begin{myenv}
%node[draw] (a) at (0,0) {A};
%end{myenv}

% Example 2: No error
ExplSyntaxOn
newcommand*{scalevalue}{l_test_scale_tl}
ExplSyntaxOff
begin{tikzpicture}[scale = scalevalue, transform shape]
node[draw] (a) at (0,0) {A};
end{tikzpicture}
end{document}

One Answer

The problem is that you use ExplSyntaxOn too late. It has to be activated at the moment when NewDocumentEnvironment is read, because at this moment it is decided how e.g. _ will be processed. So you need something like

ExplSyntaxOn
NewDocumentEnvironment{myenv}{o}{... no switching of ExpSyntax ...}
ExplSyntaxOff

But now also tikzpicture, in particular the space between transform and shape is in the scope of this syntax, and tikz will complain that transformshape (without space) is not known.

You can do something like this.

documentclass{article}

usepackage{l3keys2e}
usepackage{tikz}

ExplSyntaxOn
keys_define:nn{test} {
    scale .tl_set:N = l_test_scale_tl,
    scale .default:n = 1,
    scale .initial:n  = 1
  }
newcommandpreparePic[1]{%
  IfNoValueF{#1}{keys_set:nn {test}{#1}}%
  newcommand*{scalevalue}{thenumexprl_test_scale_tlrelax}%
}
ExplSyntaxOff

NewDocumentEnvironment{myenv}{o}
    {
        preparePic{#1}
        begin{tikzpicture}[scale = scalevalue, transform shape]
    }
    {
        end{tikzpicture}
    }

begin{document}
begin{myenv}
node[draw] (a) at (0,0) {A};
end{myenv}
end{document}

Correct answer by gernot on May 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP