Example #1
0
def pub(s):
    directives.register_directive('sc', code_block)
    overrides = {'input_encoding': default_enc
        , 'output_encoding': default_enc
        }
    return publish_parts(s, writer_name='html'
            , settings_overrides=overrides)
Example #2
0
def setup(app):
    directives.register_directive('cond', Cond)

    return {
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }
    def test_directive_basic(self):

        # test directive html output with default template
        # and settings

        directives.register_directive('unitywebgl', UnityWebgl)

        config.GAMES_ROOT_DIR = '/test_games_root'
        config.TEMPLATE_PATH = '/test_template_path/template'
        config.DEFAULT_WIDTH = 960
        config.DEFAULT_HEIGHT = 600

        html =['<link rel="stylesheet" href="/test_template_path/template/style.css">',
        '<script src="/test_template_path/template/UnityProgress.js">',
        '<script src="/test_games_root/testgame/Build/UnityLoader.js">',
        '<script>\n        var gameInstance = UnityLoader.instantiate("gameContainer", "/test_games_root/testgame/Build/testgame.json", {onProgress: UnityProgress});\n    </script>',
        '<div id="gameContainer" style="width: 960px; height: 600px; left: 50%; transform: translateX(-50%);"></div>']

        res = publish_string('.. unitywebgl:: testgame', writer_name='html', settings_overrides={'output_encoding': 'unicode'})

        passed = True

        for line in html:
            if line not in res:
                passed = False
                break

        assert passed
Example #4
0
    def rst(cls, source, safe=True):
        source = safe_unicode(source)
        try:
            from docutils.core import publish_parts
            from docutils.parsers.rst import directives
            docutils_settings = dict([(alias, None) for alias in
                                cls.RESTRUCTUREDTEXT_DISALLOWED_DIRECTIVES])

            docutils_settings.update({'input_encoding': 'unicode',
                                      'report_level': 4})

            for k, v in docutils_settings.iteritems():
                directives.register_directive(k, v)

            parts = publish_parts(source=source,
                                  writer_name="html4css1",
                                  settings_overrides=docutils_settings)

            return parts['html_title'] + parts["fragment"]
        except ImportError:
            log.warning('Install docutils to use this function')
            return cls.plain(source)
        except Exception:
            log.error(traceback.format_exc())
            if safe:
                return source
            else:
                raise
def setup():
    VARIANTS = {}
    pygments_directive.arguments = (0, 1, False)
    pygments_directive.content = 1
    pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS])
    directives.register_directive("sourcecode", pygments_directive)
    directives.register_directive("code-block", pygments_directive)
