1 #!/usr/bin/env python 2 3 """ 4 Moin wiki format parser. 5 6 Copyright (C) 2017, 2018 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 # Document transformations. 23 24 from moinformat.links import get_linker 25 from moinformat.macros import get_macro 26 27 # Parser functionality and pattern definition. 28 29 from moinformat.parsers.common import ParserBase, get_patterns, \ 30 excl, expect, group, optional, recur, \ 31 repeat 32 33 # Serialisation. 34 35 from moinformat.serialisers import serialise 36 37 # Document tree nodes. 38 39 from moinformat.tree.moin import Break, DefItem, DefTerm, FontStyle, Heading, \ 40 Larger, Link, List, ListItem, Macro, \ 41 Monospace, Region, Rule, Smaller, \ 42 Strikethrough, Subscript, Superscript, Table, \ 43 TableAttr, TableAttrs, TableCell, TableRow, \ 44 Text, Underline 45 46 join = "".join 47 48 class MoinParser(ParserBase): 49 50 "A wiki region parser." 51 52 def __init__(self, formats=None, root=None): 53 54 """ 55 Initialise the parser with any given 'formats' mapping from region type 56 names to parser objects. An optional 'root' indicates the document-level 57 parser. 58 """ 59 60 # Introduce this class as the default parser for the wiki format. 61 62 default_formats = {"wiki" : MoinParser, "moin" : MoinParser} 63 if formats: 64 default_formats.update(formats) 65 66 ParserBase.__init__(self, default_formats, root) 67 68 # Record certain node occurrences for later evaluation. 69 70 self.macros = [] 71 self.links = [] 72 73 # Principal parser methods. 74 75 def parse(self, s): 76 77 """ 78 Parse page text 's'. Pages consist of regions delimited by markers. 79 """ 80 81 self.items = self.get_items(s) 82 self.region = Region([], type="moin") 83 84 # Parse page header. 85 86 self.parse_region_header(self.region) 87 88 # Handle pages directly with this parser. Pages do not need to use an 89 # explicit format indicator. 90 91 if not self.region.type: 92 self.parse_region_content(self.items, self.region) 93 94 # Otherwise, test the type and find an appropriate parser. 95 96 else: 97 self.parse_region_type(self.region) 98 99 return self.region 100 101 102 103 # Macro evaluation. 104 105 def evaluate_macros(self): 106 107 "Evaluate the macro nodes in the document." 108 109 for node in self.macros: 110 111 # Obtain a class for the named macro. 112 113 macro_cls = get_macro(node.name) 114 if not macro_cls: 115 continue 116 117 # Instantiate the class and evaluate the macro. 118 119 macro = macro_cls(node, self.region) 120 macro.evaluate() 121 122 # Link translation. 123 124 def translate_links(self, scheme, name, base=""): 125 126 """ 127 Translate the link nodes in the document for the given 'scheme' and 128 employing the given document 'name' and 'base'. 129 """ 130 131 # Obtain a class for the named linker. 132 133 linker_cls = get_linker(scheme) 134 if not linker_cls: 135 return 136 137 # Instantiate the class with document metadata. 138 139 linker = linker_cls(name, base) 140 141 for node in self.links: 142 143 # Translate the link. 144 145 linker.translate(node) 146 147 148 # Parser methods supporting different page features. 149 150 def parse_attrname(self, attrs): 151 152 "Handle an attribute name within 'attrs'." 153 154 name = self.match_group("name") 155 attr = TableAttr(name) 156 157 preceding = self.read_until(["attrvalue"], False) 158 if preceding == "": 159 attr.quote = self.match_group("quote") 160 attr.value = self.match_group("value") 161 162 attrs.append(attr) 163 164 def parse_break(self, region): 165 166 "Handle a paragraph break within 'region'." 167 168 self.add_node(region, Break()) 169 self.new_block(region) 170 171 def parse_defitem(self, region, extra=""): 172 173 "Handle a definition item within 'region'." 174 175 pad = self.match_group("pad") 176 item = DefItem([], pad, extra) 177 self.parse_region_details(item, ["listitemend"]) 178 self.add_node(region, item) 179 self.new_block(region) 180 181 def parse_defterm(self, region): 182 183 "Handle a definition term within 'region'." 184 185 pad = self.match_group("pad") 186 term = DefTerm([], pad) 187 self.parse_region_details(term, ["deftermend", "deftermsep"]) 188 self.add_node(region, term) 189 if self.matching_pattern() == "deftermsep": 190 self.parse_defitem(region) 191 192 def parse_defterm_empty(self, region): 193 194 "Handle an empty definition term within 'region'." 195 196 extra = self.match_group("pad") 197 self.parse_region_details(region, ["deftermsep"]) 198 self.parse_defitem(region, extra) 199 200 def parse_fontstyle(self, region): 201 202 "Handle emphasis and strong styles." 203 204 n = len(self.match_group("style")) 205 206 # Handle endings. 207 208 if isinstance(region, FontStyle): 209 emphasis = n in (2, 4, 5) 210 strong = n in (3, 5, 6) 211 active = True 212 213 if region.emphasis and emphasis: 214 active = region.close_emphasis() 215 n -= 2 216 if region.strong and strong: 217 active = region.close_strong() 218 n -= 3 219 220 if not active: 221 if n: 222 self.items.rewind(n) 223 raise StopIteration 224 225 elif not n: 226 return 227 228 # Handle new styles. 229 230 emphasis = n in (2, 4, 5) 231 strong = n in (3, 5, 6) 232 double = n in (4, 6) 233 234 span = FontStyle([], emphasis, strong) 235 if not double: 236 self.parse_region_details(span, self.inline_pattern_names) 237 region.append_inline(span) 238 239 def parse_halign(self, attrs): 240 241 "Handle horizontal alignment within 'attrs'." 242 243 value = self.match_group("value") 244 attr = TableAttr("halign", value == "(" and "left" or value == ")" and "right" or "center", True) 245 attrs.append(attr) 246 247 def parse_heading(self, region): 248 249 "Handle a heading." 250 251 start_extra = self.match_group("extra") 252 level = len(self.match_group("level")) 253 start_pad = self.match_group("pad") 254 heading = Heading([], level, start_extra, start_pad) 255 self.parse_region_details(heading, ["headingend"] + self.inline_pattern_names) 256 self.add_node(region, heading) 257 self.new_block(region) 258 259 def parse_heading_end(self, heading): 260 261 "Handle the end of a heading." 262 263 level = len(self.match_group("level")) 264 if heading.level == level: 265 heading.end_pad = self.match_group("pad") 266 heading.end_extra = self.match_group("extra") 267 raise StopIteration 268 269 def parse_list(self, item): 270 271 "Create a list, starting with 'item'." 272 273 list = List([item], item.indent, item.marker, item.num) 274 self.parse_region_details(list, self.list_pattern_names, True) 275 return list 276 277 def parse_listitem(self, region): 278 279 "Handle a list item marker within 'region'." 280 281 indent = len(self.match_group("indent")) 282 marker = self.match_group("marker") 283 num = self.match_group("num") 284 space = self.match_group("pad") 285 286 last = region.node(-1) 287 288 new_list = not isinstance(last, (List, ListItem)) 289 same_indent = not new_list and indent == last.indent 290 new_marker = not new_list and last.marker != marker and same_indent 291 new_num = not new_list and num is not None and last.num != num and same_indent 292 293 # If the marker or number changes at the same indent, or if the indent 294 # is smaller, queue the item and end the list. 295 296 # Note that Moin format does not seek to support item renumbering, 297 # instead starting new lists on number changes. 298 299 if not new_list and (new_marker or new_num or indent < last.indent): 300 self.queue_match() 301 self.end_region(region) 302 303 # Obtain a list item and populate it. 304 305 item = ListItem([], indent, marker, space, num) 306 self.parse_region_details(item, self.listitem_pattern_names) 307 308 # Start a new list if not preceded by a list item, adding a trailing 309 # block for new elements. 310 311 if new_list: 312 item = self.parse_list(item) 313 self.add_node(region, item) 314 self.new_block(region) 315 316 # Add a nested list to the last item. 317 318 elif indent > last.indent: 319 item = self.parse_list(item) 320 self.add_node(last, item) 321 322 # Add the item to the current list. 323 324 else: 325 self.add_node(region, item) 326 327 def parse_rule(self, region): 328 329 "Handle a horizontal rule within 'region'." 330 331 length = len(self.match_group("rule")) 332 rule = Rule(length) 333 self.add_node(region, rule) 334 self.new_block(region) 335 336 def parse_section(self, region): 337 338 "Handle the start of a new section within 'region'." 339 340 # Parse the section and start a new block after the section. 341 342 indent = len(self.match_group("indent")) 343 level = len(self.match_group("level")) 344 345 section = self.parse_region(level, indent, "inline") 346 347 # If the section is inline, treat it like any other inline element. 348 349 if section.type == "inline": 350 region.append_inline(section) 351 352 # Otherwise, add it as a new block element. 353 354 else: 355 self.add_node(region, section) 356 if region.allow_blocks: 357 self.new_block(region) 358 359 def parse_section_end(self, region): 360 361 "Handle the end of a new section within 'region'." 362 363 level = self.match_group("level") 364 feature = self.match_group("feature") 365 region.extra = self.match_group("extra") 366 367 if region.have_end(level): 368 raise StopIteration 369 else: 370 region.append_inline(Text(feature)) 371 372 def parse_table_attrs(self, cell): 373 374 "Handle the start of table attributes within 'cell'." 375 376 attrs = TableAttrs([]) 377 self.parse_region_details(attrs, self.table_pattern_names) 378 379 # Test the validity of the attributes. 380 381 last = None 382 383 for node in attrs.nodes: 384 385 # Text separator nodes must be whitespace. 386 387 if isinstance(node, Text): 388 if node.s.strip(): 389 break 390 391 # Named attributes must be preceded by space if not the first. 392 393 elif last and not node.concise and not isinstance(last, Text): 394 break 395 396 last = node 397 398 # All nodes were valid: preserve the collection. 399 400 else: 401 # Add the attributes as a node, also recording their presence. 402 403 cell.append(attrs) 404 cell.attrs = attrs 405 return 406 407 # Invalid nodes were found: serialise the attributes as text. 408 409 cell.append_inline(Text(serialise(attrs))) 410 411 def parse_table_row(self, region): 412 413 "Handle the start of a table row within 'region'." 414 415 # Identify any active table. 416 417 table = region.node(-2) 418 block = region.node(-1) 419 420 if not (isinstance(table, Table) and block.empty()): 421 new_table = table = Table([]) 422 else: 423 new_table = None 424 425 row = TableRow([]) 426 427 while True: 428 cell = TableCell([]) 429 self.parse_region_details(cell, self.table_region_pattern_names) 430 431 # Handle the end of the row. 432 433 if self.matching_pattern() == "tableend": 434 trailing = self.match_group("extra") 435 436 # If the cell was started but not finished, convert the row into text. 437 438 if not row.nodes or not cell.empty(): 439 for node in row.nodes: 440 region.append_inline(Text(serialise(node))) 441 region.append_inline(Text(serialise(cell) + trailing)) 442 443 self.new_block(region) 444 return 445 446 # Append the final cell, if not empty. 447 448 else: 449 row.trailing = trailing 450 451 if not cell.empty(): 452 row.append(cell) 453 break 454 455 # A cell separator has been found. 456 457 row.append(cell) 458 459 # Add the row to the table and any new table to the region. 460 461 table.add(row) 462 if new_table: 463 self.add_node(region, new_table) 464 465 self.new_block(region) 466 467 def parse_valign(self, attrs): 468 469 "Handle vertical alignment within 'attrs'." 470 471 value = self.match_group("value") 472 attr = TableAttr("valign", value == "^" and "top" or "bottom", True) 473 attrs.append(attr) 474 475 476 477 # Inline formatting handlers. 478 479 def parse_inline(self, region, cls, pattern_name): 480 481 "Handle an inline region." 482 483 span = cls([]) 484 self.parse_region_details(span, self.inline_patterns_for(pattern_name)) 485 region.append_inline(span) 486 487 def parse_larger(self, region): 488 self.parse_inline(region, Larger, "larger") 489 490 def parse_monospace(self, region): 491 span = Monospace([]) 492 self.parse_region_details(span, ["monospaceend"]) 493 region.append_inline(span) 494 495 def parse_smaller(self, region): 496 self.parse_inline(region, Smaller, "smaller") 497 498 def parse_strike(self, region): 499 self.parse_inline(region, Strikethrough, "strike") 500 501 def parse_sub(self, region): 502 self.parse_inline(region, Subscript, "sub") 503 504 def parse_super(self, region): 505 self.parse_inline(region, Superscript, "super") 506 507 def parse_underline(self, region): 508 self.parse_inline(region, Underline, "underline") 509 510 511 512 # Complete inline pattern handlers. 513 514 def parse_link(self, region): 515 target = self.match_group("target") 516 text = self.match_group("text") 517 link = Link(text and [Text(text)], target) 518 region.append_inline(link) 519 520 # Record the link for later processing. 521 522 self.root.links.append(link) 523 524 def parse_macro(self, region): 525 name = self.match_group("name") 526 args = self.match_group("args") 527 528 # Obtain the raw arguments. Moin usually leaves it to the macro to 529 # interpret the individual arguments. 530 531 arglist = args and args.split(",") or [] 532 macro = Macro(name, arglist) 533 region.append_inline(macro) 534 535 # Record the macro for later processing. 536 537 self.root.macros.append(macro) 538 539 540 541 # Table attribute handlers. 542 543 def parse_table_attr(self, attrs, pattern_name): 544 545 "Handle a table attribute." 546 547 attrs.append(TableAttr(pattern_name, self.match_group("value"), True)) 548 549 def parse_colour(self, cell): 550 self.parse_table_attr(cell, "colour") 551 552 def parse_colspan(self, cell): 553 self.parse_table_attr(cell, "colspan") 554 555 def parse_rowspan(self, cell): 556 self.parse_table_attr(cell, "rowspan") 557 558 def parse_width(self, cell): 559 self.parse_table_attr(cell, "width") 560 561 562 563 # Regular expressions. 564 565 syntax = { 566 # Page regions: 567 568 "regionstart" : join((group("indent", r"\N*"), # ws... (optional) 569 group("level", repeat("[{]", 3)))), # {{{... 570 571 "regionend" : join((r"\N*", # ws... (optional) 572 group("feature", join(( 573 group("level", repeat("[}]", 3)), # }}}... 574 group("extra", r"\n"), 575 "?"))))), # nl (optional) 576 577 "header" : join(("#!", # #! 578 group("args", ".*?"), "\n")), # text-excl-nl 579 580 # Region contents: 581 582 # Line-oriented patterns support features which require their own 583 # separate lines. 584 585 "break" : r"^(\s*?)\n", # blank line 586 587 "defterm" : join(("^", 588 group("pad", r"\N+"), # ws... 589 expect(".+?::"))), # text :: 590 591 "defterm_empty" : join(("^", 592 group("pad", r"\N+"), # ws... 593 expect("::\s+"))), # :: 594 # ws... (optional) 595 596 "heading" : join(("^", 597 group("extra", r"\N*"), # ws... (optional) 598 group("level", "=+"), # =... 599 group("pad", r"\s+"), # ws... 600 expect(join((r".*?\N+", # text 601 recur("level"), # =... 602 r"\N*$"))))), # ws... (optional) 603 604 "listitem" : join(("^", 605 group("indent", r"\N+"), # ws... 606 group("marker", r"\*"), # list-marker 607 group("pad", r"\s*"))), # ws... (optional) 608 609 "listitem_num" : join(("^", 610 group("indent", r"\N+"), # ws... 611 group("marker", r"\d+\."), # decimal-marker 612 optional(join(("#", group("num", r"\d+")))), # # num (optional) 613 group("pad", r"\s+"))), # ws... 614 615 "listitem_alpha": join(("^", 616 group("indent", r"\N+"), # ws... 617 group("marker", r"[aA]\."), # alpha-marker 618 optional(join(("#", group("num", r"\d+")))), # # num (optional) 619 group("pad", r"\s+"))), # ws... 620 621 "listitem_roman": join(("^", 622 group("indent", r"\N+"), # ws... 623 group("marker", r"[iI]\."), # roman-marker 624 optional(join(("#", group("num", r"\d+")))), # # num (optional) 625 group("pad", r"\s+"))), # ws... 626 627 "listitem_dot" : join(("^", 628 group("indent", r"\N+"), # ws... 629 group("marker", r"\."), # dot-marker 630 group("pad", r"\s*"))), # ws... (optional) 631 632 "tablerow" : r"^\|\|", # || 633 634 # Region contents: 635 636 # Inline patterns are for markup features that appear within blocks. 637 # The patterns below start inline spans that can contain other markup 638 # features. 639 640 "fontstyle" : group("style", repeat("'", 2, 6)), # ''... 641 "larger" : r"~\+", # ~+ 642 "monospace" : r"`", # ` 643 "rule" : group("rule", "-----*"), # ----... 644 "smaller" : r"~-", # ~- 645 "strike" : r"--\(", # --( 646 "sub" : r",,", # ,, 647 "super" : r"\^", # ^ 648 "underline" : r"__", # __ 649 650 # Complete inline patterns are for markup features that do not support 651 # arbitrary content within them: 652 653 "link" : join((r"\[\[", # [[ 654 group("target", ".*?"), # target 655 optional(join((r"\|", group("text", ".*?")))), # | text (optional) 656 "]]")), # ]] 657 658 "macro" : join(("<<", # << 659 group("name", "\w+?"), # digit-letter... 660 optional(join((r"\(", # ( (optional) 661 group("args", ".*?"), # not-)... 662 r"\)"))), # ) (optional) 663 ">>")), # >> 664 665 # Ending patterns for inline features: 666 667 "largerend" : r"\+~", # +~ 668 "monospaceend" : r"`", # ` 669 "smallerend" : r"-~", # -~ 670 "strikeend" : r"\)--", # )-- 671 "subend" : r",,", # ,, 672 "superend" : r"\^", # ^ 673 "underlineend" : r"__", # __ 674 675 # Heading contents: 676 677 "headingend" : join((group("pad", r"\N+"), # ws... 678 group("level", "=+"), # =... 679 group("extra", r"\N*\n"))), # ws (optional) nl 680 681 # List contents: 682 683 "deftermend" : join(("::", group("pad", r"\s*?\n"))), # :: 684 # ws... (optional) 685 # nl 686 687 "deftermsep" : join(("::", group("pad", r"\s+"))), # :: 688 # ws... (optional) 689 690 "listitemend" : r"^", # next line 691 692 # Table contents: 693 694 "tableattrs" : r"<", # < 695 "tablecell" : r"\|\|", # || 696 697 "tableend" : join((group("extra", r"\s*?"), # ws... (optional) 698 "^")), # next line 699 700 # Table attributes: 701 702 "tableattrsend" : r">", # > 703 "halign" : group("value", "[(:)]"), # halign-marker 704 "valign" : group("value", "[v^]"), # valign-marker 705 "colour" : group("value", join(("\#", # # 706 repeat("[0-9A-F]", 6, 6)))), # nnnnnn 707 708 "colspan" : join(("-", # - 709 group("value", "\d+"))), # n... 710 711 "rowspan" : join((r"\|", # | 712 group("value", "\d+"))), # n... 713 714 "width" : group("value", "\d+%"), # n... % 715 716 "attrname" : join((excl(r"[-\d]"), # not-dash-or-digit 717 group("name", r"[-\w]+"))), # dash-digit-letter... 718 719 "attrvalue" : join(("=", group("quote", r"\Q"), # quote 720 group("value", ".*?"), # non-quote... (optional) 721 recur("quote"))), # quote 722 } 723 724 patterns = get_patterns(syntax) 725 726 727 728 # Patterns available within certain markup features. 729 730 table_pattern_names = [ 731 "attrname", "colour", "colspan", "halign", "rowspan", "tableattrsend", 732 "valign", "width" 733 ] 734 735 inline_pattern_names = [ 736 "fontstyle", "larger", "link", "macro", "monospace", "regionstart", 737 "smaller", "strike", "sub", "super", "underline", 738 ] 739 740 list_pattern_names = [ 741 "listitem", "listitem_alpha", "listitem_dot", "listitem_num", 742 "listitem_roman", 743 ] 744 745 listitem_pattern_names = inline_pattern_names + ["listitemend"] 746 747 region_without_table_pattern_names = inline_pattern_names + list_pattern_names + [ 748 "break", "heading", "defterm", "defterm_empty", 749 "regionend", "rule", 750 ] 751 752 region_pattern_names = region_without_table_pattern_names + ["tablerow"] 753 754 table_region_pattern_names = inline_pattern_names + [ 755 "tableattrs", "tablecell", "tableend" 756 ] 757 758 def inline_patterns_for(self, name): 759 names = self.inline_pattern_names[:] 760 names[names.index(name)] = "%send" % name 761 return names 762 763 764 765 # Pattern handlers. 766 767 end_region = ParserBase.end_region 768 769 handlers = { 770 None : end_region, 771 "attrname" : parse_attrname, 772 "break" : parse_break, 773 "colour" : parse_colour, 774 "colspan" : parse_colspan, 775 "defterm" : parse_defterm, 776 "defterm_empty" : parse_defterm_empty, 777 "deftermend" : end_region, 778 "deftermsep" : end_region, 779 "fontstyle" : parse_fontstyle, 780 "halign" : parse_halign, 781 "heading" : parse_heading, 782 "headingend" : parse_heading_end, 783 "larger" : parse_larger, 784 "largerend" : end_region, 785 "link" : parse_link, 786 "macro" : parse_macro, 787 "listitemend" : end_region, 788 "listitem" : parse_listitem, 789 "listitem_alpha" : parse_listitem, 790 "listitem_dot" : parse_listitem, 791 "listitem_num" : parse_listitem, 792 "listitem_roman" : parse_listitem, 793 "monospace" : parse_monospace, 794 "monospaceend" : end_region, 795 "regionstart" : parse_section, 796 "regionend" : parse_section_end, 797 "rowspan" : parse_rowspan, 798 "rule" : parse_rule, 799 "smaller" : parse_smaller, 800 "smallerend" : end_region, 801 "strike" : parse_strike, 802 "strikeend" : end_region, 803 "sub" : parse_sub, 804 "subend" : end_region, 805 "super" : parse_super, 806 "superend" : end_region, 807 "tableattrs" : parse_table_attrs, 808 "tableattrsend" : end_region, 809 "tablerow" : parse_table_row, 810 "tablecell" : end_region, 811 "tableend" : end_region, 812 "underline" : parse_underline, 813 "underlineend" : end_region, 814 "valign" : parse_valign, 815 "width" : parse_width, 816 } 817 818 parser = MoinParser 819 820 # vim: tabstop=4 expandtab shiftwidth=4