Let's see what happens: if \testa
and \testb
are equal, there is no problem; when \testa
and \testb
are different, from
Test \mycommand{this} is
you get "Test••is" (with • I denote a space in the output). This has nothing to do with the macro at hand, but it's a consequence of the rules. In fact, when \mycommand{this}
is expanded to nothing, the input has already been tokenized, so TeX is not any more in the state where consecutive spaces are reduced to one space token.
How to remove the space depends on what you want to do. The difference between
\newcommand{\mycommand}[1]{%
\ifx\testa\testb
#1%
\else
\ifhmode\unskip\fi
\fi}
and
\newcommand{\mycommand}[1]{%
\ifx\testa\testb
#1%
\else
\ignorespaces
\fi}
is about what of the two spaces is removed; with \unskip
it's the space before, with \ignorespaces
it's the one after.
There is, however, a conceptual difference: \unskip
just removes glue if it was there, and has nothing to do with macro expansion; \ignorespaces
, instead, expands the following tokens until finding a non expandable one that is not a space token and gobbling all space tokens it finds in the process. (That's why it's not necessary to use \expandafter
in front of it in the second definition, because it will start expanding the \fi
).
Thus it may be preferable to use the first mode, if you're afraid that expansion can happen too early. Using \relax
before \ifx
, if you don't need \mycommand
in an expansion only context, may prove useful.
Just to try being clearer, \unskip
works down in the stomach, when commands are being executed; to the contrary, \ignorespaces
works during macro expansion, much earlier than the stage when TeX executes commands. So the former can remove the last node, if it is glue, the latter cannot remove spacing instructions, but only space tokens.
Best Answer
What you want is a macro. Wikibooks has excellent tutorial on the topic. As for the code environment, use the
listings
package: Wikibooks, CTAN.Here is a quick example of what you can do. The
\newcommand
s there make three, well, new commands:\compbox
,\compline
, and\comp
.