Example #1
0
 def run(self):
   if ValueTableDirective.values[0].description is None:
     list = nodes.bullet_list()
     for v in ValueTableDirective.values:
       item = nodes.list_item()
       item += nodes.literal(v.value, v.value)
       list += item
     return [list]
   table = nodes.table()
   tgroup = nodes.tgroup()
   tbody = nodes.tbody()
   for v in ValueTableDirective.values:
     row = nodes.row()
     entry = nodes.entry()
     entry += nodes.literal(v.value, v.value)
     row += entry
     entry = nodes.entry()
     entry += nodes.paragraph(text=v.description)
     row += entry
     tbody += row
   tgroup += nodes.colspec(colwidth=10)
   tgroup += nodes.colspec(colwidth=90)
   tgroup += tbody
   table += tgroup
   return [table]
Example #2
0
    def _description_table(self, descriptions, widths, headers):
        # generate table-root
        tgroup = nodes.tgroup(cols=len(widths))
        for width in widths:
            tgroup += nodes.colspec(colwidth=width)
        table = nodes.table()
        table += tgroup

        # generate table-header
        thead = nodes.thead()
        row = nodes.row()
        for header in headers:
            entry = nodes.entry()
            entry += nodes.paragraph(text=header)
            row += entry
        thead += row
        tgroup += thead

        # generate table-body
        tbody = nodes.tbody()
        for desc in descriptions:
            row = nodes.row()
            for attr in desc:
                entry = nodes.entry()
                if not isinstance(attr, string_types):
                    attr = str(attr)
                self.state.nested_parse(ViewList([attr], source=attr),
                                        0, entry)
                row += entry
            tbody += row
        tgroup += tbody

        return table
Example #3
0
def gen_table(columns, data):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=len(columns))
        table += tgroup
        for column in columns:
            tgroup += nodes.colspec(colwidth=1)
        thead = nodes.thead()
        tgroup += thead
        headrow = nodes.row()
        for column in columns:
            entry = nodes.entry()
            para = nodes.paragraph()
            entry += para
            header = column.header()
            para += nodes.Text(header, header)
            headrow += entry
        thead += headrow
        tbody = nodes.tbody()
        tgroup += tbody
        for obj in data:
            row = nodes.row()
            for column in columns:
                entry = nodes.entry()
                para = nodes.paragraph()
                entry += para
                para += column.data(obj)
                row += entry
            tbody += row
        return [table]
Example #4
0
def build_toc(descinfo, env):
    """Return a desc table of contents node tree"""
    
    separator = EMDASH
    child_ids = descinfo['children']
    if not child_ids:
        return None
    max_fullname_len = 0
    max_summary_len = 0
    rows = []
    for fullname, refid, summary in ichild_ids(child_ids, env):
        max_fullname_len = max(max_fullname_len, len(fullname))
        max_summary_len = max(max_summary_len, len(summary))
        reference_node = toc_ref(fullname, refid)
        ref_entry_node = entry('', paragraph('', '', reference_node))
        sep_entry_node = entry('', paragraph('', separator))
        sum_entry_node = entry('', paragraph('', summary))
        row_node = row('', ref_entry_node, sep_entry_node, sum_entry_node)
        rows.append(row_node)
    col0_len = max_fullname_len + 2   # add error margin
    col1_len = len(separator)         # no padding
    col2_len = max_summary_len + 10   # add error margin
    tbody_node = tbody('', *rows)
    col0_colspec_node = colspec(colwidth=col0_len)
    col1_colspec_node = colspec(colwidth=col1_len)
    col2_colspec_node = colspec(colwidth=col2_len)
    tgroup_node = tgroup('',
                         col0_colspec_node,
                         col1_colspec_node,
                         col2_colspec_node,
                         tbody_node,
                         cols=3)
    return TocTable('', tgroup_node, classes=['toc'])
def description_table(descriptions, widths, headers):
    # generate table-root
    tgroup = nodes.tgroup(cols=len(widths))
    for width in widths:
        tgroup += nodes.colspec(colwidth=width)
    table = nodes.table()
    table += tgroup

    # generate table-header
    thead = nodes.thead()
    row = nodes.row()
    for header in headers:
        entry = nodes.entry()
        entry += nodes.paragraph(text=header)
        row += entry
    thead += row
    tgroup += thead

    # generate table-body
    tbody = nodes.tbody()
    for desc in descriptions:
        row = nodes.row()
        for col in desc:
            entry = nodes.entry()
            if not isinstance(col, basestring):
                col = str(col)
            paragraph = nodes.paragraph()
            paragraph += nodes.Text(col)
            entry += paragraph
            row += entry
        tbody += row
    tgroup += tbody

    return table
Example #6
0
    def create_cross_table(self, app, docname, node, matrix, options):
        table = nodes.table()
        table["classes"].append("traceables-crosstable")
        tgroup = nodes.tgroup(cols=len(matrix.secondaries), colwidths="auto")
        table += tgroup

        # Add column specifications.
        tgroup += nodes.colspec(colwidth=1)
        for column in matrix.secondaries:
            tgroup += nodes.colspec(colwidth=1)

        # Add heading row.
        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        thead += row
        entry = nodes.entry()
        row += entry
        for secondary in matrix.secondaries:
            entry = nodes.entry()
            row += entry
            container = nodes.container()
            entry += container
            inline = nodes.inline()
            container += inline
            paragraph = nodes.paragraph()
            inline += paragraph
            paragraph += secondary.make_reference_node(app.builder, docname)

        # Add table body.
        tbody = nodes.tbody()
        tgroup += tbody
        for primary in matrix.primaries:
            row = nodes.row()
            tbody += row
            entry = nodes.entry()
            row += entry
            paragraph = nodes.paragraph()
            entry += paragraph
            paragraph += primary.make_reference_node(app.builder, docname)

            for is_related in matrix.get_boolean_row(primary):
                entry = nodes.entry()
                row += entry
                if is_related:
                    checkmark = traceable_checkmark()
                    entry += checkmark
                    checkmark += nodes.inline(u"\u2714", u"\u2714")
                else:
                    continue

        container = traceable_matrix_crosstable()
        container += table
        container["traceables-matrix"] = matrix
#        backward = matrix.backward_relationship.capitalize()
#        forward = matrix.forward_relationship.capitalize()
#        container["relationships"] = (forward, backward)
#        container["boolean_matrix"] = 0#boolean_matrix
#        container["secondaries"] = matrix.secondaries
        return container
