Generates rst codeblock for given text and language
344725
def get_codeblock(language, text):
    
    rst = "\n\n.. code-block:: " + language + "\n\n"
    for line in text.splitlines():
        rst += "\t" + line + "\n"

    rst += "\n"
    return rst
783896
def strip_rst(docs):
    '''
    
    '''
    for func, docstring in six.iteritems(docs):
        log.debug('Stripping docstring for %s', func)
        if not docstring:
            continue
        docstring_new = docstring if six.PY3 else salt.utils.data.encode(docstring)
        for regex, repl in (
                (r' *.. code-block:: \S+\n{1,2}', ''),
                ('.. note::', 'Note:'),
                ('.. warning::', 'Warning:'),
                ('.. versionadded::', 'New in version'),
                ('.. versionchanged::', 'Changed in version')):
            if six.PY2:
                regex = salt.utils.data.encode(regex)
                repl = salt.utils.data.encode(repl)
            try:
                docstring_new = re.sub(regex, repl, docstring_new)
            except Exception:
                log.debug(
                    'Exception encountered while matching regex %r to '
                    'docstring for function %s', regex, func,
                    exc_info=True
                )
        if six.PY2:
            docstring_new = salt.utils.data.decode(docstring_new)
        if docstring != docstring_new:
            docs[func] = docstring_new
    return docs
45805
def new_code_block(self, **kwargs):
        """"""
        proto = {'content': '',
                 'type': self.code,
                 'IO': '',
                 'attributes': ''}
        proto.update(**kwargs)
        return proto
853049
def highlight_block(self, text):
        """"""
        text = to_text_string(text)
        if text.startswith("+++"):
            self.setFormat(0, len(text), self.formats["keyword"])
        elif text.startswith("---"):
            self.setFormat(0, len(text), self.formats["keyword"])
        elif text.startswith("+"):
            self.setFormat(0, len(text), self.formats["string"])
        elif text.startswith("-"):
            self.setFormat(0, len(text), self.formats["number"])
        elif text.startswith("@"):
            self.setFormat(0, len(text), self.formats["builtin"])
        
        self.highlight_spaces(text)
387730
def template(basedir, text, vars, lookup_fatal=True, expand_lists=False):
    '''  '''

    try:
        text = text.decode('utf-8')
    except UnicodeEncodeError:
        pass # already unicode
    text = varReplace(basedir, unicode(text), vars, lookup_fatal=lookup_fatal, expand_lists=expand_lists)
    return text
537336
def visit_literal_block(self, node):
        """"""
        # For "..code-block:: language"
        language = node.get('language', None)
        is_code_node = False
        if not language:
            # For "..code:: language"
            is_code_node = True
            classes = node.get('classes')
            if 'code' in classes:
                language = classes[-1]
            else:
                return

        if language in self.ignore['languages']:
            return

        if language == 'doctest' or (
                language == 'python' and
                node.rawsource.lstrip().startswith('>>> ')):
            self.visit_doctest_block(node)
            raise docutils.nodes.SkipNode

        checker = {
            'bash': bash_checker,
            'c': c_checker,
            'cpp': cpp_checker,
            'json': lambda source, _: lambda: check_json(source),
            'xml': lambda source, _: lambda: check_xml(source),
            'python': lambda source, _: lambda: check_python(source),
            'rst': lambda source, _: lambda: check_rst(source,
                                                       ignore=self.ignore)
        }.get(language)

        if checker:
            run = checker(node.rawsource, self.working_directory)
            self._add_check(node=node,
                            run=run,
                            language=language,
                            is_code_node=is_code_node)

        raise docutils.nodes.SkipNode
