TeXFind 重出江湖

本科在学习 LaTeX 时,每当在别人的模板中遇到未知控制序列(以下简称命令)或环境,总要使用搜索引擎搜索相关的信息,然后去查看宏包来源与相应描述。因此,当时我就想写一个类似 Texdoc 的工具,可以方便地查看命令或环境的来源。囿于当时编程能力,实现了基本功能但代码几乎不可读。最近刚好在 debug 时又有了类似的想法,宏包 lineno 的导入会导致修复浮动体上下间距的补丁失效,因此,我需要知道有哪些宏包或文类导入了 lineno

为了简便起见,我使用了正则表达式来提取相应的命令与环境,因此,会有因宏包写法“诡异”导致的读取结果与实际不一致的情况。同时,我只考虑了 LaTeX2ε 的语法,LaTeX3 我是一点都没有考虑进去,所以类似 ctex 的宏包都无法得到所有的信息。虽说这些改进的方向都写进了 TODO 里面,我相信在没有额外激励的前提下这些想法将永远都是 TODO,以下就是全部的代码。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
__all__ = ['TeXParser', 'TeXDistribution']
__version__ = '0.1.0'


import collections as c
import json
import pathlib as p
import re
import textwrap
import typing as t


class TeXParser:
    '''TeX Parser

    - TODO:
        - use AST instead of regular expressions
        - LaTeX3 and LaTeX2ε
    '''

    def __init__(self, content: str) -> None:
        self._content = self._remove_options(self._remove_comments(content))

    @property
    def packages(self) -> t.Set[str]:
        return self._extract_packages(self._content)

    @property
    def commands(self) -> t.Dict[str, t.Set[str]]:
        return {
            'use': self._extract_use_commands(self._content),
            'def': self._extract_def_commands(self._content),
        }

    @property
    def environs(self) -> t.Dict[str, t.Set[str]]:
        return {
            'use': self._extract_use_environs(self._content),
            'def': self._extract_def_environs(self._content),
        }

    def _remove_comments(self, content: str) -> str:
        pattern1 = re.compile(r'%[^\n]*')
        pattern2 = re.compile(r'[ \n]')
        return pattern2.sub('', pattern1.sub('', content))

    def _remove_options(self, content: str) -> str:
        mapper = {
            r'\[': '__ESCAPED_LEFT_SQUARE_BRACKETS__',
            r'\]': '__ESCAPED_RIGHT_SQUARE_BRACKETS__',
        }
        content = self._replace(content, mapper, False)
        content = re.compile(r'\[[^\]]*\]').sub('', content)
        return self._replace(content, mapper, True)

    def _extract_packages(self, content: str) -> t.Set[str]:
        packages = set()
        for command in {'RequirePackage', 'usepackage'}:
            pattern = re.compile(fr'(?<=\\{command}{"{"})[^{"}"}\\]+(?={"}"})')
            for package in pattern.findall(content):
                packages.update(map(str.strip, package.split(',')))
        return packages

    def _extract_use_commands(self, content: str) -> t.Set[str]:
        pattern = re.compile(r'(?<=\\)[a-zA-Z@\*]+')
        return set(pattern.findall(content))

    def _extract_def_commands(self, content: str) -> t.Set[str]:
        commands = set()
        for command in {'def', 'edef', 'gdef', 'xdef'}:
            pattern = re.compile(fr'(?<=\\{command})[a-zA-Z@\*]+')
            commands.update(pattern.findall(content))
        for command in {'newcommand', 'renewcommand', 'newrobustcmd'}:
            for option in {'', '\\*', '\\*{', '{'}:
                pattern = re.compile(fr'(?<=\\{command}{option}\\)[a-zA-Z@\*]+')
                commands.update(pattern.findall(content))
        return commands

    def _extract_use_environs(self, content: str) -> t.Set[str]:
       pattern = re.compile(r'(?<=\begin{)[a-zA-Z@\*]+')
       return set(pattern.findall(content))

    def _extract_def_environs(self, content: str) -> t.Set[str]:
        environs = set()
        for command in {'newenvironment', 'renewenvironment'}:
            for option in {'', '\\*'}:
                pattern = re.compile(fr'(?<=\\{command}{option}{"{"})[a-zA-Z@\*]+')
                environs.update(pattern.findall(content))
        return environs

    def _replace(self, content: str, mapper: t.Dict[str, str], reverse: bool = False) -> str:
        for old, new in mapper.items():
            if reverse:
                old, new = new, old
            content = content.replace(old, new)
        return content


