We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Arbitrary rst substitutions
Since we have transforms now, it should be easy to do something generic, like this:

`|bzr-revno|` that would be replaced by the output of `bzr revno` using a configuration like

``` py
def bzr_revno():
    return subprocess.check_output(["bzr", "revno"])

RST_SUBSTITUTIONS = {
    'bzr_revno': bzr_revno
}
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `nikola/plugins/compile/rest/__init__.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 # Copyright © 2012-2016 Roberto Alsina and others.
4 
5 # Permission is hereby granted, free of charge, to any
6 # person obtaining a copy of this software and associated
7 # documentation files (the "Software"), to deal in the
8 # Software without restriction, including without limitation
9 # the rights to use, copy, modify, merge, publish,
10 # distribute, sublicense, and/or sell copies of the
11 # Software, and to permit persons to whom the Software is
12 # furnished to do so, subject to the following conditions:
13 #
14 # The above copyright notice and this permission notice
15 # shall be included in all copies or substantial portions of
16 # the Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
19 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
20 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
21 # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
22 # OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
23 # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
24 # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 
27 """reStructuredText compiler for Nikola."""
28 
29 from __future__ import unicode_literals
30 import io
31 import os
32 
33 import docutils.core
34 import docutils.nodes
35 import docutils.utils
36 import docutils.io
37 import docutils.readers.standalone
38 import docutils.writers.html4css1
39 import docutils.parsers.rst.directives
40 
41 from nikola.plugin_categories import PageCompiler
42 from nikola.utils import unicode_str, get_logger, makedirs, write_metadata, STDERR_HANDLER
43 from nikola.shortcodes import apply_shortcodes
44 
45 
46 class CompileRest(PageCompiler):
47     """Compile reStructuredText into HTML."""
48 
49     name = "rest"
50     friendly_name = "reStructuredText"
51     demote_headers = True
52     logger = None
53 
54     def _read_extra_deps(self, post):
55         """Read contents of .dep file and returns them as a list."""
56         dep_path = post.base_path + '.dep'
57         if os.path.isfile(dep_path):
58             with io.open(dep_path, 'r+', encoding='utf8') as depf:
59                 deps = [l.strip() for l in depf.readlines()]
60                 return deps
61         return []
62 
63     def register_extra_dependencies(self, post):
64         """Add dependency to post object to check .dep file."""
65         post.add_dependency(lambda: self._read_extra_deps(post), 'fragment')
66 
67     def compile_html_string(self, data, source_path=None, is_two_file=True):
68         """Compile reST into HTML strings."""
69         # If errors occur, this will be added to the line number reported by
70         # docutils so the line number matches the actual line number (off by
71         # 7 with default metadata, could be more or less depending on the post).
72         add_ln = 0
73         if not is_two_file:
74             m_data, data = self.split_metadata(data)
75             add_ln = len(m_data.splitlines()) + 1
76 
77         default_template_path = os.path.join(os.path.dirname(__file__), 'template.txt')
78         output, error_level, deps = rst2html(
79             data, settings_overrides={
80                 'initial_header_level': 1,
81                 'record_dependencies': True,
82                 'stylesheet_path': None,
83                 'link_stylesheet': True,
84                 'syntax_highlight': 'short',
85                 'math_output': 'mathjax',
86                 'template': default_template_path,
87             }, logger=self.logger, source_path=source_path, l_add_ln=add_ln, transforms=self.site.rst_transforms)
88         if not isinstance(output, unicode_str):
89             # To prevent some weird bugs here or there.
90             # Original issue: empty files.  `output` became a bytestring.
91             output = output.decode('utf-8')
92         return output, error_level, deps
93 
94     def compile_html(self, source, dest, is_two_file=True):
95         """Compile source file into HTML and save as dest."""
96         makedirs(os.path.dirname(dest))
97         error_level = 100
98         with io.open(dest, "w+", encoding="utf8") as out_file:
99             with io.open(source, "r", encoding="utf8") as in_file:
100                 data = in_file.read()
101                 output, error_level, deps = self.compile_html_string(data, source, is_two_file)
102                 output = apply_shortcodes(output, self.site.shortcode_registry, self.site, source)
103                 out_file.write(output)
104             deps_path = dest + '.dep'
105             if deps.list:
106                 deps.list = [p for p in deps.list if p != dest]  # Don't depend on yourself (#1671)
107                 with io.open(deps_path, "w+", encoding="utf8") as deps_file:
108                     deps_file.write('\n'.join(deps.list))
109             else:
110                 if os.path.isfile(deps_path):
111                     os.unlink(deps_path)
112         if error_level < 3:
113             return True
114         else:
115             return False
116 
117     def create_post(self, path, **kw):
118         """Create a new post."""
119         content = kw.pop('content', None)
120         onefile = kw.pop('onefile', False)
121         # is_page is not used by create_post as of now.
122         kw.pop('is_page', False)
123         metadata = {}
124         metadata.update(self.default_metadata)
125         metadata.update(kw)
126         makedirs(os.path.dirname(path))
127         if not content.endswith('\n'):
128             content += '\n'
129         with io.open(path, "w+", encoding="utf8") as fd:
130             if onefile:
131                 fd.write(write_metadata(metadata))
132                 fd.write('\n')
133             fd.write(content)
134 
135     def set_site(self, site):
136         """Set Nikola site."""
137         super(CompileRest, self).set_site(site)
138         self.config_dependencies = []
139         for plugin_info in self.get_compiler_extensions():
140             self.config_dependencies.append(plugin_info.name)
141             plugin_info.plugin_object.short_help = plugin_info.description
142 
143         self.logger = get_logger('compile_rest', STDERR_HANDLER)
144         if not site.debug:
145             self.logger.level = 4
146 
147 
148 def get_observer(settings):
149     """Return an observer for the docutils Reporter."""
150     def observer(msg):
151         """Report docutils/rest messages to a Nikola user.
152 
153         Error code mapping:
154 
155         +------+---------+------+----------+
156         | dNUM |   dNAME | lNUM |    lNAME |    d = docutils, l = logbook
157         +------+---------+------+----------+
158         |    0 |   DEBUG |    1 |    DEBUG |
159         |    1 |    INFO |    2 |     INFO |
160         |    2 | WARNING |    4 |  WARNING |
161         |    3 |   ERROR |    5 |    ERROR |
162         |    4 |  SEVERE |    6 | CRITICAL |
163         +------+---------+------+----------+
164         """
165         errormap = {0: 1, 1: 2, 2: 4, 3: 5, 4: 6}
166         text = docutils.nodes.Element.astext(msg)
167         line = msg['line'] + settings['add_ln'] if 'line' in msg else 0
168         out = '[{source}{colon}{line}] {text}'.format(
169             source=settings['source'], colon=(':' if line else ''),
170             line=line, text=text)
171         settings['logger'].log(errormap[msg['level']], out)
172 
173     return observer
174 
175 
176 class NikolaReader(docutils.readers.standalone.Reader):
177     """Nikola-specific docutils reader."""
178 
179     def __init__(self, *args, **kwargs):
180         """Initialize the reader."""
181         self.transforms = kwargs.pop('transforms', [])
182         docutils.readers.standalone.Reader.__init__(self, *args, **kwargs)
183 
184     def get_transforms(self):
185         """Get docutils transforms."""
186         return docutils.readers.standalone.Reader(self).get_transforms() + self.transforms
187 
188     def new_document(self):
189         """Create and return a new empty document tree (root node)."""
190         document = docutils.utils.new_document(self.source.source_path, self.settings)
191         document.reporter.stream = False
192         document.reporter.attach_observer(get_observer(self.l_settings))
193         return document
194 
195 
196 def add_node(node, visit_function=None, depart_function=None):
197     """Register a Docutils node class.
198 
199     This function is completely optional. It is a same concept as
200     `Sphinx add_node function <http://sphinx-doc.org/extdev/appapi.html#sphinx.application.Sphinx.add_node>`_.
201 
202     For example::
203 
204         class Plugin(RestExtension):
205 
206             name = "rest_math"
207 
208             def set_site(self, site):
209                 self.site = site
210                 directives.register_directive('math', MathDirective)
211                 add_node(MathBlock, visit_Math, depart_Math)
212                 return super(Plugin, self).set_site(site)
213 
214         class MathDirective(Directive):
215             def run(self):
216                 node = MathBlock()
217                 return [node]
218 
219         class Math(docutils.nodes.Element): pass
220 
221         def visit_Math(self, node):
222             self.body.append(self.starttag(node, 'math'))
223 
224         def depart_Math(self, node):
225             self.body.append('</math>')
226 
227     For full example, you can refer to `Microdata plugin <https://plugins.getnikola.com/#microdata>`_
228     """
229     docutils.nodes._add_node_class_names([node.__name__])
230     if visit_function:
231         setattr(docutils.writers.html4css1.HTMLTranslator, 'visit_' + node.__name__, visit_function)
232     if depart_function:
233         setattr(docutils.writers.html4css1.HTMLTranslator, 'depart_' + node.__name__, depart_function)
234 
235 
236 def rst2html(source, source_path=None, source_class=docutils.io.StringInput,
237              destination_path=None, reader=None,
238              parser=None, parser_name='restructuredtext', writer=None,
239              writer_name='html', settings=None, settings_spec=None,
240              settings_overrides=None, config_section=None,
241              enable_exit_status=None, logger=None, l_add_ln=0, transforms=None):
242     """Set up & run a ``Publisher``, and return a dictionary of document parts.
243 
244     Dictionary keys are the names of parts, and values are Unicode strings;
245     encoding is up to the client.  For programmatic use with string I/O.
246 
247     For encoded string input, be sure to set the 'input_encoding' setting to
248     the desired encoding.  Set it to 'unicode' for unencoded Unicode string
249     input.  Here's how::
250 
251         publish_parts(..., settings_overrides={'input_encoding': 'unicode'})
252 
253     Parameters: see `publish_programmatically`.
254 
255     WARNING: `reader` should be None (or NikolaReader()) if you want Nikola to report
256              reStructuredText syntax errors.
257     """
258     if reader is None:
259         reader = NikolaReader(transforms=transforms)
260         # For our custom logging, we have special needs and special settings we
261         # specify here.
262         # logger    a logger from Nikola
263         # source   source filename (docutils gets a string)
264         # add_ln   amount of metadata lines (see comment in compile_html above)
265         reader.l_settings = {'logger': logger, 'source': source_path,
266                              'add_ln': l_add_ln}
267 
268     pub = docutils.core.Publisher(reader, parser, writer, settings=settings,
269                                   source_class=source_class,
270                                   destination_class=docutils.io.StringOutput)
271     pub.set_components(None, parser_name, writer_name)
272     pub.process_programmatic_settings(
273         settings_spec, settings_overrides, config_section)
274     pub.set_source(source, None)
275     pub.settings._nikola_source_path = source_path
276     pub.set_destination(None, destination_path)
277     pub.publish(enable_exit_status=enable_exit_status)
278 
279     return pub.writer.parts['docinfo'] + pub.writer.parts['fragment'], pub.document.reporter.max_level, pub.settings.record_dependencies
280 
281 # Alignment helpers for extensions
282 _align_options_base = ('left', 'center', 'right')
283 
284 
285 def _align_choice(argument):
286     return docutils.parsers.rst.directives.choice(argument, _align_options_base + ("none", ""))
287
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/nikola/plugins/compile/rest/__init__.py b/nikola/plugins/compile/rest/__init__.py
--- a/nikola/plugins/compile/rest/__init__.py
+++ b/nikola/plugins/compile/rest/__init__.py
@@ -37,6 +37,7 @@
 import docutils.readers.standalone
 import docutils.writers.html4css1
 import docutils.parsers.rst.directives
