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 self.add_node(region, self.parse_region(level, indent, "inline")) 279 self.new_block(region) 280 281 def parse_section_end(self, region): 282 283 "Handle the end of a new section within 'region'." 284 285 feature = self.match_group("level") 286 if region.have_end(feature): 287 raise StopIteration 288 else: 289 region.append_inline(Text(feature)) 290 291 def parse_table_attrs(self, cell): 292 293 "Handle the start of table attributes within 'cell'." 294 295 attrs = TableAttrs([]) 296 self.parse_region_details(attrs, self.table_pattern_names) 297 298 # Test the validity of the attributes. 299 300 last = None 301 302 for node in attrs.nodes: 303 304 # Text separator nodes must be whitespace. 305 306 if isinstance(node, Text): 307 if node.s.strip(): 308 break 309 310 # Named attributes must be preceded by space if not the first. 311 312 elif last and not node.concise and not isinstance(last, Text): 313 break 314 315 last = node 316 317 # All nodes were valid: preserve the collection. 318 319 else: 320 cell.attrs = attrs 321 return 322 323 # Invalid nodes were found: serialise the attributes as text. 324 325 cell.append_inline(Text(serialise(attrs))) 326 327 def parse_table_row(self, region): 328 329 "Handle the start of a table row within 'region'." 330 331 # Identify any active table. 332 333 table = region.node(-2) 334 block = region.node(-1) 335 336 if not (isinstance(table, Table) and block.empty()): 337 new_table = table = Table([]) 338 else: 339 new_table = None 340 341 row = TableRow([]) 342 343 while True: 344 cell = TableCell([]) 345 self.parse_region_details(cell, self.table_region_pattern_names) 346 347 # Handle the end of the row. 348 349 if self.matching_pattern() == "tableend": 350 trailing = self.match_group("extra") 351 352 # If the cell was started but not finished, convert the row into text. 353 354 if not row.nodes or not cell.empty(): 355 for node in row.nodes: 356 region.append_inline(Text(serialise(node))) 357 region.append_inline(Text(serialise(cell))) 358 region.append_inline(Text(trailing)) 359 360 self.new_block(region) 361 return 362 363 # Append the final cell, if not empty. 364 365 else: 366 row.trailing = trailing 367 368 if not cell.empty(): 369 row.append(cell) 370 break 371 372 # A cell separator has been found. 373 374 row.append(cell) 375 376 # Add the row to the table and any new table to the region. 377 378 table.add(row) 379 if new_table: 380 self.add_node(region, new_table) 381 382 self.new_block(region) 383 384 def parse_valign(self, attrs): 385 386 "Handle vertical alignment within 'attrs'." 387 388 value = self.match_group("value") 389 attr = TableAttr("valign", value == "^" and "top" or "bottom", True) 390 attrs.append(attr) 391 392 393 394 # Inline formatting handlers. 395 396 def parse_inline(self, region, cls, pattern_name): 397 398 "Handle an inline region." 399 400 span = cls([]) 401 self.parse_region_details(span, self.inline_patterns_for(pattern_name)) 402 region.append_inline(span) 403 404 def parse_larger(self, region): 405 self.parse_inline(region, Larger, "larger") 406 407 def parse_link(self, region): 408 target = self.match_group("target") 409 text = self.match_group("text") 410 link = Link(text and [Text(text)], target) 411 region.append_inline(link) 412 413 def parse_monospace(self, region): 414 self.parse_inline(region, Monospace, "monospace") 415 416 def parse_smaller(self, region): 417 self.parse_inline(region, Smaller, "smaller") 418 419 def parse_strike(self, region): 420 self.parse_inline(region, Strikethrough, "strike") 421 422 def parse_sub(self, region): 423 self.parse_inline(region, Subscript, "sub") 424 425 def parse_super(self, region): 426 self.parse_inline(region, Superscript, "super") 427 428 def parse_underline(self, region): 429 self.parse_inline(region, Underline, "underline") 430 431 432 433 # Table attribute handlers. 434 435 def parse_table_attr(self, attrs, pattern_name): 436 437 "Handle a table attribute." 438 439 attrs.append(TableAttr(pattern_name, self.match_group("value"), True)) 440 441 def parse_colour(self, cell): 442 self.parse_table_attr(cell, "colour") 443 444 def parse_colspan(self, cell): 445 self.parse_table_attr(cell, "colspan") 446 447 def parse_rowspan(self, cell): 448 self.parse_table_attr(cell, "rowspan") 449 450 def parse_width(self, cell): 451 self.parse_table_attr(cell, "width") 452 453 454 455 # Regular expressions. 456 457 syntax = { 458 # Page regions: 459 460 "regionstart" : join((group("indent", r"\N*"), # ws... (optional) 461 group("level", repeat("[{]", 3)))), # {{{... 462 463 "regionend" : join((r"\N*", # ws... (optional) 464 group("level", repeat("[}]", 3)))), # }}}... 465 466 "header" : join(("#!", # #! 467 group("args", ".*?"), "\n")), # text-excl-nl 468 469 # Region contents: 470 # Line-oriented patterns: 471 472 "break" : r"^(\s*?)\n", # blank line 473 474 "defterm" : join(("^", 475 group("pad", r"\N+"), # ws... 476 expect(".+?::"))), # text :: 477 478 "defterm_empty" : join(("^", 479 group("pad", r"\N+"), # ws... 480 expect("::\s+"))), # :: 481 # ws... (optional) 482 483 "heading" : join(("^", 484 group("extra", r"\N*"), # ws... (optional) 485 group("level", "=+"), # =... 486 group("pad", r"\s+"), # ws... 487 expect(join((r".*?\N+", # text 488 recur("level"), # =... 489 r"\N*$"))))), # ws... (optional) 490 491 "listitem" : join(("^", 492 group("indent", r"\N+"), # ws... 493 group("marker", r"\*"), # list-marker 494 group("pad", r"\s*"))), # ws... (optional) 495 496 "listitem_num" : join(("^", 497 group("indent", r"\N+"), # ws... 498 group("marker", r"\d+\."), # decimal-marker 499 optional(join(("#", group("num", r"\d+")))), # # num (optional) 500 group("pad", r"\s+"))), # ws... 501 502 "listitem_alpha": join(("^", 503 group("indent", r"\N+"), # ws... 504 group("marker", r"[aA]\."), # alpha-marker 505 optional(join(("#", group("num", r"\d+")))), # # num (optional) 506 group("pad", r"\s+"))), # ws... 507 508 "listitem_roman": join(("^", 509 group("indent", r"\N+"), # ws... 510 group("marker", r"[iI]\."), # roman-marker 511 optional(join(("#", group("num", r"\d+")))), # # num (optional) 512 group("pad", r"\s+"))), # ws... 513 514 "listitem_dot" : join(("^", 515 group("indent", r"\N+"), # ws... 516 group("marker", r"\."), # dot-marker 517 group("pad", r"\s*"))), # ws... (optional) 518 519 "tablerow" : r"^\|\|", # || 520 521 # Region contents: 522 # Inline patterns: 523 524 "fontstyle" : group("style", repeat("'", 2, 6)), # ''... 525 "larger" : r"~\+", # ~+ 526 "monospace" : r"`", # ` 527 "rule" : group("rule", "-----*"), # ----... 528 "smaller" : r"~-", # ~- 529 "strike" : r"--\(", # --( 530 "sub" : r",,", # ,, 531 "super" : r"\^", # ^ 532 "underline" : r"__", # __ 533 534 # Complete inline patterns: 535 536 "link" : join((r"\[\[", # [[ 537 group("target", ".*?"), # target 538 optional(join((r"\|", group("text", ".*?")))), # | text (optional) 539 "]]")), # ]] 540 541 # Inline contents: 542 543 "largerend" : r"\+~", # +~ 544 "monospaceend" : r"`", # ` 545 "smallerend" : r"-~", # -~ 546 "strikeend" : r"\)--", # )-- 547 "subend" : r",,", # ,, 548 "superend" : r"\^", # ^ 549 "underlineend" : r"__", # __ 550 551 # Heading contents: 552 553 "headingend" : join((group("pad", r"\N+"), # ws... 554 group("level", "=+"), # =... 555 group("extra", r"\N*\n"))), # ws (optional) nl 556 557 # List contents: 558 559 "deftermend" : join(("::", group("pad", r"\s*?\n"))), # :: 560 # ws... (optional) 561 # nl 562 563 "deftermsep" : join(("::", group("pad", r"\s+"))), # :: 564 # ws... (optional) 565 566 "listitemend" : r"^", # next line 567 568 # Table contents: 569 570 "tableattrs" : r"<", # < 571 "tablecell" : r"\|\|", # || 572 573 "tableend" : join((group("extra", r"\s*?"), # ws... (optional) 574 "^")), # next line 575 576 # Table attributes: 577 578 "tableattrsend" : r">", # > 579 "halign" : group("value", "[(:)]"), # halign-marker 580 "valign" : group("value", "[v^]"), # valign-marker 581 "colour" : group("value", join(("\#", # # 582 repeat("[0-9A-F]", 6, 6)))), # nnnnnn 583 584 "colspan" : join(("-", # - 585 group("value", "\d+"))), # n... 586 587 "rowspan" : join((r"\|", # | 588 group("value", "\d+"))), # n... 589 590 "width" : group("value", "\d+%"), # n... % 591 592 "attrname" : join((excl(r"[-\d]"), # not-dash-or-digit 593 group("name", r"[-\w]+"))), # dash-digit-letter... 594 595 "attrvalue" : join(("=", group("quote", r"\Q"), # quote 596 group("value", ".*?"), # non-quote... (optional) 597 recur("quote"))), # quote 598 } 599 600 patterns = get_patterns(syntax) 601 602 603 604 # Pattern details. 605 606 table_pattern_names = [ 607 "attrname", "colour", "colspan", "halign", "rowspan", "tableattrsend", 608 "valign", "width" 609 ] 610 611 inline_pattern_names = [ 612 "fontstyle", "larger", "link", "monospace", "regionstart", "smaller", 613 "strike", "sub", "super", "underline", 614 ] 615 616 list_pattern_names = [ 617 "listitem", "listitem_alpha", "listitem_dot", "listitem_num", 618 "listitem_roman", 619 ] 620 621 listitem_pattern_names = inline_pattern_names + ["listitemend"] 622 623 region_without_table_pattern_names = inline_pattern_names + list_pattern_names + [ 624 "break", "heading", "defterm", "defterm_empty", 625 "regionend", "rule", 626 ] 627 628 region_pattern_names = region_without_table_pattern_names + ["tablerow"] 629 630 table_region_pattern_names = inline_pattern_names + [ 631 "tableattrs", "tablecell", "tableend" 632 ] 633 634 def inline_patterns_for(self, name): 635 names = self.inline_pattern_names[:] 636 names[names.index(name)] = "%send" % name 637 return names 638 639 640 641 # Pattern handlers. 642 643 end_region = ParserBase.end_region 644 645 handlers = { 646 None : end_region, 647 "attrname" : parse_attrname, 648 "break" : parse_break, 649 "colour" : parse_colour, 650 "colspan" : parse_colspan, 651 "defterm" : parse_defterm, 652 "defterm_empty" : parse_defterm_empty, 653 "deftermend" : end_region, 654 "deftermsep" : end_region, 655 "fontstyle" : parse_fontstyle, 656 "halign" : parse_halign, 657 "heading" : parse_heading, 658 "headingend" : parse_heading_end, 659 "larger" : parse_larger, 660 "largerend" : end_region, 661 "link" : parse_link, 662 "listitemend" : end_region, 663 "listitem" : parse_listitem, 664 "listitem_alpha" : parse_listitem, 665 "listitem_dot" : parse_listitem, 666 "listitem_num" : parse_listitem, 667 "listitem_roman" : parse_listitem, 668 "monospace" : parse_monospace, 669 "monospaceend" : end_region, 670 "regionstart" : parse_section, 671 "regionend" : parse_section_end, 672 "rowspan" : parse_rowspan, 673 "rule" : parse_rule, 674 "smaller" : parse_smaller, 675 "smallerend" : end_region, 676 "strike" : parse_strike, 677 "strikeend" : end_region, 678 "sub" : parse_sub, 679 "subend" : end_region, 680 "super" : parse_super, 681 "superend" : end_region, 682 "tableattrs" : parse_table_attrs, 683 "tableattrsend" : end_region, 684 "tablerow" : parse_table_row, 685 "tablecell" : end_region, 686 "tableend" : end_region, 687 "underline" : parse_underline, 688 "underlineend" : end_region, 689 "valign" : parse_valign, 690 "width" : parse_width, 691 } 692 693 parser = MoinParser 694 695 # vim: tabstop=4 expandtab shiftwidth=4