parser.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import markdown
  2. from misago.markup.bbcode import inline
  3. def parse_text(text, author=None, allow_mentions=True, allow_links=True,
  4. allow_images=True, allow_blocks=True):
  5. """
  6. Message parser
  7. Utility for flavours to call
  8. Breaks text into paragraphs, supports code, spoiler and quote blocks,
  9. headers, lists, images, spoilers, text styles
  10. Returns dict object
  11. """
  12. md = md_factory(author=author, allow_mentions=allow_mentions,
  13. allow_links=allow_links, allow_images=allow_images,
  14. allow_blocks=allow_blocks)
  15. parsing_result = {
  16. 'original_text': text,
  17. 'parsed_text': '',
  18. 'markdown': md,
  19. }
  20. # Parse text
  21. parsed_text = md.convert(text).strip()
  22. # Store parsed text on object and return it
  23. parsing_result['parsed_text'] = parsed_text
  24. return parsing_result
  25. def md_factory(author=None, allow_mentions=True, allow_links=True,
  26. allow_images=True, allow_blocks=True):
  27. """
  28. Create and confifure markdown object
  29. """
  30. md = markdown.Markdown(safe_mode='escape',
  31. extensions=['nl2br'])
  32. # Remove references
  33. del md.preprocessors['reference']
  34. del md.inlinePatterns['reference']
  35. del md.inlinePatterns['image_reference']
  36. del md.inlinePatterns['short_reference']
  37. # Add [b], [i], [u]
  38. md.inlinePatterns.add('bb_b', inline.bold, '<strong')
  39. md.inlinePatterns.add('bb_i', inline.italics, '<emphasis')
  40. md.inlinePatterns.add('bb_u', inline.underline, '<emphasis2')
  41. if allow_mentions:
  42. # Register mentions
  43. pass
  44. if allow_links:
  45. # Add [url]
  46. pass
  47. else:
  48. # Remove links
  49. del md.inlinePatterns['link']
  50. del md.inlinePatterns['autolink']
  51. del md.inlinePatterns['automail']
  52. if allow_images:
  53. # Add [img]
  54. pass
  55. else:
  56. # Remove images
  57. del md.inlinePatterns['image_link']
  58. if allow_blocks:
  59. # Add [quote], [spoiler], [list] and [code] blocks
  60. pass
  61. else:
  62. # Remove blocks
  63. del md.parser.blockprocessors['hashheader']
  64. del md.parser.blockprocessors['setextheader']
  65. del md.parser.blockprocessors['code']
  66. del md.parser.blockprocessors['quote']
  67. del md.parser.blockprocessors['hr']
  68. del md.parser.blockprocessors['olist']
  69. del md.parser.blockprocessors['ulist']
  70. return md