Convert Markdown text to HTML
480396
def to_html(text, config, search_path):
    
    processor = misaka.Markdown(HtmlRenderer(config, search_path),
                                extensions=ENABLED_EXTENSIONS)

    text = processor(text)
    if not config.get('no_smartquotes'):
        text = misaka.smartypants(text)

    return flask.Markup(text)
570926
def render_markdown(post):
        
        from engineer.conf import settings

        # A hack to guarantee the YAML output is in a sensible order.
        # The order, assuming all metadata should be written, should be:
        # title
        # status
        # timestamp
        # link
        # via
        # via-link
        # slug
        # tags
        # updated
        # template
        # content-template
        # url
        d = [
            ('status', post.status.name),
            ('link', post.link),
            ('via', post.via),
            ('via-link', post.via_link),
            ('tags', post.tags),
            ('updated', post.updated_local.strftime(settings.TIME_FORMAT) if post.updated is not None else None),
            ('template', post.template if post.template != 'theme/post_detail.html' else None),
            ('content-template',
             post.content_template if post.content_template != 'theme/_content_default.html' else None),
        ]

        # The complete set of metadata that should be written is the union of the FINALIZE_METADATA.config setting and
        # the set of metadata that was in the file originally.
        finalization_config = FinalizationPlugin.get_settings()['config']
        metadata_to_finalize = set([m for m, s in finalization_config.iteritems() if post.status in s])
        metadata_to_finalize.update(post.metadata_original)

        if 'title' in metadata_to_finalize:
            # insert at the top of the list
            d.insert(0, ('title', post.title))
        if 'slug' in metadata_to_finalize:
            # insert right before tags
            d.insert(d.index(('tags', post.tags)), ('slug', post.slug))
        if 'timestamp' in metadata_to_finalize:
            # insert right after status
            d.insert(d.index(('status', post.status.name)), ('timestamp',
                                                             post.timestamp_local.strftime(settings.TIME_FORMAT)))
        if 'url' in metadata_to_finalize:
            # insert at end of list
            d.append(('url', post.url))

        metadata = ''
        for k, v in d:
            if v is not None and len(v) > 0:
                metadata += yaml.safe_dump(dict([(k, v)]), default_flow_style=False)

        # handle custom metadata
        if len(post.custom_properties):
            metadata += '\n'
            metadata += yaml.safe_dump(dict(post.custom_properties), default_flow_style=False)
        return settings.JINJA_ENV.get_template(post.markdown_template_path).render(metadata=metadata,
                                                                                   content=post.content_finalized,
                                                                                   post=post)
1277049
function _renderMarkdown( htmlDoc ) {
    const replacements = {};

    // First turn all outputs into text so *<span class="or-output></span>* can be detected
    htmlDoc.find( '/root/form//span[contains(@class, "or-output")]' ).forEach( ( el, index ) => {
        const key = `---output-${index}`;
        const textNode = el.childNodes()[ 0 ].clone();
        replacements[ key ] = el.toString();
        textNode.text( key );
        el.replace( textNode );
        // Note that we end up in a situation where we likely have sibling text nodes...
    } );

    // Now render markdown
    htmlDoc.find( '/root/form//span[contains(@class, "question-label") or contains(@class, "or-hint")]' ).forEach( ( el, index ) => {
        let key;
        /**
         * Using text() is done because:
         * a) We are certain that these <span>s do not contain other elements, other than formatting/markdown <span>s.
         * b) This avoids the need to merge any sibling text nodes that could have been created in the previous step.
         *
         * Note that text() will convert &gt; to >
         */
        const original = el.text().replace( '<', '&lt;' ).replace( '>', '&gt;' );
        const rendered = markdown.toHtml( original );
        if ( original !== rendered ) {
            key = `$$$${index}`;
            replacements[ key ] = rendered;
            el.text( key );
        }
    } );

    // TODO: does this result in self-closing tags?
    let htmlStr = _docToString( htmlDoc );

    // Now replace the placeholders with the rendered HTML
    // in reverse order so outputs are done last
    Object.keys( replacements ).reverse().forEach( key => {
        const replacement = replacements[ key ];
        if ( replacement ) {
            htmlStr = htmlStr.replace( key, replacement );
        }
    } );

    return htmlStr;
}
64827
def markdown_to_text(body):
    
    # Turn our input into HTML
    md = markdown.markdown(body, extensions=[
        'markdown.extensions.extra'
    ])

    # Safely parse HTML so that we don't have to parse it ourselves
    soup = BeautifulSoup(md, 'html.parser')

    # Return just the text of the parsed HTML
    return soup.get_text()
