|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# Copyright © 2014-2017 Felix Fontein |
| 4 | +# |
| 5 | +# Permission is hereby granted, free of charge, to any |
| 6 | +# person obtaining a copy of this software and associated |
| 7 | +# documentation files (the "Software"), to deal in the |
| 8 | +# Software without restriction, including without limitation |
| 9 | +# the rights to use, copy, modify, merge, publish, |
| 10 | +# distribute, sublicense, and/or sell copies of the |
| 11 | +# Software, and to permit persons to whom the Software is |
| 12 | +# furnished to do so, subject to the following conditions: |
| 13 | +# |
| 14 | +# The above copyright notice and this permission notice |
| 15 | +# shall be included in all copies or substantial portions of |
| 16 | +# the Software. |
| 17 | +# |
| 18 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY |
| 19 | +# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE |
| 20 | +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR |
| 21 | +# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS |
| 22 | +# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR |
| 23 | +# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR |
| 24 | +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
| 25 | +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 26 | + |
| 27 | +"""A basic LaTeX tokenizer.""" |
| 28 | + |
| 29 | +from __future__ import unicode_literals |
| 30 | + |
| 31 | +import nikola.utils |
| 32 | + |
| 33 | +from enum import Enum |
| 34 | + |
| 35 | +LOGGER = nikola.utils.get_logger('compile_latex.tokenizer', nikola.utils.STDERR_HANDLER) |
| 36 | + |
| 37 | + |
| 38 | +class Token(Enum): |
| 39 | + """Represents a single token.""" |
| 40 | + |
| 41 | + Whitespace = 1 |
| 42 | + NonbreakableWhitespace = 2 |
| 43 | + Text = 3 |
| 44 | + EscapedText = 4 |
| 45 | + Command = 5 # '\' followed by text |
| 46 | + InlineFormulaDelimiter = 6 # just '$' (the alternative, '\(', is a Command) |
| 47 | + DisplayFormulaDelimiter = 7 # just '$$' (the alternative, '\[', is a Command) |
| 48 | + CurlyBraketOpen = 8 # '{' |
| 49 | + CurlyBraketClose = 9 # '}' |
| 50 | + SquareBraketOpen = 10 # '[' |
| 51 | + SquareBraketClose = 11 # ']' |
| 52 | + DoubleNewLine = 12 |
| 53 | + Comment = 13 # '%' |
| 54 | + ForcedLineBreak = 14 # '\\' |
| 55 | + TableColumnDelimiter = 15 # '&' |
| 56 | + |
| 57 | + |
| 58 | +def _compute_position(input, index): |
| 59 | + """Compute line/column position given an index in a string.""" |
| 60 | + line = 1 |
| 61 | + col = 1 |
| 62 | + eol = None # last end of line character |
| 63 | + for c in input[:index]: |
| 64 | + if c == '\n' or c == '\r': |
| 65 | + if eol is None or eol == c: |
| 66 | + eol = c |
| 67 | + line += 1 |
| 68 | + col = 1 |
| 69 | + else: |
| 70 | + # ignore second of '\n\r' and '\r\n' sequences |
| 71 | + eol = None |
| 72 | + else: |
| 73 | + col += 1 |
| 74 | + return (line, col) |
| 75 | + |
| 76 | + |
| 77 | +class Tokenizer: |
| 78 | + """A simple tokenizer.""" |
| 79 | + |
| 80 | + def _is_whitespace(self, char): |
| 81 | + """Check for whitespace.""" |
| 82 | + return ord(char) <= 32 |
| 83 | + |
| 84 | + def _is_line_break(self, char): |
| 85 | + """Check for line breaks.""" |
| 86 | + return ord(char) == 10 or ord(char) == 13 |
| 87 | + |
| 88 | + def _is_command_char(self, char): |
| 89 | + """Check for a command character.""" |
| 90 | + return (char >= 'A' and char <= 'Z') or (char >= 'a' and char <= 'z') or (char == '@') |
| 91 | + |
| 92 | + def _eat_whitespace(self): |
| 93 | + """Skip whitespace and return number of contained line breaks.""" |
| 94 | + number_of_line_breaks = 0 |
| 95 | + last_line_break = None |
| 96 | + while self._position < len(self._input): |
| 97 | + if not self._is_whitespace(self._input[self._position]): |
| 98 | + break |
| 99 | + if self._is_line_break(self._input[self._position]): |
| 100 | + if last_line_break is None or last_line_break == self._input[self._position]: |
| 101 | + number_of_line_breaks += 1 |
| 102 | + last_line_break = self._input[self._position] |
| 103 | + else: |
| 104 | + last_line_break = None |
| 105 | + self._position += 1 |
| 106 | + return number_of_line_breaks |
| 107 | + |
| 108 | + def _eat_comment(self): |
| 109 | + """Skip comment's content.""" |
| 110 | + start = self._position |
| 111 | + last_line_break = None |
| 112 | + had_line_break = False |
| 113 | + while self._position < len(self._input): |
| 114 | + if had_line_break and not self._is_whitespace(self._input[self._position]): |
| 115 | + break |
| 116 | + if self._is_line_break(self._input[self._position]): |
| 117 | + if last_line_break is None or last_line_break == self._input[self._position]: |
| 118 | + if had_line_break: |
| 119 | + break |
| 120 | + last_line_break = self._input[self._position] |
| 121 | + had_line_break = True |
| 122 | + else: |
| 123 | + last_line_break = None |
| 124 | + self._position += 1 |
| 125 | + return self._input[start:self._position] |
| 126 | + |
| 127 | + def _read_text(self, strict): |
| 128 | + """Read text.""" |
| 129 | + start = self._position |
| 130 | + while self._position < len(self._input): |
| 131 | + char = self._input[self._position] |
| 132 | + if self._is_whitespace(char): |
| 133 | + break |
| 134 | + if char == "~" or char == "{" or char == "}" or char == "$" or char == "[" or char == "]" or char == "$" or char == "\\" or char == "&": |
| 135 | + break |
| 136 | + if strict and not self._is_command_char(char): |
| 137 | + break |
| 138 | + self._position += 1 |
| 139 | + return self._input[start:self._position] |
| 140 | + |
| 141 | + def _find_next(self): |
| 142 | + """Find next token.""" |
| 143 | + self._token = None |
| 144 | + self._token_value = None |
| 145 | + self._token_begin_index = None |
| 146 | + self._token_end_index = None |
| 147 | + if (self._position >= len(self._input)): |
| 148 | + return |
| 149 | + self._token_begin_index = self._position |
| 150 | + char = self._input[self._position] |
| 151 | + if self._is_whitespace(char): |
| 152 | + number_of_line_breaks = self._eat_whitespace() |
| 153 | + if number_of_line_breaks > 1: |
| 154 | + self._token = Token.DoubleNewLine |
| 155 | + else: |
| 156 | + self._token = Token.Whitespace |
| 157 | + elif char == "~": |
| 158 | + self._token = Token.NonbreakableWhitespace |
| 159 | + self._position += 1 |
| 160 | + elif char == '&': |
| 161 | + self._token = Token.TableColumnDelimiter |
| 162 | + self._position += 1 |
| 163 | + elif char == "{": |
| 164 | + self._token = Token.CurlyBraketOpen |
| 165 | + self._position += 1 |
| 166 | + elif char == "}": |
| 167 | + self._token = Token.CurlyBraketClose |
| 168 | + self._position += 1 |
| 169 | + elif char == "[": |
| 170 | + self._token = Token.SquareBraketOpen |
| 171 | + self._position += 1 |
| 172 | + elif char == "]": |
| 173 | + self._token = Token.SquareBraketClose |
| 174 | + self._position += 1 |
| 175 | + elif char == "$": |
| 176 | + self._token = Token.InlineFormulaDelimiter |
| 177 | + self._position += 1 |
| 178 | + if self._position < len(self._input) and self._input[self._position] == "$": |
| 179 | + self._token = Token.DisplayFormulaDelimiter |
| 180 | + self._position += 1 |
| 181 | + elif char == "\\": |
| 182 | + self._position += 1 |
| 183 | + if self._position == len(self._input): |
| 184 | + raise "Reached end of text after '\\'" |
| 185 | + self._token = Token.Command |
| 186 | + cmd = self._read_text(True) |
| 187 | + if len(cmd) == 0: |
| 188 | + ch = self._input[self._position] |
| 189 | + if ch == '(' or ch == ')' or ch == '[' or ch == ']': |
| 190 | + self._token_value = ch |
| 191 | + elif ch == '\\': |
| 192 | + self._token = Token.ForcedLineBreak |
| 193 | + else: |
| 194 | + self._token = Token.EscapedText |
| 195 | + self._token_value = ch |
| 196 | + self._position += 1 |
| 197 | + else: |
| 198 | + self._token_value = cmd |
| 199 | + elif char == '%': |
| 200 | + self._token = Token.Comment |
| 201 | + self._position += 1 |
| 202 | + self._token_value = self._eat_comment() |
| 203 | + else: |
| 204 | + self._token = Token.Text |
| 205 | + self._token_value = self._read_text(False) |
| 206 | + self._token_end_index = self._position |
| 207 | + |
| 208 | + def __init__(self, input): |
| 209 | + """Initialize tokenizer with input unicode string ``input``.""" |
| 210 | + self._input = input |
| 211 | + self._position = 0 |
| 212 | + self._find_next() |
| 213 | + |
| 214 | + def has_token(self): |
| 215 | + """Whether a token is available.""" |
| 216 | + return self._token is not None |
| 217 | + |
| 218 | + def token_type(self): |
| 219 | + """Return type of current token.""" |
| 220 | + return self._token |
| 221 | + |
| 222 | + def token_value(self): |
| 223 | + """Return value of current token.""" |
| 224 | + # only if token_type() returns Token.Text or Token.Command |
| 225 | + return self._token_value |
| 226 | + |
| 227 | + def token_begin_index(self): |
| 228 | + """Return beginning of token in input string.""" |
| 229 | + return self._token_begin_index |
| 230 | + |
| 231 | + def token_end_index(self): |
| 232 | + """Return end of token in input string.""" |
| 233 | + return self._token_end_index |
| 234 | + |
| 235 | + def next(self): |
| 236 | + """Proceed to next token.""" |
| 237 | + if self._token is not None: |
| 238 | + self._find_next() |
| 239 | + |
| 240 | + def get_substring(self, start_index, end_index): |
| 241 | + """Return substring of input string.""" |
| 242 | + return self._input[start_index:end_index] |
| 243 | + |
| 244 | + def get_position(self, index): |
| 245 | + """Retrieve position as (line, column) pair in input string.""" |
| 246 | + return _compute_position(self._input, index) |
| 247 | + |
| 248 | + |
| 249 | +class TokenStream: |
| 250 | + """Represent the output of a Tokenizer as a stream of tokens, allowing to peek ahead.""" |
| 251 | + |
| 252 | + def _fill_ahead(self, count): |
| 253 | + """Fill ahead buffer.""" |
| 254 | + if len(self.__ahead) < count: |
| 255 | + for i in range(len(self.__ahead), count): |
| 256 | + if self.__tokenizer.has_token(): |
| 257 | + self.__ahead.append((self.__tokenizer.token_type(), self.__tokenizer.token_value())) |
| 258 | + self.__ahead_indices.append((self.__tokenizer.token_begin_index(), self.__tokenizer.token_end_index())) |
| 259 | + self.__tokenizer.next() |
| 260 | + else: |
| 261 | + self.__ahead.append((None, None)) |
| 262 | + self.__ahead_indices.append((None, None)) |
| 263 | + |
| 264 | + def __init__(self, input): |
| 265 | + """Create TokenStream from input unicode string. Creates Tokenizer.""" |
| 266 | + self.__tokenizer = Tokenizer(input) |
| 267 | + self.__ahead = list() |
| 268 | + self.__ahead_indices = list() |
| 269 | + |
| 270 | + def current(self): |
| 271 | + """Get current token. Return pair (type, value).""" |
| 272 | + self._fill_ahead(1) |
| 273 | + return self.__ahead[0] |
| 274 | + |
| 275 | + def current_indices(self): |
| 276 | + """Get current token indices in input string.""" |
| 277 | + self._fill_ahead(1) |
| 278 | + return self.__ahead_indices[0] |
| 279 | + |
| 280 | + def current_type(self): |
| 281 | + """Get current token type.""" |
| 282 | + self._fill_ahead(1) |
| 283 | + return self.__ahead[0][0] |
| 284 | + |
| 285 | + def current_value(self): |
| 286 | + """Get current token value.""" |
| 287 | + self._fill_ahead(1) |
| 288 | + return self.__ahead[0][1] |
| 289 | + |
| 290 | + def has_current(self): |
| 291 | + """Return True if current token is available.""" |
| 292 | + self._fill_ahead(1) |
| 293 | + return self.__ahead[0][0] is not None |
| 294 | + |
| 295 | + def skip_current(self, count=1): |
| 296 | + """Skip number of tokens.""" |
| 297 | + assert count >= 0 |
| 298 | + self._fill_ahead(count) |
| 299 | + self.__ahead = self.__ahead[count:] |
| 300 | + self.__ahead_indices = self.__ahead_indices[count:] |
| 301 | + |
| 302 | + def peek(self, index): |
| 303 | + """Peek ahead in token stream. Return pair (type, value).""" |
| 304 | + assert index >= 0 |
| 305 | + self._fill_ahead(index + 1) |
| 306 | + return self.__ahead[index] |
| 307 | + |
| 308 | + def peek_indices(self, index): |
| 309 | + """Peek ahead in token stream. Return indices of token in input string.""" |
| 310 | + assert index >= 0 |
| 311 | + self._fill_ahead(index + 1) |
| 312 | + return self.__ahead_indices[index] |
| 313 | + |
| 314 | + def peek_type(self, index): |
| 315 | + """Peek ahead in token stream. Return token's type.""" |
| 316 | + assert index >= 0 |
| 317 | + self._fill_ahead(index + 1) |
| 318 | + return self.__ahead[index][0] |
| 319 | + |
| 320 | + def peek_value(self, index): |
| 321 | + """Peek ahead in token stream. Return token's value.""" |
| 322 | + assert index >= 0 |
| 323 | + self._fill_ahead(index + 1) |
| 324 | + return self.__ahead[index][1] |
| 325 | + |
| 326 | + def can_peek(self, index): |
| 327 | + """Check whether token at current index + ``index`` can be peeked at, i.e. whether it exists.""" |
| 328 | + assert index >= 0 |
| 329 | + self._fill_ahead(index + 1) |
| 330 | + return self.__ahead[index][0] is not None |
| 331 | + |
| 332 | + def get_substring(self, start_index, end_index): |
| 333 | + """Return substring of input string.""" |
| 334 | + return self.__tokenizer.get_substring(start_index, end_index) |
| 335 | + |
| 336 | + def get_position(self, index): |
| 337 | + """Retrieve position as (line, column) pair in input string.""" |
| 338 | + return self.__tokenizer.get_position(index) |
| 339 | + |
| 340 | + def set_value(self, index, new_value): |
| 341 | + """Set value of token at current index + ``index`` to ``new_value``. |
| 342 | +
|
| 343 | + Use with care! |
| 344 | + """ |
| 345 | + assert index >= 0 |
| 346 | + self._fill_ahead(index + 1) |
| 347 | + self.__ahead[index] = (self.__ahead[index][0], new_value) |
| 348 | + |
| 349 | + |
| 350 | +def recombine_tokens(tokens): |
| 351 | + """Recombine list of tokens as string.""" |
| 352 | + result = "" |
| 353 | + for type, value in tokens: |
| 354 | + if type == Token.Whitespace: |
| 355 | + result += " " |
| 356 | + if type == Token.NonbreakableWhitespace: |
| 357 | + result += "~" |
| 358 | + elif type == Token.Text: |
| 359 | + result += value |
| 360 | + elif type == Token.EscapedText: |
| 361 | + result += "\\{}".format(value) |
| 362 | + elif type == Token.Command: |
| 363 | + result += "\\{}".format(value) |
| 364 | + elif type == Token.InlineFormulaDelimiter: |
| 365 | + result += "$" |
| 366 | + elif type == Token.DisplayFormulaDelimiter: |
| 367 | + result += "$$" |
| 368 | + elif type == Token.CurlyBraketOpen: |
| 369 | + result += "{" |
| 370 | + elif type == Token.CurlyBraketClose: |
| 371 | + result += "}" |
| 372 | + elif type == Token.SquareBraketOpen: |
| 373 | + result += "[" |
| 374 | + elif type == Token.SquareBraketClose: |
| 375 | + result += "]" |
| 376 | + elif type == Token.DoubleNewLine: |
| 377 | + result += "\n\n" |
| 378 | + return result |
0 commit comments