Debian Codegraph @

texmf-dist/tex/generic/tokmap/tokmap.tex

raw
1 % tokmap.tex, version 1.0
2
3 % Copyright (C) 2025 plante
4 % This package is released under the LaTeX Project Public License (LPPL) 1.3c.
5
6 % tokmap: iterate over a token list expandably, without dropping spaces or braced groups.
7
8 % Usage: `\tokmap <command> { <tokens> }` applies command over the token list tokens.
9 % Space tokens, left and right braces are replaced with the marker tokens `\tokmap@space`,
10 % `\tokmap@bgroup`, and `\tokmap@egroup` respectively (who are `\ifx`-equal to themselves
11 % exclusively). For convenience, command may contain multiple tokens.
12 % It is assumed that `{` and `}` are the only characters with category codes 1
13 % (beginning of group) and 2 (end of group) respectively.
14 % Expandable.
15
16 % This package may be used in LaTeX by `\usepackage{tokmap}`, or
17 % in plain TeX and other formats by `\input{tokmap}`.
18
19 % See the visualtoks package for an example application.
20
21
22
23 \ifdefined\tokmap
24 \expandafter\endinput
25 \fi
26 \edef\next{\catcode`\noexpand\@=\the\catcode`\@\space}
27 \catcode`\@=11
28
29 \long\def\tokmap#1#2{\iffalse{\fi \tokmapA{#1}#2{\tokmap@nil}\tokmap@nil \iffalse}\fi}
30 \long\def\tokmapA#1#2#{%
31 \tokmapB\tokmapC{#1}#2 \tokmap@nil \tokmap@nil
32 \tokmapD{#1}%
33 }
34 \long\def\tokmapB#1 #2\tokmap@nil{%
35 \if\relax\detokenize{#2}\relax \expandafter\@firstoftwo \else \expandafter\@secondoftwo \fi
36 {#1\tokmap@nil}%
37 {\tokmapB#1\tokmap@space#2\tokmap@nil}%
38 }
39 \long\def\tokmapC#1#2{%
40 \ifx\tokmap@nil#2\expandafter\tokmapE\fi
41 #1{#2}\tokmapC{#1}%
42 }
43 \long\def\tokmapD#1#2{%
44 \if\relax\detokenize\expandafter{\tokmapE#2\tokmap@nil}\relax \else \expandafter\tokmapE \fi
45 #1\tokmap@bgroup\tokmap{#1}{#2}#1\tokmap@egroup
46 \tokmapA{#1}%
47 }
48 \long\def\tokmapE#1\tokmap@nil{}
49
50 \protected\def\tokmap@bgroup{\noexpand\tokmap@bgroup}
51 \protected\def\tokmap@egroup{\noexpand\tokmap@egroup}
52 \protected\def\tokmap@space {\noexpand\tokmap@space}
53 \protected\def\tokmap@nil{\noexpand\tokmap@nil}
54
55 \ifx\@firstoftwo\@undefined \long\def\@firstoftwo#1#2{#1} \fi
56 \ifx\@secondoftwo\@undefined \long\def\@secondoftwo#1#2{#2}\fi
57
58 \next
59
60 \endinput