我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用docutils.nodes.Element()。
def run(self): if not isinstance(self.state, states.SubstitutionDef): raise self.error( 'Invalid context: the "%s" directive can only be used within ' 'a substitution definition.' % self.name) substitution_definition = self.state_machine.node if 'trim' in self.options: substitution_definition.attributes['ltrim'] = 1 substitution_definition.attributes['rtrim'] = 1 if 'ltrim' in self.options: substitution_definition.attributes['ltrim'] = 1 if 'rtrim' in self.options: substitution_definition.attributes['rtrim'] = 1 codes = self.comment_pattern.split(self.arguments[0])[0].split() element = nodes.Element() for code in codes: try: decoded = directives.unicode_code(code) except ValueError, error: raise self.error(u'Invalid character code: %s\n%s' % (code, ErrorString(error))) element += nodes.Text(decoded) return element.children
def run(self): try: class_value = directives.class_option(self.arguments[0]) except ValueError: raise self.error( 'Invalid class attribute value for "%s" directive: "%s".' % (self.name, self.arguments[0])) node_list = [] if self.content: container = nodes.Element() self.state.nested_parse(self.content, self.content_offset, container) for node in container: node['classes'].extend(class_value) node_list.extend(container.children) else: pending = nodes.pending( misc.ClassAttribute, {'class': class_value, 'directive': self.name}, self.block_text) self.state_machine.document.note_pending(pending) node_list.append(pending) return node_list
def run(self): if not self.content: warning = self.state_machine.reporter.warning( 'Content block expected for the "%s" directive; none found.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return [warning] title, messages = self.make_title() node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) if len(node) != 1 or not isinstance(node[0], nodes.table): error = self.state_machine.reporter.error( 'Error parsing content block for the "%s" directive: exactly ' 'one table expected.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return [error] table_node = node[0] table_node['classes'] += self.options.get('class', []) self.add_name(table_node) if title: table_node.insert(0, title) return [table_node] + messages
def _resolve_citation(self, builder, fromdocname, node, contnode): docname, labelid = self.citations.get(node['reftarget'], ('', '')) if docname: try: newnode = make_refnode(builder, fromdocname, docname, labelid, contnode) return newnode except NoUri: # remove the ids we added in the CitationReferences # transform since they can't be transfered to # the contnode (if it's a Text node) if not isinstance(contnode, nodes.Element): del node['ids'][:] raise elif 'ids' in node: # remove ids attribute that annotated at # transforms.CitationReference.apply. del node['ids'][:]
def apply(self): def has_child(node, cls): return any(isinstance(child, cls) for child in node) for node in self.document.traverse(nodes.Element): if isinstance(node, nodes.figure): if has_child(node, nodes.caption): self.document.note_implicit_target(node) elif isinstance(node, nodes.image): if node.parent and has_child(node.parent, nodes.caption): self.document.note_implicit_target(node.parent) elif isinstance(node, nodes.table): if has_child(node, nodes.title): self.document.note_implicit_target(node) elif isinstance(node, nodes.literal_block): if node.parent and has_child(node.parent, nodes.caption): self.document.note_implicit_target(node.parent)
def _get_matching_child( parent_node: nodes.Element, child_class: nodes.Element, last=True): """Get the first or last child node that matches a Node subclass. Args: parent_node: The node to find the child of. child_class: The Node subclass to check against. last: If True, find the last matching child. If False, find the first one. Returns: The first or last child Node object that is an instance of the given class. """ if last: children = reversed(parent_node.children) else: children = parent_node.children for child_node in children: if isinstance(child_node, child_class): return child_node
def _extend_rst( extendable_node: nodes.Element, extra_content: List[ExtraContent] ) -> None: """Modify a node with extra content. Args: extendable_node: The node to modify with new content. extra_content: The new content to add to the node. """ for content in extra_content: if "@rst" not in content.classifiers: continue if "@after" in content.classifiers: extendable_node += content.nodes elif "@before" in content.classifiers: # The new nodes have to be added this way. Using insert() or # reassigning extendable_node.children messes up the "parent" # attribute for each of the children. extendable_node.children.reverse() extendable_node += reversed(content.nodes) extendable_node.children.reverse() elif "@replace" in content.classifiers: extendable_node.children = content.nodes
def run(self): if not isinstance(self.state, states.SubstitutionDef): raise self.error( 'Invalid context: the "%s" directive can only be used within ' 'a substitution definition.' % self.name) substitution_definition = self.state_machine.node if 'trim' in self.options: substitution_definition.attributes['ltrim'] = 1 substitution_definition.attributes['rtrim'] = 1 if 'ltrim' in self.options: substitution_definition.attributes['ltrim'] = 1 if 'rtrim' in self.options: substitution_definition.attributes['rtrim'] = 1 codes = self.comment_pattern.split(self.arguments[0])[0].split() element = nodes.Element() for code in codes: try: decoded = directives.unicode_code(code) except ValueError as error: raise self.error('Invalid character code: %s\n%s' % (code, ErrorString(error))) element += nodes.Text(decoded) return element.children
def check_classes(self, node): if isinstance(node, nodes.Element): for class_value in node['classes'][:]: if class_value in self.strip_classes: node['classes'].remove(class_value) if class_value in self.strip_elements: return 1
def visit_docinfo_item(self, node, name, meta=True): if meta: meta_tag = '<meta name="%s" content="%s" />\n' \ % (name, self.attval(node.astext())) self.add_meta(meta_tag) self.body.append(self.starttag(node, 'tr', '')) self.body.append('<th class="docinfo-name">%s:</th>\n<td>' % self.language.labels[name]) if len(node): if isinstance(node[0], nodes.Element): node[0]['classes'].append('first') if isinstance(node[-1], nodes.Element): node[-1]['classes'].append('last')
def Element(tag, attrib=None, nsmap=None, nsdict=CNSD): if attrib is None: attrib = {} tag, attrib = fix_ns(tag, attrib, nsdict) if WhichElementTree == 'lxml': el = etree.Element(tag, attrib, nsmap=nsmap) else: el = _ElementInterfaceWrapper(tag, attrib) return el
def add_doc_title(self): text = self.settings.title if text: self.title = text if not self.found_doc_title: el = Element('text:p', attrib = { 'text:style-name': self.rststyle('title'), }) el.text = text self.body_text_element.insert(0, el) el = self.find_first_text_p(self.body_text_element) if el is not None: self.attach_page_style(el)
def handle_basic_atts(self, node): if isinstance(node, nodes.Element) and node['ids']: self.pending_ids += node['ids']
def visit_footnote(self, node): self.footnote_level += 1 self.save_footnote_current = self.current_element el1 = Element('text:note-body') self.current_element = el1 self.footnote_list.append((node, el1)) if isinstance(node, docutils.nodes.citation): self.paragraph_style_stack.append(self.rststyle('citation')) else: self.paragraph_style_stack.append(self.rststyle('footnote'))
def run(self): if not self.content: warning = self.state_machine.reporter.warning( 'Content block expected for the "%s" directive; none found.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return [warning] title, messages = self.make_title() node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) if len(node) != 1 or not isinstance(node[0], nodes.table): error = self.state_machine.reporter.error( 'Error parsing content block for the "%s" directive: exactly ' 'one table expected.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return [error] table_node = node[0] table_node['classes'] += self.options.get('class', []) if 'align' in self.options: table_node['align'] = self.options.get('align') tgroup = table_node[0] if type(self.widths) == list: colspecs = [child for child in tgroup.children if child.tagname == 'colspec'] for colspec, col_width in zip(colspecs, self.widths): colspec['colwidth'] = col_width # @@@ the colwidths argument for <tgroup> is not part of the # XML Exchange Table spec (https://www.oasis-open.org/specs/tm9901.htm) # and hence violates the docutils.dtd. if self.widths == 'auto': table_node['classes'] += ['colwidths-auto'] elif self.widths: # "grid" or list of integers table_node['classes'] += ['colwidths-given'] self.add_name(table_node) if title: table_node.insert(0, title) return [table_node] + messages
def run(self): if not isinstance(self.state, states.SubstitutionDef): raise self.error( 'Invalid context: the "%s" directive can only be used within ' 'a substitution definition.' % self.name) self.assert_has_content() text = '\n'.join(self.content) element = nodes.Element(text) self.state.nested_parse(self.content, self.content_offset, element) # element might contain [paragraph] + system_message(s) node = None messages = [] for elem in element: if not node and isinstance(elem, nodes.paragraph): node = elem elif isinstance(elem, nodes.system_message): elem['backrefs'] = [] messages.append(elem) else: return [ self.state_machine.reporter.error( 'Error in "%s" directive: may contain a single paragraph ' 'only.' % (self.name), line=self.lineno) ] if node: return messages + node.children return messages
def run(self): self.assert_has_content() node = nodes.Element() new_line_offset, blank_finish = self.state.nested_list_parse( self.content, self.content_offset, node, initial_state='MetaBody', blank_finish=True, state_machine_kwargs=self.SMkwargs) if (new_line_offset - self.content_offset) != len(self.content): # incomplete parse of block? error = self.state_machine.reporter.error( 'Invalid meta directive.', nodes.literal_block(self.block_text, self.block_text), line=self.lineno) node += error return node.children
def container_wrapper(directive, literal_node, caption): container_node = nodes.container('', literal_block=True, classes=['literal-block-wrapper']) parsed = nodes.Element() directive.state.nested_parse(ViewList([caption], source=''), directive.content_offset, parsed) caption_node = nodes.caption(parsed[0].rawsource, '', *parsed[0].children) caption_node.source = parsed[0].source caption_node.line = parsed[0].line container_node += caption_node container_node += literal_node return container_node
def figure_wrapper(directive, node, caption): figure_node = nodes.figure('', node) parsed = nodes.Element() directive.state.nested_parse(ViewList([caption], source=''), directive.content_offset, parsed) caption_node = nodes.caption(parsed[0].rawsource, '', *parsed[0].children) caption_node.source = parsed[0].source caption_node.line = parsed[0].line figure_node += caption_node return figure_node
def set_role_source_info(inliner, lineno, node): node.source, node.line = inliner.reporter.get_source_and_line(lineno) # monkey-patch Element.copy to copy the rawsource and line
def _new_copy(self): newnode = self.__class__(self.rawsource, **self.attributes) if isinstance(self, nodes.Element): newnode.source = self.source newnode.line = self.line return newnode
def is_coqtop_block(node): return isinstance(node, nodes.Element) and 'coqtop_options' in node
def is_coqtop_or_coqdoc_block(node): return (isinstance(node, nodes.Element) and ('coqtop' in node['classes'] or 'coqdoc' in node['classes']))
def copy(self): '''sphinx.util.nodes (function _new_copy) monkey-patches the Element.copy method to include the source and line, however, it calls the Element constructor with a positional argument rawsource instead of using keyword arguments. That is changed here so that the constructor of this class can use other positional parameters. ''' newnode = self.__class__(self.tagname, self.attributes, self.no_write, self.skip_html, *self.children) if isinstance(self, nodes.Element): newnode.source = self.source newnode.line = self.line return newnode