Debian Codegraph @

flask_flatpages/utils.py

raw
1 """Utility functions to render Markdown text to HTML."""
2
3 from typing import Callable, TypeVar
4 import markdown
5 from markdown.extensions import codehilite
6
7
8 from .imports import PygmentsHtmlFormatter
9
10 from io import StringIO
11
12
13 P = TypeVar("P")
14
15
16 WrappedRenderer = Callable[[P], str]
17
18
19 class NamedStringIO(StringIO, object):
20 """Subclass adding a Name to :class:`StringIO` objects."""
21
22 def __init__(self, content, name):
23 """
24 Initialise the NamedStringIO.
25
26 :param content: The string to be treated as a stream
27 :param name: The name to attach to the stream. Will
28 be consumed in e.g. ReaderErrors raised by pyyaml.
29 """
30 super().__init__(content)
31 self.name = name
32
33
34 def force_unicode(value, encoding="utf-8", errors="strict"):
35 """Convert bytes or any other Python instance to string."""
36 if isinstance(value, str):
37 return value
38 return value.decode(encoding, errors)
39
40
41 def pygmented_markdown(text: str, flatpages=None):
42 """Render Markdown text to HTML.
43
44 Uses the `CodeHilite`_ extension only if `Pygments`_ is available. If
45 `Pygments`_ is not available, "codehilite" is removed from list of
46 extensions.
47
48 If you need other extensions, set them up using the
49 ``FLATPAGES_MARKDOWN_EXTENSIONS`` setting, which should be a sequence
50 of strings or Markdown Extension objects.
51 Extensions specified with entrypoint strings should be configured using
52 ``FLATPAGES_EXTENSION_CONFIGS``.
53
54 .. _CodeHilite:
55 http://www.freewisdom.org/projects/python-markdown/CodeHilite
56 .. _Pygments: http://pygments.org/
57 """
58 if flatpages:
59 extensions = flatpages.config("markdown_extensions")
60 extension_configs = flatpages.config("extension_configs")
61 else:
62 extensions = []
63 extension_configs = {}
64 if PygmentsHtmlFormatter is None:
65 original_extensions = extensions
66 original_config = extension_configs
67 extensions = []
68 extension_configs = {}
69
70 for extension in original_extensions:
71 if isinstance(extension, str) and "codehilite" in extension:
72 continue
73 elif isinstance(extension, codehilite.CodeHiliteExtension):
74 continue
75 extensions.append(extension)
76 if isinstance(extension, str):
77 if extension in original_config:
78 extension_configs[extension] = original_config[extension]
79 elif not extensions:
80 extensions = ["codehilite"]
81 return markdown.markdown(
82 text, extensions=extensions, extension_configs=extension_configs
83 )
84
85
86 def pygments_style_defs(style: str = "default") -> str:
87 """:return: the CSS definitions for the `CodeHilite`_ Markdown plugin.
88
89 :param style: The Pygments `style`_ to use.
90
91 Only available if `Pygments`_ is.
92
93 .. _CodeHilite:
94 http://www.freewisdom.org/projects/python-markdown/CodeHilite
95 .. _Pygments: http://pygments.org/
96 .. _style: http://pygments.org/docs/styles/
97 """
98 formatter = PygmentsHtmlFormatter(style=style)
99 return formatter.get_style_defs(".codehilite")