1# based on http://protips.readthedocs.io/link-roles.html
2
3#from __future__ import print_function, unicode_literals
4
5import os
6import re
7import subprocess
8from collections import namedtuple
9
10from docutils import nodes
11from sphinx.transforms.post_transforms import SphinxPostTransform
12
13URL_BASE = {
14    "zh_CN": "https://lvgl.100ask.net/"
15}
16
17class translation_link(nodes.Element):
18    """Node for "link_to_translation" role."""
19
20
21# Linking to translation is done at the "writing" stage to avoid issues with the info being cached between builders
22def link_to_translation(name, rawtext, text, lineno, inliner, options={}, content=[]):
23    node = translation_link()
24    node['expr'] = (rawtext, text, options)
25    return [node], []
26
27
28class TranslationLinkNodeTransform(SphinxPostTransform):
29    # Transform needs to happen early to ensure the new reference node is also transformed
30    default_priority = 0
31
32    def run(self, **kwargs):
33        # Only output relative links if building HTML
34        for node in self.document.traverse(translation_link):
35            if 'html' in self.app.builder.name:
36                rawtext, text, options = node['expr']
37                (language, link_text) = text.split(':')
38                env = self.document.settings.env
39                docname = env.docname
40                # doc_path = env.doc2path(docname, False)
41                if "LVGL_URLPATH" not in os.environ:
42                    os.environ['LVGL_URLPATH'] = 'master'
43                urlpath = os.getenv('LVGL_URLPATH')+'/'
44                return_path = URL_BASE.get(language, "") + urlpath
45
46                url = '{}.html'.format(os.path.join(return_path, docname))
47
48                node.replace_self(nodes.reference(rawtext, link_text, refuri=url, **options))
49            else:
50                node.replace_self([])
51
52
53def setup(app):
54
55    # link to the current documentation file in specific language version
56    app.add_role('link_to_translation', link_to_translation)
57    app.add_node(translation_link)
58    app.add_post_transform(TranslationLinkNodeTransform)
59
60    return {'parallel_read_safe': True, 'parallel_write_safe': True, 'version': '0.5'}
61