Example #7
0
def envy_resolve(app, doctree, fromdocname):
    objects = app.env.domaindata['envy']['objects']

    # add uplink info
    for holder in doctree.traverse(uplink_placeholder):
        obj = objects[holder.name]
        links = []
        for sp, pos, name, variants in obj.uplinks:
            signode = addnodes.desc_signature('', '')
            signode['first'] = False
            signode += make_refnode(app.builder, fromdocname, sp.docname, sp.iname + '-' + sp.name, addnodes.desc_addname(sp.name, sp.name), sp.name)
            text = ' {}: {}'.format(pos, name)
            signode += addnodes.desc_name(text, text)
            if variants is not None:
                text = ' [{}]'.format(variants)
                signode += addnodes.desc_annotation(text, text)
            links.append(signode)
        holder.replace_self(links)

    # add subnode list
    for holder in doctree.traverse(sub_placeholder):
        obj = objects[holder.name]
        add_variant = False
        for pos, name, child, variants in obj.subs:
            if variants is not None:
                add_variant = True
        table = nodes.table()
        headers = [(1, 'Address'), (1, 'Name'), (10, 'Description')]
        if add_variant:
            headers.insert(1, (1, 'Variants'))
        tgroup = nodes.tgroup(cols=len(headers))
        table += tgroup
        for colwidth, header in headers:
            tgroup += nodes.colspec(colwidth=colwidth)
        thead = nodes.thead()
        tgroup += thead
        headrow = nodes.row()
        for colwidth, header in headers:
            entry = nodes.entry()
            para = nodes.paragraph()
            entry += para
            para += nodes.Text(header, header)
            headrow += entry
        thead += headrow
        tbody = nodes.tbody()
        tgroup += tbody
        for pos, name, child, variants in obj.subs:
            row = nodes.row()
            row += wrap_text_entry(pos)
            if add_variant:
                row += wrap_text_entry('all' if variants is None else variants)
            row += wrap_text_entry(name)
            entry = nodes.entry()
            para = nodes.paragraph()
            entry += para
            para += make_refnode(app.builder, fromdocname, child.docname, child.iname + '-' + child.name, nodes.Text(child.brief, child.brief), obj.brief)
            row += entry
            tbody += row
        holder.replace_self([table])
    def create_list_table(self, matrix, options, docname):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=2, colwidths="auto")
        table += tgroup

        # Add column specifications.
        tgroup += nodes.colspec(colwidth=50)
        tgroup += nodes.colspec(colwidth=50)

        # Add heading row.
        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        thead += row
        entry = nodes.entry()
        row += entry
        backward_relationship = matrix.backward_relationship.capitalize()
        entry += nodes.paragraph(backward_relationship,
                                 backward_relationship)
        entry = nodes.entry()
        row += entry
        forward_relationship = matrix.forward_relationship.capitalize()
        entry += nodes.paragraph(forward_relationship,
                                 forward_relationship)

        # Add table body.
        tbody = nodes.tbody()
        tgroup += tbody
        for traceable in matrix.primaries:
            relatives = matrix.get_relatives(traceable)

            # Create first row with a first column.
            row = nodes.row()
            entry = nodes.entry(morerows=len(relatives) - 1)
            row += entry
            paragraph = nodes.paragraph()
            entry += paragraph
            paragraph += traceable.make_reference_node(
                self.app.builder, docname)

            for relative in relatives:
                if not row:
                    # Create subsequent rows without a first column.
                    row = nodes.row()
                tbody += row

                entry = nodes.entry()
                row += entry
                paragraph = nodes.paragraph()
                entry += paragraph
                paragraph += relative.make_reference_node(
                    self.app.builder, docname)

                row = None

        return table
Example #9
0
    def format(self, app, docname, node, traceables, options):
        additional_attributes = options.get("attributes") or []
        columns = ["tag", "title"] + additional_attributes

        table = nodes.table()
        table["classes"].append("traceables-listtable")
        tgroup = nodes.tgroup(cols=len(columns), colwidths="auto")
        table += tgroup

        # Add column specifications.
        for attribute_name in columns:
            tgroup += nodes.colspec(colwidth=1)

        # Add heading row.
        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        thead += row
        for attribute_name in columns:
            entry = nodes.entry()
            row += entry
            container = nodes.container()
            entry += container
            text = attribute_name.capitalize()
            inline = nodes.inline(text, text)
            container += inline

        # Add table body.
        tbody = nodes.tbody()
        tgroup += tbody
        for traceable in traceables:
            row = nodes.row()
            tbody += row

            for attribute_name in columns:
                entry = nodes.entry()
                row += entry
                if attribute_name == "tag":
                    inline = nodes.inline()
                    inline += traceable.make_reference_node(
                        app.builder, docname)
                elif attribute_name == "title":
                    text = traceable.title if traceable.has_title else ""
                    inline = nodes.inline(text, text)
                else:
                    text = traceable.attributes.get(attribute_name, "")
                    inline = nodes.inline(text, text)
                entry += inline

        return table
    def _build_markup(self, notifications):
        content = []
        cols = ['Notification class', 'Payload class', 'Sample file link']
        table = nodes.table()
        content.append(table)
        group = nodes.tgroup(cols=len(cols))
        table.append(group)

        head = nodes.thead()
        group.append(head)

        for i in range(len(cols)):
            group.append(nodes.colspec(colwidth=1))

        body = nodes.tbody()
        group.append(body)

        # fill the table header
        row = nodes.row()
        body.append(row)
        for col_name in cols:
            col = nodes.entry()
            row.append(col)
            text = nodes.strong(text=col_name)
            col.append(text)

        # fill the table content, one notification per row
        for name, payload, sample in notifications:
            row = nodes.row()
            body.append(row)
            col = nodes.entry()
            row.append(col)
            text = nodes.literal(text=name)
            col.append(text)

            col = nodes.entry()
            row.append(col)
            text = nodes.literal(text=payload)
            col.append(text)

            col = nodes.entry()
            row.append(col)
            ref = nodes.reference(refuri=self.LINK_PREFIX +
                                  self.SAMPLE_ROOT + sample)
            txt = nodes.inline()
            col.append(txt)
            txt.append(ref)
            ref.append(nodes.literal(text=sample))

        return content
Example #11
0
    def _build_grade_listing(self, matrix, content):

        summarytitle = nodes.subtitle(text="Grades")
        content.append(nodes.raw(text="Grades", attributes={'tagname': 'h2'}))
        content.append(summarytitle)
        table = nodes.table()
        table.set_class("table")
        table.set_class("table-condensed")
        grades = matrix.grades

        tablegroup = nodes.tgroup(cols=2)
        summarybody = nodes.tbody()
        summaryhead = nodes.thead()

        for i in range(2):
            tablegroup.append(nodes.colspec(colwidth=1))
        tablegroup.append(summaryhead)
        tablegroup.append(summarybody)
        table.append(tablegroup)
        content.append(table)

        header = nodes.row()
        blank = nodes.entry()
        blank.append(nodes.strong(text="Grade"))
        header.append(blank)

        blank = nodes.entry()
        blank.append(nodes.strong(text="Description"))
        header.append(blank)

        summaryhead.append(header)

        for grade in grades:
            item = nodes.row()
            namecol = nodes.entry()
            class_name = "label-%s" % grade.css_class
            status_text = nodes.paragraph(text=grade.title)
            status_text.set_class(class_name)
            status_text.set_class("label")
            namecol.append(status_text)
            item.append(namecol)

            notescol = nodes.entry()
            notescol.append(nodes.paragraph(text=grade.notes))
            item.append(notescol)

            summarybody.append(item)

        return content
Example #12
0
    def run(self):
        self.assert_has_content()

        language = self.arguments[0]
        code = '\n'.join(self.content)
        pygmentize_args = {}
        if self.options.get('number-lines', None):
            pygmentize_args['linenostart'] = int(self.options['number-lines'])
        pygmentize_args['linenos'] = 'number-lines' in self.options and 'table'
        node = nodes.table() if pygmentize_args['linenos'] else nodes.literal_block()
        node['classes'] = self.options.get('class', [])
        node.attributes['data-language'] = language
        self.add_name(node)
        set_source_info(self, node)
        # if called from "include", set the source
        if 'source' in self.options:
            node.attributes['source'] = self.options['source']
        if pygmentize_args['linenos']:
            anchor_id = node['ids'][-1] if node['ids'] else md5(code.encode('utf-8')).hexdigest()
            pygmentize_args['lineanchors'] = anchor_id
            pygmentize_args['anchorlinenos'] = True
        linespec = self.options.get('emphasize-lines')
        if linespec:
            try:
                nlines = len(self.content)
                pygmentize_args['hl_lines'] = [x + 1 for x in parselinenos(linespec, nlines)]
            except ValueError as err:
                document = self.state.document
                return [document.reporter.warning(str(err), line=self.lineno)]

        output = pygmentize(code, language, **pygmentize_args)
        # remove empty span included by Pygments
        # See:
        # https://bitbucket.org/birkenfeld/pygments-main/issues/1254/empty-at-the-begining-of-the-highlight
        output = output.replace('<span></span>', '')
        pre = re.findall('<pre.*?>(.*?)\n*</pre>', output, re.DOTALL)
        if len(pre) == 1:
            node += nodes.raw(pre[0], pre[0], format='html')
        else:  # pygments returned a table
            row = nodes.row()
            node += row
            linenos_cell = nodes.entry(classes=['linenos'])
            linenos_cell += nodes.literal_block('', '', nodes.raw(pre[0], pre[0], format='html'))
            code_cell = nodes.entry(classes=['code'])
            code_cell += nodes.literal_block('', '', nodes.raw(pre[1], pre[1], format='html'))
            row += linenos_cell
            row += code_cell

        return [node]
