예제 #1
0
def get_doctree(path):
    """
    Obtain a Sphinx doctree from the RST file at ``path``.

    Performs no Releases-specific processing; this code would, ideally, be in
    Sphinx itself, but things there are pretty tightly coupled. So we wrote
    this.

    :param str path: A relative or absolute file path string.

    :returns:
        A two-tuple of the generated ``sphinx.application.Sphinx`` app and the
        doctree (a ``docutils.document`` object).
    """
    root, filename = os.path.split(path)
    docname, _ = os.path.splitext(filename)
    # TODO: this only works for top level changelog files (i.e. ones where
    # their dirname is the project/doc root)
    app = make_app(srcdir=root)
    # Create & init a BuildEnvironment. Mm, tasty side effects.
    app._init_env(freshenv=True)
    env = app.env
    env.update(config=app.config, srcdir=root, doctreedir=app.doctreedir, app=app)
    # Code taken from sphinx.environment.read_doc; easier to manually call
    # it with a working Environment object, instead of doing more random crap
    # to trick the higher up build system into thinking our single changelog
    # document was "updated".
    env.temp_data['docname'] = docname
    env.app = app
    # NOTE: SphinxStandaloneReader API changed in 1.4 :(
    reader_kwargs = {'app': env.app, 'parsers': env.config.source_parsers}
    if sphinx.version_info[:2] < (1, 4):
        del reader_kwargs['app']
    reader = SphinxStandaloneReader(**reader_kwargs)
    pub = Publisher(reader=reader,
                    writer=SphinxDummyWriter(),
                    destination_class=NullOutput)
    pub.set_components(None, 'restructuredtext', None)
    pub.process_programmatic_settings(None, env.settings, None)
    # NOTE: docname derived higher up, from our given path
    src_path = env.doc2path(docname)
    source = SphinxFileInput(app, env, source=None, source_path=src_path,
                             encoding=env.config.source_encoding)
    pub.source = source
    pub.settings._source = src_path
    pub.set_destination(None, None)
    pub.publish()
    return app, pub.document
예제 #2
0
def convertRSTfilesToHTML(root_list):

    """This routine creates .html files from all .rst files in root_list, the list of files that have just been tangled."""
    
    for root in root_list: 
        base,fullname = g.os_path_split(root)
        name,ext = g.os_path_splitext(fullname)
        if ext == ".rst":
            file = g.os_path_join(base,name+".html")
            #@            << Convert root to corresponding .html file >>
            #@+node:EKR.20040502194930.3:<< Convert root to corresponding .html file >>
            # Leo will report the execption if docutils is not installed.
            from docutils.core import Publisher 
            from docutils.io import FileInput,StringOutput,StringInput 
            
            # Read .rst file into s.
            f = open(root,"r")
            s = f.read()
            f.close()
            
            # Restucture s into output.
            pub = Publisher() 
            pub.source = StringInput(pub.settings,source=s) 
            pub.destination = StringOutput(pub.settings,encoding="utf-8") 
            pub.set_reader('standalone',None,'restructuredtext') 
            pub.set_writer('html') 
            output = pub.publish()
            
            # EKR: 3/7/03: convert output using the present encoding.
            dict = g.scanDirectives(self.c,p=root)
            encoding = dict.get("encoding",None)
            if encoding == None:
                encoding = g.app.config.default_derived_file_encoding
            output = g.toEncodedString(output,encoding,reportErrors=True) 
            
            # Write the corresponding html file.
            f = open(file,"w")
            f.write(output)
            f.close()
