Example #1
0
    def run(self):
        nodelist = []

        if len (self.arguments) >= 1:
            nodelist.append (nodes.title ('', self.arguments[0]))

        literal = nodes.literal_block ('', '\n'.join (self.content))
        literal['classes'].append ('example-source')
        nodelist.append (literal)
        
        if 'norender' not in self.options:
            container = nodes.container ()
            container['classes'].append ('example-rendered')
            self.state.nested_parse (self.content, self.content_offset,
                                     container)
            nodelist.append (container)
        
        topic = nodes.topic ('', *nodelist)
        topic['classes'] += ['example']
        topic['classes'] += self.options.get ('class', [])
        topic['float'] = self.options.get ('float', ('here', 'top', 'bottom', 'page'))
        Example.example_count += 1
        target = lox_target (topic, 'example-%d' % Example.example_count)
        self.state_machine.document.note_implicit_target (target, target)
        return [topic]
Example #2
0
 def _status_str(self, support_status, section):
     while support_status is not None:
         sstatus = support_status.to_dict()
         if sstatus['status'] is support.SUPPORTED:
             msg = _('Available')
         else:
             msg = sstatus['status']
         if sstatus['version'] is not None:
             msg = _('%(msg)s since %(version)s') % {
                 'msg': msg,
                 'version': self._version_str(sstatus['version'])}
         if sstatus['message'] is not None:
             msg = _('%(msg)s - %(status_msg)s') % {
                 'msg': msg,
                 'status_msg': sstatus['message']}
         if not (sstatus['status'] == support.SUPPORTED and
                 sstatus['version'] is None):
             para = nodes.inline('', msg)
             para['classes'] = ['versionmodified']
             parent_para = nodes.paragraph()
             parent_para['classes'] = ['versionsupport']
             parent_para.append(para)
             note = nodes.topic()
             if sstatus['status'] == support.SUPPORTED:
                 note['classes'] = ['versionadded']
             else:
                 note['classes'] = ['deprecated']
             note.append(parent_para)
             section.append(note)
         support_status = support_status.previous_status
Example #3
0
 def run(self):
     if not (self.state_machine.match_titles or isinstance(self.state_machine.node, nodes.sidebar)):
         raise self.error('The "%s" directive may not be used within ' "topics or body elements." % self.name)
     document = self.state_machine.document
     language = languages.get_language(document.settings.language_code)
     if self.arguments:
         title_text = self.arguments[0]
         text_nodes, messages = self.state.inline_text(title_text, self.lineno)
         title = nodes.title(title_text, "", *text_nodes)
     else:
         messages = []
         if self.options.has_key("local"):
             title = None
         else:
             title = nodes.title("", language.labels["contents"])
     topic = nodes.topic(classes=["contents"])
     topic["classes"] += self.options.get("class", [])
     if self.options.has_key("local"):
         topic["classes"].append("local")
     if title:
         name = title.astext()
         topic += title
     else:
         name = language.labels["contents"]
     name = nodes.fully_normalize_name(name)
     if not document.has_name(name):
         topic["names"].append(name)
     document.note_implicit_target(topic)
     pending = nodes.pending(parts.Contents, rawsource=self.block_text)
     pending.details.update(self.options)
     document.note_pending(pending)
     topic += pending
     return [topic] + messages
Example #4
0
 def _status_str(self, support_status, section):
     while support_status is not None:
         sstatus = support_status.to_dict()
         if sstatus['status'] is support.SUPPORTED:
             msg = _('Available')
         else:
             msg = sstatus['status']
         if sstatus['version'] is not None:
             msg = _('%(msg)s since %(version)s') % {
                 'msg': msg,
                 'version': self._version_str(sstatus['version'])}
         if sstatus['message'] is not None:
             msg = _('%(msg)s - %(status_msg)s') % {
                 'msg': msg,
                 'status_msg': sstatus['message']}
         if not (sstatus['status'] == support.SUPPORTED and
                 sstatus['version'] is None):
             para = nodes.inline('', msg)
             para['classes'] = ['versionmodified']
             parent_para = nodes.paragraph()
             parent_para['classes'] = ['versionsupport']
             parent_para.append(para)
             note = nodes.topic()
             if sstatus['status'] == support.SUPPORTED:
                 note['classes'] = ['versionadded']
             else:
                 note['classes'] = ['deprecated']
             note.append(parent_para)
             section.append(note)
         support_status = support_status.previous_status
Example #5
0
 def apply(self):
     language = languages.get_language(self.document.settings.language_code)
     name = language.labels['contents']
     title = nodes.title('', name)
     topic = nodes.topic('', title, classes=['contents'])
     name = nodes.fully_normalize_name(name)
     if not self.document.has_name(name):
         topic['names'].append(name)
     self.document.note_implicit_target(topic)
     pending = nodes.pending(parts.Contents)
     topic += pending
     self.document.insert(1, topic)
     self.document.note_pending(pending)
