quotes.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import re
  2. import markdown
  3. from markdown.util import etree
  4. # Global vars
  5. QUOTE_AUTHOR_RE = re.compile(r'^(?P<arrows>(>|\s)+)?@(?P<username>\w+)$', re.UNICODE)
  6. class QuoteTitlesExtension(markdown.Extension):
  7. def extendMarkdown(self, md):
  8. md.registerExtension(self)
  9. md.preprocessors.add('mi_quote_title',
  10. QuoteTitlesPreprocessor(md),
  11. '>fenced_code_block')
  12. md.postprocessors.add('mi_quote_title',
  13. QuoteTitlesPostprocessor(md),
  14. '_end')
  15. class QuoteTitlesPreprocessor(markdown.preprocessors.Preprocessor):
  16. def __init__(self, md):
  17. markdown.preprocessors.Preprocessor.__init__(self, md)
  18. def find_quote_depth(self, line):
  19. depth = 0
  20. try:
  21. while line[0] == '>':
  22. depth += 1
  23. line = line[1:].strip()
  24. except IndexError:
  25. pass
  26. return depth
  27. def run(self, lines):
  28. clean = []
  29. quote_dept = 0
  30. for l, line in enumerate(lines):
  31. if quote_dept > self.find_quote_depth(line):
  32. clean.append("")
  33. quote_dept = self.find_quote_depth(line)
  34. try:
  35. if line.strip():
  36. at_match = QUOTE_AUTHOR_RE.match(line.strip())
  37. if at_match and lines[l + 1].strip()[0] == '>':
  38. username = '<%(token)s:quotetitle>@%(name)s</%(token)s:quotetitle>' % {'token': self.markdown.mi_token, 'name': at_match.group('username')}
  39. if at_match.group('arrows'):
  40. clean.append('> %s%s' % (at_match.group('arrows'), username))
  41. else:
  42. clean.append('> %s' % username)
  43. else:
  44. clean.append(line)
  45. else:
  46. clean.append(line)
  47. except IndexError:
  48. clean.append(line)
  49. return clean
  50. class QuoteTitlesPostprocessor(markdown.postprocessors.Postprocessor):
  51. def run(self, text):
  52. text = text.replace('&lt;%s:quotetitle&gt;' % self.markdown.mi_token, '<quotetitle>')
  53. text = text.replace('&lt;/%s:quotetitle&gt;' % self.markdown.mi_token, '</quotetitle>')
  54. lines = text.splitlines()
  55. clean = []
  56. for l, line in enumerate(lines):
  57. clean.append(line)
  58. try:
  59. if line == '<blockquote>':
  60. if lines[l + 1][0:15] != '<p><quotetitle>':
  61. clean.append('<header><quotesingletitle></header>')
  62. clean.append('<article>')
  63. if line == '</blockquote>':
  64. clean[-1] = '</article>'
  65. clean.append('</blockquote>')
  66. if line.strip()[0:15] == '<p><quotetitle>':
  67. line = line.strip()
  68. header = line[3:-4]
  69. clean[-1] = '<header>%s</header>' % header
  70. clean.append('<article>')
  71. if line[-4:] != '</p>':
  72. clean.append('<p>')
  73. except IndexError:
  74. pass
  75. return '\r\n'.join(clean).replace('<p>\r\n', '<p>')