27

I would like to define one variable containing some text that can be changed locally. The following code gives one example of the featuring I'm looking for.

\documentclass{article}
    \newcommand{\someSpecialText}{A text that can be changed locally...}
    \newcommand{\testIt}{The value of someSpecialText is : ''\someSpecialText''.}

\begin{document}

% The default behavior.
\testIt

% Here I would like to change the definition of `\someSpecialText`
% or anywhere else in the document.
\testIt

\end{document}

1 Answer 1

33

You can use a standard \renewcommand to modify the text:

enter image description here

\documentclass{article}
\newcommand{\someSpecialText}{A text that can be changed locally\ldots}
\newcommand{\testIt}{The value of \texttt{someSpecialText} is : ``\someSpecialText''.}

\begin{document}

% The default behavior.
\testIt

% Here I would like to change the definition of `\someSpecialText`
% or anywhere else in the document.
{% Start of group
\renewcommand{\someSpecialText}{A text that \textit{was} changed locally\ldots}
\testIt
}% End of group

% The default behavior.
\testIt

\end{document}​

In the above example, the \renewcommand was placed inside a group, defined by the braces { and } to localize the redefinition. If this behaviour is not desired, simply remove the braces to make the redefinition global from that point forward.


Of course, one can also write this in a macro form, which could be considered "shorter", with some default value. Here is an example:

enter image description here

\documentclass{article}
\newcommand{\testIt}[1][A text that can be changed locally\ldots]{The value passed to \texttt{testIt} is : ``#1''.}

\begin{document}

% The default behavior.
\testIt

% Here I would like to change the definition of `\someSpecialText`
% or anywhere else in the document.
\testIt[A text that \textit{was} changed locally\ldots]

% The default behavior.
\testIt

\end{document}​

\testIt is set up to output something with a default value. However, you can supply an optional argument that modifies the default behaviour.

4
  • Thanks. Is there one shorter way ?
    – projetmbc
    Nov 23, 2011 at 18:33
  • Shorter? I've updated the answer to modify \textIt into a macro that takes an optional argument. That could be considered "shorter". If not, please elaborate.
    – Werner
    Nov 23, 2011 at 18:40
  • You're right that's short enough... I'm sorry for this divagation... ;-)
    – projetmbc
    Nov 23, 2011 at 18:42
  • No, there is no short way. (That’s the right answer. ;-) Nov 30, 2013 at 11:33

You must log in to answer this question.

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