Example #6
0
 def apply(self):
     language = languages.get_language(self.document.settings.language_code)
     name = language.labels['contents']
     title = nodes.title('', name)
     topic = nodes.topic('', title, classes=['contents'])
     name = nodes.fully_normalize_name(name)
     if not self.document.has_name(name):
         topic['names'].append(name)
     self.document.note_implicit_target(topic)
     pending = nodes.pending(parts.Contents)
     topic += pending
     self.document.insert(1, topic)
     self.document.note_pending(pending)
    def run(self):
        artifact_path = os.environ.get('DOCS_ROOT', './.doc')
        full_path = '{}.json'.format(
            os.path.join('../', artifact_path, self.arguments[0]))
        with open(full_path) as f:
            obj_data = json.load(f)

        p_fields = (SerializerField(f, self).process()
                    for f in obj_data['fields'])

        class_name = obj_data['class_name']

        table_fields = nodes.tbody('')
        table_fields.extend(p_fields)

        name = nodes.title('', '{}'.format(class_name))
        table_head = nodes.thead(
            '',
            nodes.row(
                '',
                nodes.entry('', p('name')),
                nodes.entry('', p('type')),
                nodes.entry('', p('description')),
            ),
        )
        tbl = nodes.table()
        tg = nodes.tgroup()
        tbl.append(tg)
        tg.append(nodes.colspec(colwidth=1))
        tg.append(nodes.colspec(colwidth=8))
        tg.append(nodes.colspec(colwidth=8))
        tg.append(table_head)
        tg.append(table_fields)

        class_descr = 'Class: *{}.{}*'.format(obj_data['class_module'],
                                              class_name)
        filter_field_param = 'Filter field: *{}*'.format(
            obj_data['field_param'])
        description = (obj_data.get('class_doc', '') or '').strip()
        full_name = self.parse(class_descr)
        filter_param = self.parse(filter_field_param)

        sections = ['', name]
        if description:
            sections.append(self.parse(description))
        sections.extend([full_name, filter_param, p('', nodes.topic('', tbl))])

        raw = nodes.section(*sections)

        target = self.parse('.. _{name}:'.format(name=class_name))
        return [target, raw]
Example #8
0
def contents(name, arguments, options, content, lineno, content_offset,
             block_text, state, state_machine):
    """
    Table of contents.

    The table of contents is generated in two passes: initial parse and
    transform.  During the initial parse, a 'pending' element is generated
    which acts as a placeholder, storing the TOC title and any options
    internally.  At a later stage in the processing, the 'pending' element is
    replaced by a 'topic' element, a title and the table of contents proper.
    """
    if not (state_machine.match_titles
            or isinstance(state_machine.node, nodes.sidebar)):
        error = state_machine.reporter.error(
            'The "%s" directive may not be used within topics '
            'or body elements.' % name,
            nodes.literal_block(block_text, block_text),
            line=lineno)
        return [error]
    document = state_machine.document
    language = languages.get_language(document.settings.language_code)
    if arguments:
        title_text = arguments[0]
        text_nodes, messages = state.inline_text(title_text, lineno)
        title = nodes.title(title_text, '', *text_nodes)
    else:
        messages = []
        if options.has_key('local'):
            title = None
        else:
            title = nodes.title('', language.labels['contents'])
    topic = nodes.topic(classes=['contents'])
    topic['classes'] += options.get('class', [])
    if options.has_key('local'):
        topic['classes'].append('local')
    if title:
        name = title.astext()
        topic += title
    else:
        name = language.labels['contents']
    name = nodes.fully_normalize_name(name)
    if not document.has_name(name):
        topic['names'].append(name)
    document.note_implicit_target(topic)
    pending = nodes.pending(parts.Contents, rawsource=block_text)
    pending.details.update(options)
    document.note_pending(pending)
    topic += pending
    return [topic] + messages
Example #9
0
    def run(self):
        set_classes(self.options)

        title_text = self.arguments[0]
        title_elements, _ = self.state.inline_text(title_text, self.lineno)
        title_node = nodes.title('', '', *title_elements)

        text = '\n'.join(self.content)
        topic_node = nodes.topic(text, **self.options)
        topic_node['classes'] += ['m-block', self.style_class]
        topic_node.append(title_node)

        self.state.nested_parse(self.content, self.content_offset, topic_node)

        return [topic_node]
