Eliminating static calls to rewriter from strings (#7302)
[cvc5.git] / docs / ext / examples.py
1 import os
2
3 from docutils import nodes
4 from docutils.parsers.rst import Directive
5 from docutils.statemachine import StringList
6
7
8 class APIExamples(Directive):
9 """Add directive `api-examples` to be used as follows:
10
11 .. api-examples::
12 file1
13 file2
14
15 The arguments should be proper filenames to source files.
16 This directives tries to detect the language from the file extension
17 and supports the file extensions specified in `self.exts`.
18 """
19
20 # Set tab title and language for syntax highlighting
21 exts = {
22 '.cpp': {'title': 'C++', 'lang': 'c++'},
23 '.java': {'title': 'Java', 'lang': 'java'},
24 '.py': {'title': 'Python', 'lang': 'python'},
25 '.smt2': {'title': 'SMT-LIBv2', 'lang': 'smtlib'},
26 }
27
28 # The "arguments" are actually the content of the directive
29 has_content = True
30
31 def run(self):
32 # collect everything in a list of strings
33 content = ['.. tabs::', '']
34
35 for file in self.content:
36 # detect file extension
37 _, ext = os.path.splitext(file)
38 if ext in self.exts:
39 title = self.exts[ext]['title']
40 lang = self.exts[ext]['lang']
41 else:
42 title = ext
43 lang = ext
44
45 # generate tabs
46 content.append(f' .. tab:: {title}')
47 content.append(f'')
48 content.append(f' .. literalinclude:: {file}')
49 content.append(f' :language: {lang}')
50 content.append(f' :linenos:')
51
52 # parse the string list
53 node = nodes.Element()
54 self.state.nested_parse(StringList(content), 0, node)
55 return node.children
56
57
58 def setup(app):
59 app.setup_extension('sphinx_tabs.tabs')
60 app.add_directive("api-examples", APIExamples)
61 return {
62 'version': '0.1',
63 'parallel_read_safe': True,
64 'parallel_write_safe': True,
65 }