Example #13
0
 def build_table_from_list(self, table_data, col_widths, header_rows, stub_columns):
     table = nodes.table()
     tgroup = nodes.tgroup(cols=len(col_widths))
     table += tgroup
     for col_width in col_widths:
         colspec = nodes.colspec(colwidth=col_width)
         if stub_columns:
             colspec.attributes['stub'] = 1
             stub_columns -= 1
         tgroup += colspec
     rows = []
     for row in table_data:
         row_node = nodes.row()
         for cell in row:
             entry = nodes.entry()
             entry += cell
             row_node += entry
         rows.append(row_node)
     if header_rows:
         thead = nodes.thead()
         thead.extend(rows[:header_rows])
         tgroup += thead
     tbody = nodes.tbody()
     tbody.extend(rows[header_rows:])
     tgroup += tbody
     return table
Example #14
0
    def build_table(self):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=len(self.headers))
        table += tgroup

        # TODO(sdague): it would be really nice to figure out how not
        # to have this stanza, it kind of messes up all of the table
        # formatting because it doesn't let tables just be the right
        # size.
        tgroup.extend(
             nodes.colspec(colwidth=col_width, colname='c' + str(idx))
             for idx, col_width in enumerate(self.col_widths)
        )

        thead = nodes.thead()
        tgroup += thead

        row_node = nodes.row()
        thead += row_node
        row_node.extend(nodes.entry(h, nodes.paragraph(text=h))
                        for h in self.headers)

        tbody = nodes.tbody()
        tgroup += tbody

        rows, groups = self.collect_rows()
        tbody.extend(rows)
        table.extend(groups)

        return table
    def build_table(self, table_data):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=len(self.headers))
        table += tgroup

        tgroup.extend(
            nodes.colspec(colwidth=col_width, colname='c' + str(idx))
            for idx, col_width in enumerate(self.col_widths)
        )

        thead = nodes.thead()
        tgroup += thead

        row_node = nodes.row()
        thead += row_node
        row_node.extend(nodes.entry(h, nodes.paragraph(text=h))
                        for h in self.headers)

        tbody = nodes.tbody()
        tgroup += tbody

        rows, groups = self.get_rows(table_data)
        tbody.extend(rows)
        table.extend(groups)

        return table
Example #16
0
 def run(self):
     ncolumns = self.options.get('columns', 2)
     node = nodes.Element()
     node.document = self.state.document
     self.state.nested_parse(self.content, self.content_offset, node)
     if len(node.children) != 1 or not isinstance(node.children[0],
                                                  nodes.bullet_list):
         return [self.state.document.reporter.warning(
             '.. hlist content is not a list', line=self.lineno)]
     fulllist = node.children[0]
     # create a hlist node where the items are distributed
     npercol, nmore = divmod(len(fulllist), ncolumns)
     index = 0
     table = nodes.table()
     tg = nodes.tgroup()
     table += tg
     row = nodes.row()
     tbody = nodes.tbody()
     for column in range(ncolumns):
         endindex = index + (column < nmore and (npercol + 1) or npercol)
         colspec = nodes.colspec()
         colspec.attributes['stub'] = 0
         colspec.attributes['colwidth'] = 100. / ncolumns
         col = nodes.entry()
         col += nodes.bullet_list()
         col[0] += fulllist.children[index:endindex]
         index = endindex
         tg += colspec
         row += col
     tbody += row
     tg += tbody
     table['classes'].append('hlist')
     return [table]
 def create_table_row(self, row_cells):
     row = nodes.row()
     for cell in row_cells:
         entry = nodes.entry()
         row += entry
         entry += cell
     return row
Example #18
0
File: tables.py Project: axil/blog
 def build_table_from_list(self, table_data, col_widths, header_rows, stub_columns):
     table = nodes.table()
     if self.widths == 'auto':
         table['classes'] += ['colwidths-auto']
     elif self.widths: # "grid" or list of integers
         table['classes'] += ['colwidths-given']
     tgroup = nodes.tgroup(cols=len(col_widths))
     table += tgroup
     for col_width in col_widths:
         colspec = nodes.colspec()
         if col_width is not None:
             colspec.attributes['colwidth'] = col_width
         if stub_columns:
             colspec.attributes['stub'] = 1
             stub_columns -= 1
         tgroup += colspec
     rows = []
     for row in table_data:
         row_node = nodes.row()
         for cell in row:
             entry = nodes.entry()
             entry += cell
             row_node += entry
         rows.append(row_node)
     if header_rows:
         thead = nodes.thead()
         thead.extend(rows[:header_rows])
         tgroup += thead
     tbody = nodes.tbody()
     tbody.extend(rows[header_rows:])
     tgroup += tbody
     return table
    def _generate_rows(self, sensors):

        vendor_name = None
        for s in sensors:
            # only generate one row for each vendor name that serves as a group heading
            if 'vendor_name' in s and vendor_name != s['vendor_name']:
                vendor_name = s['vendor_name']

                strong = nodes.strong(text=vendor_name)
                para = nodes.paragraph()
                para += strong
                entry = nodes.entry(morecols=5)
                entry += para
                row = nodes.row()
                row += entry
                yield row

            # then generate one row for each sensor
            yield self._row([
                self._link(s.get('vendor_website', None), s.get('vendor_part_number', '')),
                ':ref:`{} <{}>`'.format(s.get('vendor_part_name', s.get('vendor_part_number', '')),
                                         s['url_name']),
                '``{}``'.format(s['name']),
                self._pretty_sensor_type(s['sensor_type']),
                self._auto_detect(s['name'], s['sensor_type']),
            ])
Example #20
0
    def create_cell(self, col_index, cell_item, is_header=False):
        # feature_template = self.options.get("feature_template",\
        # ":doc:`{target}`")
        # metric_template = self.options.get("metric_template",\
        # ":doc:`{target}`")

        cell_node = nodes.entry()
        block = None
        # if not is_header and cell_item:
        # if col_index == 4:
        # block = StringList(feature_template.format(target=cell_item)\
        # .splitlines())
        # elif col_index == 5:
        # block = StringList(metric_template.format(target=cell_item)\
        # .splitlines())
        # elif col_index == 5:
        # block = StringList(self.FEATURE_PARAMETERS_TEMPLATE\
        # .format(content=cell_item).splitlines())

        if block:
            self.state.nested_parse(block, 0, cell_node)
        else:
            text_node = nodes.Text(unicode(cell_item))
            paragraph_node = nodes.paragraph(unicode(cell_item), "", text_node)
            cell_node += paragraph_node
        return cell_node
 def build_table_from_list(self, table_data, num_cols, col_widths, header_rows, stub_columns):
     table = nodes.table()
     tgroup = nodes.tgroup(cols=len(col_widths))
     table += tgroup
     for col_width in col_widths:
         colspec = nodes.colspec(colwidth=col_width)
         if stub_columns:
             colspec.attributes['stub'] = 1
             stub_columns -= 1
         tgroup += colspec
     rows = []
     for row in table_data:
         row_node = nodes.row()
         for cell_index, cell in enumerate(row):
             entry = nodes.entry()
             entry += cell
             row_node += entry
             if self.bias == "left" and not cell_index:
                 remainder = num_cols - len(row)
                 if remainder:
                     entry["morecols"] = remainder
             if self.bias == "right" and cell_index == len(row) - 1:
                 remainder = num_cols - (cell_index + 1)
                 if remainder:
                     entry["morecols"] = remainder
         rows.append(row_node)
     if header_rows:
         thead = nodes.thead()
         thead.extend(rows[:header_rows])
         tgroup += thead
     tbody = nodes.tbody()
     tbody.extend(rows[header_rows:])
     tgroup += tbody
     return table