Example #10
0
def contents(name, arguments, options, content, lineno,
             content_offset, block_text, state, state_machine):
    """
    Table of contents.

    The table of contents is generated in two passes: initial parse and
    transform.  During the initial parse, a 'pending' element is generated
    which acts as a placeholder, storing the TOC title and any options
    internally.  At a later stage in the processing, the 'pending' element is
    replaced by a 'topic' element, a title and the table of contents proper.
    """
    if not (state_machine.match_titles
            or isinstance(state_machine.node, nodes.sidebar)):
        error = state_machine.reporter.error(
              'The "%s" directive may not be used within topics '
              'or body elements.' % name,
              nodes.literal_block(block_text, block_text), line=lineno)
        return [error]
    document = state_machine.document
    language = languages.get_language(document.settings.language_code)
    if arguments:
        title_text = arguments[0]
        text_nodes, messages = state.inline_text(title_text, lineno)
        title = nodes.title(title_text, '', *text_nodes)
    else:
        messages = []
        if options.has_key('local'):
            title = None
        else:
            title = nodes.title('', language.labels['contents'])
    topic = nodes.topic(classes=['contents'])
    topic['classes'] += options.get('class', [])
    if options.has_key('local'):
        topic['classes'].append('local')
    if title:
        name = title.astext()
        topic += title
    else:
        name = language.labels['contents']
    name = nodes.fully_normalize_name(name)
    if not document.has_name(name):
        topic['names'].append(name)
    document.note_implicit_target(topic)
    pending = nodes.pending(parts.Contents, rawsource=block_text)
    pending.details.update(options)
    document.note_pending(pending)
    topic += pending
    return [topic] + messages
Example #11
0
    def run(self):
        set_classes(self.options)

        title_text = self.arguments[0]
        title_elements, _ = self.state.inline_text(title_text, self.lineno)
        title_node = nodes.title('', '', *title_elements)

        text = '\n'.join(self.content)
        topic_node = nodes.topic(text, **self.options)
        topic_node['classes'] += ['m-block', self.style_class]
        topic_node.append(title_node)

        self.state.nested_parse(self.content, self.content_offset,
                                topic_node)

        return [topic_node]
Example #12
0
 def run(self):
     if not (self.state_machine.match_titles
             or isinstance(self.state_machine.node, nodes.sidebar)):
         raise self.error('The "%s" directive may not be used within '
                          'topics or body elements.' % self.name)
     document = self.state_machine.document
     language = languages.get_language(document.settings.language_code,
                                       document.reporter)
     if self.arguments:
         title_text = self.arguments[0]
         text_nodes, messages = self.state.inline_text(
             title_text, self.lineno)
         title = nodes.title(title_text, '', *text_nodes)
     else:
         messages = []
         if 'local' in self.options:
             title = None
         else:
             title = nodes.title('', language.labels['contents'])
     topic = nodes.topic(classes=['contents'])
     topic['classes'] += self.options.get('class', [])
     # the latex2e writer needs source and line for a warning:
     src, srcline = self.state_machine.get_source_and_line()
     topic.source = src
     topic.line = srcline - 1
     if 'local' in self.options:
         topic['classes'].append('local')
     if title:
         name = title.astext()
         topic += title
     else:
         name = language.labels['contents']
     name = nodes.fully_normalize_name(name)
     if not document.has_name(name):
         topic['names'].append(name)
     document.note_implicit_target(topic)
     pending = nodes.pending(parts.Contents, rawsource=self.block_text)
     pending.details.update(self.options)
     document.note_pending(pending)
     topic += pending
     return [topic] + messages
Example #13
0
 def run(self):
     if not (self.state_machine.match_titles
             or isinstance(self.state_machine.node, nodes.sidebar)):
         raise self.error('The "%s" directive may not be used within '
                          'topics or body elements.' % self.name)
     document = self.state_machine.document
     language = languages.get_language(document.settings.language_code,
                                       document.reporter)
     if self.arguments:
         title_text = self.arguments[0]
         text_nodes, messages = self.state.inline_text(title_text,
                                                       self.lineno)
         title = nodes.title(title_text, '', *text_nodes)
     else:
         messages = []
         if 'local' in self.options:
             title = None
         else:
             title = nodes.title('', language.labels['contents'])
     topic = nodes.topic(classes=['contents'])
     topic['classes'] += self.options.get('class', [])
     # the latex2e writer needs source and line for a warning:
     src, srcline = self.state_machine.get_source_and_line()
     topic.source = src
     topic.line = srcline - 1
     if 'local' in self.options:
         topic['classes'].append('local')
     if title:
         name = title.astext()
         topic += title
     else:
         name = language.labels['contents']
     name = nodes.fully_normalize_name(name)
     if not document.has_name(name):
         topic['names'].append(name)
     document.note_implicit_target(topic)
     pending = nodes.pending(parts.Contents, rawsource=self.block_text)
     pending.details.update(self.options)
     document.note_pending(pending)
     topic += pending
     return [topic] + messages
Example #14
0
    def apply(self) -> None:
        if not Path(self.document["source"]).match("pep-*"):
            return  # not a PEP file, exit early

        # Create the contents placeholder section
        title = nodes.title("", "Contents")
        contents_topic = nodes.topic("", title, classes=["contents"])
        if not self.document.has_name("contents"):
            contents_topic["names"].append("contents")
        self.document.note_implicit_target(contents_topic)

        # Add a table of contents builder
        pending = nodes.pending(Contents)
        contents_topic += pending
        self.document.note_pending(pending)

        # Insert the toc after title and PEP headers
        self.document.children[0].insert(2, contents_topic)

        # Add a horizontal rule before contents
        transition = nodes.transition()
        self.document[0].insert(2, transition)
