3

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

5

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.

\documentclass{article} 
\begin{document}
\expandafter\newcommand\csname h_world\endcsname[1]{Hello World #1}

\csname h_world\endcsname{!!!}
\end{document}

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.

ADDENDUM

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

\documentclass{article}
\usepackage{lmodern}
\usepackage[T1]{fontenc}
\makeatletter
\newcommand\h{\@ifnextchar_{\haux}{\loneh}}
\makeatother
\def\tmpcompare{world}
\def\haux_#1 {\def\tmp{#1}\ifx\tmp\tmpcompare Hello World \else\loneh_#1 \fi}
\begin{document}
\newcommand\loneh{[\string\h{} undefined]}

\h blah

$\h_something blah$

\h_world blah

\bigskip\renewcommand\loneh{H}

\h blah

$\h_something blah$

\h_world blah
\end{document}

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.