Example #22
0
    def visit_entry (self, node):
        """ Table cell. """

        morerows = node.get ('morerows', 0)
        morecols = node.get ('morecols', 0)

        self.cells += (morecols + 1) * (morerows + 1)

        # skip columns that are row-spanned by preceding entries
        while True:
            colspec = self.colspecs [self.column]
            if colspec.get ('spanned', 0) > 0:
                placeholder = nodes.entry ()
                placeholder.type = 'compound'
                placeholder['column'] = self.column
                placeholder.colspecs = self.colspecs[self.column:self.column + 1]
                placeholder['vspan'] = True
                node.replace_self ([placeholder, node])
                self.column += 1
            else:
                break

        # mark columns we row-span
        if morerows:
            for colspec in self.colspecs [self.column : self.column + 1 + morecols]:
                colspec['spanned'] = morerows + 1

        node['row'] = self.row
        node['column'] = self.column
        
        node.colspecs = self.colspecs[self.column:self.column + morecols + 1]

        self.column += 1 + morecols
        
        raise nodes.SkipNode
Example #23
0
            def get_row(*column_texts):
                row = nodes.row('')
                for text in column_texts:
                    node = nodes.paragraph('', '', nodes.Text(text))
                    row += nodes.entry('', node)

                return row
Example #24
0
 def append_row(*column_texts):
     row = nodes.row('')
     for text in column_texts:
         node = nodes.paragraph('')
         vl = ViewList()
         vl.append(text, '<autosummary>')
         state.nested_parse(vl, 0, node)
         row.append(nodes.entry('', node))
     body.append(row)
Example #25
0
def build_table_row(*vals):
    rv = nodes.row('')
    for val in vals:
        if isinstance(val, nodes.Node):
            node = val
        else:
            node = nodes.paragraph(val, val)
        rv.append(nodes.entry(node, node))
    return rv
Example #26
0
    def create_table_row(self, row_cells):
        row = nodes.row()

        for cell in row_cells:
            entry = nodes.entry()
            row += entry
            entry += nodes.paragraph(text=cell.strip())

        return row
Example #27
0
 def get_rows(self, table_data):
     rows = []
     groups = []
     trow = nodes.row()
     entry = nodes.entry()
     para = nodes.paragraph(text=unicode(table_data))
     entry += para
     trow += entry
     rows.append(trow)
     return rows, groups
Example #28
0
    def _build_grade_listing(self, matrix, content):

        summarytitle = nodes.title(text="Grades")
        content.append(summarytitle)
        table = nodes.table()
        grades = matrix.grades

        tablegroup = nodes.tgroup(cols=2)
        summarybody = nodes.tbody()
        summaryhead = nodes.thead()

        for i in range(2):
            tablegroup.append(nodes.colspec(colwidth=1))
        tablegroup.append(summaryhead)
        tablegroup.append(summarybody)
        table.append(tablegroup)
        content.append(table)

        header = nodes.row()
        blank = nodes.entry()
        blank.append(nodes.strong(text="Grade"))
        header.append(blank)

        blank = nodes.entry()
        blank.append(nodes.strong(text="Description"))
        header.append(blank)

        summaryhead.append(header)

        for grade in grades:
            item = nodes.row()
            namecol = nodes.entry()
            namecol.append(nodes.paragraph(text=grade.title))
            item.append(namecol)

            notescol = nodes.entry()
            notescol.append(nodes.paragraph(text=grade.notes))
            item.append(notescol)

            summarybody.append(item)

        return content
 def get_rows(self, table_data):
     rows = []
     groups = []
     for row in table_data:
         sub_table_data = None
         if self.descend:
             for elem in row:
                 if isinstance(elem, list):
                     sub_table_data = row.pop(row.index(elem))
                     break
         trow = nodes.row()
         ncols = len(row)
         for idx, cell in enumerate(row):
             if self.spantolast and \
                     ncols < self.max_cols and idx == ncols - 1:
                 morecols = self.max_cols - ncols
                 entry = nodes.entry(morecols=morecols)
             else:
                 entry = nodes.entry()
             para = nodes.paragraph(text=unicode(cell))
             entry += para
             trow += entry
         if self.descend and sub_table_data:
             subtgroup = nodes.tgroup(cols=len(self.headers))
             subtgroup.extend(
                 nodes.colspec(
                     colwidth=col_width, colname='c' + str(idx)
                 ) for idx, col_width in enumerate(self.col_widths)
             )
             subthead = nodes.thead()
             subtgroup += subthead
             subthead += trow
             subtbody = nodes.tbody()
             subtgroup += subtbody
             sub_rows, sub_groups = self.get_rows(sub_table_data)
             subtbody.extend(sub_rows)
             groups.append(subtgroup)
             groups.extend(sub_groups)
         else:
             rows.append(trow)
     return rows, groups
Example #30
0
    def build_table(self, table_data, col_widths):
        table = nodes.table()

        # Set up the column specifications
        # based on the widths.
        tgroup = nodes.tgroup(cols=len(col_widths))
        table += tgroup
        tgroup.extend(nodes.colspec(colwidth=col_width)
                      for col_width in col_widths)

        # Set the headers
        thead = nodes.thead()
        tgroup += thead
        row_node = nodes.row()
        thead += row_node
        row_node.extend(
            nodes.entry(h, nodes.paragraph(text=h))
            for h in self.HEADERS
        )

        # The body of the table is made up of rows.
        # Each row contains a series of entries,
        # and each entry contains a paragraph of text.
        tbody = nodes.tbody()
        tgroup += tbody
        rows = []
        for row in table_data:
            trow = nodes.row()
            # Iterate over the headers in the same order every time.
            for h in self.HEADERS:
                # Get the cell value from the row data, replacing None
                # in re match group with empty string.
                cell = row.get(self.HEADER_MAP[h]) or ''
                entry = nodes.entry()
                para = nodes.paragraph(text=unicode(cell))
                entry += para
                trow += entry
            rows.append(trow)
        tbody.extend(rows)

        return table
Example #31
0
 def append_row(*column_texts: str) -> None:
     row = nodes.row('')
     source, line = self.state_machine.get_source_and_line()
     for text in column_texts:
         node = nodes.paragraph('')
         vl = StringList()
         vl.append(text, '%s:%d:<autosummary>' % (source, line))
         with switch_source_input(self.state, vl):
             self.state.nested_parse(vl, 0, node)
             try:
                 if isinstance(node[0], nodes.paragraph):
                     node = node[0]
             except IndexError:
                 pass
             row.append(nodes.entry('', node))
     body.append(row)
Example #32
0
 def add_row(target, *column_texts):
     row = nodes.row('')
     for text in column_texts:
         if text is None:
             text = ""
         node = nodes.paragraph('')
         vl = ViewList()
         vl.append(text, '<autosummary>')
         self.state.nested_parse(vl, 0, node)
         try:
             if isinstance(node[0], nodes.paragraph):
                 node = node[0]
         except IndexError:
             pass
         row.append(nodes.entry('', node))
     target.append(row)
    def run(self):
        env = self.state.document.settings.env
        try:
            if self.arguments and self.content:
                raise self.warning('both argument and content. it is invalid')
            if self.arguments:
                dirname = os.path.dirname(env.doc2path(env.docname, base=None))
                relpath = os.path.join(dirname, self.arguments[0])
                abspath = os.path.join(env.srcdir, relpath)
                if not os.access(abspath, os.R_OK):
                    raise self.warning('JSON Schema file not readable: %s' %
                                       self.arguments[0])
                env.note_dependency(relpath)

                schema = JSONSchema.loadfromfile(abspath)
            else:
                schema = JSONSchema.loadfromfile(''.join(self.content))
        except ValueError as exc:
            raise self.error('Failed to parse JSON Schema: %s' % exc)

        headers = ['Name', 'Type', 'Description', 'Validations']
        widths = [1, 1, 1, 2]
        tgroup = nodes.tgroup(cols=len(headers))
        for width in widths:
            tgroup += nodes.colspec(colwidth=width)

        table = nodes.table('', tgroup)
        header_row = nodes.row()
        for header in headers:
            entry = nodes.entry('', nodes.paragraph(text=header))
            header_row += entry

        tgroup += nodes.thead('', header_row)
        tbody = nodes.tbody()
        tgroup += tbody
        for prop in schema:
            row = nodes.row()
            row += self.cell(prop.name)
            if prop.required:
                row += self.cell(prop.type + " (required)")
            else:
                row += self.cell(prop.type)
            row += self.cell(prop.description or '')
            row += self.cell('\n'.join(('* %s' % v for v in prop.validations)))
            tbody += row

        return [table]