Example #15
0
 def apply(self):
     topic = nodes.topic(CLASS='contents')
     details = self.startnode.details
     if details.has_key('class'):
         topic.set_class(details['class'])
     title = details['title']
     if details.has_key('local'):
         startnode = self.startnode.parent
         # @@@ generate an error if the startnode (directive) not at
         # section/document top-level? Drag it up until it is?
         while not isinstance(startnode, nodes.Structural):
             startnode = startnode.parent
     else:
         startnode = self.document
         if not title:
             title = nodes.title('', self.language.labels['contents'])
     if title:
         name = title.astext()
         topic += title
     else:
         name = self.language.labels['contents']
     name = nodes.fully_normalize_name(name)
     if not self.document.has_name(name):
         topic['name'] = name
     self.document.note_implicit_target(topic)
     self.toc_id = topic['id']
     if details.has_key('backlinks'):
         self.backlinks = details['backlinks']
     else:
         self.backlinks = self.document.settings.toc_backlinks
     contents = self.build_contents(startnode)
     if len(contents):
         topic += contents
         self.startnode.parent.replace(self.startnode, topic)
     else:
         self.startnode.parent.remove(self.startnode)
Example #16
0
    def run(self):
        nodelist = []

        if len(self.arguments) >= 1:
            nodelist.append(nodes.title('', self.arguments[0]))

        literal = nodes.literal_block('', '\n'.join(self.content))
        literal['classes'].append('example-source')
        nodelist.append(literal)

        if 'norender' not in self.options:
            container = nodes.container()
            container['classes'].append('example-rendered')
            self.state.nested_parse(self.content, self.content_offset,
                                    container)
            nodelist.append(container)

        topic = nodes.topic('', *nodelist)
        topic['classes'] += ['example']
        topic['classes'] += self.options.get('class', [])
        Example.example_count += 1
        target = lox_target(topic, 'example-%d' % Example.example_count)
        self.state_machine.document.note_implicit_target(target, target)
        return [topic]
Example #17
0
    def make_document(self, doc_strings):
        
        """make doctree representation of collected fragments"""

        opt = self.opt  

        big_doc = publish_doctree("")
        self.document = big_doc
        big_doc += nodes.title(text="Plugins listing generated %s" %
            time.asctime())

        contents = nodes.container()
        if opt.include_contents:
            big_doc += nodes.topic('', nodes.title(text='Contents'), contents)

        if not opt.no_summary:
            def_list = nodes.definition_list()
            alpha_list = nodes.paragraph()
            big_doc += nodes.section('', nodes.title(text="Plugins summary"),
                alpha_list, def_list)

        last_alpha = ''

        for doc in doc_strings:
            
            section = nodes.section()
            big_doc += section
            section += nodes.title(text=doc[0])

            self.add_ids(section)

            if not opt.no_summary:
                firstpara = (self.first_text(doc[2]) or
                    nodes.paragraph(text='No summary found'))
                reference = nodes.reference('', refid=section['ids'][0],
                    name = doc[0], anonymous=1)
                reference += nodes.Text(doc[0])
                def_list += nodes.definition_list_item('',
                    nodes.term('', '', reference),
                    nodes.definition('', firstpara)
                )

                # add letter quick index entry if needed
                if doc[0][0].upper() != last_alpha:
                    last_alpha = doc[0][0].upper()
                    self.add_ids(reference)
                    alpha_list += nodes.reference('',
                        nodes.Text(last_alpha+' '),
                        refid=reference['ids'][0], name = doc[0], anonymous=1)

            for element in doc[2]:
                # if the docstring has titles, we need another level
                if element.tagname == 'title':
                    subsection = nodes.section() 
                    section += subsection
                    section = subsection
                    break

            for element in doc[2]:
                try:
                    section += element.deepcopy()
                except TypeError:
                    err(
                        'Element.deepcopy() failed, dropped element for %s\n' %
                        doc[0])

        if opt.include_contents:
            contents.details = {'text': 'Contents here'}

            self.add_ids(big_doc)
            transform = Contents(big_doc, contents)
            transform.apply()

        return big_doc