Example #6
0
def setup(app):
    app.connect("builder-inited", run_autoapi)
    app.connect("doctree-read", doctree_read)
    app.connect("doctree-resolved", add_domain_to_toctree)
    app.connect("build-finished", build_finished)
    app.connect("env-updated", clear_env)
    if sphinx.version_info >= (1, 8):
        if "viewcode-find-source" in app.events.events:
            app.connect("viewcode-find-source", viewcode_find)
        if "viewcode-follow-imported" in app.events.events:
            app.connect("viewcode-follow-imported", viewcode_follow_imported)
    app.add_config_value("autoapi_type", "python", "html")
    app.add_config_value("autoapi_root", API_ROOT, "html")
    app.add_config_value("autoapi_ignore", [], "html")
    app.add_config_value("autoapi_options", default_options, "html")
    app.add_config_value("autoapi_file_patterns", None, "html")
    app.add_config_value("autoapi_dirs", [], "html")
    app.add_config_value("autoapi_keep_files", False, "html")
    app.add_config_value("autoapi_add_toctree_entry", True, "html")
    app.add_config_value("autoapi_template_dir", None, "html")
    app.add_config_value("autoapi_include_summaries", False, "html")
    app.add_config_value("autoapi_python_class_content", "class", "html")
    app.add_config_value("autoapi_generate_api_docs", True, "html")
    app.add_autodocumenter(documenters.AutoapiFunctionDocumenter)
    app.add_autodocumenter(documenters.AutoapiClassDocumenter)
    app.add_autodocumenter(documenters.AutoapiMethodDocumenter)
    app.add_autodocumenter(documenters.AutoapiDataDocumenter)
    app.add_autodocumenter(documenters.AutoapiAttributeDocumenter)
    app.add_autodocumenter(documenters.AutoapiModuleDocumenter)
    app.add_autodocumenter(documenters.AutoapiExceptionDocumenter)
    directives.register_directive("autoapi-nested-parse", NestedParse)
    directives.register_directive("autoapisummary", AutoapiSummary)
    app.setup_extension("sphinx.ext.autosummary")
    def test_post_parse_sn_youtube(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        directives.register_directive("youtube", YoutubeDirective)
def setup(app):
    directives.register_directive('openapi', OpenAPIDirective)

    return {
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }
Example #9
0
 def set_site(self, site):
     """Set Nikola site."""
     global _site
     _site = self.site = site
     directives.register_directive('chart', Chart)
     self.site.register_shortcode('chart', _gen_chart)
     return super(Plugin, self).set_site(site)
Example #10
0
    def test_post_parse(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        directives.register_directive("runpython", RunPythonDirective)
Example #11
0
 def set_site(self, site):
     """Set Nikola site."""
     self.site = site
     directives.register_directive('post-list', PostListDirective)
     directives.register_directive('post_list', PostListDirective)
     PostListDirective.site = site
     return super(Plugin, self).set_site(site)
Example #12
0
    def test_post_list(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        # the test will fail if you add a file in data/blog others
        # with rst files which is not a blog post

        directives.register_directive("blogpost", BlogPostDirective)

        path = os.path.abspath(os.path.split(__file__)[0])
        fold = os.path.join(path, "data", "blog")
        out = get_temp_folder(__file__, "temp_post_list")
        p = BlogPostList(fold)
        cats = p.get_categories()
        fLOG(cats)
        months = p.get_months()
        fLOG(months)
        assert cats == ['documentation', 'example']
        assert months == ['2015-04']

        res = p.write_aggregated(out)
        assert len(res) >= 4
        for r in res:
            assert os.path.exists(r)
Example #13
0
 def register_global_directives(self):
     if self.registered:
         return
     self.registered = True
     
     rst_directives.register_directive('write-all',
         self.write_all_directive())
Example #14
0
def setup(app):
    # type: (Sphinx) -> None
    directives.register_directive('highlight', Highlight)
    directives.register_directive('highlightlang', Highlight)  # old
    directives.register_directive('code-block', CodeBlock)
    directives.register_directive('sourcecode', CodeBlock)
    directives.register_directive('literalinclude', LiteralInclude)
    def test_post_parse_sn(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        directives.register_directive("video", VideoDirective)
Example #16
0
 def run(self):
     from wikir import publish_file
     for ep in pkg_resources.iter_entry_points('wikir.rst_directives'):
         log.info("registering RST directive: %s", str(ep))
         directives.register_directive(ep.name, ep.load())
     # from docutils.core import publish_file
     publish_file(self.input)
Example #17
0
 def add_description_unit(self, directivename, rolename, indextemplate='',
                          parse_node=None, ref_nodeclass=None):
     additional_xref_types[directivename] = (rolename, indextemplate, parse_node)
     directives.register_directive(directivename, desc_directive)
     roles.register_canonical_role(rolename, xfileref_role)
     if ref_nodeclass is not None:
         innernodetypes[rolename] = ref_nodeclass
    def test_post_list(self):
        # the test will fail if you add a file in data/blog others
        # with rst files which is not a blog post

        directives.register_directive("blogpost", BlogPostDirective)

        path = os.path.abspath(os.path.split(__file__)[0])
        fold = os.path.join(path, "data", "blog")
        out = get_temp_folder(__file__, "temp_post_list")
        p = BlogPostList(fold)
        cats = p.get_categories()
        months = p.get_months()
        self.assertEqual(cats, ['documentation', 'example'])
        self.assertEqual(months, ['2015-04'])

        res = p.write_aggregated(out)
        self.assertTrue(len(res) >= 4)
        for r in res:
            if r in (None, ''):
                raise ValueError("An empty value in {0}".format(res))
            if not os.path.exists(r):
                raise FileNotFoundError("Unable to find '{0}'".format(r))
            if 'main_0000.rst' in r:
                with open(r, 'r', encoding='utf-8') as f:
                    content = f.read()
                self.assertIn('...', content)
Example #19
0
 def add_crossref_type(self, directivename, rolename, indextemplate='',
                       ref_nodeclass=None):
     additional_xref_types[directivename] = (rolename, indextemplate, None)
     directives.register_directive(directivename, target_directive)
     roles.register_canonical_role(rolename, xfileref_role)
     if ref_nodeclass is not None:
         innernodetypes[rolename] = ref_nodeclass
Example #20
0
 def set_site(self, site):
     """Set Nikola site."""
     self.site = site
     self.site.register_shortcode('post-list', _do_post_list)
     directives.register_directive('post-list', PostList)
     PostList.site = site
     return super(Plugin, self).set_site(site)
Example #21
0
    def _register_pygments_rst_directive():
        from docutils import nodes
        from docutils.parsers.rst import directives
        from pygments import highlight
        from pygments.lexers import get_lexer_by_name, TextLexer
        from pygments.formatters import HtmlFormatter

        DEFAULT = HtmlFormatter()
        VARIANTS = {
            'linenos': HtmlFormatter(linenos=True),
        }

        def pygments_directive(name, arguments, options, content, lineno,
                               content_offset, block_text, state,
                               state_machine):
            try:
                lexer = get_lexer_by_name(arguments[0])
            except ValueError:
                # no lexer found - use the text one instead of an exception
                lexer = TextLexer()
            formatter = options and VARIANTS[options.keys()[0]] or DEFAULT
            parsed = highlight(u'\n'.join(content), lexer, formatter)
            return [nodes.raw('', parsed, format='html')]
        pygments_directive.arguments = (1, 0, 1)
        pygments_directive.content = 1
        directives.register_directive('code', pygments_directive)
Example #22
0
    def __init__(self):

        # include MoinMoin pages
        directives.register_directive('include', self.include)

        # used for MoinMoin macros
        directives.register_directive('macro', self.macro)

        # used for MoinMoin tables of content
        directives.register_directive('contents', self.table_of_content)

        # used for MoinMoin parsers
        directives.register_directive('parser', self.parser)

        # disallow a few directives in order to prevent XSS
        # for directive in ('meta', 'include', 'raw'):
        for directive in ('meta', 'raw'):
            directives.register_directive(directive, None)

        # disable the raw role
        roles._roles['raw'] = None

        # As a quick fix for infinite includes we only allow a fixed number of
        # includes per page
        self.num_includes = 0
        self.max_includes = 10
Example #23
0
def RestReader():
    try:
        from docutils.core import publish_cmdline
        from docutils.parsers.rst import directives
    except ImportError:
        raise DataError("Using reStructuredText test data requires having "
                        "'docutils' module installed.")

    # Ignore custom sourcecode directives at least we use in reST sources.
    # See e.g. ug2html.py for an example how custom directives are created.
    ignorer = lambda *args: []
    ignorer.content = 1
    directives.register_directive('sourcecode', ignorer)

    class RestReader(HtmlReader):

        def read(self, rstfile, rawdata):
            htmlpath = self._rest_to_html(rstfile.name)
            htmlfile = None
            try:
                htmlfile = open(htmlpath, 'rb')
                return HtmlReader.read(self, htmlfile, rawdata)
            finally:
                if htmlfile:
                    htmlfile.close()
                os.remove(htmlpath)

        def _rest_to_html(self, rstpath):
            filedesc, htmlpath = tempfile.mkstemp('.html')
            os.close(filedesc)
            publish_cmdline(writer_name='html', argv=[rstpath, htmlpath])
            return htmlpath
    return RestReader()
Example #24
0
def buildTemplates(template="source/ham.tmpl",page_glob="source/*.page"):
    """Build all of the *.page pages using the ham.tmpl template."""
    directives.register_directive('applet', Applet)

    base_args = {
        'metaTags':meta,
        'stylesheetTags':style,
        'javascriptTags':javascript,
        'currentYr':'2005, 2009',
        'siteCopyrightName':'Steven F. Lott',
        'siteDomainName':'http://www.me.com/s_lott',
        'siteCredits':'Designed by Steven F. Lott, Powered by Python',
    }

    load_from, template_name = os.path.split( template )
    env= jinja.Environment()
    env.loader= jinja.FileSystemLoader(load_from)
    template= env.get_template(template_name)
    for page in glob.glob(page_glob):
        print "render", page
        source= open(page,"r").read()
        args = base_args.copy()
        parts= publish_parts( source=source, writer_name='html' )
        args['name']= parts['title']
        args['text']= parts['html_body']
        args['now']= str(datetime.datetime.now())
        args['source']= page
        html= template.render( args )
        #print html
        # write page to build directory
        page_name, _ = os.path.splitext(os.path.basename(page))
        dest= open(os.path.join("build",page_name+".html"),"w")
        dest.write( html )
        dest.write( '\n' )
        dest.close()
Example #25
0
def register_directives():
    """
    To use directives in your rst system, you should register your custom
    directives.
    """
    directives.register_directive('sourcecode', Pygments)
    directives.register_directive('more', More)
Example #26
0
def pybabel():
    # This registers our minimal robot translation extractor
    import babel.messages.extract

    babel.messages.extract.DEFAULT_MAPPING.extend(
        [
            ("**.rst", "plone.app.robotframework.pybabel:extract_robot"),
            ("**.robot", "plone.app.robotframework.pybabel:extract_robot"),
        ]
    )

    # This code hides warnings for known Sphinx-only-directives when
    # executing pybot against Sphinx-documentation:
    from docutils.parsers.rst.directives import register_directive
    from docutils.parsers.rst.roles import register_local_role

    dummy_directive = lambda *args: []
    options = ("maxdepth", "creates", "numbered", "hidden")
    setattr(dummy_directive, "content", True)
    setattr(dummy_directive, "options", dict([(opt, str) for opt in options]))
    register_directive("toctree", dummy_directive)
    register_directive("robotframework", dummy_directive)
    register_local_role("ref", dummy_directive)

    from babel.messages.frontend import main

    main()
Example #27
0
def get_items_from_api_doc():
    from sphinx.ext.autosummary import Autosummary
    from docutils.core import publish_doctree
    from docutils.parsers.rst import directives
    import docutils.nodes

    def add_item(item, api_doc_items):
        item = item.astext().strip().split()
        if len(item) > 0:
            # if item comes from a hand written table (like the Exploring section of Axis in api.rst)
            # we select the text from the left column
            if isinstance(item, list):
                item = item[0]
            api_doc_items.append(item)

    api_doc_items = []
    directives.register_directive('autosummary', Autosummary)
    cleanup_line = lambda line: line.replace(':attr:', '      ').replace('`', ' ')
    check_line = lambda line: len(line) and not (line.startswith('..') or ':' in line)
    with open('./api.rst', mode='r') as f:
        content = [cleanup_line(line) for line in f.readlines()]
        content = '\n'.join([line for line in content if check_line(line)])
        document = publish_doctree(content)
        nodes = list(document)
        for node in nodes:
            if isinstance(node, docutils.nodes.block_quote):
                for item in node.children:
                    add_item(item, api_doc_items)
            if isinstance(node, docutils.nodes.table):
                for item in node[0][2].children:
                    add_item(item, api_doc_items)
    return api_doc_items
Example #28
0
    def test_post_parse_sn(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        directives.register_directive("sharenet", ShareNetDirective)
Example #29
0
def cb_start(args):
    """Register a break directive if docutils is installed."""
    try:
        from docutils import nodes
        from docutils.parsers.rst import directives, Directive
    except ImportError:
        return

    request = args['request']
    config = request.get_configuration()
    breakpoint = config.get("readmore_breakpoint", READMORE_BREAKPOINT)

    class Break(Directive):
        """
        Transform a break directive (".. break::") into the text that
        the douglas readmore plugin looks for.  This allows blog
        entries written in reST to use this plugin.
        """
        required_arguments = 0
        optional_arguments = 0
        final_argument_whitespace = True
        has_content = False

        def run(self):
            return [nodes.raw("", breakpoint + "\n", format="html")]

    directives.register_directive("break", Break)
Example #30
0
    def test_post_parse_blocref(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        directives.register_directive("blocref", BlocRef)
        directives.register_directive("blocreflist", BlocRefList)
Example #31
0
# Contact: [email protected]
# Revision: $Revision$
# Date: $Date$
# Copyright: This module has been placed in the public domain.
"""
A minimal front end to the Docutils Publisher, producing DocBook XML.
"""

import locale
try:
    locale.setlocale(locale.LC_ALL, '')
except:
    pass

from docutils.core import publish_cmdline, default_description

# cerebrum-changes starts:
from docutils.parsers.rst import directives
from rst_extensions import sysinclude, namespace, known_vars
directives.register_directive('sysinclude', sysinclude)
directives.register_directive('namespace', namespace)
# cerebrum-changes ends

description = (
    'Generates DocBook XML documents from standalone reStructuredText '
    'sources.  ' + default_description)

publish_cmdline(writer_name='docbook', description=description)

# :indentSize=4:lineSeparator=\n:noTabs=true:tabSize=4:
Example #32
0
def pdf(files, project, output):
    pdf = project['pdf'] if 'pdf' in project else None

    # Stylesheet processing
    stylesheets = []
    try:
        if pdf and ('stylesheet' in pdf):
            tmp_json = fileutils.stylesheet_to_tmp_json(pdf['stylesheet'])
            stylesheets.append(tmp_json)
        if pdf and ('stylesheets' in pdf):
            for stylesheet_file in pdf['stylesheets']:
                tmp_json = fileutils.stylesheet_to_tmp_json(stylesheet_file)
                stylesheets.append(tmp_json)
    except Exception:
        raise

    # Revisions
    if 'revisions' in project:
        revisions_text = '.. _unnumbered_revisions:\n'
        revisions_text += '.. list-table:: Revision History\n'
        revisions_text += '   :class: revisions-table\n'
        revisions_text += '   :header-rows: 1\n'
        revisions_text += '\n'
        revisions_text += '   * - Revision\n'
        revisions_text += '     - Date\n'
        revisions_text += '     - Description\n'

        last_revision = None
        last_date = None
        revisions = project['revisions']
        for revision in revisions:
            if isinstance(revision, dict):
                key = list(revision.keys())[0]
                rev = key
                date = '--'
                m = re.search(
                    r'([\w\d.-:]+)\s+(?:\(|\[)([0-9\w\s./:]+)(?:\)|\])', key)
                if m:
                    rev = m.group(1)
                    date = m.group(2)
                if not last_revision:
                    last_revision = rev
                if not last_date:
                    last_date = date
                revisions_text += '   * - **' + str(rev) + '**\n'
                revisions_text += '     - ' + date + '\n'
                revisions_text += '     - .. class:: revision-list\n'
                revisions_text += '\n'
                changes = revision[key]
                for change in changes:
                    revisions_text += '       + ' + change + '\n'
                    revisions_text += '\n'

        if not 'fields' in project:
            project['fields'] = {}
        project['fields']['revisions'] = revisions_text
        if (not 'revision' in project['fields']) and last_revision:
            project['fields']['revision'] = last_revision
        if (not 'version' in project['fields']) and last_revision:
            project['fields']['version'] = last_revision
        if (not 'date' in project['fields']) and last_date:
            project['fields']['date'] = last_date

    # Text processing
    text = ''

    # Cover page
    if pdf and ('cover' in pdf):
        cover_file = pdf['cover']
        if not os.path.isfile(cover_file):
            log.error("Unable to open cover file: '%s'", cover_file)
            raise IOError('Cover file error')
        text += preprocess.pdf(fileutils.readfile(cover_file),
                               os.path.dirname(cover_file), project)

    # Main contents processing
    for file in files:
        text += preprocess.pdf(fileutils.readfile(file['src']),
                               os.path.dirname(file['src']), project)

    # Output file name processing
    if pdf and 'output' in pdf:
        output = os.path.join(pdf['output'], output) if os.path.isdir(
            pdf['output']) else pdf['output']
        if not output.endswith('.pdf'):
            output += '.pdf'

    # Generating PDF
    options = namedtuple('Namespace', 'extensions')
    options.extensions = ['inkscape', 'vectorpdf']
    if pdf and ('toc' in pdf):
        if pdf['toc'] == 'dotted':
            options.extensions.append('dotted_toc')
    add_extensions(options)
    directives.register_directive(
        'code-block', pygments_code_block_directive.code_block_directive)
    directives.register_directive(
        'code', pygments_code_block_directive.code_block_directive)
    doctree = docutils.core.publish_doctree(text)
    doctree = preprocess.doctree(doctree, project)
    if pdf:
        doctree = preprocess.doctree_pdf(doctree, pdf)
    log.info("Generating '%s'", os.path.basename(output))
    try:
        stylesheet_names = []
        for stylesheet in stylesheets:
            stylesheet_names.append(stylesheet.name)
        RstToPdf(
            background_fit_mode='scale',
            breaklevel=pdf['break-level'] if pdf and
            ('break-level' in pdf) else 1,
            breakside=pdf['break-side'] if pdf and
            ('break-side' in pdf) else 'any',
            repeat_table_rows=pdf['repeate-table-rows'] if pdf and
            ('repeate-table-rows' in pdf) else True,
            smarty=str(pdf['smartquotes'] if pdf and (
                'smartquotes' in pdf) else 1),
            stylesheets=stylesheet_names,
        ).createPdf(doctree=doctree, output=output)
    except Exception as err:
        log.error("PDF generating failed: %s", err)
        raise

    log.info("Post-processing '%s'", os.path.basename(output))
    try:
        import pkg_resources
        __version__ = pkg_resources.get_distribution('doker').version
    except Exception:
        __version__ = None
    creator = 'Doker'
    if __version__:
        creator += ' v' + __version__
    creator += ' \\(doker.org\\)'
    with open(output, 'rb') as f:
        text = f.read()
    with open(output, 'wb') as f:
        f.write(
            re.sub(r'/Creator \(\\\(unspecified\\\)\)',
                   '/Creator (' + creator + ')', text))
Example #33
0
def register():
    '''
  '''
    directives.register_directive('avembed', avembed)
    directives.register_directive('avmetadata', avmetadata)
    directives.register_directive('extrtoolembed', extrtoolembed)
    directives.register_directive('inlineav', inlineav)
    directives.register_directive('odsalink', odsalink)
    directives.register_directive('odsascript', odsascript)
    directives.register_directive('index', index)
    directives.register_directive('codeinclude', codeinclude)
    directives.register_directive('todo', todo)
    directives.register_directive('only', only)
    directives.register_directive('glossary', glossary)
    directives.register_directive('odsafig', odsafig)
Example #34
0
def setup(builder):
    directives.register_directive('line-break', LineBreak)
Example #35
0
        error = state_machine.reporter.error(
            'The "%s" block is empty; content required.' % (name),
            nodes.literal_block(block_text, block_text), line=lineno)
        return [error]

    include_text = highlighter("\n".join(content))
    html = '<div class="codeblock %s">\n%s\n</div>\n' % (language, include_text)
    raw = nodes.raw('',html, format='html')
    return [raw]

code.content = 1
code.options = {'language' : parsers.rst.directives.unchanged }
code.arguments = (1,0,0)


directives.register_directive('code', code)

def photologue_rst( name, arguments, options, content, lineno,
             content_offset, block_text, state, state_machine ):
  """
  The code-block directive provides syntax highlighting for blocks
  of code.  It is used with the the following syntax::
  
  .. photologue:: 1
    
  The directive requires the name of a language supported by SilverCity
  as its only argument.  All code in the indented block following
  the directive will be colourized.  Note that this directive is only
  supported for HTML writers.
  """
  from photologue.models import Photo
Example #36
0
            stdout=subprocess.PIPE)
        p.stdin.write(content.encode('utf-8'))
        p.stdin.close()
        datalines = p.stdout.readlines()
        del datalines[:3]
        #ff=open(self.options['filename'],'w')
        #ff.write(data)
        #ff.close()
        #return [nodes.raw('',"""<embed src="%s" />"""%\
        #        self.options['filename'],format='html')]
        return [
            nodes.raw('', ''.join(datalines).decode('utf-8'), format='html')
        ]


directives.register_directive('dot', Dot)

#XXX: 内嵌SVG的支持
#class SVG(Directive):
#    has_content=True
#    option_spec={
#            'filename': directives.unchanged_required,
#            'height':   directives.unchanged_required,
#            'width':    directives.unchanged_required,
#            }
#
#    def run(self):
#        content=u'\n'.join(self.content)
#        filename=self.options['filename']
#        height=self.options.get('height',200)
#        width=self.options.get('width',200)
Example #37
0
        try:
            linenothreshold = int(options['linenothreshold'])
        except Exception:
            linenothreshold = 10
    else:
        linenothreshold = sys.maxint
    return [
        addnodes.highlightlang(lang=arguments[0].strip(),
                               linenothreshold=linenothreshold)
    ]


highlightlang_directive.content = 0
highlightlang_directive.arguments = (1, 0, 0)
highlightlang_directive.options = {'linenothreshold': directives.unchanged}
directives.register_directive('highlight', highlightlang_directive)
directives.register_directive('highlightlang',
                              highlightlang_directive)  # old name

# ------ code-block directive -------------------------------------------------------


def codeblock_directive(name, arguments, options, content, lineno,
                        content_offset, block_text, state, state_machine):
    code = u'\n'.join(content)
    literal = nodes.literal_block(code, code)
    literal['language'] = arguments[0]
    literal['linenos'] = 'linenos' in options
    return [literal]

Example #38
0
        break_class = arguments[0]
    else:
        break_class = 'clear'

    raw_node = nodes.raw('', '<hr class="%s" />' % break_class, format='html')

    # return [nodes.transition()]
    return [raw_node]

break_directive.arguments = (0, 1, True)
break_directive.options = {
    'class':directives.class_option
    }
break_directive.content = False

directives.register_directive('break', break_directive)

# ------------------------------------------------------------------------------
# a tag direktive!!
# ------------------------------------------------------------------------------

SEEN_TAGS_CACHE = None
TAG_COUNTER = None

class TagDirective(Directive):
    """Convert tags into HTML annotation blocks."""

    required_arguments = 0
    optional_arguments = 1
    final_argument_whitespace = True
Example #39
0
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
from docutils.parsers.rst import directives
from sphinx.directives.code import CodeBlock

directives.register_directive("code", CodeBlock)

# -- Project information -----------------------------------------------------

project = "IntelOwl"
copyright = "2020, Matteo Lodi"
author = "Matteo Lodi"

# The full version, including alpha/beta/rc tags
release = "v2.5.0"

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
Example #40
0
 def set_site(self, site):
     """Set Nikola site."""
     global _site
     _site = self.site = site
     directives.register_directive('chart', Chart)
     return super(Plugin, self).set_site(site)
Example #41
0
 def set_site(self, site):
     self.site = site
     directives.register_directive('youtube', Youtube)
     return super(Plugin, self).set_site(site)
Example #42
0
        # if self.options['showhide'] != "none":
        #   self.options['content'] = BUTTON_HTML % (self.options)

        res = CONTAINER_HTML % (self.options)

        return [nodes.raw('', res, format='html')]


source = """\
This is some text.

.. avembed:: address type

This is some more text.
"""

if __name__ == '__main__':
    from docutils.core import publish_parts

    directives.register_directive('avembed', avembed)

    doc_parts = publish_parts(source,
                              settings_overrides={
                                  'output_encoding': 'utf8',
                                  'initial_header_level': 2
                              },
                              writer_name="html")

    print doc_parts['html_body']
Example #43
0
def register_directives():
    directives.register_directive('video', video_directive)
        def run(self):
            latex = ' '.join(self.content)
            try:
                mathml_tree = parse_latex_math(latex, inline=False)
            except SyntaxError, msg:
                error = self.state_machine.reporter.error(msg,
                                                          nodes.literal_block(
                                                              self.block_text,
                                                              self.block_text),
                                                          line=self.lineno)
                return [error]
            node = latex_math(self.block_text, mathml_tree)
            return [node]

    directives.register_directive('latex-math', latex_math_directive)


# Add visit/depart methods to HTML-Translator:
def visit_latex_math(self, node):
    mathml = ''.join(node.mathml_tree.xml())
    self.body.append(mathml)
    if not self.has_mathml_dtd:
        doctype = ('<!DOCTYPE html'
                   ' PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN"'
                   ' "http://www.w3.org/Math/DTD/mathml2/'
                   'xhtml-math11-f.dtd">\n')
        if self.settings.xml_declaration:
            self.head_prefix[1] = doctype
        else:
            self.head_prefix[0] = doctype
Example #45
0
            res = res + SCRIPTTAG % self.options['modelfile']
        if 'viewerfile' in self.options:
            res = res + SCRIPTTAG % self.options['viewerfile']

        res = res + SRC % self.options
        return [nodes.raw('', res, format='html')]


source = '''
.. animation:: testanim
   :modelfile: sortmodels.js
   :viewerfile: sortviewers.js
   :model: SortModel
   :viewer: BarViewer

'''

if __name__ == '__main__':
    from docutils.core import publish_parts

    directives.register_directive('animation', Animation)

    doc_parts = publish_parts(source,
                              settings_overrides={
                                  'output_encoding': 'utf8',
                                  'initial_header_level': 2
                              },
                              writer_name="html")

    print doc_parts['html_body']
Example #46
0
def register():
    directives.register_directive('podcast', Podcast)
Example #47
0
from docutils.parsers.rst import directives
from pkg_resources import parse_version

import sphinx
import numpy as np

sys.path.insert(
    0, os.path.join(os.path.dirname(__file__), '..', 'doc', 'sphinxext'))
from numpydoc.docscrape_sphinx import get_doc_object

SKIPBLOCK = doctest.register_optionflag('SKIPBLOCK')

if parse_version(sphinx.__version__) >= parse_version('1.5'):
    # Enable specific Sphinx directives
    from sphinx.directives.other import SeeAlso, Only
    directives.register_directive('seealso', SeeAlso)
    directives.register_directive('only', Only)
else:
    # Remove sphinx directives that don't run without Sphinx environment.
    # Sphinx < 1.5 installs all directives on import...
    directives._directives.pop('versionadded', None)
    directives._directives.pop('versionchanged', None)
    directives._directives.pop('moduleauthor', None)
    directives._directives.pop('sectionauthor', None)
    directives._directives.pop('codeauthor', None)
    directives._directives.pop('toctree', None)

BASE_MODULE = "numpy"

PUBLIC_SUBMODULES = [
    'core',
Example #48
0
from config import nav_root_template, nav_item_template

def navtree_directive(name, arguments, options, content, lineno,
                       content_offset, block_text, state, state_machine):
    context = state.document.settings.context
    request = state.document.settings.request

    parsed = nav_tree(context, request, options.get('root_depth', 2))
    return [nodes.raw('', parsed, format='html')]

navtree_directive.arguments = (0, 1, 0) 
navtree_directive.has_content = 1
navtree_directive.content = 1  
navtree_directive.options = {'root_depth': int}

directives.register_directive('navtree', navtree_directive)

# 生成navtree
def nav_tree(context, request, root_depth):
    """render navtree structure, root_depth from root"""
    navtree = getMultiAdapter((context,request), INavtreeData)
    if navtree == None:
        return
    # get the root accoding to root_depth
    con = context
    parents = []
    while con.__parent__ != None:
        parents.insert(0,con.__parent__)
        con = con.__parent__

    if IFRSFolder.providedBy(context):
Example #49
0
                return markdown2.markdown(plain, extras=cls.extras)

        all.append(Markdown2)
    except ImportError:
        logging.warn('Markdown not enabled.')


# Include ReStructuredText Parser, if we have docutils
try:
    import docutils.core
    from docutils.writers.html4css1 import Writer as rst_html_writer
    from docutils.parsers.rst import directives

    if have_pygments:
        from wok.rst_pygments import Pygments as RST_Pygments
        directives.register_directive('Pygments', RST_Pygments)

    class ReStructuredText(Renderer):
        """reStructuredText renderer."""
        extensions = ['rst']

        @classmethod
        def render(cls, plain):
            w = rst_html_writer()
            return docutils.core.publish_parts(plain, writer=w)['body']

    all.append(ReStructuredText)
except ImportError:
    logging.warn('reStructuredText not enabled.')

Example #50
0
def setup(app):
    # type: (Sphinx) -> Dict[unicode, Any]
    directives.register_directive('toctree', TocTree)
    directives.register_directive('sectionauthor', Author)
    directives.register_directive('moduleauthor', Author)
    directives.register_directive('codeauthor', Author)
    directives.register_directive('index', Index)
    directives.register_directive('deprecated', VersionChange)
    directives.register_directive('versionadded', VersionChange)
    directives.register_directive('versionchanged', VersionChange)
    directives.register_directive('seealso', SeeAlso)
    directives.register_directive('tabularcolumns', TabularColumns)
    directives.register_directive('centered', Centered)
    directives.register_directive('acks', Acks)
    directives.register_directive('hlist', HList)
    directives.register_directive('only', Only)
    directives.register_directive('include', Include)

    # register the standard rst class directive under a different name
    # only for backwards compatibility now
    directives.register_directive('cssclass', Class)
    # new standard name when default-domain with "class" is in effect
    directives.register_directive('rst-class', Class)

    return {
        'version': 'builtin',
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }
Example #51
0
        label = self.options.get('label', None)
        fontsize = self.options.get('fontsize', None)
        color = self.options.get('color', None)
        return [
            math_node(latex=latex,
                      label=label,
                      fontsize=fontsize,
                      color=color,
                      rawsource=''.join(self.content))
        ]

    def __repr__(self):
        return ''.join(self.content)


directives.register_directive('math', Math)


class math_node(General, Inline, Element):

    children = ()

    def __init__(self,
                 rawsource='',
                 label=None,
                 fontsize=12,
                 color='black',
                 *children,
                 **attributes):
        self.rawsource = rawsource
        self.math_data = attributes['latex']
Example #52
0
 def set_site(self, site):
     """Set Nikola site."""
     self.site = site
     directives.register_directive('vimeo', Vimeo)
     return super().set_site(site)
Example #53
0
def setup(builder):
    directives.register_directive('youtube', Youtube)
Example #54
0
            'height': directives.nonnegative_int
        }

        def run(self):
            set_classes(self.options)
            node = role_video(source=self.arguments[0], **self.options)
            return [node]

    generic_docroles = {'doc': role_doc}

    for rolename, nodeclass in generic_docroles.items():
        generic = roles.GenericRole(rolename, nodeclass)
        role = roles.CustomRole(rolename, generic, {'classes': [rolename]})
        roles.register_local_role(rolename, role)

    directives.register_directive('video', VideoDirective)

Builder.load_string('''
#:import parse_color kivy.parser.parse_color



<RstDocument>:
    content: content
    scatter: scatter
    do_scroll_x: False
    canvas:
        Color:
            rgba: parse_color(root.colors['background'])
        Rectangle:
            pos: self.pos
Example #55
0
# -*- coding: utf-8 -*-
# This code is from http://countergram.com/youtube-in-rst

from docutils import nodes
from docutils.parsers.rst import directives

CODE = """\
<object class="rst-youtube" type="application/x-shockwave-flash"
        %(attrs)s data="http://www.youtube.com/v/%(yid)s">
    <param name="movie" value="http://www.youtube.com/v/%(yid)s"></param>
    <param name="wmode" value="transparent"></param> %(extra)s
</object>
"""

PARAM = """\n<param name="%s" value="%s"></param>"""


def youtube(name, args, options, content, lineno, contentOffset, blockText,
            state, stateMachine):
    """Restructured text extension for inserting youtube embedded videos."""
    if len(content) == 0: return
    string_vars = {'yid': content[0], 'attrs': '', 'extra': ''}
    attrs = content[1:]  # Because content[0] is ID
    attrs = [attr.strip() for attr in content[1:]]  # key=value
    string_vars['attrs'] = " ".join(attrs)
    return [nodes.raw('', CODE % (string_vars), format='html')]


youtube.content = True
directives.register_directive('youtube', youtube)
Example #56
0
 def set_site(self, site):
     self.site = site
     directives.register_directive('post-list', PostList)
     PostList.site = site
     return super(Plugin, self).set_site(site)
Example #57
0
                       content_offset, block_text, state, state_machine):
    try:
        lexer = get_lexer_by_name(arguments[0])
    except ValueError:
        # no lexer found - use the text one instead of an exception
        lexer = TextLexer()
    # take an arbitrary option if more than one is given
    formatter = options and VARIANTS[options.keys()[0]] or DEFAULT
    parsed = highlight(u'\n'.join(content), lexer, formatter)
    return [nodes.raw('', parsed, format='html')]

pygments_directive.arguments = (1, 0, 1)
pygments_directive.content = 1
pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS])

directives.register_directive('sourcecode', pygments_directive)

# ----------------------------------------------------------------------------

import math_directive
math_directive.register()

try:
    import locale
    locale.setlocale(locale.LC_ALL, '')
except:
    pass

from docutils.core import publish_cmdline, default_description

description = ('Generates (X)HTML documents from standalone reStructuredText '
        'anchorlinenos': directives.flag,
        'noclasses': directives.flag,
    }
    has_content = True

    def run(self):
        self.assert_has_content()
        try:
            lexer = get_lexer_by_name(self.arguments[0])
        except ValueError:
            # no lexer found
            lexer = get_lexer_by_name('text')

        options = {}
        for (option, converter) in self.option_spec.iteritems():
            if converter == directives.flag:
                if option in self.options:
                    options[option] = True
            elif option in self.options:
                options[option] = self.options[option]

        formatter = HtmlFormatter(**options)
        parsed = highlight(u'\n'.join(self.content), lexer, formatter)
        return [nodes.raw('', parsed, format='html')]


directives.register_directive('code', Pygments)
directives.register_directive('code-block', Pygments)
directives.register_directive('sourcecode', Pygments)
directives.register_directive('sourcecode-block', Pygments)
Example #59
0
        # TODO: validate options here and (maybe) display an error
        defaults = {}
        for option in defaults.keys():
            assert option in self.option_spec

        return defaults

    def run(self):
        if len(self.content) == 0:
            return

        # from nikola.plugins.compile.rest import rst2html
        # content = rst2html('\n'.join(self.content))

        # TODO: use nikola.plugins.compile.rest.rst2html to compile this
        import uuid
        from docutils.core import publish_parts
        content = publish_parts('\n'.join(self.content),
                                writer_name='html')['html_body']

        output = self.site.template_system.render_template(
            'collapse.tmpl', None, {
                'uuid': uuid.uuid4().hex,
                'title': ' '.join(self.arguments),
                'content': content,
            })
        return [nodes.raw('', output, format='html')]


directives.register_directive('collapse', Collapse)
def setup(app):
    directives.register_directive('only', EagerOnly)