Convert markdown to serialized XHTML or HTML. Keyword arguments: * source: Source text as a Unicode string.
(self, source)
| 359 | % (format, list(self.output_formats.keys()))) |
| 360 | |
| 361 | def convert(self, source): |
| 362 | """ |
| 363 | Convert markdown to serialized XHTML or HTML. |
| 364 | |
| 365 | Keyword arguments: |
| 366 | |
| 367 | * source: Source text as a Unicode string. |
| 368 | |
| 369 | """ |
| 370 | |
| 371 | # Fixup the source text |
| 372 | if not source.strip(): |
| 373 | return "" # a blank unicode string |
| 374 | try: |
| 375 | source = str(source) |
| 376 | except UnicodeDecodeError: |
| 377 | message(CRITICAL, 'UnicodeDecodeError: Markdown only accepts unicode or ascii input.') |
| 378 | return "" |
| 379 | |
| 380 | source = source.replace(STX, "").replace(ETX, "") |
| 381 | source = source.replace("\r\n", "\n").replace("\r", "\n") + "\n\n" |
| 382 | source = re.sub(r'\n\s+\n', '\n\n', source) |
| 383 | source = source.expandtabs(TAB_LENGTH) |
| 384 | |
| 385 | # Split into lines and run the line preprocessors. |
| 386 | self.lines = source.split("\n") |
| 387 | for prep in list(self.preprocessors.values()): |
| 388 | self.lines = prep.run(self.lines) |
| 389 | |
| 390 | # Parse the high-level elements. |
| 391 | root = self.parser.parseDocument(self.lines).getroot() |
| 392 | |
| 393 | # Run the tree-processors |
| 394 | for treeprocessor in list(self.treeprocessors.values()): |
| 395 | newRoot = treeprocessor.run(root) |
| 396 | if newRoot: |
| 397 | root = newRoot |
| 398 | |
| 399 | # Serialize _properly_. Strip top-level tags. |
| 400 | output, length = codecs.utf_8_decode(self.serializer(root, encoding="utf-8")) |
| 401 | if self.stripTopLevelTags: |
| 402 | try: |
| 403 | start = output.index('<%s>'%DOC_TAG)+len(DOC_TAG)+2 |
| 404 | end = output.rindex('</%s>'%DOC_TAG) |
| 405 | output = output[start:end].strip() |
| 406 | except ValueError: |
| 407 | if output.strip().endswith('<%s />'%DOC_TAG): |
| 408 | # We have an empty document |
| 409 | output = '' |
| 410 | else: |
| 411 | # We have a serious problem |
| 412 | message(CRITICAL, 'Failed to strip top level tags.') |
| 413 | |
| 414 | # Run the text post-processors |
| 415 | for pp in list(self.postprocessors.values()): |
| 416 | output = pp.run(output) |
| 417 | |
| 418 | return output.strip() |