Example #18
0
    def make_document(self, doc_strings):
        """make doctree representation of collected fragments"""

        opt = self.opt

        big_doc = publish_doctree("")
        self.document = big_doc
        big_doc += nodes.title(text="Plugins listing generated %s" %
                               time.asctime())

        contents = nodes.container()
        if opt.include_contents:
            big_doc += nodes.topic('', nodes.title(text='Contents'), contents)

        if not opt.no_summary:
            def_list = nodes.definition_list()
            alpha_list = nodes.paragraph()
            big_doc += nodes.section('', nodes.title(text="Plugins summary"),
                                     alpha_list, def_list)

        last_alpha = ''

        for doc in doc_strings:

            section = nodes.section()
            big_doc += section
            section += nodes.title(text=doc[0])

            self.add_ids(section)

            if not opt.no_summary:
                firstpara = (self.first_text(doc[2])
                             or nodes.paragraph(text='No summary found'))
                reference = nodes.reference('',
                                            refid=section['ids'][0],
                                            name=doc[0],
                                            anonymous=1)
                reference += nodes.Text(doc[0])
                def_list += nodes.definition_list_item(
                    '', nodes.term('', '', reference),
                    nodes.definition('', firstpara))

                # add letter quick index entry if needed
                if doc[0][0].upper() != last_alpha:
                    last_alpha = doc[0][0].upper()
                    self.add_ids(reference)
                    alpha_list += nodes.reference('',
                                                  nodes.Text(last_alpha + ' '),
                                                  refid=reference['ids'][0],
                                                  name=doc[0],
                                                  anonymous=1)

            for element in doc[2]:
                # if the docstring has titles, we need another level
                if element.tagname == 'title':
                    subsection = nodes.section()
                    section += subsection
                    section = subsection
                    break

            for element in doc[2]:
                try:
                    section += element.deepcopy()
                except TypeError:
                    err('Element.deepcopy() failed, dropped element for %s\n' %
                        doc[0])

        if opt.include_contents:
            contents.details = {'text': 'Contents here'}

            self.add_ids(big_doc)
            transform = Contents(big_doc, contents)
            transform.apply()

        return big_doc
Example #19
0
                    para += valpara
            except TypeError, e:
                pass # didn't convert to python, but okay. maybe v.val was boost::posix_time::ptime or something.
        

            entry += nodes.paragraph('', v.doc)

        return section

    d['name'] = CellType.__name__
    d['short_doc'] = CellType.short_doc

    cell = nodes.section()
    cell += nodes.title(text=CellType.__name__)
    cell += content
    top = nodes.topic()
    cell += top
    cell['ids'].append(CellType.__name__)
    cell['names'].append(CellType.__name__)
    # cell += nodes.title(text=CellType.__name__, rawtest=CellType.__name__)
    para = nodes.title(text="Brief doc")
    para += nodes.paragraph(text=CellType.short_doc)
    top += para
    #params = nodes.rubric(text='parameters')
    # params += nodes.subtitle(text="parameters")

    inst = CellType.inspect((),{})

    top += gettendril('Parameters', inst.params, True)
    top += gettendril('Inputs', inst.inputs, False)
    top += gettendril('Outputs', inst.outputs, False)
