Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save FriendsAtDawn/c1384851b84c39f7bc04840dc25ea137 to your computer and use it in GitHub Desktop.

Select an option

Save FriendsAtDawn/c1384851b84c39f7bc04840dc25ea137 to your computer and use it in GitHub Desktop.
How to use number in latex arguments \command{#}

Dynamic Object Definition in LaTeX: Define and Call Objects with Custom Commands

Description

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}).

Code

\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
        }%
    }%
}

Usage Example

% 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"

Key Features

  1. Dynamic Commands: No need to hardcode \newcommand for every object.
  2. Short/Long Names: Toggle between verbose and compact versions with !.
  3. Scalable: Works for any object type (e.g., \InitNuevoObjeto{book}).

Dependencies

  • Requires the xstring package for \IfSubStr and \StrBefore. Add to preamble:
    \usepackage{xstring}

Why This Matters

  • 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.

Feedback

Found a bug or have a suggestion? Open an issue or fork this GIST!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment