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 | lines.append(str1 + str2)
|
---|
44 | return '\n'.join(lines)
|
---|
45 |
|
---|
46 | register.filter('mrakdown', escape_without_markdown_syntax) # Смешная версия названия фильтра :)
|
---|
47 | # It's fun version of filter name
|
---|
48 | # for russians users
|
---|
49 |
|
---|
50 | register.filter('escape_markdown', escape_without_markdown_syntax)
|
---|
51 |
|
---|
52 |
|
---|
53 | def delete_markdown_quoted_text(text):
|
---|
54 | lines = []
|
---|
55 | for s in text.split('\n'):
|
---|
56 | if len(s) == 0:
|
---|
57 | lines.append('')
|
---|
58 | continue
|
---|
59 | i = 0
|
---|
60 | while i < len(s) and s[i] == ' ':
|
---|
61 | i+=1
|
---|
62 | if s[i] == '>':
|
---|
63 | continue
|
---|
64 | else:
|
---|
65 | lines.append(s)
|
---|
66 | return '\n'.join(lines)
|
---|
67 |
|
---|
68 | register.filter('delete_markdown_blockquotes', delete_markdown_quoted_text)
|
---|