Example #20
0
    def translate(self):
        visitor = PDFTranslator(self.document, self.builder)
        self.document.walkabout(visitor)
        lang = self.config.language or 'en'
        langmod = get_language_available(lang)[2]
        self.docutils_languages = {lang: langmod}

        # Generate Contents topic manually
        if self.use_toc:
            contents=nodes.topic(classes=['contents'])
            contents+=nodes.title('')
            contents[0]+=nodes.Text(langmod.labels['contents'])
            contents['ids']=['Contents']
            pending=nodes.topic()
            contents.append(pending)
            pending.details={}
            self.document.insert(0,nodes.raw(text='SetPageCounter 1 arabic', format='pdf'))
            self.document.insert(0,nodes.raw(text='OddPageBreak %s'%self.page_template, format='pdf'))
            self.document.insert(0,contents)
            self.document.insert(0,nodes.raw(text='SetPageCounter 1 lowerroman', format='pdf'))
            contTrans=PDFContents(self.document)
            contTrans.toc_depth = self.toc_depth
            contTrans.startnode=pending
            contTrans.apply()

        if self.use_coverpage:
            # Generate cover page

            # FIXME: duplicate from createpdf, refactor!
            # Add the Sphinx template paths
            def add_template_path(path):
                return os.path.join(self.srcdir, path)

            jinja_env = jinja2.Environment(
                loader=jinja2.FileSystemLoader([
                        self.srcdir, os.path.expanduser('~/.rst2pdf'),
                        os.path.join(self.PATH,'templates')] +
                        list(map(add_template_path, self.config.templates_path))),
                autoescape=jinja2.select_autoescape(['html', 'xml'])
            )

            try:
                template = jinja_env.get_template(self.config.pdf_cover_template)
            except jinja2.TemplateNotFound:
                log.error("Can't find cover template %s, using default"%self.config.pdf_cover_template)
                template = jinja_env.get_template('sphinxcover.tmpl')

            # This is what's used in the python docs because
            # Latex does a manual linebreak. This sucks.
            authors=self.document.settings.author.split('\\')

            # Honour the "today" config setting
            if self.config.today :
                date = self.config.today
            else:
                date=time.strftime(self.config.today_fmt or _('%B %d, %Y'))

            # Feed data to the template, get restructured text.
            cover_text = template.render(
                                title=self.document.settings.title or visitor.elements['title'],
                                subtitle='%s %s'%(_('version'),self.config.version),
                                authors=authors,
                                date=date
                                )

            cover_tree = docutils.core.publish_doctree(cover_text)
            self.document.insert(0, cover_tree)

        sio=BytesIO()

        if self.invariant:
            createpdf.patch_PDFDate()
            createpdf.patch_digester()

        createpdf.RstToPdf(sphinx=True,
                 stylesheets=self.stylesheets,
                 language=self.__language,
                 breaklevel=self.breaklevel,
                 breakside=self.breakside,
                 fit_mode=self.fitmode,
                 font_path=self.fontpath,
                 inline_footnotes=self.inline_footnotes,
                 highlightlang=self.highlightlang,
                 splittables=self.splittables,
                 style_path=self.style_path,
                 repeat_table_rows=self.repeat_table_rows,
                 basedir=self.srcdir,
                 def_dpi=self.default_dpi,
                 real_footnotes=self.real_footnotes,
                 numbered_links=self.use_numbered_links,
                 background_fit_mode=self.fit_background_mode,
                 baseurl=self.baseurl,
                 section_header_depth=self.section_header_depth
                ).createPdf(doctree=self.document,
                    output=sio,
                    compressed=self.compressed)
        self.output=sio.getvalue()
    def translate(self):
        visitor = PDFTranslator(self.document, self.builder)
        self.document.walkabout(visitor)
        lang = self.config.language or 'en'
        langmod = get_language_available(lang)[2]
        self.docutils_languages = {lang: langmod}

        # Generate Contents topic manually
        if self.use_toc:
            contents = nodes.topic(classes=['contents'])
            contents += nodes.title('')
            contents[0] += nodes.Text(langmod.labels['contents'])
            contents['ids'] = ['Contents']
            pending = nodes.topic()
            contents.append(pending)
            pending.details = {}
            self.document.insert(
                0, nodes.raw(text='SetPageCounter 1 arabic', format='pdf'))
            self.document.insert(
                0,
                nodes.raw(text='OddPageBreak %s' % self.page_template,
                          format='pdf'))
            self.document.insert(0, contents)
            self.document.insert(
                0, nodes.raw(text='SetPageCounter 1 lowerroman', format='pdf'))
            contTrans = PDFContents(self.document)
            contTrans.toc_depth = self.toc_depth
            contTrans.startnode = pending
            contTrans.apply()

        if self.use_coverpage:
            # Generate cover page

            # FIXME: duplicate from createpdf, refactor!

            # Find cover template, save it in cover_file
            def find_cover(name):
                cover_path = [
                    self.srcdir,
                    os.path.expanduser('~/.rst2pdf'),
                    os.path.join(self.PATH, 'templates')
                ]

                # Add the Sphinx template paths
                def add_template_path(path):
                    return os.path.join(self.srcdir, path)

                cover_path.extend(
                    map(add_template_path, self.config.templates_path))

                cover_file = None
                for d in cover_path:
                    if os.path.exists(os.path.join(d, name)):
                        cover_file = os.path.join(d, name)
                        break
                return cover_file

            cover_file = find_cover(self.config.pdf_cover_template)
            if cover_file is None:
                log.error("Can't find cover template %s, using default" %
                          self.custom_cover)
                cover_file = find_cover('sphinxcover.tmpl')

            # This is what's used in the python docs because
            # Latex does a manual linebreak. This sucks.
            authors = self.document.settings.author.split('\\')

            # Feed data to the template, get restructured text.
            cover_text = createpdf.renderTemplate(
                tname=cover_file,
                title=self.document.settings.title
                or visitor.elements['title'],
                subtitle='%s %s' % (_('version'), self.config.version),
                authors=authors,
                date=ustrftime(self.config.today_fmt or _('%B %d, %Y')))

            cover_tree = docutils.core.publish_doctree(cover_text)
            self.document.insert(0, cover_tree)

        sio = StringIO()

        if self.invariant:
            createpdf.patch_PDFDate()
            createpdf.patch_digester()

        createpdf.RstToPdf(sphinx=True,
                           stylesheets=self.stylesheets,
                           language=self.__language,
                           breaklevel=self.breaklevel,
                           breakside=self.breakside,
                           fit_mode=self.fitmode,
                           font_path=self.fontpath,
                           inline_footnotes=self.inline_footnotes,
                           highlightlang=self.highlightlang,
                           splittables=self.splittables,
                           style_path=self.style_path,
                           basedir=self.srcdir,
                           def_dpi=self.default_dpi,
                           real_footnotes=self.real_footnotes,
                           numbered_links=self.use_numbered_links,
                           background_fit_mode=self.fit_background_mode,
                           baseurl=self.baseurl,
                           section_header_depth=self.section_header_depth,
                           floating_images=self.floating_images).createPdf(
                               doctree=self.document,
                               output=sio,
                               compressed=self.compressed)
        self.output = sio.getvalue()
