| 1 | #escape_markdown.py
|
|---|
| 2 |
|
|---|
| 3 | from django.template import Library
|
|---|
| 4 |
|
|---|
| 5 | register = Library()
|
|---|
| 6 |
|
|---|
| 7 | def escape_without_markdown_syntax(text):
|
|---|
| 8 | """ This function escapes '<', '>', '&' into text in HTML-entities
|
|---|
| 9 | For example:
|
|---|
| 10 | > > I said, give me <more> M&M's
|
|---|
| 11 | > Nobody gives you more M&M's!
|
|---|
| 12 | You are fucking greedy!
|
|---|
| 13 |
|
|---|
| 14 | Translates into
|
|---|
| 15 | > > I said, give me >more< M&M's
|
|---|
| 16 | > Nobody gives you more M&M's!
|
|---|
| 17 | ___You are fucking greedy!___
|
|---|
| 18 |
|
|---|
| 19 | After that, Markdown filter can translate it into
|
|---|
| 20 | <blockquote>
|
|---|
| 21 | <blockquote> I said, give me >more< M&M's</blockquote>
|
|---|
| 22 | <blockqoute> Nobody gives you more M&M's!</blockquote>
|
|---|
| 23 | <strong>You are fucking greedy!</strong>
|
|---|
| 24 |
|
|---|
| 25 | For correctly using this filter write "|escape_markdown" before using Markdown filter
|
|---|
| 26 | filters:
|
|---|
| 27 | And now we present you a Markdown: <fieldset>{{ text|escape_markdown|markdown }}</fieldset>
|
|---|
| 28 |
|
|---|
| 29 | Also it fixes Markdown error with backslash '\'
|
|---|
| 30 |
|
|---|
| 31 | """
|
|---|
| 32 | lines = []
|
|---|
| 33 | for s in text.split('\n'):
|
|---|
| 34 | i = 0
|
|---|
| 35 | while i < len(s) and (s[i] == ' ' or s[i] == '>') :
|
|---|
| 36 | i+=1
|
|---|
| 37 | str1 = s[0:i]
|
|---|
| 38 | str2 = s[i:]
|
|---|
| 39 | str2 = str2.replace('&','&')
|
|---|
| 40 | str2 = str2.replace('>','>')
|
|---|
| 41 | str2 = str2.replace('<','<')
|
|---|
| 42 | str2 = str2.replace('\\','\')
|
|---|
| 43 | #str2 = str2.replace('&shy;','⁠')
|
|---|
| 44 | str2 = str2.replace('&shy;','<df></df>')
|
|---|
| 45 | #str2 = str2.replace('&shy;','­')
|
|---|
| 46 | lines.append(str1 + str2)
|
|---|
| 47 | return '\n'.join(lines)
|
|---|
| 48 |
|
|---|
| 49 | register.filter('mrakdown', escape_without_markdown_syntax) # Смешная версия названия фильтра :)
|
|---|
| 50 | # It's fun version of filter name
|
|---|
| 51 | # for russians users
|
|---|
| 52 |
|
|---|
| 53 | register.filter('escape_markdown', escape_without_markdown_syntax)
|
|---|
| 54 |
|
|---|
| 55 | def delete_markdown_quoted_text(text):
|
|---|
| 56 | lines = []
|
|---|
| 57 | for s in text.split('\n'):
|
|---|
| 58 | if len(s) == 0:
|
|---|
| 59 | lines.append('')
|
|---|
| 60 | continue
|
|---|
| 61 | i = 0
|
|---|
| 62 | while i < len(s) and s[i] == ' ':
|
|---|
| 63 | i+=1
|
|---|
| 64 | if s[i] == '>':
|
|---|
| 65 | continue
|
|---|
| 66 | else:
|
|---|
| 67 | lines.append(s)
|
|---|
| 68 | return '\n'.join(lines)
|
|---|
| 69 |
|
|---|
| 70 | register.filter('delete_markdown_blockquotes', delete_markdown_quoted_text) # Смешная версия названия фильтра :)
|
|---|