Files
documentation/extensions/switcher/__init__.py
T

66 lines
1.9 KiB
Python
Raw Normal View History

2021-04-30 12:40:29 +02:00
import os.path
from docutils import nodes
2015-07-08 13:24:24 +02:00
from docutils.parsers.rst import Directive
from pygments.lexers import get_lexer_by_name
2021-04-30 12:40:29 +02:00
2015-07-08 13:24:24 +02:00
def setup(app):
app.add_directive('switcher', SwitcherDirective)
app.add_directive('case', CaseDirective)
2021-04-30 12:40:29 +02:00
app.connect('env-updated', add_statics)
return {
2021-05-12 13:22:41 +02:00
'parallel_read_safe': True,
2021-04-30 12:40:29 +02:00
'parallel_write_safe': True
}
def add_statics(app, env):
app.add_js_file('js/switcher.js')
env.config.html_static_path.append(statics())
statics = lambda *p: os.path.join(
os.path.abspath(os.path.dirname(__file__)),
'static', *p)
2015-07-08 13:24:24 +02:00
class SwitcherDirective(Directive):
has_content = True
def run(self):
self.assert_has_content()
2021-04-30 12:40:29 +02:00
body = nodes.compound('\n'.join(self.content), classes=['tab-content'])
2015-07-08 13:24:24 +02:00
self.state.nested_parse(self.content, self.content_offset, body)
titles = []
for child in body.children:
if isinstance(child, nodes.literal_block):
titles.append(get_lexer_by_name(child['language']).name)
else:
2021-04-30 12:40:29 +02:00
assert child['names'], (
"A switcher case must be either a code block or a compound with a name"
)
2015-07-08 13:24:24 +02:00
titles.append(' '.join(child['names']))
tabs = nodes.bullet_list('', *[
2021-04-30 12:40:29 +02:00
nodes.list_item('', nodes.Text(title), classes=['nav-link'])
2015-07-08 13:24:24 +02:00
for title in titles
2021-04-30 12:40:29 +02:00
], classes=['nav nav-tabs'] )
2015-07-08 13:24:24 +02:00
node = nodes.compound('', tabs, body, classes=['content-switcher'])
return [node]
2021-04-30 12:40:29 +02:00
2015-07-08 13:24:24 +02:00
class CaseDirective(Directive):
required_arguments = 1
final_argument_whitespace = True
has_content = True
def run(self):
self.assert_has_content()
node = nodes.compound('\n'.join(self.content), names=[self.arguments[0]])
self.state.nested_parse(self.content, self.content_offset, node)
return [node]