[Tex/LaTex] syntax of passing arguments to a command

syntax

From general programming languages, I'm used to calling functions in the following way:

myfunction(argument1, argument2, ..., argumentn)

It seems like latex requires this syntax

\mycommand{argument1}{argument2}...{argumentn}

to use commands. Can I call commands using the usual function syntax (instead of writing out braces for every single argument)? I want to be able to do this:

\mycommand{argument1, argument2, ..., argumentn}

Best Answer

Other answers have dealt with how one can split at commas, but perhaps some wider explanation is also useful. It's important to start with the fact that whilst LaTeX can be programmed generally, it is a document preparation system for typesetting. The design of the underlying language (TeX) also reflects the same aim, and LaTeX largely uses the same conventions as TeX itself here.

In terms of passing arguments, TeX deals with 'balanced text', which is some arbitrary material (normally) starting with { and ending with }. The characters used to delimit the 'balanced text' can be altered, but not the fact that we need the two and that they are distinct. That means we have to pass arguments in the form

\foo{balanced text 1}{balanced text 2}

etc. TeX does allow a more complex 'delimited' argument type, so we can set up (as David as done) to split material at commas

\def\foo(#1,#2){Stuff with #1 and #2}
\foo(abc,def) => #1 = abc, #2 = def

but this has to be defined at the programming layer: we can't just 'switch the core syntax'. Moreover, the simple definition I've just used requires a comma in the input: if you are modelling on other general languages you are likely expecting the arguments to be optional. One can use more elaborate programming to split at variable numbers of commas, but this will always be a layer on top of the core.

One key point to bear in mind is that TeX doesn't have string data or a function/variable split: we have just 'tokens'. Importantly, this means that we might well expect a comma to be used anywhere, and so have to 'protect' commas if we use the \foo(abc,efg) syntax:

\foo({abc,def},ghi) => #1 = abc,def; #2 = ghi

which (to me) is no clearer than

\baz{abc,def}{ghi}

Also worth noting here is that using ( ... ) also carries some issues: they can't appear in the arguments without causing issues or without a more complex code set up (see xparse).

Related Question