Example #22
0
    def translate(self):
        visitor = PDFTranslator(self.document, self.builder)
        self.document.walkabout(visitor)
        lang = self.config.language or 'en'
        langmod = get_language_available(lang)[2]
        self.docutils_languages = {lang: langmod}

        # Generate Contents topic manually
        if self.use_toc:
            contents=nodes.topic(classes=['contents'])
            contents+=nodes.title('')
            contents[0]+=nodes.Text(langmod.labels['contents'])
            contents['ids']=['Contents']
            pending=nodes.topic()
            contents.append(pending)
            pending.details={}
            self.document.insert(0,nodes.raw(text='SetPageCounter 1 arabic', format='pdf'))
            self.document.insert(0,nodes.raw(text='OddPageBreak %s'%self.page_template, format='pdf'))
            self.document.insert(0,contents)
            self.document.insert(0,nodes.raw(text='SetPageCounter 1 lowerroman', format='pdf'))
            contTrans=PDFContents(self.document)
            contTrans.toc_depth = self.toc_depth
            contTrans.startnode=pending
            contTrans.apply()

        if self.use_coverpage:
            # Generate cover page

            # FIXME: duplicate from createpdf, refactor!

            # Find cover template, save it in cover_file
            def find_cover(name):
                cover_path=[self.srcdir, os.path.expanduser('~/.rst2pdf'),
                                            os.path.join(self.PATH,'templates')]

                # Add the Sphinx template paths
                def add_template_path(path):
                    return os.path.join(self.srcdir, path)

                cover_path.extend(map(add_template_path, self.config.templates_path))

                cover_file=None
                for d in cover_path:
                    if os.path.exists(os.path.join(d,name)):
                        cover_file=os.path.join(d,name)
                        break
                return cover_file

            cover_file=find_cover(self.config.pdf_cover_template)
            if cover_file is None:
                log.error("Can't find cover template %s, using default"%self.custom_cover)
                cover_file=find_cover('sphinxcover.tmpl')

            # This is what's used in the python docs because
            # Latex does a manual linebreak. This sucks.
            authors=self.document.settings.author.split('\\')

            # Feed data to the template, get restructured text.
            cover_text = createpdf.renderTemplate(tname=cover_file,
                                title=self.document.settings.title or visitor.elements['title'],
                                subtitle='%s %s'%(_('version'),self.config.version),
                                authors=authors,
                                date=ustrftime(self.config.today_fmt or _('%B %d, %Y'))
                                )

            cover_tree = docutils.core.publish_doctree(cover_text)
            self.document.insert(0, cover_tree)

        sio=StringIO()

        if self.invariant:
            createpdf.patch_PDFDate()
            createpdf.patch_digester()

        createpdf.RstToPdf(sphinx=True,
                 stylesheets=self.stylesheets,
                 language=self.__language,
                 breaklevel=self.breaklevel,
                 breakside=self.breakside,
                 fit_mode=self.fitmode,
                 font_path=self.fontpath,
                 inline_footnotes=self.inline_footnotes,
                 highlightlang=self.highlightlang,
                 splittables=self.splittables,
                 style_path=self.style_path,
                 basedir=self.srcdir,
                 def_dpi=self.default_dpi,
                 real_footnotes=self.real_footnotes,
                 numbered_links=self.use_numbered_links,
                 background_fit_mode=self.fit_background_mode,
                 baseurl=self.baseurl,
                 section_header_depth=self.section_header_depth
                ).createPdf(doctree=self.document,
                    output=sio,
                    compressed=self.compressed)
        self.output=sio.getvalue()
Example #23
0
    def build_node(self) -> nodes.Node:
        book_topic = nodes.topic(classes=['book-topic'])
        book_topic += nodes.target('', '', ids=[self.id])
        book_title = nodes.paragraph(text=self.title, classes=['book-title'])
        if not self.subtitle == '':
            book_title += nodes.inline(text=': ', classes=['book-punctuation'])
            book_title += nodes.inline(text=self.subtitle,
                                       classes=['book-subtitle'])

        book_topic += book_title

        if not self.title_localized == '':
            book_title_localized = nodes.paragraph(
                text=self.title_localized, classes=['book-title-localized'])

            if not self.subtitle_localized == '':
                book_title_localized += nodes.inline(
                    text=': ', classes=['book-punctuation'])
                book_title_localized += nodes.inline(
                    text=self.subtitle_localized,
                    classes=['book-subtitle-localized'])

            book_topic += book_title_localized

        book_tags = nodes.paragraph(classes=['book-tags-container'])

        first_space = True
        for t in self.tags:
            if first_space:
                first_space = False
            if not first_space:
                book_tags += nodes.inline(text=' ',
                                          classes=['book-punctuation'])

            tag_unique_id = -1 \
                if self.domain is None else self.domain.get_tag_unique_id(t.strip())
            domain_name = 'problematic' if self.domain is None else self.domain.name
            current_file_name = 'problematic' \
                if self.domain is None else self.domain.env.docname

            tag_index_file_name = '{}-{}_{}'.format(domain_name, 'tag',
                                                    tag_unique_id)

            tag_reference = nodes.reference(internal=True)
            tag_reference[
                'refuri'] = self.domain.env.app.builder.get_relative_uri(
                    current_file_name, tag_index_file_name)
            tag_reference += nodes.inline(text=t.strip(), classes=['book-tag'])
            book_tags += tag_reference

        book_topic += book_tags

        book_folder_component = nodes.paragraph(
            text=self.build_folder_title(), classes=['book-file-component'])
        book_topic += book_folder_component

        book_left_bullet_list = nodes.bullet_list(bullet='*')

        authors_list_item = nodes.list_item()
        authors_list_item += self.build_node_authors()
        book_left_bullet_list += authors_list_item

        book_right_bullet_list = nodes.bullet_list(bullet='*')

        issues_list_item = nodes.list_item()
        issues_list_item += self.build_node_issues()
        book_right_bullet_list += issues_list_item

        root_hlist = addnodes.hlist()
        root_hlist += addnodes.hlistcol('', book_left_bullet_list)
        root_hlist += addnodes.hlistcol('', book_right_bullet_list)
        book_topic += root_hlist

        return book_topic
