views:

620

answers:

3

I am trying to build a command which is similar to LaTeX \cite{}, which accepts a comma-separated list of parameters like this

\cite{Wall91, Schwartz93}

I would like to pass each item in the comma-separated list which the parameter represents to another command and return the concatenation of the individual results. I imagine it to be something like this:

\newcommand{\mycite}[1]{%
  \@for\var:=\split{#1} do{%
    \processCitation{\var}%
  }%
}

Literature on String manipulation, variables and looping in LaTeX would be great!

Also: Is there a way to join the individual results using commas again?

Thanks!

+2  A: 

I've never used it, but apparently someone did exactly what you're talking about.

Roberto Aloi
Darn complicated...
Christopher Oezbek
+5  A: 

Using Roberto's link I arrived at this solution:

\makeatletter

% Functional foreach construct 
% #1 - Function to call on each comma-separated item in #3
% #2 - Parameter to pass to function in #1 as first parameter
% #3 - Comma-separated list of items to pass as second parameter to function #1
\def\foreach#1#2#3{%
  \@test@foreach{#1}{#2}#3,\@end@token%
}

% Internal helper function - Eats one input
\def\@swallow#1{}

% Internal helper function - Checks the next character after #1 and #2 and 
% continues loop iteration if \@end@token is not found 
\def\@test@foreach#1#2{%
  \@ifnextchar\@end@token%
    {\@swallow}%
    {\@foreach{#1}{#2}}%
}

% Internal helper function - Calls #1{#2}{#3} and recurses
% The magic of splitting the third parameter occurs in the pattern matching of the \def
\def\@foreach#1#2#3,#4\@end@token{%
  #1{#2}{#3}%
  \@test@foreach{#1}{#2}#4\@end@token%
}

\makeatother

Usage example:

% Example-function used in foreach, which takes two params and builds hrefs
\def\makehref#1#2{\href{#1/#2}{#2}}

% Using foreach by passing #1=function, #2=constant parameter, #3=comma-separated list
\foreach{\makehref}{http://stackoverflow.com}{2409851,2408268}

% Will in effect do
\href{http://stackoverflow.com/2409851}{2409851}\href{http://stackoverflow.com/2408268}{2408268}
Christopher Oezbek
And how does one use this? Could you give an example?
AVB
Thanks for the example! +1 for question and answer both.Do you mind taking a look here: http://stackoverflow.com/questions/2389081/Maybe you'll have an idea.
AVB
No problem. Thanks for the vote. Have a look at the solution I gave in your post!
Christopher Oezbek
A: 

how could i use this to define a command with a list of arguments that could be printed in a numbered list? something like: \cmd{arg1,arg2,arg3...argN} resulting in: 1. arg1. 2. arg2. 3. arg3. ... N. argN.

h.b.pasti