I tried creating a new command with an underscore as shown below, but doesn't work.

\newcommand{\h\_world}[1]{Hello World #1}

At the output I see without even initiating the command : worldHello World 1


Don't do it, unless there is a special reason to.

Underscores have special meaning (category code 8), to denote a subscript in math mode. Only catcode 11 (alphabetic) characters can be invoked in a macro name as \macroname.

Other approaches could be used to place an underscore in a macro name as shown below, but gyrations are required to invoke the macro name.

\expandafter\newcommand\csname h_world\endcsname[1]{Hello World #1}

\csname h_world\endcsname{!!!}

enter image description here

Note the space before the exclamation points is there because !!! is the argument to \csname h_world\endcsname, and shows up, after as space, as #1 in the output of that macro.

See https://en.wikibooks.org/wiki/TeX/catcode for more explanation of available catcodes.


If you were crazy and had to implement, without the use of \csname a syntax of \h_world, here is a possibility:

\def\haux_#1 {\def\tmp{#1}\ifx\tmp\tmpcompare Hello World \else\loneh_#1 \fi}
\newcommand\loneh{[\string\h{} undefined]}

\h blah

$\h_something blah$

\h_world blah


\h blah

$\h_something blah$

\h_world blah

enter image description here

The first group of 3 lines tests

  1. \h by itself, whose action is now defined in \loneh

  2. \h_<incorrect keyword> where incorrect keyword is anything other than the string world. It produces the result \loneh_<incorrect keyword> where the underscore is taken with the traditional meaning.

  3. \h_world, with the desired output.

In the first group of 3 lines \loneh is defined as [\string\h{} undefined] and in the second group of 3 lines, it is defined simply as H.

  • Makes life complicated o_O – user42826 Apr 24 '16 at 16:42
  • @user42826 Please see my addendum. – Steven B. Segletes Sep 13 '18 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.