예제 #3
0
파일: __init__.py 프로젝트: nwf/sphinx
    def read_doc(self, docname, app=None):
        # type: (unicode, Sphinx) -> None
        """Parse a file and add/update inventory entries for the doctree."""

        self.temp_data['docname'] = docname
        # defaults to the global default, but can be re-set in a document
        self.temp_data['default_domain'] = \
            self.domains.get(self.config.primary_domain)

        self.settings['input_encoding'] = self.config.source_encoding
        self.settings['trim_footnote_reference_space'] = \
            self.config.trim_footnote_reference_space
        self.settings['gettext_compact'] = self.config.gettext_compact

        docutilsconf = path.join(self.srcdir, 'docutils.conf')
        # read docutils.conf from source dir, not from current dir
        OptionParser.standard_config_files[1] = docutilsconf
        if path.isfile(docutilsconf):
            self.note_dependency(docutilsconf)

        with sphinx_domains(self):
            if self.config.default_role:
                role_fn, messages = roles.role(self.config.default_role, english,
                                               0, dummy_reporter)
                if role_fn:
                    roles._roles[''] = role_fn
                else:
                    logger.warning('default role %s not found', self.config.default_role,
                                   location=docname)

            codecs.register_error('sphinx', self.warn_and_replace)  # type: ignore

            # publish manually
            reader = SphinxStandaloneReader(self.app, parsers=self.config.source_parsers)
            pub = Publisher(reader=reader,
                            writer=SphinxDummyWriter(),
                            destination_class=NullOutput)
            pub.set_components(None, 'restructuredtext', None)
            pub.process_programmatic_settings(None, self.settings, None)
            src_path = self.doc2path(docname)
            source = SphinxFileInput(app, self, source=None, source_path=src_path,
                                     encoding=self.config.source_encoding)
            pub.source = source
            pub.settings._source = src_path
            pub.set_destination(None, None)
            pub.publish()
            doctree = pub.document

        # post-processing
        for domain in itervalues(self.domains):
            domain.process_doc(self, docname, doctree)

        # allow extension-specific post-processing
        if app:
            app.emit('doctree-read', doctree)

        # store time of reading, for outdated files detection
        # (Some filesystems have coarse timestamp resolution;
        # therefore time.time() can be older than filesystem's timestamp.
        # For example, FAT32 has 2sec timestamp resolution.)
        self.all_docs[docname] = max(
            time.time(), path.getmtime(self.doc2path(docname)))

        if self.versioning_condition:
            old_doctree = None
            if self.versioning_compare:
                # get old doctree
                try:
                    with open(self.doc2path(docname,
                                            self.doctreedir, '.doctree'), 'rb') as f:
                        old_doctree = pickle.load(f)
                except EnvironmentError:
                    pass

            # add uids for versioning
            if not self.versioning_compare or old_doctree is None:
                list(add_uids(doctree, self.versioning_condition))
            else:
                list(merge_doctrees(
                    old_doctree, doctree, self.versioning_condition))

        # make it picklable
        doctree.reporter = None
        doctree.transformer = None
        doctree.settings.warning_stream = None
        doctree.settings.env = None
        doctree.settings.record_dependencies = None

        # cleanup
        self.temp_data.clear()
        self.ref_context.clear()
        roles._roles.pop('', None)  # if a document has set a local default role

        # save the parsed doctree
        doctree_filename = self.doc2path(docname, self.doctreedir,
                                         '.doctree')
        ensuredir(path.dirname(doctree_filename))
        with open(doctree_filename, 'wb') as f:
            pickle.dump(doctree, f, pickle.HIGHEST_PROTOCOL)
예제 #4
0
        properties = controls[control].properties.keys()
        properties.sort()
        l("    *Properties*\n%s" % ("\n\n".join(["        %s" %
                    prop for prop in properties]),))

        methods = controls[control].methods.keys()
        methods.sort()
        l("\n    *Methods*\n%s" % ("\n\n".join(["        %s" %
                    str(controls[control].methods[method]) for method in methods]),))

    text = "\n".join(results)

    # << Convert to HTML >>
    import StringIO
    rstFile = StringIO.StringIO(text)

    from docutils.core import Publisher
    from docutils.io import StringOutput, StringInput

    pub = Publisher()
    # Initialize the publisher
    pub.source = StringInput(source=text)
    pub.destination = StringOutput(encoding="utf-8")
    pub.set_reader('standalone', None, 'restructuredtext')
    pub.set_writer('html')
    output = pub.publish()

    print output
    # -- end -- << Convert to HTML >>
