Protecting fragile contents 

Newsgroups: comp.text.tex
>I want to define a command to wrap the listing package:
>
>...
>
>\newcommand{\flisting}[4]{
>\begin{lstlisting}[caption={[#1]#1#2} #3]{}
>#4
>\end{lstlisting}
>}
>
>\flisting{Training dataset } { \citep{mitchell:1997:MLbook}}
>{,frame=tb,  basicstyle=\ttfamily,  labelstep=2, label=lst:knn:tds2}{
>   672346       NY     25   Low
>   008301       NY     27   High
>   563482       CA     30   Average
>   127893       CA     60   Average
>   389245       NY     67   Low
>   240389       CA     90   Low
>}

I did not check the listing package, but I am rather sure that it changes some catcodes to reckognize the spaces and newlines (and probably also some other catcodes are changed). With your above macro the last argument is scanned have the `usual' (wrong) catcode.

To say it in other words: It is *in principle* not possible to pass your table as a parameter to the listing package (unless you change catcodes before `by hand' which I would not recommend).

the table is read. For example, you might try (untested!):

\newcommand{\flisting}[3]{\begin{lstlisting}[caption={[#1]#1#2} #3]{}}

which must be called in the strange way:

\flisting{...}{...}{...}
  your table
\end{lstlisting}

As a less `clean' but more intuitive alternative, you could also try

\newenvironment{flisting}[3]{\begin{lstlisting}[caption={[#1]#1#2} #3]{}}%
 {\end{lstlisting}}

which may be called in the more intuitive way

\begin{flisting}{...}{...}{...}
  your table
\end{flisting}

However, whether the latter works depends on the implementation of the listing package (it might be the case that the listing package looks for

(Martin Vaeth)