TransWikia.com

Write a macro to define a new command and locally invoke it

TeX - LaTeX Asked on December 22, 2020

I would write a macro defineThisCommand that defines a new command TheCommand and, then, locally invokes it. The code has to be something like this:

defineThisCommand{}{
      newcommand ThisCommand{
           #1
      }
      ThisCommand
}

begin{document}
    defineTopicOne{Some text printed}
    defineTopicTwo{and this too}
end{document}

generating, at the end, the output

Some text printed

and this too

Please, can you suggest me a way of solving this problem?

2 Answers

Do you mean something like this:

documentclass[]{article}

newcommanddefineanduse[2]
  {%
    newcommand#1{#2}%
    #1%
  }

begin{document}

defineandusemycmd{abc}

defineandusemyothercmd{def}

mycmdmyothercmd

end{document}

enter image description here

Correct answer by Skillmon on December 22, 2020

When TeX finds a control sequence foo, there are two cases to distinguish first: either TeX is doing macro expansion, or it isn’t. The latter case is not of a concern in your situation, so we look at what happens in the former case. The cases are:

  1. the control sequence has been assigned a meaning, or
  2. the control sequence is undefined.

In the first case, TeX uses the meaning, which should be appropriate to the context: if foo is a macro, it will be expanded, if it is a chardef token the corresponding character will be printed, and so on.

In the second case, TeX will stop, issue an error message and ignore the undefined token.

Thus you can’t do like you’d like to, unless you have previously defined a bunch of macros

newcommanddefineThisCommand[1]{newcommandThisCommand{#1}ThisCommand}

for every local command you need. This obviously defies your intention: you cannot have defineOtherCommand if you haven’t previously defined it.

The strategy to use is to have a generic macro with two arguments:

newcommanddefine[2]{%
  newcommand#1{#2}% define the local command
  #2% and also use it now
}

which allows you to say

defineThisCommand{whatever}

to do what you want.

Answered by egreg on December 22, 2020

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