예제 #5
0
파일: util.py 프로젝트: tony/releases
def get_doctree(path, **kwargs):
    """
    Obtain a Sphinx doctree from the RST file at ``path``.

    Performs no Releases-specific processing; this code would, ideally, be in
    Sphinx itself, but things there are pretty tightly coupled. So we wrote
    this.

    Any additional kwargs are passed unmodified into an internal `make_app`
    call.

    :param str path: A relative or absolute file path string.

    :returns:
        A two-tuple of the generated ``sphinx.application.Sphinx`` app and the
        doctree (a ``docutils.document`` object).

    .. versionchanged:: 1.6
        Added support for passing kwargs to `make_app`.
    """
    root, filename = os.path.split(path)
    docname, _ = os.path.splitext(filename)
    # TODO: this only works for top level changelog files (i.e. ones where
    # their dirname is the project/doc root)
    app = make_app(srcdir=root, **kwargs)
    # Create & init a BuildEnvironment. Mm, tasty side effects.
    app._init_env(freshenv=True)
    env = app.env
    # More arity/API changes: Sphinx 1.3/1.4-ish require one to pass in the app
    # obj in BuildEnvironment.update(); modern Sphinx performs that inside
    # Application._init_env() (which we just called above) and so that kwarg is
    # removed from update(). EAFP.
    kwargs = dict(
        config=app.config,
        srcdir=root,
        doctreedir=app.doctreedir,
        app=app,
    )
    try:
        env.update(**kwargs)
    except TypeError:
        # Assume newer Sphinx w/o an app= kwarg
        del kwargs['app']
        env.update(**kwargs)
    # Code taken from sphinx.environment.read_doc; easier to manually call
    # it with a working Environment object, instead of doing more random crap
    # to trick the higher up build system into thinking our single changelog
    # document was "updated".
    env.temp_data['docname'] = docname
    env.app = app
    # NOTE: SphinxStandaloneReader API changed in 1.4 :(
    reader_kwargs = {
        'app': app,
        'parsers': env.config.source_parsers,
    }
    if sphinx.version_info[:2] < (1, 4):
        del reader_kwargs['app']
    # This monkeypatches (!!!) docutils to 'inject' all registered Sphinx
    # domains' roles & so forth. Without this, rendering the doctree lacks
    # almost all Sphinx magic, including things like :ref: and :doc:!
    with sphinx_domains(env):
        reader = SphinxStandaloneReader(**reader_kwargs)
        pub = Publisher(reader=reader,
                        writer=SphinxDummyWriter(),
                        destination_class=NullOutput)
        pub.set_components(None, 'restructuredtext', None)
        pub.process_programmatic_settings(None, env.settings, None)
        # NOTE: docname derived higher up, from our given path
        src_path = env.doc2path(docname)
        source = SphinxFileInput(
            app,
            env,
            source=None,
            source_path=src_path,
            encoding=env.config.source_encoding,
        )
        pub.source = source
        pub.settings._source = src_path
        pub.set_destination(None, None)
        pub.publish()
        return app, pub.document