Example #34
0
    def dfes_table(self, species):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=3)
        colspec = nodes.colspec(colwidth=1)
        tgroup.append(colspec)
        colspec = nodes.colspec(colwidth=1)
        tgroup.append(colspec)
        colspec = nodes.colspec(colwidth=1)
        tgroup.append(colspec)

        table += tgroup

        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        entry = nodes.entry()
        entry += nodes.paragraph(text="ID")
        row += entry
        entry = nodes.entry()
        entry += nodes.paragraph(text="Year")
        row += entry
        entry = nodes.entry()
        entry += nodes.paragraph(text="Description")
        row += entry

        thead.append(row)

        rows = []

        for dfe in species.dfes:
            row = nodes.row()
            rows.append(row)

            dfe_id = self.get_dfe_id(species, dfe)
            entry = nodes.entry()
            para = nodes.paragraph()
            entry += para
            para += nodes.reference(internal=True, refid=dfe_id, text=dfe.id)
            row += entry

            entry = nodes.entry()
            entry += nodes.paragraph(text=dfe.citations[0].year)
            row += entry

            entry = nodes.entry()
            para = nodes.paragraph()
            entry += nodes.paragraph(text=dfe.description)
            row += entry

        tbody = nodes.tbody()
        tbody.extend(rows)
        tgroup += tbody

        return table
Example #35
0
    def buildTableRowNode(self, row_data, classes=None):
        classes = [] if classes is None else classes
        row = nodes.row()
        for cell in row_data:
            if cell is None:
                continue
            cspan, rspan, cellElements = cell

            attributes = {"classes" : classes}
            if rspan:
                attributes['morerows'] = rspan
            if cspan:
                attributes['morecols'] = cspan
            entry = nodes.entry(**attributes)
            entry.extend(cellElements)
            row += entry
        return row
Example #36
0
 def row(self, prop, tbody):
     row = nodes.row()
     anchor = '{},{},{}'.format(
         self.arguments[0].split('/')[-1],
         self.options.get('pointer', ''),
         prop.name)
     target = nodes.target(ids=[anchor], names=[anchor.lower()])
     if 'addtargets' in self.options:
         self.state.document.note_explicit_target(target)
     cell = nodes.entry('', target, nodes.literal('', nodes.Text(prop.name)), morecols=1)
     row += cell
     row += self.cell(prop.type)
     row += self.cell(prop.format or '')
     row += self.cell('Required' if prop.required else '')
     tbody += row
     row = nodes.row()
     row += self.cell(prop.title)
     if prop.description:
         cell = self.cell(prop.description or '', morecols=3)
         if prop.name in self.external_links:
             reference = nodes.reference(
                 '',
                 '',
                 nodes.Text(self.external_links[prop.name]['text']),
                 internal=False,
                 refuri=self.external_links[prop.name]['url'],
                 anchorname='')
             cell += nodes.paragraph('', nodes.Text('\n\nSee '), reference)
         elif 'nocrossref' not in self.options:
             ref = None
             if hasattr(prop.attributes, '__reference__'):
                 ref = prop.attributes.__reference__['$ref']
             elif hasattr(prop.items, '__reference__'):
                 ref = prop.items.__reference__['$ref']
             if ref:
                 # just use the name at the end of the ref
                 ref = ref.split('/')[-1]
                 reference = nodes.reference('', '', nodes.Text(ref), internal=False, refuri='#' + ref.lower(),
                                             anchorname='')
                 cell += nodes.paragraph('', nodes.Text('\n\nSee '), reference)
             if prop.deprecated:
                 cell += nodes.paragraph('', nodes.Text('This property was deprecated in version {}'
                                                        .format(prop.deprecated['deprecatedVersion'])))
                 cell += nodes.paragraph('', nodes.Text(prop.deprecated['description']))
         row += cell
     tbody += row
Example #37
0
def prepare_table_header(titles, widths):
    """Build docutil empty table """
    ncols = len(titles)
    assert len(widths) == ncols

    tgroup = nodes.tgroup(cols=ncols)
    for width in widths:
        tgroup += nodes.colspec(colwidth=width)
    header = nodes.row()
    for title in titles:
        header += nodes.entry('', nodes.paragraph(text=title))
    tgroup += nodes.thead('', header)

    tbody = nodes.tbody()
    tgroup += tbody

    return nodes.table('', tgroup), tbody
Example #38
0
 def _create_row(self, *column_texts):
     row = nodes.row('')
     source, line = self.state_machine.get_source_and_line()
     for text_line in column_texts:
         node = nodes.paragraph('')
         vl = ViewList()
         for text in text_line.split('\n'):
             vl.append(text, '%s:%d' % (source, line))
         with switch_source_input(self.state, vl):
             self.state.nested_parse(vl, 0, node)
             try:
                 if isinstance(node[0], nodes.paragraph) and len(node.children) == 1:
                     node = node[0]
             except IndexError:
                 pass
             row.append(nodes.entry('', node))
     return row
Example #39
0
def make_row(data):
    row = nodes.row()
    for text in data:
        entry = nodes.entry()
        row += entry
        para = nodes.paragraph()
        entry += para
        if isinstance(text, list):
            lb = nodes.line_block()
            para += lb
            for t in text:
                line = nodes.line()
                lb += line
                line += nodes.Text(t)
        else:
            para += nodes.Text(text)
    return row
    def create_cell(self, contents, url=None):
        """
        Creates a table entry node with the given contents inside. If a string is given, it gets used inside a paragraph
        node, either as a text node or a reference node in case a URL is given.

        Args:
            contents (str|nodes.Node): Title text to be displayed.

        Returns:
            (nodes.entry) Entry node containing a paragraph with the given contents.
        """
        if isinstance(contents, str):
            if url is not None:
                contents = self.create_ref_node(contents, url)
            else:
                contents = nodes.paragraph(text=contents)

        return nodes.entry('', contents)
Example #41
0
def resolve_devindex(app, doctree, fromdocname):
    env = app.builder.env

    for indexnode in doctree.traverse(device_index):
        table = nodes.table('')
        group = nodes.tgroup('',
                             nodes.colspec('', colwidth=30),
                             nodes.colspec('', colwidth=30),
                             nodes.colspec('', colwidth=30),
                             cols=3)
        table.append(group)

        group.append(
            nodes.thead(
                '',
                nodes.row(
                    '',
                    nodes.entry('', nodes.paragraph('', 'Class')),
                    nodes.entry('', nodes.paragraph('', 'Module')),
                    nodes.entry('', nodes.paragraph('', 'Description')),
                )))

        body = nodes.tbody('')
        group.append(body)

        for entry in sorted(itervalues(env.nicos_all_devices),
                            key=lambda v: v['name']):
            if not entry['module'].startswith('nicos.devices.'):
                continue
            row = nodes.row('')

            reftgt = '%s.%s' % (entry['module'], entry['name'])
            node = nodes.paragraph(
                '', '',
                addnodes.pending_xref('',
                                      nodes.Text(entry['name']),
                                      refdomain='py',
                                      reftype='class',
                                      reftarget=reftgt))
            env.resolve_references(node, fromdocname, app.builder)
            row.append(nodes.entry('', node))

            row.append(
                nodes.entry(
                    '',
                    nodes.paragraph('', '',
                                    nodes.literal('', entry['module'][6:]))))

            row.append(nodes.entry('', nodes.paragraph('', entry['blurb'])))

            body.append(row)
        indexnode.replace_self([table])
