Debian Codegraph @

tools/dev/create_unimap.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 # $Id: create_unimap.py 10025 2025-03-08 01:03:56Z aa-turner $
4 # Author: Lea Wiemann <[email protected]>
5 # Copyright: This file has been placed in the public domain.
6
7 # Call: create_unimap.py < unicode.xml > unicode_latex.py
8 #
9 # Get unicode.xml from
10 # <https://www.w3.org/2003/entities/xml/unicode.xml>.
11
12 from __future__ import annotations
13
14 import pprint
15 import sys
16 from xml.dom import minidom
17
18 text_map: dict[str, str] = {}
19 math_map: dict[str, str] = {}
20
21
22 class Visitor:
23 """Node visitor for contents of unicode.xml."""
24
25 def visit_character(self, node: minidom.Element) -> None:
26 for n in node.childNodes:
27 if n.nodeName == 'latex':
28 code = node.attributes['dec'].value
29 if '-' in code:
30 # I don't know what this means, but we probably
31 # don't need it....
32 continue
33 if int(code) < 128:
34 # Wrong (maps "-" to "$-$", which is too wide) and
35 # unnecessary (maps "a" to "{a}").
36 continue
37 latex_code = n.childNodes[0].nodeValue.encode('ascii').strip()
38 if node.attributes['mode'].value == 'math':
39 math_map[chr(int(code))] = '$%s$' % latex_code
40 else:
41 text_map[chr(int(code))] = '{%s}' % latex_code
42
43
44 def call_visitor(
45 node: minidom.Document | minidom.Element | minidom.Text,
46 visitor: Visitor = Visitor(),
47 ) -> None:
48 if isinstance(node, minidom.Text):
49 name = 'Text'
50 else:
51 name = node.nodeName.replace('#', '_')
52 if hasattr(visitor, 'visit_' + name):
53 getattr(visitor, 'visit_' + name)(node)
54 for child in node.childNodes:
55 call_visitor(child)
56 if hasattr(visitor, 'depart_' + name):
57 getattr(visitor, 'depart_' + name)(node)
58
59
60 document = minidom.parse(sys.stdin)
61 call_visitor(document)
62
63 unicode_map: dict[str, str] = math_map
64 unicode_map.update(text_map)
65 # Now unicode_map contains the text entries plus dollar-enclosed math
66 # entries for those chars for which no text entry exists.
67
68 print('# $%s$' % 'Id')
69 print('# Author: Lea Wiemann <[email protected]>')
70 print('# Copyright: This file has been placed in the public domain.')
71 print()
72 print('# This is a mapping of Unicode characters to LaTeX equivalents.')
73 print('# The information has been extracted from')
74 print('# <https://www.w3.org/2003/entities/xml/unicode.xml>, written by')
75 print('# David Carlisle and Sebastian Rahtz.')
76 print('#')
77 print('# The extraction has been done by the "create_unimap.py" script')
78 print('# located at <https://docutils.sourceforge.io/tools/dev/create_unimap.py>.') # noqa: E501
79 print()
80 print('unicode_map = %s' % pprint.pformat(unicode_map, indent=0))