예제 #6
0
def onIconDoubleClick(tag,keywords):

    v = keywords.get("p") or keywords.get("v")
    c = keywords.get("c")
    # g.trace(c)

    h = v.headString().strip()
    if g.match_word(h,0,"@text"):
        fname = h[5:]
        ext = os.path.splitext(fname)[1].lower()
        if ext in ('.htm','.html','.tex'):
            #@            << write rST as HTML/LaTeX >>
            #@+node:edream.111803100242.4:<< write rST as HTML/LaTeX >>
            try:
                import docutils
            except ImportError:
                docutils = None
                g.es('HTML/LaTeX generation requires docutils')
            
            if docutils:
                import StringIO
                rstFile = StringIO.StringIO()
                writeTreeAsRst(rstFile, fname, v, c)
                rstText = rstFile.getvalue()
                # Set the writer and encoding for the converted file
                if ext in ('.html','.htm'):
                    writer='html'
                    enc="utf-8"
                else:
                    writer='latex'
                    enc="iso-8859-1"
                #@    << convert rST to HTML/LaTeX >>
                #@+node:edream.111803100242.5:<< convert rST to HTML/LaTeX >>
                # this code snipped has been taken from code contributed by Paul Paterson 2002-12-05
                from docutils.core import Publisher
                from docutils.io import StringOutput, StringInput
                
                pub = Publisher()
                # Initialize the publisher
                pub.source = StringInput(source=rstText)
                pub.destination = StringOutput(pub.settings, encoding=enc)
                pub.set_reader('standalone', None, 'restructuredtext')
                pub.set_writer(writer)
                output = pub.publish(argv=[''])
                #@nonl
                #@-node:edream.111803100242.5:<< convert rST to HTML/LaTeX >>
                #@nl
                convertedFile = file(fname,'w')
                convertedFile.write(output)
                convertedFile.close()
                rstFile.close()
                g.es('written: '+str(fname))
            #@nonl
            #@-node:edream.111803100242.4:<< write rST as HTML/LaTeX >>
            #@nl
        else:
            #@            << write rST file >>
            #@+node:edream.111803100242.6:<< write rST file >>
            rstFile = file(fname,'w')
            writeTreeAsRst(rstFile, fname, v, c)
            rstFile.close()
            g.es('written: '+str(fname))
예제 #7
0
def onIconDoubleClick(tag, keywords):

    v = keywords.get("p") or keywords.get("v")
    c = keywords.get("c")
    # g.trace(c)

    h = v.headString().strip()
    if g.match_word(h, 0, "@text"):
        fname = h[5:]
        ext = os.path.splitext(fname)[1].lower()
        if ext in ('.htm', '.html', '.tex'):
            #@            << write rST as HTML/LaTeX >>
            #@+node:edream.111803100242.4:<< write rST as HTML/LaTeX >>
            try:
                import docutils
            except ImportError:
                docutils = None
                g.es('HTML/LaTeX generation requires docutils')

            if docutils:
                import StringIO
                rstFile = StringIO.StringIO()
                writeTreeAsRst(rstFile, fname, v, c)
                rstText = rstFile.getvalue()
                # Set the writer and encoding for the converted file
                if ext in ('.html', '.htm'):
                    writer = 'html'
                    enc = "utf-8"
                else:
                    writer = 'latex'
                    enc = "iso-8859-1"
                #@    << convert rST to HTML/LaTeX >>
                #@+node:edream.111803100242.5:<< convert rST to HTML/LaTeX >>
                # this code snipped has been taken from code contributed by Paul Paterson 2002-12-05
                from docutils.core import Publisher
                from docutils.io import StringOutput, StringInput

                pub = Publisher()
                # Initialize the publisher
                pub.source = StringInput(source=rstText)
                pub.destination = StringOutput(pub.settings, encoding=enc)
                pub.set_reader('standalone', None, 'restructuredtext')
                pub.set_writer(writer)
                output = pub.publish(argv=[''])
                #@nonl
                #@-node:edream.111803100242.5:<< convert rST to HTML/LaTeX >>
                #@nl
                convertedFile = file(fname, 'w')
                convertedFile.write(output)
                convertedFile.close()
                rstFile.close()
                g.es('written: ' + str(fname))
            #@nonl
            #@-node:edream.111803100242.4:<< write rST as HTML/LaTeX >>
            #@nl
        else:
            #@            << write rST file >>
            #@+node:edream.111803100242.6:<< write rST file >>
            rstFile = file(fname, 'w')
            writeTreeAsRst(rstFile, fname, v, c)
            rstFile.close()
            g.es('written: ' + str(fname))
