Convert markdown to restructured text
346368
def markdown_2_rst(lines):
    
    out = []
    code = False
    for line in lines:
        # code blocks
        if line.strip() == "```":
            code = not code
            space = " " * (len(line.rstrip()) - 3)
            if code:
                out.append("\n\n%s.. code-block:: none\n\n" % space)
            else:
                out.append("\n")
        else:
            if code and line.strip():
                line = "    " + line
            else:
                # escape any backslashes
                line = line.replace("\\", "\\\\")
            out.append(line)
    return out
294184
function mdToHtml(input) {
    let rule = myna.allRules['markdown.document'];
    let ast = myna.parse(rule, input);
    return mdAstToHtml(ast, []).join("");
}
591163
def to_markdown(self):
        
        if self.type == "text":
            return self.text
        elif self.type == "url" or self.type == "image":
            return "[" + self.text + "](" + self.attributes["ref"] + ")"
        elif self.type == "title":
            return "#" * int(self.attributes["size"]) + " " + self.text

        return None
1331284
def markdownify_operative_config_str(string):
  """"""

  # TODO(b/37527917): Total hack below. Implement more principled formatting.
  def process(line):
    """Convert a single line to markdown format."""
    if not line.startswith('#'):
      return '    ' + line

    line = line[2:]
    if line.startswith('===='):
      return ''
    if line.startswith('None'):
      return '    # None.'
    if line.endswith(':'):
      return '#### ' + line
    return line

  output_lines = []
  for line in string.splitlines():
    procd_line = process(line)
    if procd_line is not None:
      output_lines.append(procd_line)

  return '\n'.join(output_lines)
841380
def restructuredtext(value, settings=RESTRUCTUREDTEXT_SETTINGS):
    
    try:
        from docutils.core import publish_parts
    except ImportError:
        warnings.warn("The Python docutils library isn't installed.",
                      RuntimeWarning)
        return value

    parts = publish_parts(source=force_bytes(value),
                          writer_name='html4css1',
                          settings_overrides=settings)
    return force_text(parts['fragment'])
66497
def convert_content(self) -> dict:
        """"""
        source_content = self.load_content()

        converted = {}

        md_extenstions = [
            'full_yaml_metadata',
            'markdown.extensions.fenced_code',
        ]
        md = markdown.Markdown(md_extenstions)
        content = md.convert(source_content)
        meta = md.Meta

        if meta:
            converted.update(meta)

        if content:
            converted['content'] = content.strip()

        return converted
177218
def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
        """"""
        escape = escape or self.escape
        results = []
        here = 0

        # XXX Note that this regular expression does not allow for the
        # hyperlinking of arbitrary strings being used as method
        # names. Only methods with names consisting of word characters
        # and '.'s are hyperlinked.
        pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
                                r'RFC[- ]?(\d+)|'
                                r'PEP[- ]?(\d+)|'
                                r'(self\.)?((?:\w|\.)+))\b')
        while 1:
            match = pattern.search(text, here)
            if not match: break
            start, end = match.span()
            results.append(escape(text[here:start]))

            all, scheme, rfc, pep, selfdot, name = match.groups()
            if scheme:
                url = escape(all).replace('"', '&quot;')
                results.append('<a href="%s">%s</a>' % (url, url))
            elif rfc:
                url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
                results.append('<a href="%s">%s</a>' % (url, escape(all)))
            elif pep:
                url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
                results.append('<a href="%s">%s</a>' % (url, escape(all)))
            elif text[end:end+1] == '(':
                results.append(self.namelink(name, methods, funcs, classes))
            elif selfdot:
                results.append('self.<strong>%s</strong>' % name)
            else:
                results.append(self.namelink(name, classes))
            here = end
        results.append(escape(text[here:]))
        return ''.join(results)
642692
def _filter(self, text):
        """"""

        self.markdown.reset()
        return self.markdown.convert(text)
305331
def _repr_html_(self, **kwargs):
        """"""
        from jinja2 import Template
        from markdown import markdown as convert_markdown

        extensions = [
            'markdown.extensions.extra',
            'markdown.extensions.admonition'
        ]

        return convert_markdown(self.markdown, extensions)
