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