예제 #8
0
    print 'symbol_footnotes', pformat(document.symbol_footnotes)
    print 'symbol_footnote_refs', pformat(document.symbol_footnote_refs)
    print 'footnotes', pformat(document.footnotes)
    print 'citations', pformat(document.citations)
    print 'autofootnote_start', pformat(document.autofootnote_start)
    print 'symbol_footnote_start', pformat(document.symbol_footnote_start)
    print 'id_start', pformat(document.id_start)
    print 'transform_messages', pformat(document.transform_messages)
    print 'transformer', pformat(document.transformer)
    print 'decoration', pformat(document.decoration)
    sys.exit()
#dump(document)

### 2. Render doctree to output format, 
###    apply completion transforms.

pub.source = io.DocTreeInput(document)
pub.destination_class = io.FileOutput
pub.set_destination()

pub.reader = doctree.Reader(parser_name='null')
pub.writer = Writer()

pub.apply_transforms()
output = pub.writer.write(pub.document, pub.destination)
#pub.writer.assemble_parts()


# ----

예제 #9
0
def onIconDoubleClick(tag,keywords):

    c = keywords.get("c")
    p = keywords.get("p")
    # g.trace(c)

    if not c or not p:
        return
    
    applyConfiguration(c)
    config.tag = tag

    h = p.headString().strip()

    if g.match_word(h,0,"@rst"):
        if len(h) > 5:
            fname = h[5:]
            ext = os.path.splitext(fname)[1].lower()
            if ext in ('.htm','.html','.tex'):
                #@                << write rST as HTML/LaTeX >>
                #@+node:ekr.20040331071319.4:<< write rST as HTML/LaTeX >>
                try:
                    import docutils
                except:
                    g.es('HTML/LaTeX generation requires docutils')
                    return
                else:
                    import docutils.parsers.rst
                    from docutils.core import Publisher
                    from docutils.io import StringOutput, StringInput, FileOutput,FileInput
                    import StringIO
                    
                # Set the writer and encoding for the converted file
                if ext in ('.html','.htm'):
                    writer='html' ; enc="utf-8"
                else:
                    writer='latex' ; enc="iso-8859-1"
                
                syntax = False
                if writer == 'html':
                    try:
                        import SilverCity
                        #@        << define code-block >>
                        #@+node:ekr.20040331071319.5:<< define code-block >>
                        def code_block(name,arguments,options,content,lineno,content_offset,block_text,state,state_machine):
                            
                            """Create a code-block directive for docutils."""
                            
                            # See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252170
                            language = arguments[0]
                            module = getattr(SilverCity,language)
                            generator = getattr(module,language+"HTMLGenerator")
                            io = StringIO.StringIO()
                            generator().generate_html(io, '\n'.join(content))
                            html = '<div class="code-block">\n%s\n</div>\n'%io.getvalue()
                            raw = docutils.nodes.raw('',html, format='html') #(self, rawsource='', text='', *children, **attributes):
                            return [raw]
                            
                        # These are documented at http://docutils.sourceforge.net/spec/howto/rst-directives.html.
                        code_block.arguments = (
                            1, # Number of required arguments.
                            0, # Number of optional arguments.
                            0) # True if final argument may contain whitespace.
                        
                        # A mapping from option name to conversion function.
                        code_block.options = {
                            'language' :
                            docutils.parsers.rst.directives.unchanged # Return the text argument, unchanged
                        }
                        
                        code_block.content = 1 # True if content is allowed.
                         
                        # Register the directive with docutils.
                        docutils.parsers.rst.directives.register_directive('code-block',code_block)
                        
                        config.do_replace_code_blocks = False
                        #@nonl
                        #@-node:ekr.20040331071319.5:<< define code-block >>
                        #@nl
                        syntax = True
                    except ImportError:
                        g.es('SilverCity not present so no syntax highlighting')
                        #@        << define alternate code block implementation>>
                        #@+node:bwmulder.20050326114320: << define alternate code block implementation>>
                        # Don't know what to do here: Can someone make a suggestion?
                        #import docutils.parsers.rst.directives.admonitions
                        #import docutils.parsers.rst.directives.body
                        # docutils.parsers.rst.directives._directives['code-block'] = docutils.parsers.rst.directives.body.block 
                        # docutils.parsers.rst.directives.register_directive('code-block', docutils.parsers.rst.directives.admonitions.admonition)
                        #docutils.parsers.rst.directives._directives['code-block'] = docutils.parsers.rst.directives.body.pull_quote 
                        # g.es("Registered some alternate implementation for code-block directive")
                        config.do_replace_code_blocks = config.rst2_replace_code_blocks
                        #@-node:bwmulder.20050326114320: << define alternate code block implementation>>
                        #@nl
                
                if config.rst2file:
                    rstFileName = os.path.splitext(fname)[0] + ".txt"
                    rstFile = file(rstFileName, "w")
                    g.es("Using %s as rst file" % rstFileName)
                else:
                    rstFile = StringIO.StringIO()
                config.current_file = fname
                writeTreeAsRst(rstFile,fname,p,c,syntax=syntax)
                if config.rst2file:
                    rstFile.close()
                else:
                    rstText = rstFile.getvalue()
                
                # This code snipped has been taken from code contributed by Paul Paterson 2002-12-05.
                pub = Publisher()
                if config.rst2file:
                    pub.source = FileInput(source_path=rstFileName)
                    pub.destination = FileOutput(destination_path=fname, encoding='unicode')
                else:
                    pub.source = StringInput(source=rstText)
                    pub.destination = StringOutput(pub.settings, encoding=enc)
                pub.set_reader('standalone', None, 'restructuredtext')
                pub.set_writer(writer)
                output = pub.publish(argv=[''])
                
                if config.rst2file:
                    pass
                else:
                    convertedFile = file(fname,'w')
                    convertedFile.write(output)
                    convertedFile.close()
                rstFile.close()
                writeFullFileName(fname)
                return http_support_main(tag, fname)
                
                #@-node:ekr.20040331071319.4:<< write rST as HTML/LaTeX >>
                #@nl
            else:
                #@                << write rST file >>
                #@+node:ekr.20040331071319.6:<< write rST file >>
                rstFile = file(fname,'w')
                writeTreeAsRst(rstFile,fname,p,c)
                rstFile.close()
                writeFullFileName(fname)
                #@nonl
                #@-node:ekr.20040331071319.6:<< write rST file >>
                #@nl
        else:
            # if the headline only contains @rst then open the node and its parent in text editor
            # this works for me but needs to be generalized and should probably be a component
            # of the open_with plugin.
            if 0:
                c.openWith(("os.startfile", None, ".txt"))
                c.selectVnode(p.parent())
                c.openWith(("os.startfile", None, ".tp"))
