TransWikia.com

How to use keyword arguments in a LaTeX environment?

TeX - LaTeX Asked on July 12, 2021

I would like to define a convenient way to pass arguments to an environment using the notation key=value. I don’t know how to find this on the documentation.

For exemple:

newenvironment{foobar}[3]{
...
}

begin{foobar}[foo=1,bar=2,baz=3]
    text1
end{foobar}

begin{foobar}[bar=10]
    text2
end{foobar}

And the result could be:

begin_foobar
you said that foo equals 1, bar equals 2 and baz equals 3
text1
end_foobar

begin_foobar
you said that bar equals 10
text2
end_foobar

(if you have any advise for a good documentation about LaTeX plumbery, I take it)

2 Answers

Here an example of what you can do:

documentclass{article}
usepackage{environ}
usepackage{keyval}

makeatletter
define@key{myenv@keys}{foo}{defmyenv@foo{#1}}%
define@key{myenv@keys}{bar}{defmyenv@bar{#1}}%

newenvironment{myenv}[1][]{%
    setkeys{myenv@keys}{foo=4,bar=4,#1}
    Foo=myenv@foopar
    Bar=myenv@barpar
    Beforepar
}{
    After
}
makeatother

begin{document}

begin{myenv}[foo=42]
    Inside
end{myenv}

begin{myenv}[bar=42]
    Inside
end{myenv}

end{document}

Answered by nowox on July 12, 2021

With expl3:

documentclass{article}
usepackage{xparse}

ExplSyntaxOn

NewDocumentEnvironment{foobar}{O{}}
 {
  par
  nowox_foobar_init:n { #1 }
 }
 {
  par
 }

keys_define:nn { nowox/foobar }
 {
  foo .tl_set:N = l_nowox_foobar_foo_tl,
  bar .tl_set:N = l_nowox_foobar_bar_tl,
  baz .tl_set:N = l_nowox_foobar_baz_tl,
 }

seq_new:N l__nowox_foobar_args_seq

cs_new_protected:Nn __nowox_foobar_arg_add:nn
 {
  tl_if_empty:nF { #2 }
   {
    seq_put_right:Nn l__nowox_foobar_args_seq
     {
      #1~equals~#2
     }
   }
 }
cs_generate_variant:Nn __nowox_foobar_arg_add:nn { nV }

cs_new_protected:Nn nowox_foobar_init:n
 {
  keys_set:nn { nowox/foobar } { #1 }
  __nowox_foobar_arg_add:nV {foo} l_nowox_foobar_foo_tl
  __nowox_foobar_arg_add:nV {bar} l_nowox_foobar_bar_tl
  __nowox_foobar_arg_add:nV {baz} l_nowox_foobar_baz_tl
  seq_if_empty:NF l__nowox_foobar_args_seq
   {
    you~said~that~seq_use:Nnnn l__nowox_foobar_args_seq { ~and~ } { ,~ } { ~and~ } par
   }
 }

ExplSyntaxOff

begin{document}

begin{foobar}[foo=1,bar=2,baz=3]
    text1
end{foobar}

begin{foobar}[bar=10]
    text2
end{foobar}

begin{foobar}
    text3
end{foobar}

end{document}

enter image description here

The keys are set locally, so they don't change their empty status at the beginning. The nonempty values are added to a sequence that can be “used” with different text between entries (a comma between two, “and” between only two and ”and” between the last two, if more than two.

Answered by egreg on July 12, 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