144338
def html(self, text=TEXT):
        
        self.logger.debug("Generating the HTML report{}..."
                          .format(["", " (text only)"][text]))
        html = []
        for piece in self._pieces:
            if isinstance(piece, string_types):
                html.append(markdown2.markdown(piece, extras=["tables"]))
            elif isinstance(piece, Element):
                html.append(piece.html())
        return "\n\n".join(html)
210157
public String markdownToHtml(String markdownString) {
		MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
		params.putSingle("md", markdownString);
		return getEntity(invokeGet("utils/md2html", params), String.class);
	}
1349743
public String markdownToHtml(char[] markdownSource, LinkRenderer linkRenderer) {
	    return markdownToHtml(markdownSource, linkRenderer, Collections.<String, VerbatimSerializer>emptyMap());
    }
1028852
def markdown(text)
      erbified = ERB.new(text.html_safe).result(binding)
      red = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true)
      red.render(erbified).html_safe
    end
922232
def parse_html(self, text):
        
        bs = BeautifulSoup(text, "html5lib")
        file_reg = re.compile(MARKDOWN_IMAGE_REGEX, flags=re.IGNORECASE)
        tags = bs.findAll('img')

        for tag in tags:
            # Look for src attribute, remove formatting if added to image
            src_text = tag.get("src") or ""
            formatted_src_match = file_reg.search(src_text)
            src_text = formatted_src_match.group(2) if formatted_src_match else src_text

            alt_text = tag.get("alt") or ""
            tag.replaceWith("![{alt}]({src})".format(alt=alt_text, src=src_text))
        return html.unescape(bs.find('body').renderContents().decode('utf-8'))
1308422
def markdown_to_notebook(infile, outfile):
    """"""

    # Read infile into a string
    with open(infile, 'r') as fin:
        str = fin.read()
    # Enclose the markdown within triple quotes and convert from
    # python to notebook
    str = '"""' + str + '"""'
    nb = py2jn.py_string_to_notebook(str)
    py2jn.tools.write_notebook(nb, outfile, nbver=4)
759970
def MarkDown(node):
    
    cur = node.first_child

    # Go into each child, in turn
    output = []
    while cur is not None:
        t = cur.t
        if t == 'paragraph':
            output.append(paragraph(cur))
        elif t == 'text':
            output.append(text(cur))
        elif t == 'softbreak':
            output.append(softbreak(cur))
        elif t == 'linebreak':
            output.append(hardbreak(cur))
        elif t == 'link':
            output.append(reference(cur))
        elif t == 'heading':
            output.append(title(cur))
        elif t == 'emph':
            output.append(emphasis(cur))
        elif t == 'strong':
            output.append(strong(cur))
        elif t == 'code':
            output.append(literal(cur))
        elif t == 'code_block':
            output.append(literal_block(cur))
        elif t == 'html_inline' or t == 'html_block':
            output.append(raw(cur))
        elif t == 'block_quote':
            output.append(block_quote(cur))
        elif t == 'thematic_break':
            output.append(transition(cur))
        elif t == 'image':
            output.append(image(cur))
        elif t == 'list':
            output.append(listNode(cur))
        elif t == 'item':
            output.append(listItem(cur))
        elif t == 'MDsection':
            output.append(section(cur))
        else:
            print('Received unhandled type: {}. Full print of node:'.format(t))
            cur.pretty()

        cur = cur.nxt

    return output
435864
def _convert_markup_basic(self, soup):
        
        # Inject meta charset tag
        meta = soup.new_tag('meta', charset='UTF-8')
        soup.insert(0, meta)

        # 1. Inject basic CSS style
        css = "".join([
            INSTRUCTIONS_HTML_INJECTION_PRE,
            self._mathjax_cdn_url,
            INSTRUCTIONS_HTML_INJECTION_AFTER])
        css_soup = BeautifulSoup(css)
        soup.append(css_soup)

        # 2. Replace <text> with <p>
        while soup.find('text'):
            soup.find('text').name = 'p'

        # 3. Replace <heading level="1"> with <h1>
        while soup.find('heading'):
            heading = soup.find('heading')
            heading.name = 'h%s' % heading.attrs.get('level', '1')

        # 4. Replace <code> with <pre>
        while soup.find('code'):
            soup.find('code').name = 'pre'

        # 5. Replace <list> with <ol> or <ul>
        while soup.find('list'):
            list_ = soup.find('list')
            type_ = list_.attrs.get('bullettype', 'numbers')
            list_.name = 'ol' if type_ == 'numbers' else 'ul'