예제 #10
0
파일: util.py 프로젝트: sdss/sdsstools
def get_doctree(path, **kwargs):
    """
    Obtain a Sphinx doctree from the RST file at ``path``.

    Performs no Releases-specific processing; this code would, ideally, be in
    Sphinx itself, but things there are pretty tightly coupled. So we wrote
    this.

    Any additional kwargs are passed unmodified into an internal `make_app`
    call.

    :param str path: A relative or absolute file path string.

    :returns:
        A two-tuple of the generated ``sphinx.application.Sphinx`` app and the
        doctree (a ``docutils.document`` object).

    .. versionchanged:: 1.6
        Added support for passing kwargs to `make_app`.
    """
    root, filename = os.path.split(path)
    docname, _ = os.path.splitext(filename)
    # TODO: this only works for top level changelog files (i.e. ones where
    # their dirname is the project/doc root)
    app = make_app(srcdir=root, **kwargs)
    # Create & init a BuildEnvironment. Mm, tasty side effects.
    app._init_env(freshenv=True)
    env = app.env
    # More arity/API changes: Sphinx 1.3/1.4-ish require one to pass in the app
    # obj in BuildEnvironment.update(); modern Sphinx performs that inside
    # Application._init_env() (which we just called above) and so that kwarg is
    # removed from update(). EAFP.
    kwargs = dict(
        config=app.config,
        srcdir=root,
        doctreedir=app.doctreedir,
        app=app,
    )
    try:
        env.update(**kwargs)
    except TypeError:
        # Assume newer Sphinx w/o an app= kwarg
        del kwargs["app"]
        env.update(**kwargs)
    # Code taken from sphinx.environment.read_doc; easier to manually call
    # it with a working Environment object, instead of doing more random crap
    # to trick the higher up build system into thinking our single changelog
    # document was "updated".
    env.temp_data["docname"] = docname
    env.app = app
    # NOTE: SphinxStandaloneReader API changed in 1.4 :(
    reader_kwargs = {
        "app": app,
        "parsers": env.config.source_parsers,
    }
    if sphinx.version_info[:2] < (1, 4):
        del reader_kwargs["app"]
    # This monkeypatches (!!!) docutils to 'inject' all registered Sphinx
    # domains' roles & so forth. Without this, rendering the doctree lacks
    # almost all Sphinx magic, including things like :ref: and :doc:!
    with sphinx_domains(env):
        try:
            reader = SphinxStandaloneReader(**reader_kwargs)
        except TypeError:
            # If we import from io, this happens automagically, not in API
            del reader_kwargs["parsers"]
            reader = SphinxStandaloneReader(**reader_kwargs)
        pub = Publisher(
            reader=reader, writer=SphinxDummyWriter(), destination_class=NullOutput
        )
        pub.set_components(None, "restructuredtext", None)
        pub.process_programmatic_settings(None, env.settings, None)
        # NOTE: docname derived higher up, from our given path
        src_path = env.doc2path(docname)
        source = SphinxFileInput(
            app,
            env,
            source=None,
            source_path=src_path,
            encoding=env.config.source_encoding,
        )
        pub.source = source
        pub.settings._source = src_path
        pub.set_destination(None, None)
        pub.publish()
        return app, pub.document