Example #24
0
    def translate(self):
        visitor = PDFTranslator(self.document, self.builder)
        self.document.walkabout(visitor)
        
        if self.config.language:
            langmod = languages.get_language(self.config.language[:2])
        else:
            langmod = languages.get_language('en')
            
        # Generate Contents topic manually
        contents=nodes.topic(classes=['contents'])
        contents+=nodes.title('')
        contents[0]+=nodes.Text( langmod.labels['contents'])
        contents['ids']=['Contents']
        pending=nodes.topic()
        contents.append(pending)
        pending.details={}
        self.document.insert(0,nodes.raw(text='SetPageCounter 1 arabic', format='pdf'))
        self.document.insert(0,nodes.raw(text='OddPageBreak %s'%self.page_template, format='pdf'))
        self.document.insert(0,contents)
        self.document.insert(0,nodes.raw(text='SetPageCounter 1 lowerroman', format='pdf'))
        contTrans=PDFContents(self.document)
        contTrans.startnode=pending
        contTrans.apply()

        if self.config.pdf_use_coverpage:
            # Generate cover page
            spacer=docutils.core.publish_doctree('.. raw:: pdf\n\n    Spacer 0 3cm\n\n')[0]
            doctitle=nodes.title()
            doctitle.append(nodes.Text(self.document.settings.title or visitor.elements['title']))
            docsubtitle=nodes.subtitle()
            docsubtitle.append(nodes.Text('%s %s'%(_('version'),self.config.version)))
            # This is what's used in the python docs because
            # Latex does a manual linrebreak. This sucks.
            authors=self.document.settings.author.split('\\') 
                                       
            authornodes=[]
            for author in authors:
                node=nodes.paragraph()
                node.append(nodes.Text(author))
                node['classes']=['author']
                authornodes.append(node)
            date=nodes.paragraph()
            date.append(nodes.Text(ustrftime(self.config.today_fmt or _('%B %d, %Y'))))
            date['classes']=['author']
            self.document.insert(0,nodes.raw(text='OddPageBreak %s'%self.page_template, format='pdf'))
            self.document.insert(0,date)
            self.document.insert(0,spacer)
            for node in authornodes[::-1]:
                self.document.insert(0,node)
            self.document.insert(0,spacer)
            self.document.insert(0,docsubtitle)
            self.document.insert(0,doctitle)
        
        
        
        sio=StringIO()
        
        if self.invariant:
            createpdf.patch_PDFDate()
            createpdf.patch_digester()
        
        createpdf.RstToPdf(sphinx=True,
                 stylesheets=self.stylesheets,
                 language=self.__language,
                 breaklevel=self.breaklevel,
                 breakside=self.breakside,
                 fit_mode=self.fitmode,
                 font_path=self.fontpath,
                 inline_footnotes=self.inline_footnotes,
                 highlightlang=self.highlightlang,
                 splittables=self.splittables,
                 style_path=[self.srcdir],
                 basedir=self.srcdir,
                 def_dpi=self.default_dpi,
                ).createPdf(doctree=self.document,
                    output=sio,
                    compressed=self.compressed)
        self.output=sio.getvalue()
                        valpara += nodes.literal(
                            '', "%s (%d)   " % (str(thename), thevalue))
                    para += valpara
            except TypeError, e:
                pass  # didn't convert to python, but okay. maybe v.val was boost::posix_time::ptime or something.

            entry += nodes.paragraph('', v.doc)

        return section

    d['name'] = CellType.__name__
    d['short_doc'] = getattr(CellType, 'short_doc', '')
    cell = nodes.section()
    cell += nodes.title(text=CellType.__name__)
    cell += content
    top = nodes.topic()
    cell += top
    cell['ids'].append(CellType.__name__)
    cell['names'].append(CellType.__name__)

    para = nodes.title(text="Brief doc")
    para += nodes.paragraph(text=d['short_doc'])
    top += para

    inst = CellType.inspect()

    top += gettendril('Parameters', inst.params, True)
    top += gettendril('Inputs', inst.inputs, False)
    top += gettendril('Outputs', inst.outputs, False)

    return cell