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 Break, DefItem, DefTerm, FontStyle, Heading, \ 39 Larger, LineBreak, Link, List, ListItem, \ 40 Macro, Monospace, Region, Rule, Smaller, \ 41 Strikethrough, Subscript, Superscript, Table, \ 42 TableAttr, TableAttrs, TableCell, TableRow, \ 43 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_linebreak(self, region): 485 region.append_inline(LineBreak()) 486 487 def parse_link(self, region): 488 target = self.match_group("target") 489 text = self.match_group("text") 490 link = Link(text and [Text(text)], target) 491 region.append_inline(link) 492 493 def parse_macro(self, region): 494 name = self.match_group("name") 495 args = self.match_group("args") 496 497 # Obtain the raw arguments. Moin usually leaves it to the macro to 498 # interpret the individual arguments. 499 500 arglist = args and args.split(",") or [] 501 macro = Macro(name, arglist, region.append_point()) 502 region.append_inline(macro) 503 504 # Record the macro for later processing. 505 506 self.root.macros.append(macro) 507 508 509 510 # Table attribute handlers. 511 512 def parse_table_attr(self, attrs, pattern_name): 513 514 "Handle a table attribute." 515 516 attrs.append(TableAttr(pattern_name, self.match_group("value"), True)) 517 518 def parse_colour(self, cell): 519 self.parse_table_attr(cell, "colour") 520 521 def parse_colspan(self, cell): 522 self.parse_table_attr(cell, "colspan") 523 524 def parse_rowspan(self, cell): 525 self.parse_table_attr(cell, "rowspan") 526 527 def parse_width(self, cell): 528 self.parse_table_attr(cell, "width") 529 530 531 532 # Regular expressions. 533 534 syntax = { 535 # Page regions: 536 537 "regionstart" : join((group("indent", r"\N*"), # ws... (optional) 538 group("level", repeat("[{]", 3)))), # {{{... 539 540 "regionend" : join((r"\N*", # ws... (optional) 541 group("feature", join(( 542 group("level", repeat("[}]", 3)), # }}}... 543 group("extra", r"\n"), 544 "?"))))), # nl (optional) 545 546 "header" : join(("#!", # #! 547 group("args", ".*?"), "\n")), # text-excl-nl 548 549 # Region contents: 550 551 # Line-oriented patterns support features which require their own 552 # separate lines. 553 554 "break" : r"^(\s*?)\n", # blank line 555 556 "defterm" : join(("^", 557 group("pad", r"\N+"), # ws... 558 expect(".+?::"))), # text :: 559 560 "defterm_empty" : join(("^", 561 group("pad", r"\N+"), # ws... 562 expect("::\s+"))), # :: 563 # ws... (optional) 564 565 "heading" : join(("^", 566 group("extra", r"\N*"), # ws... (optional) 567 group("level", "=+"), # =... 568 group("pad", r"\s+"), # ws... 569 expect(join((r".*?\N+", # text 570 recur("level"), # =... 571 r"\N*$"))))), # ws... (optional) 572 573 "listitem" : join(("^", 574 group("indent", r"\N+"), # ws... 575 group("marker", r"\*"), # list-marker 576 group("pad", r"\s*"))), # ws... (optional) 577 578 "listitem_num" : join(("^", 579 group("indent", r"\N+"), # ws... 580 group("marker", r"\d+\."), # decimal-marker 581 optional(join(("#", group("num", r"\d+")))), # # num (optional) 582 group("pad", r"\s+"))), # ws... 583 584 "listitem_alpha": join(("^", 585 group("indent", r"\N+"), # ws... 586 group("marker", r"[aA]\."), # alpha-marker 587 optional(join(("#", group("num", r"\d+")))), # # num (optional) 588 group("pad", r"\s+"))), # ws... 589 590 "listitem_roman": join(("^", 591 group("indent", r"\N+"), # ws... 592 group("marker", r"[iI]\."), # roman-marker 593 optional(join(("#", group("num", r"\d+")))), # # num (optional) 594 group("pad", r"\s+"))), # ws... 595 596 "listitem_dot" : join(("^", 597 group("indent", r"\N+"), # ws... 598 group("marker", r"\."), # dot-marker 599 group("pad", r"\s*"))), # ws... (optional) 600 601 "tablerow" : r"^\|\|", # || 602 603 # Region contents: 604 605 # Inline patterns are for markup features that appear within blocks. 606 # The patterns below start inline spans that can contain other markup 607 # features. 608 609 "fontstyle" : group("style", repeat("'", 2, 6)), # ''... 610 "larger" : r"~\+", # ~+ 611 "monospace" : r"`", # ` 612 "rule" : group("rule", "-----*"), # ----... 613 "smaller" : r"~-", # ~- 614 "strike" : r"--\(", # --( 615 "sub" : r",,", # ,, 616 "super" : r"\^", # ^ 617 "underline" : r"__", # __ 618 619 # Complete inline patterns are for markup features that do not support 620 # arbitrary content within them: 621 622 "linebreak" : r"\\\\", # \\ 623 624 "link" : join((r"\[\[", # [[ 625 group("target", ".*?"), # target 626 optional(join((r"\|", group("text", ".*?")))), # | text (optional) 627 "]]")), # ]] 628 629 "macro" : join(("<<", # << 630 group("name", "\w+?"), # digit-letter... 631 optional(join((r"\(", # ( (optional) 632 group("args", ".*?"), # not-)... 633 r"\)"))), # ) (optional) 634 ">>")), # >> 635 636 # Ending patterns for inline features: 637 638 "largerend" : r"\+~", # +~ 639 "monospaceend" : r"`", # ` 640 "smallerend" : r"-~", # -~ 641 "strikeend" : r"\)--", # )-- 642 "subend" : r",,", # ,, 643 "superend" : r"\^", # ^ 644 "underlineend" : r"__", # __ 645 646 # Heading contents: 647 648 "headingend" : join((group("pad", r"\N+"), # ws... 649 group("level", "=+"), # =... 650 group("extra", r"\N*\n"))), # ws (optional) nl 651 652 # List contents: 653 654 "deftermend" : join(("::", group("pad", r"\s*?\n"))), # :: 655 # ws... (optional) 656 # nl 657 658 "deftermsep" : join(("::", group("pad", r"\s+"))), # :: 659 # ws... (optional) 660 661 "listitemend" : r"^", # next line 662 663 # Table contents: 664 665 "tableattrs" : join(("<", # lt 666 excl("<"))), # not-lt 667 668 "tablecell" : r"\|\|", # || 669 670 "tableend" : join((group("extra", r"\s*?"), # ws... (optional) 671 "^")), # next line 672 673 # Table attributes: 674 675 "tableattrsend" : r">", # > 676 "halign" : group("value", "[(:)]"), # halign-marker 677 "valign" : group("value", "[v^]"), # valign-marker 678 "colour" : group("value", join(("\#", # # 679 repeat("[0-9A-F]", 6, 6)))), # nnnnnn 680 681 "colspan" : join(("-", # - 682 group("value", "\d+"))), # n... 683 684 "rowspan" : join((r"\|", # | 685 group("value", "\d+"))), # n... 686 687 "width" : group("value", "\d+%"), # n... % 688 689 "attrname" : join((excl(r"[-\d]"), # not-dash-or-digit 690 group("name", r"[-\w]+"))), # dash-digit-letter... 691 692 "attrvalue" : join(("=", group("quote", r"\Q"), # quote 693 group("value", ".*?"), # non-quote... (optional) 694 recur("quote"))), # quote 695 } 696 697 patterns = get_patterns(syntax) 698 699 700 701 # Patterns available within certain markup features. 702 703 table_attr_pattern_names = [ 704 "attrname", "colour", "colspan", "halign", "rowspan", "tableattrsend", 705 "valign", "width" 706 ] 707 708 inline_pattern_names = [ 709 "fontstyle", "larger", "linebreak", "link", "macro", "monospace", 710 "regionstart", "smaller", "strike", "sub", "super", "underline", 711 ] 712 713 list_pattern_names = [ 714 "listitem", "listitem_alpha", "listitem_dot", "listitem_num", 715 "listitem_roman", 716 ] 717 718 listitem_pattern_names = inline_pattern_names + ["listitemend"] 719 720 region_without_table_pattern_names = inline_pattern_names + list_pattern_names + [ 721 "break", "heading", "defterm", "defterm_empty", 722 "regionend", "rule", 723 ] 724 725 table_row_pattern_names = inline_pattern_names + [ 726 "tableattrs", "tablecell", "tableend" 727 ] 728 729 # The region pattern names are specifically used by the common parser 730 # functionality. 731 732 region_pattern_names = region_without_table_pattern_names + ["tablerow"] 733 734 735 736 # Pattern handlers. 737 738 end_region = ParserBase.end_region 739 parse_section_end = ParserBase.parse_region_end 740 741 handlers = { 742 None : end_region, 743 "attrname" : parse_attrname, 744 "break" : parse_break, 745 "colour" : parse_colour, 746 "colspan" : parse_colspan, 747 "defterm" : parse_defterm, 748 "defterm_empty" : parse_defterm_empty, 749 "deftermend" : end_region, 750 "deftermsep" : end_region, 751 "fontstyle" : parse_fontstyle, 752 "halign" : parse_halign, 753 "heading" : parse_heading, 754 "headingend" : parse_heading_end, 755 "larger" : parse_larger, 756 "largerend" : end_region, 757 "linebreak" : parse_linebreak, 758 "link" : parse_link, 759 "macro" : parse_macro, 760 "listitemend" : end_region, 761 "listitem" : parse_listitem, 762 "listitem_alpha" : parse_listitem, 763 "listitem_dot" : parse_listitem, 764 "listitem_num" : parse_listitem, 765 "listitem_roman" : parse_listitem, 766 "monospace" : parse_monospace, 767 "monospaceend" : end_region, 768 "regionstart" : parse_section, 769 "regionend" : parse_section_end, 770 "rowspan" : parse_rowspan, 771 "rule" : parse_rule, 772 "smaller" : parse_smaller, 773 "smallerend" : end_region, 774 "strike" : parse_strike, 775 "strikeend" : end_region, 776 "sub" : parse_sub, 777 "subend" : end_region, 778 "super" : parse_super, 779 "superend" : end_region, 780 "tableattrs" : parse_table_attrs, 781 "tableattrsend" : end_region, 782 "tablerow" : parse_table_row, 783 "tablecell" : end_region, 784 "tableend" : end_region, 785 "underline" : parse_underline, 786 "underlineend" : end_region, 787 "valign" : parse_valign, 788 "width" : parse_width, 789 } 790 791 parser = MoinParser 792 793 # vim: tabstop=4 expandtab shiftwidth=4