90946
def markdown(text)
      renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: false, with_toc_data: false)
      options = {
        autolink: true,
        no_intra_emphasis: true,
        fenced_code_blocks: true,
        lax_html_blocks: true,
        tables: true,
        strikethrough: true,
        superscript: true,
        xhtml: true
      }
      Redcarpet::Markdown.new(renderer, options).render(text).html_safe
    end
251491
public function markdownToText(string $markdown): string
    {
        if (empty($markdown)) {
            return '';
        }

        $pattern = array(
            '/(\.|)#/',
            '/(\.|)\*/',
            '/(\.|)~/'
        );

        return preg_replace($pattern, '', $markdown);
    }
918189
def parse(self, text):
        
        if self.format == 'markdown':
            try:
                import markdown
            except ImportError:
                raise RuntimeError(u"Looks like markdown is not installed")

            if text.startswith(u'\ufeff'):  # check for unicode BOM
                text = text[1:]

            return markdown.markdown(text, extensions=self.md_extensions)
        elif self.format == 'restructuredtext':
            try:
                from landslide.rst import html_body
            except ImportError:
                raise RuntimeError(u"Looks like docutils are not installed")

            html = html_body(text, input_encoding=self.encoding)

            # RST generates pretty much markup to be removed in our case
            for (pattern, replacement, mode) in self.RST_REPLACEMENTS:
                html = re.sub(re.compile(pattern, mode), replacement, html, 0)

            return html.strip()
        elif self.format == 'textile':
            try:
                import textile
            except ImportError:
                raise RuntimeError(u"Looks like textile is not installed")

            text = text.replace('\n---\n', '\n<hr />\n')

            return textile.textile(text, encoding=self.encoding)
        else:
            raise NotImplementedError(u"Unsupported format %s, cannot parse"
                                      % self.format)
1107111
def markdown(iterable, renderer=HTMLRenderer):
    
    with renderer() as renderer:
        return renderer.render(Document(iterable))
62153
function stripMeta (markdownContent) {
  switch (true) {
    case _metaRegex.test(markdownContent):
      return markdownContent.replace(_metaRegex, '').trim();
    case _metaRegexYaml.test(markdownContent):
      return markdownContent.replace(_metaRegexYaml, '').trim();
    default:
      return markdownContent.trim();
  }
}
781423
def markdown_table(data, headers):
    

    maxx = [max([len(x) for x in column]) for column in zip(*data)]
    maxx = [max(ll) for ll in zip(maxx, [len(x) for x in headers])]
    mask = " | ".join(["%-{0:d}s".format(n) for n in maxx])

    ret = [mask % headers]

    ret.append(" | ".join(["-"*n for n in maxx]))
    for line in data:
        ret.append(mask % line)
    return ret
601055
def _from_docstring_md(doc):
    

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

        def fix_tags(line):
            # In markdown we need to escape < > and & for display
            # but we don't want to do this is the value is quoted
            # by backticks ``

            def fn(match):
                # swap matched chars
                found = match.group(1)
                if found == "<":
                    return "&lt;"
                if found == ">":
                    return "&gt;"
                if found == "&":
                    return "&amp;"
                return match.group(0)

            return re_from_tag.sub(fn, line)

        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), fix_tags(m.group(3)))
            # status items
            elif re_from_status.match(line):
                m = re_from_status.match(line)
                line = "  - `{}` {}".format(m.group(1), fix_tags(m.group(3)))
            # bullets
            elif re_from_item.match(line):
                line = re_from_item.sub(r"  -", fix_tags(line))
            # is continuation line
            else:
                line = fix_tags(line)
                line = " " * 4 + line.lstrip()
        else:
            line = fix_tags(line)
        return line

    return _reformat_docstring(doc, format_fn, code_newline="\n")
505881
def restructuredtext(text, **kwargs):
    
    from docutils import core
    parts = core.publish_parts(source=text,
                               writer_name='html4css1',
                               **kwargs)
    return parts['fragment']