예제 #11
0
def onIconDoubleClick(tag, keywords):

    c = keywords.get("c")
    p = keywords.get("p")
    # g.trace(c)

    if not c or not p:
        return

    applyConfiguration(c)
    config.tag = tag

    h = p.headString().strip()

    if g.match_word(h, 0, "@rst"):
        if len(h) > 5:
            fname = h[5:]
            ext = os.path.splitext(fname)[1].lower()
            if ext in ('.htm', '.html', '.tex'):
                #@                << write rST as HTML/LaTeX >>
                #@+node:ekr.20040331071319.4:<< write rST as HTML/LaTeX >>
                try:
                    import docutils
                except:
                    g.es('HTML/LaTeX generation requires docutils')
                    return
                else:
                    import docutils.parsers.rst
                    from docutils.core import Publisher
                    from docutils.io import StringOutput, StringInput, FileOutput, FileInput
                    import StringIO

                # Set the writer and encoding for the converted file
                if ext in ('.html', '.htm'):
                    writer = 'html'
                    enc = "utf-8"
                else:
                    writer = 'latex'
                    enc = "iso-8859-1"

                syntax = False
                if writer == 'html':
                    try:
                        import SilverCity

                        #@        << define code-block >>
                        #@+node:ekr.20040331071319.5:<< define code-block >>
                        def code_block(name, arguments, options, content,
                                       lineno, content_offset, block_text,
                                       state, state_machine):
                            """Create a code-block directive for docutils."""

                            # See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252170
                            language = arguments[0]
                            module = getattr(SilverCity, language)
                            generator = getattr(module,
                                                language + "HTMLGenerator")
                            io = StringIO.StringIO()
                            generator().generate_html(io, '\n'.join(content))
                            html = '<div class="code-block">\n%s\n</div>\n' % io.getvalue(
                            )
                            raw = docutils.nodes.raw(
                                '', html, format='html'
                            )  #(self, rawsource='', text='', *children, **attributes):
                            return [raw]

                        # These are documented at http://docutils.sourceforge.net/spec/howto/rst-directives.html.
                        code_block.arguments = (
                            1,  # Number of required arguments.
                            0,  # Number of optional arguments.
                            0
                        )  # True if final argument may contain whitespace.

                        # A mapping from option name to conversion function.
                        code_block.options = {
                            'language': docutils.parsers.rst.directives.
                            unchanged  # Return the text argument, unchanged
                        }

                        code_block.content = 1  # True if content is allowed.

                        # Register the directive with docutils.
                        docutils.parsers.rst.directives.register_directive(
                            'code-block', code_block)

                        config.do_replace_code_blocks = False
                        #@nonl
                        #@-node:ekr.20040331071319.5:<< define code-block >>
                        #@nl
                        syntax = True
                    except ImportError:
                        g.es(
                            'SilverCity not present so no syntax highlighting')
                        #@        << define alternate code block implementation>>
                        #@+node:bwmulder.20050326114320: << define alternate code block implementation>>
                        # Don't know what to do here: Can someone make a suggestion?
                        #import docutils.parsers.rst.directives.admonitions
                        #import docutils.parsers.rst.directives.body
                        # docutils.parsers.rst.directives._directives['code-block'] = docutils.parsers.rst.directives.body.block
                        # docutils.parsers.rst.directives.register_directive('code-block', docutils.parsers.rst.directives.admonitions.admonition)
                        #docutils.parsers.rst.directives._directives['code-block'] = docutils.parsers.rst.directives.body.pull_quote
                        # g.es("Registered some alternate implementation for code-block directive")
                        config.do_replace_code_blocks = config.rst2_replace_code_blocks
                        #@-node:bwmulder.20050326114320: << define alternate code block implementation>>
                        #@nl

                if config.rst2file:
                    rstFileName = os.path.splitext(fname)[0] + ".txt"
                    rstFile = file(rstFileName, "w")
                    g.es("Using %s as rst file" % rstFileName)
                else:
                    rstFile = StringIO.StringIO()
                config.current_file = fname
                writeTreeAsRst(rstFile, fname, p, c, syntax=syntax)
                if config.rst2file:
                    rstFile.close()
                else:
                    rstText = rstFile.getvalue()

                # This code snipped has been taken from code contributed by Paul Paterson 2002-12-05.
                pub = Publisher()
                if config.rst2file:
                    pub.source = FileInput(source_path=rstFileName)
                    pub.destination = FileOutput(destination_path=fname,
                                                 encoding='unicode')
                else:
                    pub.source = StringInput(source=rstText)
                    pub.destination = StringOutput(pub.settings, encoding=enc)
                pub.set_reader('standalone', None, 'restructuredtext')
                pub.set_writer(writer)
                output = pub.publish(argv=[''])

                if config.rst2file:
                    pass
                else:
                    convertedFile = file(fname, 'w')
                    convertedFile.write(output)
                    convertedFile.close()
                rstFile.close()
                writeFullFileName(fname)
                return http_support_main(tag, fname)

                #@-node:ekr.20040331071319.4:<< write rST as HTML/LaTeX >>
                #@nl
            else:
                #@                << write rST file >>
                #@+node:ekr.20040331071319.6:<< write rST file >>
                rstFile = file(fname, 'w')
                writeTreeAsRst(rstFile, fname, p, c)
                rstFile.close()
                writeFullFileName(fname)
                #@nonl
                #@-node:ekr.20040331071319.6:<< write rST file >>
                #@nl
        else:
            # if the headline only contains @rst then open the node and its parent in text editor
            # this works for me but needs to be generalized and should probably be a component
            # of the open_with plugin.
            if 0:
                c.openWith(("os.startfile", None, ".txt"))
                c.selectVnode(p.parent())
                c.openWith(("os.startfile", None, ".tp"))