import os
from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.parsers.rst.directives.images import Image
from sphinx.directives.code import LiteralInclude
class LvExample(Directive):
required_arguments = 3
def run(self):
example_path = self.arguments[0]
example_name = os.path.split(example_path)[1]
language = self.arguments[2]
node_list = []
env = self.state.document.settings.env
if self.arguments[2] == 'py':
paragraph_node = nodes.raw(text=f"Click to try in the simulator!", format='html')
else:
paragraph_node = nodes.raw(text=f"", format='html')
toggle = nodes.container('', literal_block=False, classes=['toggle'])
header = nodes.container('', literal_block=False, classes=['header'])
toggle.append(header)
example_file = os.path.abspath("../examples/" + example_path + "." + self.arguments[2])
try:
with open(example_file) as f:
contents = f.read()
except FileNotFoundError:
contents = 'Error encountered while trying to open ' + example_file
literal_list = nodes.literal_block(contents, contents)
literal_list['language'] = language
toggle.append(literal_list)
header.append(nodes.raw(text=f"
code view on GitHub
", format='html')) if env.app.tags.has('html'): node_list.append(paragraph_node) node_list.append(toggle) return node_list def setup(app): app.add_directive("lv_example", LvExample) app.add_config_value("repo_commit_hash", "", "env") return { 'version': '0.1', 'parallel_read_safe': True, 'parallel_write_safe': True, }