![列表解析ascii空格字符](https://rvso.com/image/305767/%E5%88%97%E8%A1%A8%E8%A7%A3%E6%9E%90ascii%E7%A9%BA%E6%A0%BC%E5%AD%97%E7%AC%A6.png)
我一直在使用 etoolbox 中的清單解析功能,並且我有一個奇怪的用例,其中我想要一個空格分隔的清單。
\usepackage{etoolbox}
\DeclareListParser*{\symbolListParser}{<symbol for space character>}
\newcommand{\processSymbolList}[1]{
\symbolListParser{}{#1}
}
我不確定從哪裡開始尋找。我已經瀏覽了一段時間,查看有關列表的文檔、有關空間的文檔和有關 ascii 字符的文檔,但無濟於事。
因此,如果有人可以告訴我如何做到這一點,在哪裡尋找或這是不可能的,我將非常感激。
更新:我確實找到了這但我一直在尋找一些更乾淨的東西,就像OP想要的那樣
更新2:感謝托比的回答。我已經接受了。下面是 spacelist 的更通用版本,其行為更像列表解析器
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{ \spacelist }{ mm }{
\seq_set_split:Nnn \l_tmpa_seq { ~ } { #2 }
\seq_map_inline:Nn \l_tmpa_seq {
#1{##1}
}
}
\ExplSyntaxOff
% to use you would write it like:
\spacelist{\fbox}{Boxes and Spaces in a List}
答案1
這是一種使用的方法expl3
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{ \spacelist }{ m }{
\seq_set_split:Nnn \l_tmpa_seq { ~ } { #1 }
\seq_map_inline:Nn \l_tmpa_seq {
\fbox { ##1 }
}
}
\ExplSyntaxOff
\begin{document}
List: \spacelist{Boxes and Spaces in a List}
\end{document}
該程式碼使用所謂的序列它是透過拆分at 空格#1
的參數產生的,在新語法*中,而普通空格被忽略。亮片儲存在一個名為 的本地臨時變數中,我們可以迭代序列中的所有項目。當前項目以參數 code 給出,這是因為映射嵌套在定義內。\spacelist
~
\l_tempa_seq
\seq_map_inline
#1
##1
您可以更換零件\fbox
以滿足您的需求...
*新文法表示 LaTeX3 引入的語法,目前可作為expl3
打包使用,由xparse
.要了解更多信息,請參閱expl3
或的手冊source3
。
答案2
該listofitems
包可以以渲染或去標記的形式提供它:
\documentclass{article}
\usepackage{lmodern}
\usepackage[T1]{fontenc}
\usepackage{listofitems}
\newcommand\spacelist[2][]{
\setsepchar{ }%
\readlist\mylist{#2}%
\showitems#1\mylist%
}
\begin{document}
List: \spacelist{Boxes and \textbf{Spaces} in a List}
Tokens: \spacelist[*]{Boxes and \textbf{Spaces} in a List}
\end{document}
答案3
您可以用兩行 TeX 巨集編寫一個無套件方法來實現您的目標。
\documentclass{article}
\catcode`z 3
\makeatletter
\newcommand\spacelist[1]{\spacelist@boxit #1 {z} }%
\long\def\spacelist@boxit #1 {\ifx z#1\relax\else
\fbox{#1}\expandafter\spacelist@boxit\fi}
\catcode`z 11
\makeatother
\begin{document}
List: \spacelist{Boxes and Spaces in a List}
\end{document}
承認有罪:如果解析的清單包含\else
或\fi
標記,則該方法很脆弱。
這是更強大的方法,仍然具有簡單的手段。但參數不應包含 catcode 3 字母 Z...
\documentclass{article}
\usepackage[T1]{fontenc}
\catcode`Z 3
\makeatletter
\newcommand\spacelist[1]{\spacelist@getone{}#1 Z }%
\long\def\spacelist@getone #1 {\spacelist@check #1.Z\spacelist@check{#1}}%
\long\def\spacelist@check #1Z#2\spacelist@check#3%
{\if\relax\detokenize{#1}\relax
\expandafter\@gobbletwo % abort parse
\else
%
% #3 contains the searched for item, but with an empty brace pair
% added, which serves to prevent brace removal in processing
% so I am showing here how to remove it with \expandafter/\@gobble
% initial braces are not lost.
%
\fbox{\detokenize\expandafter{\@gobble#3}}%
\fi
\spacelist@getone{}}%
\catcode`Z 11
\makeatother
\begin{document}
List: \spacelist{Boxes {and Spaces} in a {List with \if, \else, \end tokens}}
\end{document}