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