[Tex/LaTex] How to detect that some macro expands to empty string or spaces only

conditionalsmacrosstrings

I need to check several macros and do some actions only if their expansion is not empty nor space only.

In pseudo code I would look like this

\if\macroToBeTested
    \doSomething
    \doSomethingElse
\fi

macros \doSomething and \doSomethingElse should only execute if \macroToBeTested expands to something that contains at least one character which is not space.

How can I implement that? I prefer using something like this

\if\test{\macroToBeTested}%
  \doSomething%
  \doSomethingElse%
\fi

rather then anything like this

\test{\macroToBeTested}{%
  \doSomething%
  \doSomethingElse%
}

EDIT

Here is example (pseudocode)

\newcommand{\macroToBeTested}{   }%
Hello%
\if\test{\macro}%
  World!%
\fi

This would print only "Hello", while this

\newcommand{\macroToBeTested}{  s }%
Hello%
\if\test{\macro}%
  World!%
\fi

should print "Hello World!".

Best Answer

Just use the code by D. Arsenau mentioned in Is "conditionals" name of package? with an additional macro:

\makeatletter
{\catcode`\!=8 % funny catcode so ! will be a delimiter
 \catcode`\Q=3 % funny catcode so Q will be a delimiter
\long\gdef\given#1{88\fi\Ifbl@nk#1QQQ\empty!}
\long\gdef\blank#1{88\fi\Ifbl@nk#1QQ..!}% if null or spaces
\long\gdef\nil#1{\IfN@Ught#1* {#1}!}% if null
\long\gdef\IfN@Ught#1 #2!{\blank{#2}}
\long\gdef\Ifbl@nk#1#2Q#3!{\ifx#3}% same as above
}
\makeatother
\def\expblank{\expandafter\blank\expandafter} % additional macro

Now

\if\expblank{\mymacro}%
  <code if \mymacro expands only to zero or more spaces>%
\else
  <code if \mymacro expansion contains non space tokens>%
\fi

will do.

You can define similarly \expnil and \expgiven.

Complete example

\documentclass{article}
\makeatletter
{\catcode`\!=8 % funny catcode so ! will be a delimiter
 \catcode`\Q=3 % funny catcode so Q will be a delimiter
\long\gdef\given#1{88\fi\Ifbl@nk#1QQQ\empty!}
\long\gdef\blank#1{88\fi\Ifbl@nk#1QQ..!}% if null or spaces
\long\gdef\nil#1{\IfN@Ught#1* {#1}!}% if null
\long\gdef\IfN@Ught#1 #2!{\blank{#2}}
\long\gdef\Ifbl@nk#1#2Q#3!{\ifx#3}% same as above
}
\makeatother
\def\expblank{\expandafter\blank\expandafter}
\def\expgiven{\expandafter\given\expandafter}
\def\expnil{\expandafter\nil\expandafter}

\def\foo{ }
\def\bar{}
\def\baz{\bar}

\if\expgiven{\foo}
  \typeout{NOT BLANK}
\else
  \typeout{BLANK}
\fi

\if\expblank{\foo}
  \typeout{BLANK}
\else
  \typeout{NOT BLANK}
\fi

\if\expblank{\bar}
  \typeout{BLANK}
\else
  \typeout{NOT BLANK}
\fi

\if\expblank{\baz}
  \typeout{BLANK}
\else
  \typeout{NOT BLANK}
\fi

The log shows

BLANK
BLANK
BLANK
NOT BLANK
Related Question