Debian Codegraph @

markupfield/markup.py

raw symbols SCIP
1 from functools import partial
2 from django.utils.html import escape, linebreaks, urlize
3 from django.utils.translation import pgettext_lazy as _
4 from django.conf import settings
5
6 # build DEFAULT_MARKUP_TYPES
7 DEFAULT_MARKUP_TYPES = [
8 ("html", lambda markup: markup, _("django-markupfield", "HTML")),
9 (
10 "plain",
11 lambda markup: linebreaks(urlize(escape(markup))),
12 _("django-markupfield", "Plain"),
13 ),
14 ]
15
16 try:
17 import pygments # noqa
18
19 PYGMENTS_INSTALLED = True
20
21 def _register_pygments_rst_directive():
22 from docutils import nodes
23 from docutils.parsers.rst import directives
24 from pygments import highlight
25 from pygments.lexers import get_lexer_by_name, TextLexer
26 from pygments.formatters import HtmlFormatter
27
28 DEFAULT = HtmlFormatter()
29 VARIANTS = {
30 "linenos": HtmlFormatter(linenos=True),
31 }
32
33 def pygments_directive(
34 name,
35 arguments,
36 options,
37 content,
38 lineno,
39 content_offset,
40 block_text,
41 state,
42 state_machine,
43 ):
44 try:
45 lexer = get_lexer_by_name(arguments[0])
46 except ValueError:
47 # no lexer found - use the text one instead of an exception
48 lexer = TextLexer()
49 formatter = options and VARIANTS[options.keys()[0]] or DEFAULT
50 parsed = highlight(u"\n".join(content), lexer, formatter)
51 return [nodes.raw("", parsed, format="html")]
52
53 pygments_directive.arguments = (1, 0, 1)
54 pygments_directive.content = 1
55 directives.register_directive("code", pygments_directive)
56
57
58 except ImportError:
59 PYGMENTS_INSTALLED = False
60
61 try:
62 import markdown
63
64 md_filter = markdown.markdown
65
66 # try and replace if pygments & codehilite are available
67 if PYGMENTS_INSTALLED:
68 try:
69 from markdown.extensions.codehilite import makeExtension # noqa
70
71 md_filter = partial(
72 markdown.markdown, extensions=[makeExtension(css_class="highlight")]
73 )
74 except ImportError:
75 pass
76
77 # whichever markdown_filter was available
78 DEFAULT_MARKUP_TYPES.append(
79 ("markdown", md_filter, _("django-markupfield", "Markdown"))
80 )
81
82 except ImportError:
83 pass
84
85 try:
86 from docutils.core import publish_parts
87
88 if PYGMENTS_INSTALLED:
89 _register_pygments_rst_directive()
90
91 def render_rest(markup):
92 overrides = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {})
93 overrides.update({"raw_enabled": False, "file_insertion_enabled": False})
94 parts = publish_parts(
95 source=markup, writer_name="html4css1", settings_overrides=overrides
96 )
97 return parts["fragment"]
98
99 DEFAULT_MARKUP_TYPES.append(
100 ("restructuredtext", render_rest, _("django-markupfield", "Restructured Text"))
101 )
102 except ImportError:
103 pass