Debian Codegraph @

citeproc/source/bibtex/latex/__init__.py

raw
1
2 import unicodedata
3
4 from collections import namedtuple
5 from warnings import warn
6
7
8 __all__ = ['parse_latex', 'substitute_ligatures']
9
10
11 def parse_latex(string, macros={}):
12 tokens = Tokenizer(string)
13 output = ''
14 for result in dispatch(tokens, macros):
15 output += result
16 return substitute_ligatures(output)
17
18
19 Token = namedtuple('Token', ['type', 'value'])
20
21
22 TOGGLE_MATH = 'TOGGLE-MATH'
23 WHITESPACE = 'WHITESPACE'
24 CLOSE_SCOPE = 'CLOSE-SCOPE'
25 OPEN_SCOPE = 'OPEN-SCOPE'
26 START_MACRO = 'START-MACRO'
27 CHARACTER = 'CHARACTER'
28
29
30 class Tokenizer(object):
31 def __init__(self, string):
32 self.string = string
33 self._tokens = self.tokenize(string)
34 self._next_token = None
35
36 @staticmethod
37 def tokenize(input_string):
38 for char in input_string:
39 if char == '\\':
40 yield Token(START_MACRO, char)
41 elif char == '{':
42 yield Token(OPEN_SCOPE, char)
43 elif char == '}':
44 yield Token(CLOSE_SCOPE, char)
45 elif char in ' \t\n':
46 yield Token(WHITESPACE, char)
47 elif char == '$':
48 yield Token(TOGGLE_MATH, char)
49 else:
50 yield Token(CHARACTER, char)
51
52 def __iter__(self):
53 return self
54
55 def __next__(self):
56 if self._next_token:
57 token = self._next_token
58 self._next_token = None
59 else:
60 token = next(self._tokens)
61 return token
62
63 next = __next__
64
65 def peek(self):
66 if self._next_token is None:
67 self._next_token = next(self._tokens)
68 return self._next_token
69
70
71 def eat_whitespace(tokens):
72 while tokens.peek().type == WHITESPACE:
73 next(tokens)
74
75
76 class ScopeClosing(Exception):
77 pass
78
79
80 def dispatch(tokens, macros, level=0):
81 while True:
82 try:
83 next_token = tokens.peek()
84 except StopIteration:
85 if level > 0:
86 warn("Unbalanced parenthesis in '{}'".format(tokens.string))
87 break
88 if next_token.type == OPEN_SCOPE:
89 yield handle_scope(tokens, macros, level)
90 elif next_token.type == CLOSE_SCOPE:
91 raise ScopeClosing
92 elif next_token.type == START_MACRO:
93 yield handle_macro(tokens, macros)
94 elif next_token.type == TOGGLE_MATH:
95 yield handle_math(tokens)
96 else:
97 assert next_token.type in (CHARACTER, WHITESPACE)
98 yield next(tokens).value
99
100
101 def handle_scope(tokens, macros, level):
102 assert next(tokens).type == OPEN_SCOPE
103 output = ''
104 try:
105 for result in dispatch(tokens, macros, level + 1):
106 output += result
107 except ScopeClosing:
108 assert next(tokens).type == CLOSE_SCOPE
109 return output
110
111
112 def parse_argument(tokens, macros, level=0):
113 eat_whitespace(tokens)
114 return next(dispatch(tokens, macros, level))
115
116
117 def handle_macro(tokens, macros):
118 assert next(tokens).type == START_MACRO
119 name = parse_macro_name(tokens)
120 try:
121 macro = MACROS[name]
122 except KeyError:
123 macro = macros[name]
124 return macro.parse_arguments_and_expand(tokens, macros)
125
126
127 def parse_macro_name(tokens):
128 token = next(tokens)
129 assert token.type in (CHARACTER, TOGGLE_MATH, WHITESPACE)
130 name = token.value
131 if name.isalpha():
132 while tokens.peek().type == CHARACTER and tokens.peek().value.isalpha():
133 name += next(tokens).value
134 eat_whitespace(tokens)
135 return name
136
137
138 def handle_math(tokens):
139 assert next(tokens).type == TOGGLE_MATH
140 output = ''
141 for token in tokens:
142 if token.type == START_MACRO:
143 output += token.value
144 token = next(tokens)
145 elif token.type == TOGGLE_MATH:
146 break
147 output += token.value
148 return '$' + output + '$'
149
150
151 def substitute_ligatures(string):
152 for chars, ligature in SUBSTITUTIONS.items():
153 string = string.replace(chars, unicodedata.lookup(ligature))
154 return string
155
156
157 SUBSTITUTIONS = {"~": 'NO-BREAK SPACE',
158
159 # ligatures defined in Computer Modern (symbol shortcuts)
160 "--": 'EN DASH',
161 "---": 'EM DASH',
162 "''": 'RIGHT DOUBLE QUOTATION MARK',
163 "``": 'LEFT DOUBLE QUOTATION MARK',
164 "!`": 'INVERTED EXCLAMATION MARK',
165 "?`": 'INVERTED QUESTION MARK',
166 ",,": 'DOUBLE LOW-9 QUOTATION MARK',
167 "<<": 'LEFT-POINTING DOUBLE ANGLE QUOTATION MARK',
168 ">>": 'RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK',
169 }
170
171
172 from .macro import MACROS