如何使用宏参数作为逗号分隔的单词进行过滤

如何使用宏参数作为逗号分隔的单词进行过滤

所以我有这个宏列表\entry,它接受一个参数,该参数只是一个文本。

\entry{whatevercoutent}

我想使用第二个参数作为逗号分隔的单词列表,用于过滤条目。

例如,

Some way to declare to only filter "filter1"

\entry{content1}{filter1, filter2, filter3}
\entry{content2}{filter1}
\entry{content3}{filter3}

在上面的例子中,我们声明了将进行过滤filter1。这将导致仅呈现 content1 和 content2。

有办法实现这个吗?

提前致谢。

答案1

思路如下:每个“过滤器”定义一个用于存储条目的新序列。最后,您可以使用这些序列。我还定义了一个全局序列来存储所有条目。

\documentclass{article}

\ExplSyntaxOn

\NewDocumentCommand{\entry}{mo}
 {% #1 is an entry, #2 is a list of filters (optional)
  \egreg_filterentry:nn { #1 } { #2 }
 }

\NewDocumentCommand{\printentries}{o}
 {
  \seq_use:cn { g__egreg_filterentry_ \IfNoValueTF { #1 } { global } { filter_#1 } _seq } {,~}
 }

\seq_new:N \g__egreg_filterentry_global_seq

\cs_new_protected:Nn \egreg_filterentry:nn
 {
  % store the entry in the global list
  \seq_gput_right:Nn \g__egreg_filterentry_global_seq { #1 }
  \tl_if_novalue:nF { #2 }
   {% we have a list of filters
    \clist_map_inline:nn { #2 }
     {% add the entry to the list corresponding to each given filter
      \__egreg_filterentry_filter:nn { #1 } { ##1 }
     }
   }
 }

\cs_new_protected:Nn \__egreg_filterentry_filter:nn
 {%
  \seq_if_exist:cF { g__egreg_filterentry_filter_#2_seq }
   {% create the list if not yet existing
    \seq_new:c { g__egreg_filterentry_filter_#2_seq }
   }
  \seq_gput_right:cn { g__egreg_filterentry_filter_#2_seq } { #1 }
 }

\ExplSyntaxOff

\begin{document}

\entry{content0}
\entry{content1}[filter1, filter2, filter3]
\entry{content2}[filter1]
\entry{content3}[filter3]

Global list: \printentries

filter 1: \printentries[filter1]

filter 2: \printentries[filter2]

filter 3: \printentries[filter3]

\end{document}

在此处输入图片描述

答案2

egreg 解决的任务不需要 expl3 就可以完成:

\newcount\entrynum
\def\entries{}
\def\entry#1[#2]{\advance\entrynum by1
   \expandafter\entryA \expandafter{\the\entrynum}{#1}%
   \sdef{e:\the\entrynum:}{}%
   \entryB #2,\end,}
\def\entryA #1#2{\addto\entries{\tryprint{#1}{#2}}}
\def\entryB #1#2,{\ifx\end#1\else \sdef{e:\the\entrynum:#1#2}{}\expandafter\entryB\fi}

\def\sdef#1{\expandafter\def\csname#1\endcsname}
\def\addto#1#2{\expandafter\def\expandafter#1\expandafter{#1#2}}

\def\tryprint#1#2{\ifcsname e:#1:\filter\endcsname \maybecomma #2\fi}
\def\printentries[#1]{\def\maybecomma{\def\maybecomma{, }}\def\filter{#1}\entries}

\entry{content1}[filter1, filter2, filter3]
\entry{content2}[filter1]
\entry{content3}[filter3]

Global list: \printentries[]

filter 1: \printentries[filter1]

filter 2: \printentries[filter2]

filter 3: \printentries[filter3]

\bye

OP 提出的问题不清楚。

相关内容