Example #42
0
def build_row(row_data):
    """
    Creates new rst table row node tree.

    Args:
        row_data (list): list of rst nodes with content of the row,
            length of the list should match number of columns in the table

    Returns:
        docutils.nodes.row: rst row node tree which contains given data
    """
    row_node = nodes.row()
    # create entry nodes for data
    for content_nodes in row_data:
        entry_node = nodes.entry()
        row_node += entry_node
        for node in content_nodes:
            entry_node += node
    return row_node
Example #43
0
    def _append_row(self, body, column_texts):
        # type: (Any, str) -> None
        table_row = nodes.row('')
        source, line = self.state_machine.get_source_and_line()

        for text in column_texts:
            node = nodes.paragraph('')

            vl = ViewList()
            vl.append(text, f'{source}:{line}:<{self.name}>')

            with switch_source_input(self.state, vl):
                self.state.nested_parse(vl, 0, node)
                while len(node) > 0 and isinstance(node[0], nodes.paragraph):
                    node = node[0]

                table_row.append(nodes.entry('', node))

        body.append(table_row)
Example #44
0
def append_row(tbody, cells):
    row = nodes.row()
    tbody += row

    for cell in cells:
        entry = nodes.entry()
        row += entry

        try:
            if isinstance(cell, basestring):
                node = nodes.paragraph(text=cell)
            else:
                node = cell

        except NameError:
            if isinstance(cell, str):
                node = nodes.paragraph(text=cell)
            else:
                node = cell

        entry += node
Example #45
0
def td(__node, **args):
    entry = nodes.entry(**args)
    para = nodes.paragraph()
    entry += para

    if isinstance(__node, type('')) or \
           isinstance(__node, type(u'')):
        str = __node
        #mark literates
        if str.count('``')%2 == 0:
            for i in range(str.count('``')/2):
                if str.find('``') != 0:
                    para += nodes.Text(str[0:str.find('``')])
                str = str[str.find('``')+2:len(str)]
                literal = nodes.literal(para, nodes.Text(str[0:str.find('``')]))
                para += literal
                str = str[str.find('``')+2:len(str)]
        __node = nodes.Text(str)

    para += __node
    return entry
Example #46
0
def build_row(app, fromdocname, rowdata):
    row = nodes.row()
    for cell in rowdata:
        entry = nodes.entry()
        row += entry
        if isinstance(cell, list):
            for item in cell:
                if isinstance(item, dict):
                    entry += process_cmd_node(app, item, fromdocname, '')
                else:
                    entry += nodes.paragraph(text=item)
        elif isinstance(cell, bool):
            if cell:
                entry += nodes.paragraph(text="✔")
                entry['classes'] = ['coverage-ok']
            else:
                entry += nodes.paragraph(text="✕")
                entry['classes'] = ['coverage-fail']
        else:
            entry += nodes.paragraph(text=cell)
    return row
Example #47
0
    def run(self) -> List[Node]:
        ncolumns = self.options.get('columns', 2)
        node = addnodes.compact_paragraph()
        node.document = self.state.document
        self.state.nested_parse(self.content, self.content_offset, node)
        if len(node.children) != 1 or not isinstance(node.children[0],
                                                     nodes.bullet_list):
            reporter = self.state.document.reporter
            raise SphinxError('table_from_list content is not a list')
        fulllist = node.children[0]

        # fill list with empty items to have a number of entries
        # that is divisible by ncolumns
        if (len(fulllist) % ncolumns) != 0:
            missing = int(ncolumns - (len(fulllist) % ncolumns))
            for i in range(0, missing):
                fulllist += list_item()

        table = nodes.table()
        tgroup = nodes.tgroup(cols=ncolumns)
        table += tgroup

        for i in range(ncolumns):
            tgroup += nodes.colspec(colwidth=1)

        tbody = nodes.tbody()
        tgroup += tbody
        current_row = nodes.row()

        for idx, cell in enumerate(fulllist.children):
            if len(current_row.children) == ncolumns:
                tbody += current_row
                current_row = nodes.row()
            entry = nodes.entry()
            current_row += entry
            if len(cell.children) > 0:
                entry += cell.children[0]

        tbody += current_row
        return [table]
    def get_filled_row(self, defect, columns, *args):
        """ Goes through each column and decides if it is there or prints empty cell.

        Args:
            defect (suds.sudsobject.mergedDefectDataObj): Defect object from suds.
            columns (list): List of column names (str).

        Returns:
            (nodes.row) Filled row node.
        """
        row = nodes.row()
        for item_col in columns:
            item_col = item_col.upper()
            if item_col == 'CID':
                # CID is default and even if it is in disregard
                row += self.create_cell(
                    str(defect['cid']),
                    url=self.coverity_service.get_defect_url(
                        self.stream, str(defect['cid'])))
            elif item_col == 'LOCATION':
                info = self.coverity_service.get_defect(
                    str(defect['cid']), self.stream)
                linenum = info[-1]['defectInstances'][-1]['events'][-1][
                    'lineNumber']
                row += self.create_cell("{}#L{}".format(
                    defect['filePathname'], linenum))
            elif item_col in self.column_map:
                row += self.create_cell(defect[self.column_map[item_col]])
            elif item_col in ('COMMENT', 'REFERENCE'):
                row += nodes.entry(
                    '',
                    self.create_paragraph_with_links(
                        defect, self.defect_states_map[item_col], *args))
            elif item_col in self.defect_states_map:
                row += self.cov_attribute_value_to_col(
                    defect, self.defect_states_map[item_col])
            else:
                # generic check which, if it is missing, prints empty cell anyway
                row += self.cov_attribute_value_to_col(defect, item_col)
        return row
Example #49
0
File: flags.py Project: tfausak/ghc
def build_table_from_list(table_data, col_widths):
    table = nodes.table()
    tgroup = nodes.tgroup(cols=len(col_widths))
    table += tgroup
    for col_width in col_widths:
        colspec = nodes.colspec(colwidth=col_width)
        tgroup += colspec
    rows = []
    for row in table_data:
        row_node = nodes.row()
        for cell in row:
            entry = nodes.entry()
            entry += cell
            row_node += entry
        rows.append(row_node)
    thead = nodes.thead()
    thead.extend(rows[:1])
    tgroup += thead
    tbody = nodes.tbody()
    tbody.extend(rows[1:])
    tgroup += tbody
    return table
Example #50
0
def env_vars_to_table(env_vars, ci):
    table = nodes.table()
    tgroup = nodes.tgroup(cols=3)
    table += tgroup

    colspec = nodes.colspec()
    tgroup += colspec
    tgroup += colspec
    tgroup += colspec

    thead = nodes.thead()
    tgroup += thead
    row = nodes.row()
    row += nodes.entry("", nodes.paragraph(text="ENV-VARS"))
    row += nodes.entry("", nodes.paragraph(text="Required?"))
    row += nodes.entry("", nodes.paragraph(text="Notes"))
    thead += row

    tbody = nodes.tbody()
    for env_var in env_vars:
        row = nodes.row()
        row += nodes.entry("", nodes.paragraph(text=env_var.name))
        if env_var.is_required(ci):
            required = 'yes'
        else:
            required = 'no'
        row += nodes.entry("", nodes.paragraph(text=required))
        notes = env_var.notes(ci)
        if notes == "<FINGERPRINT_LINK>":
            ref = "../../fingerprints/docker_fingerprint.html"
            para = nodes.paragraph(text="")
            para += nodes.reference('',
                                    'Fingerprint',
                                    internal=False,
                                    refuri=ref)
            row += nodes.entry("", para)
        else:
            row += nodes.entry("", nodes.paragraph(text=notes))
        tbody += row
    tgroup += tbody
    return table