class TeXDistribution:
    '''TeX Distribution
    '''

    Self = __qualname__
    suffixes = {'.cls', '.sty'}

    def __init__(self, root: str) -> None:
        self._root = p.Path(root)
        self._cache_path = self._root / 'texfind.json'
        self._cache = self._initialize_cache()

    def __repr__(self) -> str:
        return f'<TeXDistribution @ "{self._root}">'

    def __iter__(self) -> t.Iterator[str]:
        yield from self.cache['path']

    def __getitem__(self, package: str) -> t.Optional['Information']:
        for suffix in ['', *self.suffixes]:
            try:
                return self.information(package+suffix)
            except KeyError:
                pass
        return None

    @property
    def cache(self) -> t.Dict[str, t.Any]:
        self.update(overwrite=False)
        return self._cache

    def search(self, string: str) -> t.List[str]:
        # TODO: yield?
        string = string.lower()
        packages = []
        for package in self.cache['path']:
            if string in package.lower():
                packages.append(package)
        return packages

    def information(self, package: str) -> 'Information':
        package = package.lower()
        for target in self.cache['path']:
            if package == target.lower():
                break
        else:
            raise KeyError
        return Information(target, {
            'path': [self._root/p for p in self.cache['path'][target]],
            'package': self.cache['package'][target],
            'command': self.cache['command'][target],
            'environ': self.cache['environ'][target],
        })

    def update(self, overwrite: bool = False) -> Self:
        if not (overwrite or self._cache is None):
            return self
        self._cache = self._update_cache()
        self._cache_path.write_text(json.dumps(self._cache, ensure_ascii=False, separators=(',', ':')))
        return self

    def _initialize_cache(self) -> t.Optional[t.Dict[str, t.Any]]:
        try:
            self._cache_path.touch()
        except PermissionError:
            print(f'Please create {self._cache_path} manually and make it readable and writable')
        content = self._cache_path.read_text()
        return json.loads(content) if content else None

    def _update_cache(self) -> t.Dict[str, t.Any]:
        paths = c.defaultdict(set)
        packages = c.defaultdict(set)
        commands = c.defaultdict(lambda: c.defaultdict(set))
        environs = c.defaultdict(lambda: c.defaultdict(set))
        for path in self._tqdm(self._root.rglob('*')):
            if path.suffix in self.suffixes:
                paths[path.name].add(path.relative_to(self._root).as_posix())
                parser = TeXParser(path.read_text(errors='replace'))
                packages[path.name].update(parser.packages)
                for key, value in parser.commands.items():
                    commands[path.name][key].update(value)
                for key, value in parser.environs.items():
                    environs[path.name][key].update(value)
        return {
            'version': __version__,
            'path': {k: list(v) for k, v in paths.items()},
            'package': {k: list(v) for k, v in packages.items()},
            'command': {
                name: {k: list(v) for k, v in command.items()}
                for name, command in commands.items()
            },
            'environ': {
                name: {k: list(v) for k, v in command.items()}
                for name, command in commands.items()
            },
        }

    def _tqdm(self, iterable: t.Iterable) -> t.Iterator[t.Any]:
        try:
            import tqdm
        except:
            yield from iterable
        else:
            yield from tqdm.tqdm(iterable)


class Information:
    '''Wrapper of TeXDistribution::information
    '''

    def __init__(self, name: str, data: t.Dict[str, t.Any]) -> None:
        self._name = name
        self._path = data['path']
        self._package = data['package']
        self._command = data['command']
        self._environ = data['environ']

    def __repr__(self) -> str:
        return textwrap.dedent(f'''
        <Information @ "{self._name}"
            path:        List[Path], len={len(self._path)}
            package:     List[str],  len={len(self._package)}
            command_use: List[str],  len={len(self._command['use'])}
            command_def: List[str],  len={len(self._command['def'])}
            environ_use: List[str],  len={len(self._environ['use'])}
            environ_def: List[str],  len={len(self._environ['def'])}
        >
        ''')[1:-1]

    @property
    def path(self) -> t.List[p.Path]:
        return self._path

    @property
    def package(self) -> t.List[str]:
        return self._package

    @property
    def command(self) -> t.Dict[str, t.List[str]]:
        return self._command

    @property
    def command_use(self) -> t.List[str]:
        return self._command['use']

    @property
    def command_def(self) -> t.List[str]:
        return self._command['def']

    @property
    def environ(self) -> t.Dict[str, t.List[str]]:
        return self._environ

    @property
    def environ_use(self) -> t.List[str]:
        return self._environ['use']

    @property
    def environ_def(self) -> t.List[str]:
        return self._environ['def']


if __name__ == '__main__':
    texlive = TeXDistribution('/usr/local/texlive/').update(overwrite=False)
    print(texlive.search('cjk'))
    print(texlive.information('cjk.sty'))
    print(texlive['lineno'])
    # ['CJKmove.sty', 'lwarp-CJK.sty', 'lwarp-CJKutf8.sty', 'bxcjkjatype.sty', 'bxjscjkcat.sty', 'pxcjkcat.sty', 'acjk.sty', 'CJKvert.sty', 'CJKnumb.sty', 'CJKfntef.sty', 'CJKulem.sty', 'CJKspace.sty', 'CJK.sty', 'CJKutf8.sty', 'xCJK2uni.sty', 'CJKpunct.sty', 'cjkutf8-nanummjhanja.sty', 'cjkutf8-josa.sty', 'cjkutf8-ko.sty', 'xeCJK.sty', 'xeCJKfntef.sty', 'xeCJK-listings.sty']
    # <Information @ "ctex.sty"
    #     path:        List[Path], len=1
    #     package:     List[str],  len=12
    #     command_use: List[str],  len=114
    #     command_def: List[str],  len=0
    #     environ_use: List[str],  len=114
    #     environ_def: List[str],  len=0
    # >
    # <Information @ "lineno.sty"
    #     path:        List[Path], len=1
    #     package:     List[str],  len=3
    #     command_use: List[str],  len=233
    #     command_def: List[str],  len=8
    #     environ_use: List[str],  len=233
    #     environ_def: List[str],  len=8
    # >