我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用docutils.nodes.container()。
def run(self): self.assert_has_content() text = '\n'.join(self.content) try: if self.arguments: classes = directives.class_option(self.arguments[0]) else: classes = [] except ValueError: raise self.error( 'Invalid class attribute value for "%s" directive: "%s".' % (self.name, self.arguments[0])) node = nodes.container(text) node['classes'].extend(classes) self.add_name(node) self.state.nested_parse(self.content, self.content_offset, node) return [node]
def get_figtype(node): """Return figtype for given node.""" def has_child(node, cls): return any(isinstance(child, cls) for child in node) from docutils import nodes if isinstance(node, nodes.figure): return 'figure' elif isinstance(node, nodes.image) and isinstance(node.parent, nodes.figure): # bare image node is not supported because it doesn't have caption and # no-caption-target isn't a numbered figure. return 'figure' elif isinstance(node, nodes.table): return 'table' elif isinstance(node, nodes.container): if has_child(node, nodes.literal_block): return 'code-block' return None
def depart_caption(self, node): self.body.append('</span>') # append permalink if available if isinstance(node.parent, nodes.container) and node.parent.get('literal_block'): self.add_permalink_ref(node.parent, _('Permalink to this code')) elif isinstance(node.parent, nodes.figure): image_nodes = node.parent.traverse(nodes.image) target_node = image_nodes and image_nodes[0] or node.parent self.add_permalink_ref(target_node, _('Permalink to this image')) elif node.parent.get('toctree'): self.add_permalink_ref(node.parent.parent, _('Permalink to this toctree')) if isinstance(node.parent, nodes.container) and node.parent.get('literal_block'): self.body.append('</div>\n') else: BaseTranslator.depart_caption(self, node)
def get_figtype(self, node): """Get figure type of nodes.""" def has_child(node, cls): return any(isinstance(child, cls) for child in node) if isinstance(node, nodes.container): if node.get('literal_block') and has_child(node, nodes.literal_block): return 'code-block' else: return None else: figtype, _ = self.enumerable_nodes.get(node.__class__, (None, None)) return figtype
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 depart_caption(self, node): if (isinstance(node.parent, nodes.figure) or (isinstance(node.parent, nodes.container) and node.parent.get('literal_block'))): self.body.append('}\n')
def add_fignumber(self, node): def append_fignumber(figtype, figure_id): if figure_id in self.builder.fignumbers.get(figtype, {}): self.body.append('<span class="caption-number">') prefix = self.builder.config.numfig_format.get(figtype, '') numbers = self.builder.fignumbers[figtype][figure_id] self.body.append(prefix % '.'.join(map(str, numbers)) + ' ') self.body.append('</span>') if isinstance(node.parent, nodes.figure): append_fignumber('figure', node.parent['ids'][0]) elif isinstance(node.parent, nodes.table): append_fignumber('table', node.parent['ids'][0]) elif isinstance(node.parent, nodes.container): append_fignumber('code-block', node.parent['ids'][0])
def visit_caption(self, node): if isinstance(node.parent, nodes.container) and node.parent.get('literal_block'): self.body.append('<div class="code-block-caption">') else: BaseTranslator.visit_caption(self, node) self.add_fignumber(node) self.body.append(self.starttag(node, 'span', '', CLASS='caption-text'))
def run(self): """ Parse a tabs directive """ self.assert_has_content() env = self.state.document.settings.env node = nodes.container() node['classes'] = ['sphinx-tabs'] tabs_node = nodes.container() tabs_node.tagname = 'div' classes = 'ui top attached tabular menu sphinx-menu' tabs_node['classes'] = classes.split(' ') env.temp_data['tab_ids'] = [] env.temp_data['tab_titles'] = [] env.temp_data['is_first_tab'] = True self.state.nested_parse(self.content, self.content_offset, node) tab_titles = env.temp_data['tab_titles'] for idx, [data_tab, tab_name] in enumerate(tab_titles): tab = nodes.container() tab.tagname = 'a' tab['classes'] = ['item'] if idx > 0 else ['active', 'item'] tab['classes'].append(data_tab) tab += tab_name tabs_node += tab node.children.insert(0, tabs_node) return [node]
def run(self): """ Parse a tab directive """ self.assert_has_content() group_name = self.content[0] self.content.trim_start(2) for idx, line in enumerate(self.content.data): self.content.data[idx] = ' ' + line tab_args = { 'tab_id': base64.b64encode( group_name.encode('utf-8')).decode('utf-8') } new_content = [ '.. tab:: {}'.format(json.dumps(tab_args)), ' {}'.format(group_name), '', ] for idx, line in enumerate(new_content): self.content.data.insert(idx, line) self.content.items.insert(idx, (None, idx)) node = nodes.container() self.state.nested_parse(self.content, self.content_offset, node) return node.children
def run(self): """ Parse a tab directive """ self.assert_has_content() args = self.content[0].strip().split() self.content.trim_start(2) lang = args[0] tab_name = ' '.join(args[1:]) if len(args) > 1 else LEXER_MAP[lang] for idx, line in enumerate(self.content.data): self.content.data[idx] = ' ' + line tab_args = { 'tab_id': base64.b64encode( tab_name.encode('utf-8')).decode('utf-8'), 'classes': ['code-tab'], } new_content = [ '.. tab:: {}'.format(json.dumps(tab_args)), ' {}'.format(tab_name), '', ' .. code-block:: {}'.format(lang), '', ] for idx, line in enumerate(new_content): self.content.data.insert(idx, line) self.content.items.insert(idx, (None, idx)) node = nodes.container() self.state.nested_parse(self.content, self.content_offset, node) return node.children
def unknown_visit(self, node): if not self._found and isinstance(node, nodes.container) and \ 'classes' in node and isinstance(node['classes'], list): self._found = 'sphinx-tabs' in node['classes']
def run(self): # Uses a ‘container’ instead of a ‘literal_block’ to disable # Pygments-based post-processing (we could also set rawsource to '') content = '\n'.join(self.content) options = self.arguments[0].split() if self.arguments else ['in'] if 'all' in options: options.extend(['in', 'out']) node = nodes.container(content, coqtop_options = list(set(options)), classes=['coqtop', 'literal-block']) self.add_name(node) return [node]
def run(self): # Uses a ‘container’ instead of a ‘literal_block’ to disable # Pygments-based post-processing (we could also set rawsource to '') content = '\n'.join(self.content) node = nodes.inline(content, '', *highlight_using_coqdoc(content)) wrapper = nodes.container(content, node, classes=['coqdoc', 'literal-block']) return [wrapper]
def run(self): # get result from parent implementation code_block = CodeBlock.run(self) def find_and_wrap_literal_block(node): """ Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`. """ if isinstance(node, container): # container node => handle all children children = [] for child in node.children: children.append(find_and_wrap_literal_block(child)) node.children = children return node elif isinstance(node, literal_block): # literal block => replace it return self._wrap_literal_block(node) else: # no idea what that is => leave it alone return node # replace all created literal_blocks with literal_block_ext instances return map(find_and_wrap_literal_block, code_block)
def run(self): self.assert_has_content() text = '\n'.join(self.content) node = nodes.container(text) node['classes'].append('rosetta_outer') if self.arguments and self.arguments[0]: node['classes'].append(self.arguments[0]) self.add_name(node) self.state.nested_parse(self.content, self.content_offset, node) return [node]
def setup(app): """add custom directive into Sphinx so that it is found during document parsing""" app.add_directive('content-container', ContentContainerDirective) app.add_directive('embed-compare', EmbedCompareDirective) return {'version': sphinx.__display_version__, 'parallel_read_safe': True}
def process_service(self, filename): data = self.get_json_from_file(os.path.join(self.dir, filename)) request_filename = self.write_tmp(data['request'] or '') response_filename = self.write_tmp(data['response'] or '') example = HTTPExample( 'http:example', arguments=['curl', 'httpie', 'python-requests'], options={ 'request': request_filename, 'response': response_filename }, content=self.content, lineno=self.lineno, content_offset=self.content_offset, block_text='.. http:example::', state=self.state, state_machine=self.state_machine ) method = data['method'].upper() service = data['service'] name = service.get('name') or '' path_scheme = data.get('path_scheme') or name summary = service.get('summary') or '' permission = service.get('permission') or '' container = nodes.container('') container.append(addnodes.desc_name('', method + ' ')) container.append(addnodes.desc_name('', path_scheme)) inner_container = nodes.definition('') container.append(inner_container) inner_container.append(nodes.paragraph(summary, summary)) inner_container.append(addnodes.desc_name('permission', 'permission')) perm_label = ': ' + permission inner_container.append(addnodes.desc_annotation(perm_label, perm_label)) inner_container.append(example.run()[0]) # extra = nodes.paragraph('', '') # inner_container.append(extra) # if service.get('responses'): # extra.append(nodes.strong('', 'Responses')) # blist = nodes.bullet_list('') # extra.append(blist) # for code, config in service['responses'].items(): # blist.append(render_response(code, 'Hello')) # cleanup os.remove(request_filename) os.remove(response_filename) return container
def run(self): """ Parse a tab directive """ self.assert_has_content() env = self.state.document.settings.env args = self.content[0].strip() try: args = json.loads(args) self.content.trim_start(1) except ValueError: args = {} tab_name = nodes.container() self.state.nested_parse( self.content[:1], self.content_offset, tab_name) args['tab_name'] = tab_name if 'tab_id' not in args: args['tab_id'] = env.new_serialno('tab_id') i = 1 while args['tab_id'] in env.temp_data['tab_ids']: args['tab_id'] = '%s-%d' % (args['tab_id'], i) i += 1 env.temp_data['tab_ids'].append(args['tab_id']) data_tab = "sphinx-data-tab-{}".format(args['tab_id']) env.temp_data['tab_titles'].append((data_tab, args['tab_name'])) text = '\n'.join(self.content) node = nodes.container(text) classes = 'ui bottom attached sphinx-tab tab segment' node['classes'] = classes.split(' ') node['classes'].extend(args.get('classes', [])) node['classes'].append(data_tab) if env.temp_data['is_first_tab']: node['classes'].append('active') env.temp_data['is_first_tab'] = False self.state.nested_parse(self.content[2:], self.content_offset, node) return [node]