def transform_content(self, contentnode: addnodes.desc_content) -> None: if 'options' in self.options: code_block_directive = CodeBlock( name='code-block', arguments=[], options={ 'caption': 'Options', }, content=[self.options['options']], lineno=self.lineno, content_offset=self.content_offset, block_text='', state=self.state, state_machine=self.state_machine) contentnode += code_block_directive.run()[0] if 'examples' in self.options: code_block_directive = CodeBlock( name='code-block', arguments=[], options={ 'caption': 'Examples', }, content=[self.options['examples'].replace('\n::\n', '\n\n')], lineno=self.lineno, content_offset=self.content_offset, block_text='', state=self.state, state_machine=self.state_machine) contentnode += code_block_directive.run()[0] if self.display_code_block: code_block_content = [] for name_prefix in self.names: name, prefix = name_prefix line = name if 'suffix' in self.options: if self.space_between_suffix: line += ' ' line += self.options['suffix'] if 'prefix' in self.options: line = self.options['prefix'] + line if prefix and self.prefix_in_code_block: line = prefix + line code_block_content.append(line) code_block_directive = CodeBlock( name='code-block', arguments=[], options={}, content=code_block_content, lineno=self.lineno, content_offset=self.content_offset, block_text='', state=self.state, state_machine=self.state_machine) contentnode.insert(0, code_block_directive.run()[0])
def run(self): env = self.state.document.settings.env version = str(env.config['version']) self.content = [ line.replace('|version|', version) for line in self.content ] return CodeBlock.run(self)
def run(self): literal = CodeBlock.run(self) if not self.file: return literal text = str(literal[0][0]) if os.path.exists(self.file[1]): in_ = open(self.file[1]) in_.readline() # Skip header old = str(in_.read()) else: old = "" if text != old: self.message("updating %s" % darkgreen(self.file[0])) f = open(self.file[1], "w") f.write( "# Automatically generated; edit in Sphinx source code, not here.\n" ) f.write(text) f.close() return literal
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): code_node = CodeBlock.run(self) nodes.image() from PIL import Image lib_path = os.path.abspath('..') working_path = os.path.dirname(os.path.realpath(__file__)) static_path = os.path.join(working_path, '..', '_static') sys.path.append(lib_path) os.chdir(working_path) node = PILNode() g = globals() l = locals() for line in self.content: result = exec(line, g, l) buffer = io.BytesIO() new_img = l.get('new_img') new_img.save(buffer, format='PNG') image_node = nodes.image() image_node['alt'] = 'New Image' image_node['uri'] = 'data:image/png;base64,' + base64.b64encode( buffer.getvalue()).decode() node += code_node node += image_node return [node]
def run(self): """Parse a code-tab directive""" self.assert_has_content() if len(self.arguments) > 1: tab_name = self.arguments[1] elif self.arguments[0] in lexer_classes and not isinstance( lexer_classes[self.arguments[0]], partial): tab_name = lexer_classes[self.arguments[0]].name else: try: tab_name = LEXER_MAP[self.arguments[0]] except KeyError as invalid_lexer_error: raise ValueError("Lexer not implemented: {}".format( self.arguments[0])) from invalid_lexer_error self.tab_classes.add("code-tab") # All content parsed as code code_block = CodeBlock.run(self) # Reset to generate panel self.content.data = [tab_name, ""] self.content.items = [(None, 0), (None, 1)] node = super().run() node[0].extend(code_block) return node
def run(self): dict_obj = getattr(importlib.import_module(self.arguments[0]), self.arguments[1]) new_dict = {} for k, v in dict_obj.items(): new_dict[k] = '%s' % v.__name__ string = self.arguments[0] + '.' + self.arguments[ 1] + ' = ' + json.dumps(new_dict, indent=2, sort_keys=True) self.arguments = ['Javascript'] self.content = string.split('\n') return CodeBlock.run(self)
def create_generic_code_block(self, lexer): properties = self.supported_lexers[lexer] content = ( "We don't have a {} code example for this API call yet.\n\n" + "If you have some time to spare, feel free to open a pull request at:\n" + "https://github.com/centrahq/api-documentation").format( properties["language_text"]) code_block = CodeBlock("generic-code-block", ["html"], {"linenos": True}, [content], self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) parsed_block = code_block.run() return parsed_block[0]
def run(self): dialect = postgresql.dialect() res = [] for table in Base.metadata.sorted_tables: cb = CodeBlock(*self.args, **self.kwargs) cb.arguments = ['postgresql'] cb.content = itertools.chain( [str(CreateTable(table).compile(dialect=dialect))], ( str(CreateIndex(index).compile(dialect=dialect)) for index in table.indexes ) ) res.extend(cb.run()) return res
def run(self): """ Replace placeholders with given variables. """ app = self.state.document.settings.env.app new_content = [] existing_content = self.content for item in existing_content: for pair in app.config.substitutions: original, replacement = pair item = item.replace(original, replacement) new_content.append(item) self.content = new_content return list(CodeBlock.run(self))
def run(self): classes = 'filename' if 'first_of_file' in self.options: classes = 'filename first_of_file' filename = [self.raw_html('<div class="%s">%s</div>' % (classes, self.arguments[0]))] # Set self.arguments[0] to be the highlight language for CodeBlock. if self.arguments[0].endswith('.c') or self.arguments[0].endswith('.h'): self.arguments[0] = 'c' else: self.arguments[0] = 'python' [literal] = CodeBlock.run(self) return [self.raw_html('<div class="source">')] + filename + [literal] + \ [self.raw_html('</div>')]
def run(self): openstack = [] selfclosing = [] annotations = [] line_num = 0 loc = 0 for line in slicer(self.content): processed = [] for part in re.split(u'(\d«» |\d«|»)', line[0]): if u'«» ' in part: openstack.append((part[0], line_num, loc)) selfclosing.append(part[0]) elif u'«' in part: openstack.append((part[0], line_num, loc)) elif u'»' in part: start = openstack.pop() annotations.append( (start[0], start[1], start[2], line_num, loc)) else: processed.append(part) loc += len(part) for tag in selfclosing: start = openstack.pop() annotations.append( (start[0], start[1], start[2], line_num, loc)) selfclosing = [] line_num += 1 loc = 0 line[0] = u''.join(processed) # run the original code-block on the now cleaned content originals = CodeBlock.run(self) # place the results as children of a node holding annotation info node = altered_node() node['annotations'] = annotations for item in originals: node.append(item) return [node]
def run(self): rst_source = self.state_machine.node.document["source"] rst_filename = basename(rst_source) serial_no = self.env.new_serialno("ccb") target_id = f"{rst_filename}.ccb-{serial_no}".replace(".", "-") target = nodes.target("", "", ids=[target_id]) block = collapsible_code_block(target_id=target_id, heading=self.options.get( "heading", "Code")) cb = CodeBlock.run(self) block.setup_child(cb[0]) block.children.append(cb[0]) return [target, block]
def run(self): openstack = [] selfclosing = [] annotations = [] line_num = 0 loc = 0 for line in slicer(self.content): processed = [] for part in re.split(u'(\d«» |\d«|»)', line[0]): if u'«» ' in part: openstack.append((part[0], line_num, loc)) selfclosing.append(part[0]) elif u'«' in part: openstack.append((part[0], line_num, loc)) elif u'»' in part: start = openstack.pop() annotations.append((start[0], start[1], start[2], line_num, loc)) else: processed.append(part) loc += len(part) for tag in selfclosing: start = openstack.pop() annotations.append((start[0], start[1], start[2], line_num, loc)) selfclosing = [] line_num += 1 loc = 0 line[0] = u''.join(processed) # run the original code-block on the now cleaned content originals = CodeBlock.run(self) # place the results as children of a node holding annotation info node = altered_node() node['annotations'] = annotations for item in originals: node.append(item) return [node]
def run(self): literal = CodeBlock.run(self) language = literal[0]['language'] if not self.file: return literal text = str(literal[0][0]) if os.path.exists(self.file[1]): in_ = open(self.file[1]) in_.readline() # Skip header old = str(in_.read()) else: old = "" if text != old: self.message("updating %s" % darkgreen(self.file[0])) f = open(self.file[1], "w") f.write( "# Automatically generated; edit in Sphinx source code, not here.\n" ) f.write(text) f.close() ntext = "" include = 1 for line in text.split("\n"): if "%hide-begin%" in line: include -= 1 continue if "%hide-end%" in line: include += 1 continue if include > 0: ntext += line + "\n" ntext = ntext.strip() literal[0] = nodes.literal_block(ntext, ntext) literal[0]['language'] = language return literal
def run(self): env = self.state.document.settings.env rst_source = self.state_machine.node.document['source'] rst_filename = basename(rst_source) target_id = "%s.ccb-%d" % (rst_filename, env.new_serialno('bokeh-plot')) target_id = target_id.replace(".", "-") target_node = nodes.target('', '', ids=[target_id]) node = collapsible_code_block() node['target_id'] = target_id node['heading'] = self.options.get('heading', "Code") cb = CodeBlock.run(self) node.setup_child(cb[0]) node.children.append(cb[0]) return [target_node, node]
def run(self) -> List[Node]: new_content = [] doc = self.state.document replacements = [(i.attributes['names'][0], i.children[0]) for i in doc.substitution_defs.values()] # Config values need to be added manually at this time. replacements.append(('version', Text(doc.settings.env.config.version))) for item in self.content: for rep in replacements: item = item.replace('|' + rep[0] + '|', rep[1]) new_content.append(item) self.content = new_content return CodeBlock.run(self)
def run(self): env = self.state.document.settings.env rst_source = self.state_machine.node.document['source'] rst_filename = basename(rst_source) target_id = "%s.ccb-%d" % (rst_filename, env.new_serialno('ccb')) target_id = target_id.replace(".", "-") target_node = nodes.target('', '', ids=[target_id]) node = collapsible_code_block() node['target_id'] = target_id node['heading'] = self.options.get('heading', "Code") cb = CodeBlock.run(self) node.setup_child(cb[0]) node.children.append(cb[0]) return [target_node, node]
def run(self): classes = 'filename' if 'first_of_file' in self.options: classes = 'filename first_of_file' filename = [ self.raw_html('<div class="%s">%s</div>' % (classes, self.arguments[0])) ] # Set self.arguments[0] to be the highlight language for CodeBlock. if self.arguments[0].endswith('.c') or self.arguments[0].endswith( '.h'): self.arguments[0] = 'c' else: self.arguments[0] = 'python' [literal] = CodeBlock.run(self) return [self.raw_html('<div class="source">')] + filename + [literal] + \ [self.raw_html('</div>')]
def run(self): newlines = [] env = self.state.document.settings.env # Random id for the code block is used in the line anchors randomid = str(env.new_serialno('lineref_codeblock')) labelpattern = re.compile(r':[\w-]+:') if not hasattr(env, 'code_line_labels'): env.code_line_labels = {} linecount = 0 for line in self.content: linecount += 1 anchor = randomid + '-' + str(linecount) newline = process_line(self, line, labelpattern, anchor) newlines.append(newline) self.content = newlines originals = CodeBlock.run(self) node = codeblock_lineref() node.extend(originals) node['lineanchor_id'] = randomid return [node]
def run(self): env = self.state.document.settings.env rst_source = self.state_machine.node.document["source"] rst_filename = basename(rst_source) serial_no = env.new_serialno("ccb") target_id = f"{rst_filename}.ccb-{serial_no}" target_id = target_id.replace(".", "-") target_node = nodes.target("", "", ids=[target_id]) node = collapsible_code_block() node["target_id"] = target_id node["heading"] = self.options.get("heading", "Code") cb = CodeBlock.run(self) node.setup_child(cb[0]) node.children.append(cb[0]) return [target_node, node]
def create_generic_code_block(self, lexer): properties = self.supported_lexers[lexer] content = ( "We don't have a {} code example for this API call yet.\n\n" + "If you have some time to spare, feel free to open a pull request at:\n" + "https://github.com/mollie/api-documentation" ).format(properties["language_text"]) code_block = CodeBlock( "generic-code-block", ["html"], {"linenos": True}, [content], self.lineno, self.content_offset, self.block_text, self.state, self.state_machine ) parsed_block = code_block.run() return parsed_block[0]
def run(self): if self.env.app.builder.name != "man": self.arguments = ["fish-synopsis"] return CodeBlock.run(self) lexer = FishSynopsisLexer() result = nodes.line_block() for (start, tok, text) in lexer.get_tokens_unprocessed("\n".join(self.content)): if ( # Literal text. (tok in (Name.Function, Name.Constant) and not text.isupper()) or text.startswith( "-") # Literal option, even if it's uppercase. or tok in (Operator, Punctuation) or text == " ]" # Tiny hack: the closing bracket of the test(1) alias is a literal. ): node = nodes.strong(text=text) elif (tok in (Name.Constant, Name.Function) and text.isupper()): # Placeholder parameter. node = nodes.emphasis(text=text) else: # Grammar metacharacter or whitespace. node = nodes.inline(text=text) result.append(node) return [result]
def run(self): source, line = self.state_machine.get_source_and_line(self.lineno) # built-in directives.unchanged_required option validator produces a confusing error message if self.options.get('type-name') == None: raise ExtensionError("Expected type name in: {0} line: {1}".format( source, line)) if not ValidatingCodeBlock.skip_validation: args = [ 'bazel-bin/tools/config_validation/validate_fragment', self.options.get('type-name'), '-s', '\n'.join(self.content) ] completed = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8') if completed.returncode != 0: raise ExtensionError( "Failed config validation for type: '{0}' in: {1} line: {2}:\n {3}" .format(self.options.get('type-name'), source, line, completed.stderr)) self.options.pop('type-name', None) return list(CodeBlock.run(self))
def run(self): latest = get_installable_version(version) self.content = [ item.replace(PLACEHOLDER, latest) for item in self.content ] return CodeBlock.run(self)
def run(self): config = self.state.document.settings.env.config # Read enabled builders; Defaults to None chosen_builders = choose_builders(self.arguments) # Enable 'http' language for http part self.arguments = ['http'] # process 'query' reST fields if self.content: raw = ('\r\n'.join(self.content)).encode('utf-8') request = parsers.parse_request(raw) params, _ = request.extract_fields('query') params = [(p[1], p[2]) for p in params] new_path = utils.add_url_params(request.path, params) self.content[0] = ' '.join( [request.command, new_path, request.request_version]) # split the request and optional response in the content. # The separator is two empty lines followed by a line starting with # 'HTTP/' or 'HTTP ' request_content = StringList() request_content_no_fields = StringList() response_content = None emptylines_count = 0 in_response = False is_field = r':({}) (.+): (.+)'.format('|'.join(AVAILABLE_FIELDS)) for i, line in enumerate(self.content): source = self.content.source(i) if in_response: response_content.append(line, source) else: if emptylines_count >= 2 and \ (line.startswith('HTTP/') or line.startswith('HTTP ')): in_response = True response_content = StringList() response_content.append(line, source) elif line == '': emptylines_count += 1 else: request_content.extend( StringList([''] * emptylines_count, source)) request_content.append(line, source) if not re.match(is_field, line): request_content_no_fields.extend( StringList([''] * emptylines_count, source)) request_content_no_fields.append(line, source) emptylines_count = 0 # Load optional external request cwd = os.path.dirname(self.state.document.current_source) if 'request' in self.options: request = utils.resolve_path(self.options['request'], cwd) with open(request) as fp: request_content = request_content_no_fields = StringList( list(map(str.rstrip, fp.readlines())), request) # Load optional external response if 'response' in self.options: response = utils.resolve_path(self.options['response'], cwd) with open(response) as fp: response_content = StringList( list(map(str.rstrip, fp.readlines())), response) # reset the content to the request, stripped of the reST fields self.content = request_content_no_fields # Wrap and render main directive as 'http-example-http' klass = 'http-example-http' container = nodes.container('', classes=[klass]) container.append(nodes.caption('', 'http')) container.extend(super(HTTPExample, self).run()) # Init result node list result = [container] # reset the content to just the request self.content = request_content # Append builder responses if request_content_no_fields: raw = ('\r\n'.join(request_content_no_fields)).encode('utf-8') for name in chosen_builders: request = parsers.parse_request(raw, config.httpexample_scheme) builder_, language = AVAILABLE_BUILDERS[name] command = builder_(request) content = StringList([command], request_content_no_fields.source(0)) options = self.options.copy() options.pop('name', None) options.pop('caption', None) block = CodeBlock('code-block', [language], options, content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) # Wrap and render main directive as 'http-example-{name}' klass = 'http-example-{}'.format(name) container = nodes.container('', classes=[klass]) container.append(nodes.caption('', name)) container.extend(block.run()) # Append to result nodes result.append(container) # Append optional response if response_content: options = self.options.copy() options.pop('name', None) options.pop('caption', None) block = CodeBlock('code-block', ['http'], options, response_content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) # Wrap and render main directive as 'http-example-response' klass = 'http-example-response' container = nodes.container('', classes=[klass]) container.append(nodes.caption('', 'response')) container.extend(block.run()) # Append to result nodes result.append(container) # Final wrap container_node = nodes.container('', classes=['http-example']) container_node.extend(result) return [container_node]
def run(self): latest = get_installable_version(version) self.content = [item.replace(PLACEHOLDER, latest) for item in self.content] return CodeBlock.run(self)
def run(self): env = self.state.document.settings.env version = str(env.config['version']) self.content = [line.replace('|version|', version) for line in self.content] return CodeBlock.run(self)