GeneralConditional Branch in new Command

LaTeX specific issues not fitting into one of the other forums of this category.
Post Reply
parnmatt
Posts: 2
Joined: Sun Oct 16, 2011 6:33 pm

Conditional Branch in new Command

Post by parnmatt »

Hi, I was wondering if anyone can suggest a way to get \ifthenelse working within another command.

This segment is what I have at the moment, granted I know it doesn't work, but it should give you an idea what I mean.

Code: Select all

\usepackage{xifthen}
\usepackage{minted}

\newcommand{\codesrc}[5][]{%
	\inputminted[%
		\ifthenelse{\isempty{#1}}{}{label=#1,}%
		frame=lines,%
		framesep=1.2em,%
		linenos=true,%
		\ifthenelse{\isempty{#2}}{}{firstnumber=#2,firstline=#2,}{}%
		\ifthenelse{\isempty{#3}}{}{lastline=#3,}{}%
	]{#4}{#5}%
}
I've thought perhaps trying to add to a string str = str + "new code" if that's even possible, and to then execute that string as LaTeX code, though I don't know how to do it …if it's even possible.

OK, those are the two possible ideas I have. If anyone has any constructive advice or ideas on this, please comment.

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

josephwright
Site Moderator
Posts: 814
Joined: Tue Jul 01, 2008 2:19 pm

Conditional Branch in new Command

Post by josephwright »

You are trying to use a 'functional' approach, which is not how TeX works. The usual approach to this sort of problem is to create the input you want using \edef. However, \ifthenelse is not 'expandable' and this will not work. Instead, I would use the so-called 'e-TeX extensions', which are automatically available in any modern LaTeX

Code: Select all

\makeatetter
\newcommand{\codesrc}[5][]{%
  \begingroup
  \edef\@tempa{%
    \endgroup
    \noexpand\inputminted[%
      \expandafter\ifx\expandafter A\detokenize{\@gobble #1?}A%
      \else
        label=\unexpanded{#1},%
      \fi
      frame=lines,%
      framesep=1.2em,%
      linenos=true,%
      \expandafter\ifx\expandafter A\detokenize{\@gobble #2?}A%
      \else
        firstnumber=\unexpanded{#2},firstline=\unexpanded{#2},%
      \fi
      \expandafter\ifx\expandafter A\detokenize{\@gobble #3?}A%
      \else
        lastline=\unexpanded{#3}%
      \fi
    ]%
  }%
  \@tempa{#4}{#5}%
}
\makeatother
The idea here is that we construct \@tempa to contain what you would have typed in if you'd done this directly. Then we use that to execute the command you want.
Joseph Wright
Post Reply