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

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?

• Note that you have to place % at the end of lines if you don't want those line endings to turn into a space (this isn't necessary after macros like \ThisCommand, as spaces are ignored there, but after the opening braces and the closing brace of the \newcommand, as well as after #1). Nov 13 '20 at 7:21

Do you mean something like this:

\documentclass[]{article}

\newcommand\defineanduse[2]
{%
\newcommand#1{#2}%
#1%
}

\begin{document}

\defineanduse\mycmd{abc}

\defineanduse\myothercmd{def}

\mycmd\myothercmd

\end{document}


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



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:

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


which allows you to say

\define\ThisCommand{whatever}


to do what you want.