Example #51
0
    def _get_row(self, obj):
        template = ":{}:`{} <{}>`\\ {}"
        if "nosignatures" in self.options:
            template = ":{}:`{} <{}>`"

        col1 = template.format("obj", obj.short_name, obj.name,
                               escape("({})".format(obj.args)))
        col2 = obj.summary

        row = nodes.row("")
        for text in (col1, col2):
            node = nodes.paragraph("")
            view_list = ViewList()
            view_list.append(text, "<autosummary>")
            self.state.nested_parse(view_list, 0, node)
            try:
                if isinstance(node[0], nodes.paragraph):
                    node = node[0]
            except IndexError:
                pass
            row.append(nodes.entry("", node))

        return row
Example #52
0
def model_table(model):
    table = nodes.table()
    tgroup = nodes.tgroup(cols=2)

    colspec = nodes.colspec(colwidth=1)
    tgroup.append(colspec)
    colspec = nodes.colspec(colwidth=1)
    tgroup.append(colspec)

    table += tgroup

    rows = []

    row = nodes.row()
    rows.append(row)
    entry = nodes.entry()
    entry += nodes.paragraph(text="id")
    row += entry
    entry = nodes.entry()
    entry += nodes.paragraph(text=model.id)
    row += entry

    row = nodes.row()
    rows.append(row)
    entry = nodes.entry()
    entry += nodes.paragraph(text="name")
    row += entry
    entry = nodes.entry()
    entry += nodes.paragraph(text=model.name)
    row += entry

    row = nodes.row()
    rows.append(row)
    entry = nodes.entry()
    entry += nodes.paragraph(text="num_populations")
    row += entry
    entry = nodes.entry()
    entry += nodes.paragraph(text=model.num_populations)
    row += entry

    tbody = nodes.tbody()
    tbody.extend(rows)
    tgroup += tbody

    return table
    def build_table(self):
        table = nodes.table()
        tgroup = nodes.tgroup(cols=len(self.header))
        table += tgroup

        tgroup.extend(
            nodes.colspec(colwidth=col_width, colname="c" + str(idx)) for idx, col_width in enumerate(self.col_widths)
        )

        thead = nodes.thead()
        tgroup += thead

        row_node = nodes.row()
        thead += row_node
        row_node.extend(nodes.entry(h, nodes.paragraph(text=h)) for h in self.header)

        tbody = nodes.tbody()
        tgroup += tbody

        rows, groups = self.collect_rows()
        tbody.extend(rows)
        table.extend(groups)

        return table
Example #54
0
    def run(self) -> List[Node]:
        ncolumns = self.options.get('columns', 2)
        node = addnodes.compact_paragraph()
        node.document = self.state.document
        self.state.nested_parse(self.content, self.content_offset, node)
        if len(node.children) != 1 or not isinstance(node.children[0],
                                                     nodes.bullet_list):
            reporter = self.state.document.reporter
            raise SphinxError('table_from_list content is not a list')
        fulllist = node.children[0]

        if (len(fulllist) % ncolumns) != 0:
            raise SphinxError('number of list elements not a multiple of column number')

        table = nodes.table()
        tgroup = nodes.tgroup(cols=ncolumns)
        table += tgroup

        for i in range(ncolumns):
            tgroup += nodes.colspec(colwidth=1)

        tbody = nodes.tbody()
        tgroup += tbody
        current_row = nodes.row()

        for idx, cell in enumerate(fulllist.children):
            if len(current_row.children) == ncolumns:
                tbody += current_row
                current_row = nodes.row()
            entry = nodes.entry()
            current_row += entry
            if len(cell.children) > 0:
                entry += cell.children[0]

        tbody += current_row
        return [table]
    def _generate_rows(self, motors):
        vendor_name = None
        for m in motors:
            # only generate one row for each vendor name that serves as a group heading
            if 'vendor_name' in m and vendor_name != m['vendor_name']:
                vendor_name = m['vendor_name']

                strong = nodes.strong(text=vendor_name)
                para = nodes.paragraph()
                para += strong
                entry = nodes.entry(morecols=5)
                entry += para
                row = nodes.row()
                row += entry
                yield row

            # then generate one row for each sensor
            yield self._row([
                self._link(m.get('vendor_website', None), m['vendor_part_number']),
                m['vendor_part_name'],
                '``{}``'.format(m['name']),
                m['motor_type'],
                self._auto_detect(m['name'], m['motor_type']),
            ])
Example #56
0
    def run(self):
        table = nodes.table(
            "",
            classes=[
                "longtable",
                "colwidths-auto",
                # "colwidths-given",
            ],
        )

        group = nodes.tgroup("", cols=3)
        table.append(group)
        group.append(nodes.colspec("", colwidth=35))
        group.append(nodes.colspec("", colwidth=15))
        group.append(nodes.colspec("", colwidth=50))

        thead = nodes.thead("")
        group.append(thead)

        headrow = nodes.row("")
        thead.append(headrow)

        headrow.append(nodes.entry("", nodes.paragraph(text="Config Option")))
        headrow.append(nodes.entry("", nodes.paragraph(text="Default Value")))
        headrow.append(nodes.entry("", nodes.paragraph(text="Description")))

        tbody = nodes.tbody("")
        group.append(tbody)

        for config_option in pn.config._options_registry.values():
            row = nodes.row("")
            tbody.append(row)

            name = config_option.name
            default_value = config_option.default_value
            description = config_option.description

            row.append(nodes.entry("", nodes.literal(text=name)))
            row.append(nodes.entry("",
                                   nodes.literal(text=repr(default_value))))
            row.append(nodes.entry("", self._parse_string(description)))

        return [table]
Example #57
0
 def buildTableFromFieldList(self, headerRows, stubColumns):
     table = nodes.table()
     tgroup = nodes.tgroup(cols=len(self.tableInfo[0]))
     table += tgroup
     for info in self.tableInfo[0]:
         colwidth = info['colwidth']
         colspec = nodes.colspec(colwidth=colwidth)
         if stubColumns:
             colspec.attributes['stub'] = 1
             stubColumns = stubColumns - 1
         if not info['align'] is None:
             colspec.attributes['align'] = info['align']
         if not info['more'] is None:
             colspec.attributes['more'] = info['more']
         tgroup += colspec
     rows = []
     for self.rowNum, row in enumerate(self.tableData):
         if self.definitionRow and self.rowNum == 0:
             continue
         rowNode = nodes.row()
         for self.colNum, cell in enumerate(row):
             info = self.tableInfo[self.rowNum][self.colNum]
             if info.get('isInColspan'):
                 pass
             elif info.get('isFollowingRow'):
                 pass
             else:
                 entry = nodes.entry()
                 if self.options.get('debug-cellinfo') in ['yes','1']:
                     interesting = [
                         (1,'colNum'),
                         (1,'rowNum'),
                         (0,'colwidth'),
                         (0,'columnId'),
                         (0,'align'),
                         (0,'more'),
                         (1,'colspan'),
                         (1,'rowspan'),
                         (1,'columnIdRange'),
                         (1,'columnIdRaw'),
                         (1,'fieldNameRaw')]
                     debugLines = []
                     for flag,k in interesting:
                         if flag:
                             debugLines.append('| %s=%s \n' %
                                               (k, info.get(k)))
                     if debugLines:
                         p = nodes.paragraph('', ''.join(debugLines))
                         entry += p
                 entry += cell
                 info = self.tableInfo[self.rowNum][self.colNum]
                 morecols = info.get('colspan',1) - 1
                 if morecols:
                     entry.attributes['morecols'] = morecols
                 morerows = info.get('rowspan', 1) - 1
                 if morerows:
                     entry.attributes['morerows'] = morerows
                 align = info.get('align')
                 if align:
                     entry.attributes['align'] = align
                 more = info.get('more')
                 if more:
                     entry.attributes['more'] = more
                 rowNode += entry
         rows.append(rowNode)
     if headerRows:
         thead = nodes.thead()
         thead.extend(rows[:headerRows])
         tgroup += thead
     tbody = nodes.tbody()
     tbody.extend(rows[headerRows:])
     tgroup += tbody
     return table