984859
protected static String formatBlockText(String content, String languageName, Function2<String, String, String> blockFormat) {
		String replacement = Strings.nullToEmpty(content);
		final String[] lines = replacement.trim().split("[\n\r]+"); //$NON-NLS-1$
		int minIndent = Integer.MAX_VALUE;
		final Pattern wpPattern = Pattern.compile("^(\\s*)[^\\s]"); //$NON-NLS-1$
		for (int i = lines.length > 1 ? 1 : 0; i < lines.length; ++i) {
			final String line = lines[i];
			final Matcher matcher = wpPattern.matcher(line);
			if (matcher.find()) {
				final int n = matcher.group(1).length();
				if (n < minIndent) {
					minIndent = n;
					if (minIndent <= 0) {
						break;
					}
				}
			}
		}
		final StringBuilder buffer = new StringBuilder();
		buffer.append(lines[0]);
		buffer.append("\n"); //$NON-NLS-1$
		for (int i = 1; i < lines.length; ++i) {
			final String line = lines[i];
			buffer.append(line.replaceFirst("^\\s{0," + minIndent + "}", "")); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
			buffer.append("\n"); //$NON-NLS-1$
		}
		replacement = buffer.toString().replaceFirst("[\n\r]+$", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
		if (!Strings.isNullOrEmpty(replacement) && !"\n".equals(replacement)) { //$NON-NLS-1$
			if (blockFormat != null) {
				return blockFormat.apply(languageName, replacement);
			}
			return replacement;
		}
		return ""; //$NON-NLS-1$
	}
238855
def parse_rst(text: str) -> docutils.nodes.document:
    """"""
    parser = docutils.parsers.rst.Parser()
    components = (docutils.parsers.rst.Parser,)
    settings = docutils.frontend.OptionParser(components=components).get_default_values()
    document = docutils.utils.new_document('<rst-doc>', settings=settings)
    parser.parse(text, document)
    return document
384375
def highlightBlock(self, text):
        
        text = nativestring(text)
        for pattern, format in self.patterns():
            for result in re.finditer(pattern, text):
                grps = result.groups()
                if grps:
                    for i in range(len(grps)):
                        start, end = result.span(i+1)
                        self.setFormat(start, end - start, format)
                else:
                    self.setFormat(result.start(),
                                   result.end() - result.start(),
                                   format)
        
        self.setCurrentBlockState(0)
        if self.previousBlockState() == 1:
            return
        
        for form, open, close in self._multiline:
            open = QtCore.QRegExp(open)
            close = QtCore.QRegExp(close)
            
            start = open.indexIn(text)
            processed = False
            
            while start >= 0:
                processed = True
                end = close.indexIn(text, start)

                if end == -1:
                    self.setCurrentBlockState(1)
                    length = len(text) - start
                else:
                    length = end - start + close.matchedLength()

                self.setFormat(start, length, form)
                start = open.indexIn(text, start + length)
            
            if processed:
                break
400761
def wrap_toks(self, block, lineno, indent):
        """"""
        tokens = tokenize.generate_tokens(self.gen_lines(block, indent).next)
        for type, value, (line0, col0), (line1, col1), line_text in tokens:
            line0 += lineno - 1
            line1 += lineno - 1
            # Don't bother updating the columns; this is too complicated
            # since line_text would also have to be updated and it would
            # still break for tokens spanning lines.  Let the user guess
            # that the column numbers for doctests are relative to the
            # end of the prompt string (PS1 or PS2).
            yield type, value, (line0, col0), (line1, col1), line_text
789739
private Context translateStatementBlock(WyilFile.Stmt.Block block, Context context) {
		for (int i = 0; i != block.size(); ++i) {
			WyilFile.Stmt stmt = block.get(i);
			context = translateStatement(stmt, context);
			if (stmt instanceof WyilFile.Stmt.Return) {
				return null;
			}
		}
		return context;
	}
378995
def generate_code_cover(self):
        

        lst = [ ]
        for irsb_addr in self.cfg.nodes():
            if irsb_addr not in self._block_size:
                continue
            irsb_size = self._block_size[irsb_addr]
            lst.append((irsb_addr, irsb_size))

        lst = sorted(lst, key=lambda x: x[0])

        return lst
702734
def remove_codeblock_syntax_sentinals(code_text):
    
    """
    flags = re.MULTILINE | re.DOTALL
    code_text_ = code_text
    code_text_ = re.sub(r'^ *# *REM [^\n]*$\n?', '', code_text_, flags=flags)
    code_text_ = re.sub(r'^ *# STARTBLOCK *$\n', '', code_text_, flags=flags)
    code_text_ = re.sub(r'^ *# ENDBLOCK *$\n?', '', code_text_, flags=flags)
    code_text_ = code_text_.rstrip()
    return code_text_
144643
def _from_docstring_rst(doc):
    

    def format_fn(line, status):
        """ format function """

        if re_from_data.match(line):
            line = re_from_data.sub(r"**\1** ", line)
            status["add_line"] = True
        line = re_from_defaults.sub(r"*\1*", line)
        if status["listing"]:
            # parameters
            if re_from_param.match(line):
                m = re_from_param.match(line)
                line = "  - ``{}`` {}".format(m.group(1), m.group(3))
            # status items
            elif re_from_status.match(line):
                m = re_from_status.match(line)
                line = "  - ``{}`` {}".format(m.group(1), m.group(3))
            # bullets
            elif re_from_item.match(line):
                line = re_from_item.sub(r"  -", line)
            # is continuation line
            else:
                line = " " * 4 + line.lstrip()
        # in .rst format code samples use double backticks vs single ones for
        # .md This converts them.
        line = re_lone_backtick.sub("``", line)
        return line

    return _reformat_docstring(doc, format_fn, code_newline="\n")
1318733
def setup_regex(self):
        """"""
        #Regex for grabbing out valid XML tags that represent known docstrings that we can work with.
        self.keywords = [ "summary", "usage", "errors", "member", "group", "local", 
                          "comments", "parameter" ]
        #Regex for extracting the contents of docstrings minus the !! and any leading spaces.
        self._RX_DOCS = "^\s*!!(?P<docstring>.+?)$"
        self.RE_DOCS = re.compile(self._RX_DOCS, re.M)
        #Regex for handling cross references in the documentation
        self._RX_REFS = r"@CREF\[(?P<reference>[^\]]+)\]"
        self.RE_REFS = re.compile(self._RX_REFS)
        #Regex to match first lines of declarations for code elements that can be
        #decorated by docstrings.
        self._RX_DECOR = (r"((?P<type>character|real|type|logical|integer|complex)?"
                          r"(?P<kind>\([a-z0-9_]+\))?)?(,?(?P<modifiers>[^\n]+?))?"
                          r"\s*(?P<codetype>subroutine|function|type|module|interface)\s+(?P<name>[^(]+)")
        self.RE_DECOR = re.compile(self._RX_DECOR, re.I)
        #Regex for getting the docstrings decorating one or more modules in a code file,
        #Since they aren't contained inside any other code element, we can't just use
        #the normal docblocks routines.
        self._RX_MODDOCS = (r"^(?P<docstring>\s*!!.+?)\n\s*module\s+(?P<name>[A-Za-z0-9_]+)"
                            ".+?end\s+module(\s+(?P=name))?")
        self.RE_MODDOCS = re.compile(self._RX_MODDOCS, re.DOTALL | re.I)
404668
function rstr(s, utf8) {
        s = (utf8) ? utf8Encode(s) : s;
        return binb2rstr(binb(rstr2binb(s), s.length * 8));
      }
552259
def build_code(self, lang, body):
        """"""
        self.out.append("```" + lang)
        self.build_markdown(lang, body)
        self.out.append("```")