1 #!/usr/bin/env python 2 3 """ 4 Moin wiki format parser. 5 6 Copyright (C) 2017 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from moinformat.tree import Block, Break, DefItem, DefTerm, FontStyle, Heading, \ 23 Larger, ListItem, Monospace, Region, Rule, Smaller, \ 24 Subscript, Superscript, TableAttr, TableAttrs, \ 25 TableCell, TableRow, Text, Underline 26 import re 27 28 # Regular expressions. 29 30 syntax = { 31 # Page regions: 32 "regionstart" : r"((^\s*)([{]{3,}))", # {{{... 33 "regionend" : r"^\s*([}]{3,})", # }}}... 34 "header" : r"#!(.*?)\n", # #! char-excl-nl 35 36 # Region contents: 37 # Line-oriented patterns: 38 # blank line 39 "break" : r"^(\s*?)\n", 40 # ws... expecting text :: 41 "defterm" : r"^(\s+)(?=.+?::)", 42 # ws... expecting :: ws... 43 "defterm_empty" : r"^(\s+)(?=::\s+)", 44 # [ws...] =... ws... expecting headingend 45 "heading" : r"^(\s*)(?P<x>=+)(\s+)(?=.*?\s+(?P=x)\s*\n)", 46 # ws... list-item [ws...] 47 "listitem" : r"^(\s+)(\*)(\s*)", 48 # ws... number-item ws... 49 "listitem_num" : r"^(\s+)(\d+\.)(\s+)", 50 # ws... alpha-item ws... 51 "listitem_alpha": r"^(\s+)([aA]\.)(\s+)", 52 # ws... roman-item ws... 53 "listitem_roman": r"^(\s+)([iI]\.)(\s+)", 54 # ws... dot-item [ws...] 55 "listitem_dot" : r"^(\s+)(\.)(\s*)", 56 # || 57 "tablerow" : r"^\|\|", 58 59 # Region contents: 60 # Inline patterns: 61 "fontstyle" : r"('{2,6})", 62 "larger" : r"~\+", 63 "monospace" : r"`", 64 "rule" : r"(-----*)", # ----... 65 "smaller" : r"~-", 66 "sub" : r",,", 67 "super" : r"\^", 68 "underline" : r"__", 69 70 # Inline contents: 71 "largerend" : r"\+~", 72 "monospaceend" : r"`", 73 "smallerend" : r"-~", 74 "subend" : r",,", 75 "superend" : r"\^", 76 "underlineend" : r"__", 77 78 # Heading contents: 79 "headingend" : r"(\s+)(=+)(\s*\n)", # ws... =... [ws...] nl 80 81 # List contents: 82 "deftermend" : r"::(\s*?\n)", 83 "deftermsep" : r"::(\s+)", 84 "listitemend" : r"^", # next line 85 86 # Table contents: 87 "tableattrs" : r"<", 88 "tablecell" : r"\|\|", 89 "tableend" : r"(\s*?)^", # [ws...] next line 90 91 # Table attributes: 92 "tableattrsend" : r">", 93 "halign" : r"([(:)])", 94 "valign" : r"([v^])", 95 "colour" : r"(\#[0-9A-F]{6})", 96 "colspan" : r"\|(\d+)", 97 "rowspan" : r"-(\d+)", 98 "width" : r"(\d+%)", 99 "attrname" : r"((?![-\d])[-\w]+)", # not-dash-or-digit dash-or-word-char... 100 "attrvalue" : r"""=(?P<x>['"])(.*?)(?P=x)""", 101 } 102 103 # Define pattern details. 104 105 table_pattern_names = ["attrname", "colour", "colspan", "halign", "rowspan", "tableattrsend", "valign", "width"] 106 107 inline_pattern_names = ["fontstyle", "larger", "monospace", "smaller", "sub", "super", "underline"] 108 109 def inline_patterns_for(name): 110 names = inline_pattern_names[:] 111 names[names.index(name)] = "%send" % name 112 return names 113 114 # Define patterns for the regular expressions. 115 116 patterns = {} 117 for name, value in syntax.items(): 118 patterns[name] = re.compile(value, re.UNICODE | re.MULTILINE) 119 120 121 122 # Tokenising functions. 123 124 class TokenStream: 125 126 "A stream of tokens taken from a string." 127 128 def __init__(self, s): 129 self.s = s 130 self.pos = 0 131 self.match = None 132 self.matching = None 133 134 def rewind(self, length): 135 136 "Rewind in the string by 'length'." 137 138 self.pos -= min(length, self.pos) 139 140 def read_until(self, pattern_names, remaining=True): 141 142 """ 143 Find the first match for the given 'pattern_names'. Return the text 144 preceding any match, the remaining text if no match was found, or None 145 if no match was found and 'remaining' is given as a false value. 146 """ 147 148 first = None 149 self.matching = None 150 151 # Find the first matching pattern. 152 153 for pattern_name in pattern_names: 154 match = patterns[pattern_name].search(self.s, self.pos) 155 if match: 156 start, end = match.span() 157 if self.matching is None or start < first: 158 first = start 159 self.matching = pattern_name 160 self.match = match 161 162 if self.matching is None: 163 if remaining: 164 return self.s[self.pos:] 165 else: 166 return None 167 else: 168 return self.s[self.pos:first] 169 170 def read_match(self, group=1): 171 172 """ 173 Return the matched text, updating the position in the stream. If 'group' 174 is specified, the indicated group in a match will be returned. 175 Typically, group 1 should contain all pertinent data, but groups defined 176 within group 1 can provide sections of the data. 177 """ 178 179 if self.match: 180 _start, self.pos = self.match.span() 181 try: 182 return self.match.group(group) 183 except IndexError: 184 return "" 185 else: 186 self.pos = len(self.s) 187 return None 188 189 190 191 # Parser functions. 192 193 def parse_page(s): 194 195 """ 196 Parse page text 's'. Pages consist of regions delimited by markers. 197 """ 198 199 return parse_region(TokenStream(s)) 200 201 def parse_region(items, level=0, indent=0): 202 203 """ 204 Parse the data provided by 'items' to populate a region with the given 205 'level' at the given 'indent'. 206 """ 207 208 region = Region([], level, indent) 209 210 # Parse section headers. 211 212 parse_region_header(items, region) 213 214 # Parse section body. 215 216 if region.is_transparent(): 217 parse_region_wiki(items, region) 218 else: 219 parse_region_opaque(items, region) 220 221 return region 222 223 def parse_region_header(items, region): 224 225 """ 226 Parse the region header from the 'items', setting it for the given 'region'. 227 """ 228 229 if items.read_until(["header"], False) == "": # None means no header 230 region.type = items.read_match() 231 232 def parse_region_wiki(items, region): 233 234 "Parse the data provided by 'items' to populate a wiki 'region'." 235 236 new_block(region) 237 parse_region_details(items, region, inline_pattern_names + [ 238 "break", "heading", 239 "defterm", "defterm_empty", 240 "listitem", "listitem_alpha", "listitem_dot", "listitem_num", 241 "listitem_roman", 242 "regionstart", "regionend", 243 "rule", 244 "tablerow", 245 ]) 246 247 def parse_region_opaque(items, region): 248 249 "Parse the data provided by 'items' to populate an opaque 'region'." 250 251 parse_region_details(items, region, ["regionend"]) 252 253 def parse_region_details(items, region, pattern_names): 254 255 "Parse 'items' within 'region' searching using 'pattern_names'." 256 257 try: 258 while True: 259 260 # Obtain text before any marker or the end of the input. 261 262 preceding = items.read_until(pattern_names) 263 if preceding: 264 region.append_inline(Text(preceding)) 265 266 # End of input. 267 268 if not items.matching: 269 break 270 271 # Obtain any feature. 272 273 feature = items.read_match() 274 handler = handlers.get(items.matching) 275 276 # Handle each feature or add text to the region. 277 278 if handler: 279 handler(items, region) 280 else: 281 region.append_inline(Text(feature)) 282 283 except StopIteration: 284 pass 285 286 region.normalise() 287 288 def end_region(items, region): 289 290 "End the parsing of 'region'." 291 292 raise StopIteration 293 294 def parse_attrname(items, attrs): 295 296 "Handle an attribute name within 'attrs'." 297 298 name = items.read_match() 299 attr = TableAttr(name) 300 301 preceding = items.read_until(["attrvalue"], False) 302 if preceding == "": 303 attr.value = items.read_match(2) 304 305 attrs.append(attr) 306 307 def parse_break(items, region): 308 309 "Handle a paragraph break within 'region'." 310 311 region.add(Break()) 312 new_block(region) 313 314 def parse_defitem(items, region, extra=""): 315 316 "Handle a definition item within 'region'." 317 318 pad = items.read_match(1) 319 item = DefItem([], pad, extra) 320 parse_region_details(items, item, ["listitemend"]) 321 region.add(item) 322 new_block(region) 323 324 def parse_defterm(items, region): 325 326 "Handle a definition term within 'region'." 327 328 pad = items.read_match(1) 329 term = DefTerm([], pad) 330 parse_region_details(items, term, ["deftermend", "deftermsep"]) 331 region.add(term) 332 if items.matching == "deftermsep": 333 parse_defitem(items, region) 334 335 def parse_defterm_empty(items, region): 336 337 "Handle an empty definition term within 'region'." 338 339 extra = items.read_match(1) 340 parse_region_details(items, region, ["deftermsep"]) 341 parse_defitem(items, region, extra) 342 343 def parse_fontstyle(items, region): 344 345 "Handle emphasis and strong styles." 346 347 n = len(items.read_match(1)) 348 349 # Handle endings. 350 351 if isinstance(region, FontStyle): 352 emphasis = n in (2, 4, 5) 353 strong = n in (3, 5, 6) 354 active = True 355 356 if region.emphasis and emphasis: 357 active = region.close_emphasis() 358 n -= 2 359 if region.strong and strong: 360 active = region.close_strong() 361 n -= 3 362 363 if not active: 364 if n: 365 items.rewind(n) 366 raise StopIteration 367 368 elif not n: 369 return 370 371 # Handle new styles. 372 373 emphasis = n in (2, 4, 5) 374 strong = n in (3, 5, 6) 375 double = n in (4, 6) 376 377 span = FontStyle([], emphasis, strong) 378 if not double: 379 parse_region_details(items, span, inline_pattern_names) 380 region.append_inline(span) 381 382 def parse_halign(items, attrs): 383 384 "Handle horizontal alignment within 'attrs'." 385 386 value = items.read_match() 387 attr = TableAttr("halign", value == "(" and "left" or value == ")" and "right" or "center", True) 388 attrs.append(attr) 389 390 def parse_heading(items, region): 391 392 "Handle a heading." 393 394 start_extra = items.read_match(1) 395 level = len(items.read_match(2)) 396 start_pad = items.read_match(3) 397 heading = Heading([], level, start_extra, start_pad) 398 parse_region_details(items, heading, ["headingend"] + inline_pattern_names) 399 region.add(heading) 400 new_block(region) 401 402 def parse_heading_end(items, heading): 403 404 "Handle the end of a heading." 405 406 level = len(items.read_match(2)) 407 if heading.level == level: 408 heading.end_pad = items.read_match(1) 409 heading.end_extra = items.read_match(3) 410 raise StopIteration 411 412 def parse_listitem(items, region): 413 414 "Handle a list item marker within 'region'." 415 416 indent = len(items.read_match(1)) 417 marker = items.read_match(2) 418 space = items.read_match(3) 419 item = ListItem([], indent, marker, space) 420 parse_region_details(items, item, ["listitemend"]) 421 region.add(item) 422 new_block(region) 423 424 def parse_rule(items, region): 425 426 "Handle a horizontal rule within 'region'." 427 428 length = len(items.read_match(1)) 429 rule = Rule(length) 430 region.add(rule) 431 new_block(region) 432 433 def parse_section(items, region): 434 435 "Handle the start of a new section within 'region'." 436 437 # Parse the section and start a new block after the section. 438 439 indent = len(items.read_match(2)) 440 level = len(items.read_match(3)) 441 region.add(parse_region(items, level, indent)) 442 new_block(region) 443 444 def parse_section_end(items, region): 445 446 "Handle the end of a new section within 'region'." 447 448 feature = items.read_match() 449 if region.have_end(feature): 450 raise StopIteration 451 else: 452 region.append_inline(Text(feature)) 453 454 def parse_table_attrs(items, cell): 455 456 "Handle the start of table attributes within 'cell'." 457 458 attrs = TableAttrs([]) 459 parse_region_details(items, attrs, table_pattern_names) 460 cell.attrs = attrs 461 462 def parse_table_row(items, region): 463 464 "Handle the start of a table row within 'region'." 465 466 row = TableRow([]) 467 468 while True: 469 cell = TableCell([]) 470 parse_region_details(items, cell, ["tableattrs", "tablecell", "tableend"]) 471 472 # Handle the end of the row. 473 474 if items.matching == "tableend": 475 trailing = items.read_match() 476 477 # If the cell was started but not finished, convert the row into text. 478 479 if not row.nodes or not cell.empty(): 480 region.append_inline(Text("||")) 481 482 # Convert all cells. 483 484 for node in row.nodes: 485 region.append_inline_many(node.nodes) 486 region.append_inline(Text("||")) 487 488 region.append_inline_many(cell.nodes) 489 region.append_inline(Text(trailing)) 490 491 new_block(region) 492 return 493 494 # Append the final cell, if not empty. 495 496 else: 497 row.trailing = trailing 498 499 if not cell.empty(): 500 row.append(cell) 501 break 502 503 # A cell separator has been found. 504 505 row.append(cell) 506 507 region.add(row) 508 new_block(region) 509 510 def parse_valign(items, attrs): 511 512 "Handle vertical alignment within 'attrs'." 513 514 value = items.read_match() 515 attr = TableAttr("valign", value == "^" and "top" or "bottom", True) 516 attrs.append(attr) 517 518 # Inline formatting handlers. 519 520 def parse_inline(items, region, cls, pattern_name): 521 522 "Handle an inline region." 523 524 span = cls([]) 525 parse_region_details(items, span, inline_patterns_for(pattern_name)) 526 region.append_inline(span) 527 528 parse_larger = lambda items, region: parse_inline(items, region, Larger, "larger") 529 parse_monospace = lambda items, region: parse_inline(items, region, Monospace, "monospace") 530 parse_smaller = lambda items, region: parse_inline(items, region, Smaller, "smaller") 531 parse_sub = lambda items, region: parse_inline(items, region, Subscript, "sub") 532 parse_super = lambda items, region: parse_inline(items, region, Superscript, "super") 533 parse_underline = lambda items, region: parse_inline(items, region, Underline, "underline") 534 535 # Table attribute handlers. 536 537 def parse_table_attr(items, attrs, pattern_name): 538 539 "Handle a table attribute." 540 541 value = items.read_match() 542 attrs.append(TableAttr(pattern_name, value, True)) 543 544 parse_colour = lambda items, cell: parse_table_attr(items, cell, "colour") 545 parse_colspan = lambda items, cell: parse_table_attr(items, cell, "colspan") 546 parse_rowspan = lambda items, cell: parse_table_attr(items, cell, "rowspan") 547 parse_width = lambda items, cell: parse_table_attr(items, cell, "width") 548 549 # Pattern handlers. 550 551 handlers = { 552 None : end_region, 553 "attrname" : parse_attrname, 554 "break" : parse_break, 555 "colour" : parse_colour, 556 "colspan" : parse_colspan, 557 "defterm" : parse_defterm, 558 "defterm_empty" : parse_defterm_empty, 559 "deftermend" : end_region, 560 "deftermsep" : end_region, 561 "fontstyle" : parse_fontstyle, 562 "halign" : parse_halign, 563 "heading" : parse_heading, 564 "headingend" : parse_heading_end, 565 "larger" : parse_larger, 566 "largerend" : end_region, 567 "listitemend" : end_region, 568 "listitem" : parse_listitem, 569 "listitem_alpha" : parse_listitem, 570 "listitem_dot" : parse_listitem, 571 "listitem_num" : parse_listitem, 572 "listitem_roman" : parse_listitem, 573 "monospace" : parse_monospace, 574 "monospaceend" : end_region, 575 "regionstart" : parse_section, 576 "regionend" : parse_section_end, 577 "rowspan" : parse_rowspan, 578 "rule" : parse_rule, 579 "smaller" : parse_smaller, 580 "smallerend" : end_region, 581 "sub" : parse_sub, 582 "subend" : end_region, 583 "super" : parse_super, 584 "superend" : end_region, 585 "tableattrs" : parse_table_attrs, 586 "tableattrsend" : end_region, 587 "tablerow" : parse_table_row, 588 "tablecell" : end_region, 589 "tableend" : end_region, 590 "underline" : parse_underline, 591 "underlineend" : end_region, 592 "valign" : parse_valign, 593 "width" : parse_width, 594 } 595 596 def new_block(region): 597 598 "Start a new block in 'region'." 599 600 block = Block([]) 601 region.add(block) 602 603 604 605 # Top-level functions. 606 607 parse = parse_page 608 609 # vim: tabstop=4 expandtab shiftwidth=4