Dynamic Object Definition in LaTeX: Define and Call Objects with Custom Commands
Tired of manually defining dozens of similar LaTeX commands for objects like chair1, chair2, etc.?
This macro lets you dynamically create and manage object families (e.g., chairs, tables, equations) with long and short names, all while keeping your code clean and scalable.
- Define once:
\InitNuevoObjeto{chair}creates\defineChair{key}{long}{short}. - Use anywhere: Call
\chair{1}for the long name or\chair{1!}for the short version. - No limits: Works for any object type (e.g.,
\InitNuevoObjeto{table},\InitNuevoObjeto{equation}).
\newcommand{\InitNuevoObjeto}[1]{%
% Constructor: \define#1{key}{long_name}{short_name}
\expandafter\newcommand\csname define#1\endcsname[3]{%
% Long command: \#1<key>
\expandafter\newcommand\csname #1##1\endcsname{##2}%
% Short command: \#1<key>short
\expandafter\newcommand\csname #1##1short\endcsname{##3}%
}%
% Caller: \#1{key} or \#1{key!} (for short name)
\expandafter\providecommand\csname #1\endcsname[1]{%
\IfSubStr{##1}{!}{%
\StrBefore{##1}{!}[\tempclave]%
\csname #1\tempclave short\endcsname
}{%
\csname #1##1\endcsname
}%
}%
}% Initialize the object family "chair"
\InitNuevoObjeto{chair}
% Define chair1: long name = "Dining Chair", short name = "DC1"
\defineChair{1}{Dining Chair}{DC1}
% Use in document:
Long: \chair{1} % Output: "Dining Chair"
Short: \chair{1!} % Output: "DC1"- Dynamic Commands: No need to hardcode
\newcommandfor every object. - Short/Long Names: Toggle between verbose and compact versions with
!. - Scalable: Works for any object type (e.g.,
\InitNuevoObjeto{book}).
- Requires the
xstringpackage for\IfSubStrand\StrBefore. Add to preamble:\usepackage{xstring}
- Saves time: Define hundreds of objects with a single macro.
- Reduces errors: No copy-paste mistakes from manual definitions.
- Cleaner code: Focus on content, not repetitive LaTeX commands.
Found a bug or have a suggestion? Open an issue or fork this GIST!