+from docutils.parsers.rst import roles
 
 from nikola.plugin_categories import PageCompiler
 from nikola.utils import unicode_str, get_logger, makedirs, write_metadata, STDERR_HANDLER
@@ -193,6 +194,16 @@
         return document
 
 
+def shortcode_role(name, rawtext, text, lineno, inliner,
+                   options={}, content=[]):
+    """A shortcode role that passes through raw inline HTML."""
+    return [docutils.nodes.raw('', text, format='html')], []
+
+roles.register_canonical_role('raw-html', shortcode_role)
+roles.register_canonical_role('html', shortcode_role)
+roles.register_canonical_role('sc', shortcode_role)
+
+
 def add_node(node, visit_function=None, depart_function=None):
     """Register a Docutils node class.

{"golden_diff": "diff --git a/nikola/plugins/compile/rest/__init__.py b/nikola/plugins/compile/rest/__init__.py\n--- a/nikola/plugins/compile/rest/__init__.py\n+++ b/nikola/plugins/compile/rest/__init__.py\n@@ -37,6 +37,7 @@\n import docutils.readers.standalone\n import docutils.writers.html4css1\n import docutils.parsers.rst.directives\n+from docutils.parsers.rst import roles\n \n from nikola.plugin_categories import PageCompiler\n from nikola.utils import unicode_str, get_logger, makedirs, write_metadata, STDERR_HANDLER\n@@ -193,6 +194,16 @@\n         return document\n \n \n+def shortcode_role(name, rawtext, text, lineno, inliner,\n+                   options={}, content=[]):\n+    \"\"\"A shortcode role that passes through raw inline HTML.\"\"\"\n+    return [docutils.nodes.raw('', text, format='html')], []\n+\n+roles.register_canonical_role('raw-html', shortcode_role)\n+roles.register_canonical_role('html', shortcode_role)\n+roles.register_canonical_role('sc', shortcode_role)\n+\n+\n def add_node(node, visit_function=None, depart_function=None):\n     \"\"\"Register a Docutils node class.\n", "issue": "Arbitrary rst substitutions\nSince we have transforms now, it should be easy to do something generic, like this:\n\n`|bzr-revno|` that would be replaced by the output of `bzr revno` using a configuration like\n\n``` py\ndef bzr_revno():\n    return subprocess.check_output([\"bzr\", \"revno\"])\n\nRST_SUBSTITUTIONS = {\n    'bzr_revno': bzr_revno\n}\n```\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Copyright \u00a9 2012-2016 Roberto Alsina and others.\n\n# Permission is hereby granted, free of charge, to any\n# person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the\n# Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the\n# Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice\n# shall be included in all copies or substantial portions of\n# the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\"\"reStructuredText compiler for Nikola.\"\"\"\n\nfrom __future__ import unicode_literals\nimport io\nimport os\n\nimport docutils.core\nimport docutils.nodes\nimport docutils.utils\nimport docutils.io\nimport docutils.readers.standalone\nimport docutils.writers.html4css1\nimport docutils.parsers.rst.directives\n\nfrom nikola.plugin_categories import PageCompiler\nfrom nikola.utils import unicode_str, get_logger, makedirs, write_metadata, STDERR_HANDLER\nfrom nikola.shortcodes import apply_shortcodes\n\n\nclass CompileRest(PageCompiler):\n    \"\"\"Compile reStructuredText into HTML.\"\"\"\n\n    name = \"rest\"\n    friendly_name = \"reStructuredText\"\n    demote_headers = True\n    logger = None\n\n    def _read_extra_deps(self, post):\n        \"\"\"Read contents of .dep file and returns them as a list.\"\"\"\n        dep_path = post.base_path + '.dep'\n        if os.path.isfile(dep_path):\n            with io.open(dep_path, 'r+', encoding='utf8') as depf:\n                deps = [l.strip() for l in depf.readlines()]\n                return deps\n        return []\n\n    def register_extra_dependencies(self, post):\n        \"\"\"Add dependency to post object to check .dep file.\"\"\"\n        post.add_dependency(lambda: self._read_extra_deps(post), 'fragment')\n\n    def compile_html_string(self, data, source_path=None, is_two_file=True):\n        \"\"\"Compile reST into HTML strings.\"\"\"\n        # If errors occur, this will be added to the line number reported by\n        # docutils so the line number matches the actual line number (off by\n        # 7 with default metadata, could be more or less depending on the post).\n        add_ln = 0\n        if not is_two_file:\n            m_data, data = self.split_metadata(data)\n            add_ln = len(m_data.splitlines()) + 1\n\n        default_template_path = os.path.join(os.path.dirname(__file__), 'template.txt')\n        output, error_level, deps = rst2html(\n            data, settings_overrides={\n                'initial_header_level': 1,\n                'record_dependencies': True,\n                'stylesheet_path': None,\n                'link_stylesheet': True,\n                'syntax_highlight': 'short',\n                'math_output': 'mathjax',\n                'template': default_template_path,\n            }, logger=self.logger, source_path=source_path, l_add_ln=add_ln, transforms=self.site.rst_transforms)\n        if not isinstance(output, unicode_str):\n            # To prevent some weird bugs here or there.\n            # Original issue: empty files.  `output` became a bytestring.\n            output = output.decode('utf-8')\n        return output, error_level, deps\n\n    def compile_html(self, source, dest, is_two_file=True):\n        \"\"\"Compile source file into HTML and save as dest.\"\"\"\n        makedirs(os.path.dirname(dest))\n        error_level = 100\n        with io.open(dest, \"w+\", encoding=\"utf8\") as out_file:\n            with io.open(source, \"r\", encoding=\"utf8\") as in_file:\n                data = in_file.read()\n                output, error_level, deps = self.compile_html_string(data, source, is_two_file)\n                output = apply_shortcodes(output, self.site.shortcode_registry, self.site, source)\n                out_file.write(output)\n            deps_path = dest + '.dep'\n            if deps.list:\n                deps.list = [p for p in deps.list if p != dest]  # Don't depend on yourself (#1671)\n                with io.open(deps_path, \"w+\", encoding=\"utf8\") as deps_file:\n                    deps_file.write('\\n'.join(deps.list))\n            else:\n                if os.path.isfile(deps_path):\n                    os.unlink(deps_path)\n        if error_level < 3:\n            return True\n        else:\n            return False\n\n    def create_post(self, path, **kw):\n        \"\"\"Create a new post.\"\"\"\n        content = kw.pop('content', None)\n        onefile = kw.pop('onefile', False)\n        # is_page is not used by create_post as of now.\n        kw.pop('is_page', False)\n        metadata = {}\n        metadata.update(self.default_metadata)\n        metadata.update(kw)\n        makedirs(os.path.dirname(path))\n        if not content.endswith('\\n'):\n            content += '\\n'\n        with io.open(path, \"w+\", encoding=\"utf8\") as fd:\n            if onefile:\n                fd.write(write_metadata(metadata))\n                fd.write('\\n')\n            fd.write(content)\n\n    def set_site(self, site):\n        \"\"\"Set Nikola site.\"\"\"\n        super(CompileRest, self).set_site(site)\n        self.config_dependencies = []\n        for plugin_info in self.get_compiler_extensions():\n            self.config_dependencies.append(plugin_info.name)\n            plugin_info.plugin_object.short_help = plugin_info.description\n\n        self.logger = get_logger('compile_rest', STDERR_HANDLER)\n        if not site.debug:\n            self.logger.level = 4\n\n\ndef get_observer(settings):\n    \"\"\"Return an observer for the docutils Reporter.\"\"\"\n    def observer(msg):\n        \"\"\"Report docutils/rest messages to a Nikola user.\n\n        Error code mapping:\n\n        +------+---------+------+----------+\n        | dNUM |   dNAME | lNUM |    lNAME |    d = docutils, l = logbook\n        +------+---------+------+----------+\n        |    0 |   DEBUG |    1 |    DEBUG |\n        |    1 |    INFO |    2 |     INFO |\n        |    2 | WARNING |    4 |  WARNING |\n        |    3 |   ERROR |    5 |    ERROR |\n        |    4 |  SEVERE |    6 | CRITICAL |\n        +------+---------+------+----------+\n        \"\"\"\n        errormap = {0: 1, 1: 2, 2: 4, 3: 5, 4: 6}\n        text = docutils.nodes.Element.astext(msg)\n        line = msg['line'] + settings['add_ln'] if 'line' in msg else 0\n        out = '[{source}{colon}{line}] {text}'.format(\n            source=settings['source'], colon=(':' if line else ''),\n            line=line, text=text)\n        settings['logger'].log(errormap[msg['level']], out)\n\n    return observer\n\n\nclass NikolaReader(docutils.readers.standalone.Reader):\n    \"\"\"Nikola-specific docutils reader.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Initialize the reader.\"\"\"\n        self.transforms = kwargs.pop('transforms', [])\n        docutils.readers.standalone.Reader.__init__(self, *args, **kwargs)\n\n    def get_transforms(self):\n        \"\"\"Get docutils transforms.\"\"\"\n        return docutils.readers.standalone.Reader(self).get_transforms() + self.transforms\n\n    def new_document(self):\n        \"\"\"Create and return a new empty document tree (root node).\"\"\"\n        document = docutils.utils.new_document(self.source.source_path, self.settings)\n        document.reporter.stream = False\n        document.reporter.attach_observer(get_observer(self.l_settings))\n        return document\n\n\ndef add_node(node, visit_function=None, depart_function=None):\n    \"\"\"Register a Docutils node class.\n\n    This function is completely optional. It is a same concept as\n    `Sphinx add_node function <http://sphinx-doc.org/extdev/appapi.html#sphinx.application.Sphinx.add_node>`_.\n\n    For example::\n\n        class Plugin(RestExtension):\n\n            name = \"rest_math\"\n\n            def set_site(self, site):\n                self.site = site\n                directives.register_directive('math', MathDirective)\n                add_node(MathBlock, visit_Math, depart_Math)\n                return super(Plugin, self).set_site(site)\n\n        class MathDirective(Directive):\n            def run(self):\n                node = MathBlock()\n                return [node]\n\n        class Math(docutils.nodes.Element): pass\n\n        def visit_Math(self, node):\n            self.body.append(self.starttag(node, 'math'))\n\n        def depart_Math(self, node):\n            self.body.append('</math>')\n\n    For full example, you can refer to `Microdata plugin <https://plugins.getnikola.com/#microdata>`_\n    \"\"\"\n    docutils.nodes._add_node_class_names([node.__name__])\n    if visit_function:\n        setattr(docutils.writers.html4css1.HTMLTranslator, 'visit_' + node.__name__, visit_function)\n    if depart_function:\n        setattr(docutils.writers.html4css1.HTMLTranslator, 'depart_' + node.__name__, depart_function)\n\n\ndef rst2html(source, source_path=None, source_class=docutils.io.StringInput,\n             destination_path=None, reader=None,\n             parser=None, parser_name='restructuredtext', writer=None,\n             writer_name='html', settings=None, settings_spec=None,\n             settings_overrides=None, config_section=None,\n             enable_exit_status=None, logger=None, l_add_ln=0, transforms=None):\n    \"\"\"Set up & run a ``Publisher``, and return a dictionary of document parts.\n\n    Dictionary keys are the names of parts, and values are Unicode strings;\n    encoding is up to the client.  For programmatic use with string I/O.\n\n    For encoded string input, be sure to set the 'input_encoding' setting to\n    the desired encoding.  Set it to 'unicode' for unencoded Unicode string\n    input.  Here's how::\n\n        publish_parts(..., settings_overrides={'input_encoding': 'unicode'})\n\n    Parameters: see `publish_programmatically`.\n\n    WARNING: `reader` should be None (or NikolaReader()) if you want Nikola to report\n             reStructuredText syntax errors.\n    \"\"\"\n    if reader is None:\n        reader = NikolaReader(transforms=transforms)\n        # For our custom logging, we have special needs and special settings we\n        # specify here.\n        # logger    a logger from Nikola\n        # source   source filename (docutils gets a string)\n        # add_ln   amount of metadata lines (see comment in compile_html above)\n        reader.l_settings = {'logger': logger, 'source': source_path,\n                             'add_ln': l_add_ln}\n\n    pub = docutils.core.Publisher(reader, parser, writer, settings=settings,\n                                  source_class=source_class,\n                                  destination_class=docutils.io.StringOutput)\n    pub.set_components(None, parser_name, writer_name)\n    pub.process_programmatic_settings(\n        settings_spec, settings_overrides, config_section)\n    pub.set_source(source, None)\n    pub.settings._nikola_source_path = source_path\n    pub.set_destination(None, destination_path)\n    pub.publish(enable_exit_status=enable_exit_status)\n\n    return pub.writer.parts['docinfo'] + pub.writer.parts['fragment'], pub.document.reporter.max_level, pub.settings.record_dependencies\n\n# Alignment helpers for extensions\n_align_options_base = ('left', 'center', 'right')\n\n\ndef _align_choice(argument):\n    return docutils.parsers.rst.directives.choice(argument, _align_options_base + (\"none\", \"\"))\n", "path": "nikola/plugins/compile/rest/__init__.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Copyright \u00a9 2012-2016 Roberto Alsina and others.\n\n# Permission is hereby granted, free of charge, to any\n# person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the\n# Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the\n# Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice\n# shall be included in all copies or substantial portions of\n# the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\"\"reStructuredText compiler for Nikola.\"\"\"\n\nfrom __future__ import unicode_literals\nimport io\nimport os\n\nimport docutils.core\nimport docutils.nodes\nimport docutils.utils\nimport docutils.io\nimport docutils.readers.standalone\nimport docutils.writers.html4css1\nimport docutils.parsers.rst.directives\nfrom docutils.parsers.rst import roles\n\nfrom nikola.plugin_categories import PageCompiler\nfrom nikola.utils import unicode_str, get_logger, makedirs, write_metadata, STDERR_HANDLER\nfrom nikola.shortcodes import apply_shortcodes\n\n\nclass CompileRest(PageCompiler):\n    \"\"\"Compile reStructuredText into HTML.\"\"\"\n\n    name = \"rest\"\n    friendly_name = \"reStructuredText\"\n    demote_headers = True\n    logger = None\n\n    def _read_extra_deps(self, post):\n        \"\"\"Read contents of .dep file and returns them as a list.\"\"\"\n        dep_path = post.base_path + '.dep'\n        if os.path.isfile(dep_path):\n            with io.open(dep_path, 'r+', encoding='utf8') as depf:\n                deps = [l.strip() for l in depf.readlines()]\n                return deps\n        return []\n\n    def register_extra_dependencies(self, post):\n        \"\"\"Add dependency to post object to check .dep file.\"\"\"\n        post.add_dependency(lambda: self._read_extra_deps(post), 'fragment')\n\n    def compile_html_string(self, data, source_path=None, is_two_file=True):\n        \"\"\"Compile reST into HTML strings.\"\"\"\n        # If errors occur, this will be added to the line number reported by\n        # docutils so the line number matches the actual line number (off by\n        # 7 with default metadata, could be more or less depending on the post).\n        add_ln = 0\n        if not is_two_file:\n            m_data, data = self.split_metadata(data)\n            add_ln = len(m_data.splitlines()) + 1\n\n        default_template_path = os.path.join(os.path.dirname(__file__), 'template.txt')\n        output, error_level, deps = rst2html(\n            data, settings_overrides={\n                'initial_header_level': 1,\n                'record_dependencies': True,\n                'stylesheet_path': None,\n                'link_stylesheet': True,\n                'syntax_highlight': 'short',\n                'math_output': 'mathjax',\n                'template': default_template_path,\n            }, logger=self.logger, source_path=source_path, l_add_ln=add_ln, transforms=self.site.rst_transforms)\n        if not isinstance(output, unicode_str):\n            # To prevent some weird bugs here or there.\n            # Original issue: empty files.  `output` became a bytestring.\n            output = output.decode('utf-8')\n        return output, error_level, deps\n\n    def compile_html(self, source, dest, is_two_file=True):\n        \"\"\"Compile source file into HTML and save as dest.\"\"\"\n        makedirs(os.path.dirname(dest))\n        error_level = 100\n        with io.open(dest, \"w+\", encoding=\"utf8\") as out_file:\n            with io.open(source, \"r\", encoding=\"utf8\") as in_file:\n                data = in_file.read()\n                output, error_level, deps = self.compile_html_string(data, source, is_two_file)\n                output = apply_shortcodes(output, self.site.shortcode_registry, self.site, source)\n                out_file.write(output)\n            deps_path = dest + '.dep'\n            if deps.list:\n                deps.list = [p for p in deps.list if p != dest]  # Don't depend on yourself (#1671)\n                with io.open(deps_path, \"w+\", encoding=\"utf8\") as deps_file:\n                    deps_file.write('\\n'.join(deps.list))\n            else:\n                if os.path.isfile(deps_path):\n                    os.unlink(deps_path)\n        if error_level < 3:\n            return True\n        else:\n            return False\n\n    def create_post(self, path, **kw):\n        \"\"\"Create a new post.\"\"\"\n        content = kw.pop('content', None)\n        onefile = kw.pop('onefile', False)\n        # is_page is not used by create_post as of now.\n        kw.pop('is_page', False)\n        metadata = {}\n        metadata.update(self.default_metadata)\n        metadata.update(kw)\n        makedirs(os.path.dirname(path))\n        if not content.endswith('\\n'):\n            content += '\\n'\n        with io.open(path, \"w+\", encoding=\"utf8\") as fd:\n            if onefile:\n                fd.write(write_metadata(metadata))\n                fd.write('\\n')\n            fd.write(content)\n\n    def set_site(self, site):\n        \"\"\"Set Nikola site.\"\"\"\n        super(CompileRest, self).set_site(site)\n        self.config_dependencies = []\n        for plugin_info in self.get_compiler_extensions():\n            self.config_dependencies.append(plugin_info.name)\n            plugin_info.plugin_object.short_help = plugin_info.description\n\n        self.logger = get_logger('compile_rest', STDERR_HANDLER)\n        if not site.debug:\n            self.logger.level = 4\n\n\ndef get_observer(settings):\n    \"\"\"Return an observer for the docutils Reporter.\"\"\"\n    def observer(msg):\n        \"\"\"Report docutils/rest messages to a Nikola user.\n\n        Error code mapping:\n\n        +------+---------+------+----------+\n        | dNUM |   dNAME | lNUM |    lNAME |    d = docutils, l = logbook\n        +------+---------+------+----------+\n        |    0 |   DEBUG |    1 |    DEBUG |\n        |    1 |    INFO |    2 |     INFO |\n        |    2 | WARNING |    4 |  WARNING |\n        |    3 |   ERROR |    5 |    ERROR |\n        |    4 |  SEVERE |    6 | CRITICAL |\n        +------+---------+------+----------+\n        \"\"\"\n        errormap = {0: 1, 1: 2, 2: 4, 3: 5, 4: 6}\n        text = docutils.nodes.Element.astext(msg)\n        line = msg['line'] + settings['add_ln'] if 'line' in msg else 0\n        out = '[{source}{colon}{line}] {text}'.format(\n            source=settings['source'], colon=(':' if line else ''),\n            line=line, text=text)\n        settings['logger'].log(errormap[msg['level']], out)\n\n    return observer\n\n\nclass NikolaReader(docutils.readers.standalone.Reader):\n    \"\"\"Nikola-specific docutils reader.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Initialize the reader.\"\"\"\n        self.transforms = kwargs.pop('transforms', [])\n        docutils.readers.standalone.Reader.__init__(self, *args, **kwargs)\n\n    def get_transforms(self):\n        \"\"\"Get docutils transforms.\"\"\"\n        return docutils.readers.standalone.Reader(self).get_transforms() + self.transforms\n\n    def new_document(self):\n        \"\"\"Create and return a new empty document tree (root node).\"\"\"\n        document = docutils.utils.new_document(self.source.source_path, self.settings)\n        document.reporter.stream = False\n        document.reporter.attach_observer(get_observer(self.l_settings))\n        return document\n\n\ndef shortcode_role(name, rawtext, text, lineno, inliner,\n                   options={}, content=[]):\n    \"\"\"A shortcode role that passes through raw inline HTML.\"\"\"\n    return [docutils.nodes.raw('', text, format='html')], []\n\nroles.register_canonical_role('raw-html', shortcode_role)\nroles.register_canonical_role('html', shortcode_role)\nroles.register_canonical_role('sc', shortcode_role)\n\n\ndef add_node(node, visit_function=None, depart_function=None):\n    \"\"\"Register a Docutils node class.\n\n    This function is completely optional. It is a same concept as\n    `Sphinx add_node function <http://sphinx-doc.org/extdev/appapi.html#sphinx.application.Sphinx.add_node>`_.\n\n    For example::\n\n        class Plugin(RestExtension):\n\n            name = \"rest_math\"\n\n            def set_site(self, site):\n                self.site = site\n                directives.register_directive('math', MathDirective)\n                add_node(MathBlock, visit_Math, depart_Math)\n                return super(Plugin, self).set_site(site)\n\n        class MathDirective(Directive):\n            def run(self):\n                node = MathBlock()\n                return [node]\n\n        class Math(docutils.nodes.Element): pass\n\n        def visit_Math(self, node):\n            self.body.append(self.starttag(node, 'math'))\n\n        def depart_Math(self, node):\n            self.body.append('</math>')\n\n    For full example, you can refer to `Microdata plugin <https://plugins.getnikola.com/#microdata>`_\n    \"\"\"\n    docutils.nodes._add_node_class_names([node.__name__])\n    if visit_function:\n        setattr(docutils.writers.html4css1.HTMLTranslator, 'visit_' + node.__name__, visit_function)\n    if depart_function:\n        setattr(docutils.writers.html4css1.HTMLTranslator, 'depart_' + node.__name__, depart_function)\n\n\ndef rst2html(source, source_path=None, source_class=docutils.io.StringInput,\n             destination_path=None, reader=None,\n             parser=None, parser_name='restructuredtext', writer=None,\n             writer_name='html', settings=None, settings_spec=None,\n             settings_overrides=None, config_section=None,\n             enable_exit_status=None, logger=None, l_add_ln=0, transforms=None):\n    \"\"\"Set up & run a ``Publisher``, and return a dictionary of document parts.\n\n    Dictionary keys are the names of parts, and values are Unicode strings;\n    encoding is up to the client.  For programmatic use with string I/O.\n\n    For encoded string input, be sure to set the 'input_encoding' setting to\n    the desired encoding.  Set it to 'unicode' for unencoded Unicode string\n    input.  Here's how::\n\n        publish_parts(..., settings_overrides={'input_encoding': 'unicode'})\n\n    Parameters: see `publish_programmatically`.\n\n    WARNING: `reader` should be None (or NikolaReader()) if you want Nikola to report\n             reStructuredText syntax errors.\n    \"\"\"\n    if reader is None:\n        reader = NikolaReader(transforms=transforms)\n        # For our custom logging, we have special needs and special settings we\n        # specify here.\n        # logger    a logger from Nikola\n        # source   source filename (docutils gets a string)\n        # add_ln   amount of metadata lines (see comment in compile_html above)\n        reader.l_settings = {'logger': logger, 'source': source_path,\n                             'add_ln': l_add_ln}\n\n    pub = docutils.core.Publisher(reader, parser, writer, settings=settings,\n                                  source_class=source_class,\n                                  destination_class=docutils.io.StringOutput)\n    pub.set_components(None, parser_name, writer_name)\n    pub.process_programmatic_settings(\n        settings_spec, settings_overrides, config_section)\n    pub.set_source(source, None)\n    pub.settings._nikola_source_path = source_path\n    pub.set_destination(None, destination_path)\n    pub.publish(enable_exit_status=enable_exit_status)\n\n    return pub.writer.parts['docinfo'] + pub.writer.parts['fragment'], pub.document.reporter.max_level, pub.settings.record_dependencies\n\n# Alignment helpers for extensions\n_align_options_base = ('left', 'center', 'right')\n\n\ndef _align_choice(argument):\n    return docutils.parsers.rst.directives.choice(argument, _align_options_base + (\"none\", \"\"))\n", "path": "nikola/plugins/compile/rest/__init__.py"}]}