Example #58
0
    def _grid_simple(self, colwidths, side_left, side_right, footer):
        """
        Creates most "simple" grid layouts.
        Side parts and footer can be activated via config.

        .. code-block:: text

            +------+---------+------+
            |      | Head    |      |
            |      +---------+      |
            |      | Meta    |      |
            | Side +---------+ Side |
            |      | Content |      |
            |      +---------+      |
            |      | Footer  |      |
            +------+---------+------+

        Only one active side is supported, as the section name is "side" for left and right section.

        If ``side_right`` or ``side_left`` is set to ``partial``, the table grids looks like::

        +------+------+------+
        |      | Head |      |
        | Side +------+ Side |
        |      | Meta |      |
        +------+------+------+
        | Content            |
        +--------------------+
        | Footer             |
        +--------------------+


        :param colwidths: List of integer for column widths
        :param side_left: False, 'full' or 'part'
        :param side_right: False, 'full' or 'part'
        :param footer:  True or False
        :return: need-table node
        """
        common_more_cols = 0

        if side_left:
            if side_left == 'full':
                side_left_morerows = 2
            else:
                side_left_morerows = 1
                common_more_cols += 1
            if footer:
                side_left_morerows += 1

        if side_right:
            if side_right == 'full':
                side_right_morerows = 2
            else:
                side_right_morerows = 1
                common_more_cols += 1
            if footer:
                side_right_morerows += 1

        # Table definition
        node_tgroup = nodes.tgroup(cols=common_more_cols)
        self.node_table += node_tgroup

        for width in colwidths:
            node_colspec = nodes.colspec(colwidth=width)
            node_tgroup += node_colspec

        # HEAD row
        head_row = nodes.row(classes=['need', 'head'])

        if side_left:
            side_entry = nodes.entry(classes=['need', 'side'],
                                     morerows=side_left_morerows)
            side_entry += self.get_section('side')
            head_row += side_entry

        head_entry = nodes.entry(classes=['need', 'head'])
        head_entry += self.get_section('head')
        head_row += head_entry

        if side_right:
            side_entry = nodes.entry(classes=['need', 'side'],
                                     morerows=side_right_morerows)
            side_entry += self.get_section('side')
            head_row += side_entry

        # META row
        meta_row = nodes.row(classes=['need', 'meta'])
        meta_entry = nodes.entry(classes=['need', 'meta'])
        meta_entry += self.get_section('meta')
        meta_row += meta_entry

        # CONTENT row
        content_row = nodes.row(classes=['need', 'content'])
        content_entry = nodes.entry(classes=['need', 'content'],
                                    morecols=common_more_cols)
        content_entry.insert(0, self.node.children)
        content_row += content_entry

        # FOOTER row
        if footer:
            footer_row = nodes.row(classes=['need', 'footer'])
            footer_entry = nodes.entry(classes=['need', 'footer'],
                                       morecols=common_more_cols)
            footer_entry += self.get_section('footer')
            footer_row += footer_entry

        # Construct table
        self.node_tbody += head_row
        self.node_tbody += meta_row
        self.node_tbody += content_row
        if footer:
            self.node_tbody += footer_row
        node_tgroup += self.node_tbody
Example #59
0
    def _grid_complex(self):
        node_tgroup = nodes.tgroup(cols=6)
        self.node_table += node_tgroup

        col_widths = [10, 10, 30, 30, 10, 10]
        for width in col_widths:
            node_colspec = nodes.colspec(colwidth=width)
            node_tgroup += node_colspec

        # HEAD row
        head_row = nodes.row(classes=['head'])
        self.node_tbody += head_row
        # HEAD left
        head_left_entry = nodes.entry(classes=['head_left'], morecols=1)
        head_left_entry += self.get_section('head_left')
        head_row += head_left_entry
        # HEAD mid
        head_entry = nodes.entry(classes=['head_center'], morecols=1)
        head_entry += self.get_section('head')
        head_row += head_entry
        # HEAD right
        head_right_entry = nodes.entry(classes=['head_right'], morecols=1)
        head_right_entry += self.get_section('head_right')
        head_row += head_right_entry

        # META row
        meta_row = nodes.row(classes=['meta'])
        self.node_tbody += meta_row
        # META left
        meta_left_entry = nodes.entry(classes=['meta'], morecols=2)
        meta_left_entry += self.get_section('meta_left')
        meta_row += meta_left_entry
        # META right
        meta_right_entry = nodes.entry(classes=['meta'], morecols=2)
        meta_right_entry += self.get_section('meta_right')
        meta_row += meta_right_entry

        # CONTENT row
        content_row = nodes.row(classes=['content'])
        self.node_tbody += content_row
        content_entry = nodes.entry(classes=['content'], morecols=5)
        content_entry.insert(0, self.node.children)
        content_row += content_entry

        # FOOTER row
        footer_row = nodes.row(classes=['footer'])
        self.node_tbody += footer_row
        # FOOTER left
        footer_left_entry = nodes.entry(classes=['footer_left'], morecols=1)
        footer_left_entry += self.get_section('footer_left')
        footer_row += footer_left_entry
        # FOOTER mid
        footer_entry = nodes.entry(classes=['footer'], morecols=1)
        footer_entry += self.get_section('footer')
        footer_row += footer_entry
        # FOOTER right
        footer_right_entry = nodes.entry(classes=['footer_right'], morecols=1)
        footer_right_entry += self.get_section('footer_right')
        footer_row += footer_right_entry

        # Construct table
        node_tgroup += self.node_tbody
Example #60
0
    def _grid_content(self, colwidths, side_left, side_right, footer):
        """
        Creates most "content" based grid layouts.
        Side parts and footer can be activated via config.

        +------+---------+------+
        |      | Content |      |
        | Side +---------+ Side |
        |      | Footer  |      |
        +------+---------+------+

        Only one active side is supported, as the section name is "side" for left and right section.

        :param colwidths: List of integer for column widths
        :param side_left: True or False
        :param side_right: True or False
        :param footer:  True or False
        :return: need-table node
        """
        side_morerows = 0
        if footer:
            side_morerows = 1

        # Table definition
        node_tgroup = nodes.tgroup(cols=len(colwidths))
        self.node_table += node_tgroup

        for width in colwidths:
            node_colspec = nodes.colspec(colwidth=width)
            node_tgroup += node_colspec

        # CONTENT row
        content_row = nodes.row(classes=['content'])

        if side_left:
            side_entry = nodes.entry(classes=['side', 'left'],
                                     morerows=side_morerows)
            side_entry += self.get_section('side')
            content_row += side_entry

        content_entry = nodes.entry(classes=['content'])
        content_entry.insert(0, self.node.children)
        content_row += content_entry

        if side_right:
            side_entry = nodes.entry(classes=['side', 'right'],
                                     morerows=side_morerows)
            side_entry += self.get_section('side')
            content_row += side_entry

        # FOOTER row
        if footer:
            footer_row = nodes.row(classes=['footer'])
            footer_entry = nodes.entry(classes=['footer'])
            footer_entry += self.get_section('footer')
            footer_row += footer_entry

        # Construct table
        self.node_tbody += content_row
        if footer:
            self.node_tbody += footer_row
        node_tgroup += self.node_tbody