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 span = Monospace([]) 415 self.parse_region_details(span, ["monospaceend"]) 416 region.append_inline(span) 417 418 def parse_smaller(self, region): 419 self.parse_inline(region, Smaller, "smaller") 420 421 def parse_strike(self, region): 422 self.parse_inline(region, Strikethrough, "strike") 423 424 def parse_sub(self, region): 425 self.parse_inline(region, Subscript, "sub") 426 427 def parse_super(self, region): 428 self.parse_inline(region, Superscript, "super") 429 430 def parse_underline(self, region): 431 self.parse_inline(region, Underline, "underline") 432 433 434 435 # Table attribute handlers. 436 437 def parse_table_attr(self, attrs, pattern_name): 438 439 "Handle a table attribute." 440 441 attrs.append(TableAttr(pattern_name, self.match_group("value"), True)) 442 443 def parse_colour(self, cell): 444 self.parse_table_attr(cell, "colour") 445 446 def parse_colspan(self, cell): 447 self.parse_table_attr(cell, "colspan") 448 449 def parse_rowspan(self, cell): 450 self.parse_table_attr(cell, "rowspan") 451 452 def parse_width(self, cell): 453 self.parse_table_attr(cell, "width") 454 455 456 457 # Regular expressions. 458 459 syntax = { 460 # Page regions: 461 462 "regionstart" : join((group("indent", r"\N*"), # ws... (optional) 463 group("level", repeat("[{]", 3)))), # {{{... 464 465 "regionend" : join((r"\N*", # ws... (optional) 466 group("level", repeat("[}]", 3)))), # }}}... 467 468 "header" : join(("#!", # #! 469 group("args", ".*?"), "\n")), # text-excl-nl 470 471 # Region contents: 472 # Line-oriented patterns: 473 474 "break" : r"^(\s*?)\n", # blank line 475 476 "defterm" : join(("^", 477 group("pad", r"\N+"), # ws... 478 expect(".+?::"))), # text :: 479 480 "defterm_empty" : join(("^", 481 group("pad", r"\N+"), # ws... 482 expect("::\s+"))), # :: 483 # ws... (optional) 484 485 "heading" : join(("^", 486 group("extra", r"\N*"), # ws... (optional) 487 group("level", "=+"), # =... 488 group("pad", r"\s+"), # ws... 489 expect(join((r".*?\N+", # text 490 recur("level"), # =... 491 r"\N*$"))))), # ws... (optional) 492 493 "listitem" : join(("^", 494 group("indent", r"\N+"), # ws... 495 group("marker", r"\*"), # list-marker 496 group("pad", r"\s*"))), # ws... (optional) 497 498 "listitem_num" : join(("^", 499 group("indent", r"\N+"), # ws... 500 group("marker", r"\d+\."), # decimal-marker 501 optional(join(("#", group("num", r"\d+")))), # # num (optional) 502 group("pad", r"\s+"))), # ws... 503 504 "listitem_alpha": join(("^", 505 group("indent", r"\N+"), # ws... 506 group("marker", r"[aA]\."), # alpha-marker 507 optional(join(("#", group("num", r"\d+")))), # # num (optional) 508 group("pad", r"\s+"))), # ws... 509 510 "listitem_roman": join(("^", 511 group("indent", r"\N+"), # ws... 512 group("marker", r"[iI]\."), # roman-marker 513 optional(join(("#", group("num", r"\d+")))), # # num (optional) 514 group("pad", r"\s+"))), # ws... 515 516 "listitem_dot" : join(("^", 517 group("indent", r"\N+"), # ws... 518 group("marker", r"\."), # dot-marker 519 group("pad", r"\s*"))), # ws... (optional) 520 521 "tablerow" : r"^\|\|", # || 522 523 # Region contents: 524 # Inline patterns: 525 526 "fontstyle" : group("style", repeat("'", 2, 6)), # ''... 527 "larger" : r"~\+", # ~+ 528 "monospace" : r"`", # ` 529 "rule" : group("rule", "-----*"), # ----... 530 "smaller" : r"~-", # ~- 531 "strike" : r"--\(", # --( 532 "sub" : r",,", # ,, 533 "super" : r"\^", # ^ 534 "underline" : r"__", # __ 535 536 # Complete inline patterns: 537 538 "link" : join((r"\[\[", # [[ 539 group("target", ".*?"), # target 540 optional(join((r"\|", group("text", ".*?")))), # | text (optional) 541 "]]")), # ]] 542 543 # Inline contents: 544 545 "largerend" : r"\+~", # +~ 546 "monospaceend" : r"`", # ` 547 "smallerend" : r"-~", # -~ 548 "strikeend" : r"\)--", # )-- 549 "subend" : r",,", # ,, 550 "superend" : r"\^", # ^ 551 "underlineend" : r"__", # __ 552 553 # Heading contents: 554 555 "headingend" : join((group("pad", r"\N+"), # ws... 556 group("level", "=+"), # =... 557 group("extra", r"\N*\n"))), # ws (optional) nl 558 559 # List contents: 560 561 "deftermend" : join(("::", group("pad", r"\s*?\n"))), # :: 562 # ws... (optional) 563 # nl 564 565 "deftermsep" : join(("::", group("pad", r"\s+"))), # :: 566 # ws... (optional) 567 568 "listitemend" : r"^", # next line 569 570 # Table contents: 571 572 "tableattrs" : r"<", # < 573 "tablecell" : r"\|\|", # || 574 575 "tableend" : join((group("extra", r"\s*?"), # ws... (optional) 576 "^")), # next line 577 578 # Table attributes: 579 580 "tableattrsend" : r">", # > 581 "halign" : group("value", "[(:)]"), # halign-marker 582 "valign" : group("value", "[v^]"), # valign-marker 583 "colour" : group("value", join(("\#", # # 584 repeat("[0-9A-F]", 6, 6)))), # nnnnnn 585 586 "colspan" : join(("-", # - 587 group("value", "\d+"))), # n... 588 589 "rowspan" : join((r"\|", # | 590 group("value", "\d+"))), # n... 591 592 "width" : group("value", "\d+%"), # n... % 593 594 "attrname" : join((excl(r"[-\d]"), # not-dash-or-digit 595 group("name", r"[-\w]+"))), # dash-digit-letter... 596 597 "attrvalue" : join(("=", group("quote", r"\Q"), # quote 598 group("value", ".*?"), # non-quote... (optional) 599 recur("quote"))), # quote 600 } 601 602 patterns = get_patterns(syntax) 603 604 605 606 # Pattern details. 607 608 table_pattern_names = [ 609 "attrname", "colour", "colspan", "halign", "rowspan", "tableattrsend", 610 "valign", "width" 611 ] 612 613 inline_pattern_names = [ 614 "fontstyle", "larger", "link", "monospace", "regionstart", "smaller", 615 "strike", "sub", "super", "underline", 616 ] 617 618 list_pattern_names = [ 619 "listitem", "listitem_alpha", "listitem_dot", "listitem_num", 620 "listitem_roman", 621 ] 622 623 listitem_pattern_names = inline_pattern_names + ["listitemend"] 624 625 region_without_table_pattern_names = inline_pattern_names + list_pattern_names + [ 626 "break", "heading", "defterm", "defterm_empty", 627 "regionend", "rule", 628 ] 629 630 region_pattern_names = region_without_table_pattern_names + ["tablerow"] 631 632 table_region_pattern_names = inline_pattern_names + [ 633 "tableattrs", "tablecell", "tableend" 634 ] 635 636 def inline_patterns_for(self, name): 637 names = self.inline_pattern_names[:] 638 names[names.index(name)] = "%send" % name 639 return names 640 641 642 643 # Pattern handlers. 644 645 end_region = ParserBase.end_region 646 647 handlers = { 648 None : end_region, 649 "attrname" : parse_attrname, 650 "break" : parse_break, 651 "colour" : parse_colour, 652 "colspan" : parse_colspan, 653 "defterm" : parse_defterm, 654 "defterm_empty" : parse_defterm_empty, 655 "deftermend" : end_region, 656 "deftermsep" : end_region, 657 "fontstyle" : parse_fontstyle, 658 "halign" : parse_halign, 659 "heading" : parse_heading, 660 "headingend" : parse_heading_end, 661 "larger" : parse_larger, 662 "largerend" : end_region, 663 "link" : parse_link, 664 "listitemend" : end_region, 665 "listitem" : parse_listitem, 666 "listitem_alpha" : parse_listitem, 667 "listitem_dot" : parse_listitem, 668 "listitem_num" : parse_listitem, 669 "listitem_roman" : parse_listitem, 670 "monospace" : parse_monospace, 671 "monospaceend" : end_region, 672 "regionstart" : parse_section, 673 "regionend" : parse_section_end, 674 "rowspan" : parse_rowspan, 675 "rule" : parse_rule, 676 "smaller" : parse_smaller, 677 "smallerend" : end_region, 678 "strike" : parse_strike, 679 "strikeend" : end_region, 680 "sub" : parse_sub, 681 "subend" : end_region, 682 "super" : parse_super, 683 "superend" : end_region, 684 "tableattrs" : parse_table_attrs, 685 "tableattrsend" : end_region, 686 "tablerow" : parse_table_row, 687 "tablecell" : end_region, 688 "tableend" : end_region, 689 "underline" : parse_underline, 690 "underlineend" : end_region, 691 "valign" : parse_valign, 692 "width" : parse_width, 693 } 694 695 parser = MoinParser 696 697 # vim: tabstop=4 expandtab shiftwidth=4