900929
def process_markdown_inside_elements(doc)
      elts = []
      @fragment.each_element('//*[@markdown]') do |e|
        elts << e
      end

      d = @fragment.children.first
      if d && HTML_INLINE_ELEMS.include?(first_node_name)
        elts << d unless d.attributes['markdown']
        elts += span_descendents(d)
      end

      # find span elements or elements with 'markdown' attribute
      elts.each do |e|
        # should we parse block-level or span-level?
        how = e.attributes['markdown']
        e.attributes.delete('markdown')

        next if "0" == how # user requests no markdown parsing inside
        parse_blocks = (how == 'block') || BLOCK_TAGS.include?(e.name)

        # Select all text children of e
        e.texts.each do |original_text|
          s = MaRuKu::Out::HTML.escapeHTML(original_text.value)
          unless s.strip.empty?
            # TODO extract common functionality
            parsed = parse_blocks ? doc.parse_text_as_markdown(s) : doc.parse_span(s)
            # restore leading and trailing spaces
            padding = /\A(\s*).*?(\s*)\z/.match(s)
            parsed = [padding[1]] + parsed + [padding[2]] if padding

            el = doc.md_el(:dummy, parsed)

            new_html = "<dummy>"
            el.children_to_html.each do |x|
              new_html << x.to_s
            end
            new_html << "</dummy>"

            newdoc = REXML::Document.new(new_html).root

            p = original_text.parent
            newdoc.children.each do |c|
              p.insert_before(original_text, c)
            end

            p.delete(original_text)
          end
        end
      end
    end
600437
def html_from_markdown(markdown):
    

    if login:
        r = requests.get(gh_url+"/rate_limit", auth=login.auth())
        if r.status_code >= 400:
            if r.status_code != 401:
                err = RequestError('Bad HTTP Status Code: %s' % r.status_code)
                raise err
            if verbose:
                sys.stderr.write('Unauthorized. Proceeding without login...\n')
            login.devalue()

    headers = {'content-type': 'text/plain', 'charset': 'utf-8'}

    r = requests.post(gh_url + "/markdown/raw", data=markdown.encode('utf-8'),
                      auth=login.auth(), headers=headers)
    if r.status_code >= 400 and r.status_code != 403:
            err = RequestError('Bad HTTP Status Code: %s' % r.status_code)
            raise err

    if verbose:
        sys.stderr.write("%s requests remaining, resets in %d minutes\n"
                         % rate_limit_info())
    return r.text
766508
def docstring_to_markdown(docstring):
    
    new_docstring_lst = []

    for idx, line in enumerate(docstring.split('\n')):
        line = line.strip()
        if set(line) in ({'-'}, {'='}):
            new_docstring_lst[idx-1] = '**%s**' % new_docstring_lst[idx-1]
        elif line.startswith('>>>'):
            line = '    %s' % line
        new_docstring_lst.append(line)

    for idx, line in enumerate(new_docstring_lst[1:]):
        if line:
            if line.startswith('Description : '):
                new_docstring_lst[idx+1] = (new_docstring_lst[idx+1]
                                            .replace('Description : ', ''))
            elif ' : ' in line:
                line = line.replace(' : ', '` : ')
                new_docstring_lst[idx+1] = '\n- `%s\n' % line
            elif '**' in new_docstring_lst[idx-1] and '**' not in line:
                new_docstring_lst[idx+1] = '\n%s' % line.lstrip()
            elif '**' not in line:
                new_docstring_lst[idx+1] = '    %s' % line.lstrip()

    clean_lst = []
    for line in new_docstring_lst:
        if set(line.strip()) not in ({'-'}, {'='}):
            clean_lst.append(line)
    return clean_lst
1293094
function markdown(preset, options) {
  var stream = through(transform, flush)
  var parser = new Remarkable(preset, options)
  var buffer = []

  function transform(chunk, encoding, done) {
    buffer.push(chunk)
    done()
  }

  function flush(done) {
    this.push(parser.render(buffer.join('\n')))
    done()
  }

  return stream
}
1312741
def fromMarkdown(md, *args, **kwargs):
        
        return TOC.fromHTML(markdown(md, *args, **kwargs))