Python mistune.markdown() Examples

The following are 18 code examples of mistune.markdown(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mistune , or try the search function .
Example #1
Source File: test_ast.py    From mistune with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_fixtures(cls, case_file):
        cases = fixtures.load_json(case_file)

        def attach_case(n, data):

            def method(self):
                tokens = mistune.markdown(data['text'], renderer='ast')
                self.assertEqual(tokens, data['tokens'])

            name = 'test_{}'.format(n)
            method.__name__ = name
            method.__doc__ = 'Run fixture {} - {}'.format(case_file, n)
            setattr(cls, name, method)

        for n, data in enumerate(cases):
            attach_case(n, data) 
Example #2
Source File: models.py    From niji with MIT License 6 votes vote down vote up
def render_content(content_raw, sender):
    """
    :param content_raw: Raw content
    :param sender: user as username
    :return: (rendered_content, mentioned_user_list)
    """
    content_rendered = mistune.markdown(content_raw)
    mentioned = list(set(re.findall(MENTION_REGEX, content_raw)))
    mentioned = [x for x in mentioned if x != sender]
    mentioned_users = get_user_model().objects.filter(username__in=mentioned)
    for user in mentioned_users:
        content_rendered = re.sub(
            r'(?P<username>@%s)(?P<whitespace>\s|<\/p>)' % user.username,
            partial(_replace_username, reverse('niji:user_info', kwargs={"pk": user.pk})),
            content_rendered,
            re.M
        )
    return content_rendered, mentioned_users 
Example #3
Source File: search_opportunities.py    From Python-Automation-Cookbook with MIT License 6 votes vote down vote up
def compose_email_body(articles, keywords, feed_list):
    '''
    From the list of articles, keywords and feeds, fill the email template

    Set the list in the adequate format for the template
    '''
    # Compose the list of articles
    ARTICLE_TEMPLATE = '* **{title}** {summary}: {link}'
    article_list = [ARTICLE_TEMPLATE.format(title=title, summary=summary,
                                            link=link)
                    for title, summary, link in articles]

    data = {
        'article_list': '\n'.join(article_list),
        'keywords': ', '.join(keywords),
        'feed_list': ', '.join(feed_list),
    }
    text = EMAIL_TEMPLATE.format(**data)

    html_content = mistune.markdown(text)
    html = jinja2.Template(EMAIL_STYLING).render(content=html_content)

    return text, html 
Example #4
Source File: convert.py    From markdown-to-confluence with Apache License 2.0 6 votes vote down vote up
def parse(post_path):
    """Parses the metadata and content from the provided post.

    Arguments:
        post_path {str} -- The absolute path to the Markdown post
    """
    raw_yaml = ''
    markdown = ''
    in_yaml = True
    with open(post_path, 'r') as post:
        for line in post.readlines():
            # Check if this is the ending tag
            if line.strip() == YAML_BOUNDARY:
                if in_yaml and raw_yaml:
                    in_yaml = False
                    continue
            if in_yaml:
                raw_yaml += line
            else:
                markdown += line
    front_matter = yaml.load(raw_yaml, Loader=yaml.SafeLoader)
    markdown = markdown.strip()
    return front_matter, markdown 
Example #5
Source File: search_keywords.py    From Python-Automation-Cookbook with MIT License 6 votes vote down vote up
def compose_email_body(articles, keywords, feed_list):
    '''
    From the list of articles, keywords and feeds, fill the email template

    Set the list in the adequate format for the template
    '''
    # Compose the list of articles
    ARTICLE_TEMPLATE = '* **{title}** {summary}: {link}'
    article_list = [ARTICLE_TEMPLATE.format(title=title, summary=summary,
                                            link=link)
                    for title, summary, link in articles]

    data = {
        'article_list': '\n'.join(article_list),
        'keywords': ', '.join(keywords),
        'feed_list': ', '.join(feed_list),
    }
    text = EMAIL_TEMPLATE.format(**data)

    html_content = mistune.markdown(text)
    html = jinja2.Template(EMAIL_STYLING).render(content=html_content)

    return text, html 
Example #6
Source File: main.py    From skydoc with Apache License 2.0 6 votes vote down vote up
def _create_jinja_environment(runfiles, site_root, link_ext):
  def _Load(path):
    loc = runfiles.Rlocation(posixpath.join(WORKSPACE_DIR, TEMPLATE_PATH, path))
    if loc:
      with open(loc, "rb") as f:
        return f.read().decode("utf-8")
    return None

  env = jinja2.Environment(
      loader=jinja2.FunctionLoader(_Load),
      keep_trailing_newline=True,
      line_statement_prefix='%')
  env.filters['markdown'] = lambda text: jinja2.Markup(mistune.markdown(text))
  env.filters['doc_link'] = (
      lambda fname: site_root + '/' + fname + '.' + link_ext)
  env.filters['link'] = lambda fname: site_root + '/' + fname
  return env


# TODO(dzc): Remove this workaround once we switch to a self-contained Python
# binary format such as PEX. 
Example #7
Source File: __init__.py    From adr-viewer with MIT License 5 votes vote down vote up
def parse_adr_to_config(path):
    adr_as_html = mistune.markdown(open(path).read())

    soup = BeautifulSoup(adr_as_html, features='html.parser')

    status = list(extract_statuses_from_adr(soup))

    if any([line.startswith("Amended by") for line in status]):
        status = 'amended'
    elif any([line.startswith("Accepted") for line in status]):
        status = 'accepted'
    elif any([line.startswith("Superceded by") for line in status]):
        status = 'superceded'
    elif any([line.startswith("Pending") for line in status]):
        status = 'pending'
    else:
        status = 'unknown'

    header = soup.find('h1')

    if header:
          return {
                'status': status,
                'body': adr_as_html,
                'title': header.text
            }
    else:
        return None 
Example #8
Source File: base.py    From flasgger with MIT License 5 votes vote down vote up
def MK_SANITIZER(text):
    return Markup(markdown(text)) if text else text 
Example #9
Source File: models.py    From djanblog with MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):
        self.content = mistune.markdown(self.content_raw)
        super(Post, self).save(*args, **kwargs) 
Example #10
Source File: main.py    From skydoc with Apache License 2.0 5 votes vote down vote up
def _write_ruleset(self, output_dir, ruleset, nav):
    # Load template and render markdown.
    template = self.__env.get_template('html.jinja')
    out = template.render(title=ruleset.title, ruleset=ruleset, nav=nav)

    # Write output to file. Output files are created in a directory structure
    # that matches that of the input file.
    output_path = ruleset.output_file + '.html'
    output_file = "%s/%s" % (output_dir, output_path)
    file_dirname = os.path.dirname(output_file)
    if not os.path.exists(file_dirname):
      os.makedirs(file_dirname)
    with open(output_file, "w") as f:
      f.write(out)
    return (output_file, output_path) 
Example #11
Source File: main.py    From skydoc with Apache License 2.0 5 votes vote down vote up
def _write_ruleset(self, output_dir, ruleset):
    # Load template and render Markdown.
    template = self.__env.get_template('markdown.jinja')
    out = template.render(ruleset=ruleset)

    # Write output to file. Output files are created in a directory structure
    # that matches that of the input file.
    output_path = ruleset.output_file + '.md'
    output_file = "%s/%s" % (output_dir, output_path)
    file_dirname = os.path.dirname(output_file)
    if not os.path.exists(file_dirname):
      os.makedirs(file_dirname)
    with open(output_file, "w") as f:
      f.write(out)
    return (output_file, output_path) 
Example #12
Source File: core.py    From ttbp with MIT License 5 votes vote down vote up
def write_entry(filename):
    '''
    entry text generator

    * dump given file into entry format by parsing file as markdown
    * return as list of strings
    '''

    date = util.parse_date(filename)

    entry = [
        "\t\t<p><a name=\""+date[0]+date[1]+date[2]+"\"></a><br /><br /></p>\n",
        "\t\t<div class=\"entry\">\n",
        "\t\t\t<h5><a href=\"#"+date[0]+date[1]+date[2]+"\">"+date[2]+"</a> "+chatter.month(date[1])+" "+date[0]+"</h5>\n"
        #"\t\t\t<P>"
    ]

    raw = []
    rawfile = open(os.path.join(config.MAIN_FEELS, filename), "r")

    for line in rawfile:
        raw.append(line)
    rawfile.close()

    entry.append("\t\t\t"+mistune.markdown("".join(raw), escape=False, hard_wrap=False))

    #for line in raw:
        #entry.append(line+"\t\t\t")
        #if line == "\n":
        #    entry.append("</p>\n\t\t\t<p>")

    #entry.append("</p>\n")
    entry.append("\t\t\t<p class=\"permalink\"><a href=\""+"".join(date)+".html\">permalink</a></p>\n")
    entry.append("\n\t\t</div>\n")

    return entry 
Example #13
Source File: drymail.py    From drymail with MIT License 5 votes vote down vote up
def prepare(self):
        """
        Prepare the `self.message` object.
        """
        if self.prepared_message:
            self.message = message_from_bytes(self.prepared_message)
            self.prepared = True
            return

        self.text = self.text or BeautifulSoup(self.html, 'html.parser').get_text(strip=True)
        self.html = self.html or mistune.markdown(self.text)

        self.message['Sender'] = stringify_address(self.sender)
        self.message['From'] = stringify_addresses(self.authors) if self.authors else stringify_address(self.sender)
        self.message['To'] = stringify_addresses(self.receivers)
        self.message['Subject'] = self.subject
        if self.cc:
            self.message['CC'] = stringify_addresses(self.cc)
        if self.bcc:
            self.message['BCC'] = stringify_addresses(self.bcc)
        if self.reply_to:
            self.message['Reply-To'] = stringify_addresses(self.reply_to)
        if self.headers:
            for key, value in self.headers.items():
                self.message[key] = value

        body = MIMEMultipart('alternative')
        plaintext_part = MIMEText(self.text, 'plain')
        html_part = MIMEText(self.html, 'html')
        body.attach(plaintext_part)
        body.attach(html_part)
        self.message.attach(body)
        self.prepared = True 
Example #14
Source File: convert.py    From markdown-to-confluence with Apache License 2.0 5 votes vote down vote up
def convtoconf(markdown, front_matter={}):
    if front_matter is None:
        front_matter = {}

    author_keys = front_matter.get('author_keys', [])
    renderer = ConfluenceRenderer(authors=author_keys)
    content_html = mistune.markdown(markdown, renderer=renderer)
    page_html = renderer.layout(content_html)

    return page_html, renderer.attachments 
Example #15
Source File: models.py    From niji with MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):
        new_hash = xxhash.xxh64(self.content_raw).hexdigest()
        if new_hash != self.raw_content_hash or (not self.pk):
            self.content_rendered = mistune.markdown(self.content_raw)
        super(Appendix, self).save(*args, **kwargs)
        self.raw_content_hash = new_hash 
Example #16
Source File: models.py    From django_reddit with Apache License 2.0 5 votes vote down vote up
def create(cls, author, raw_comment, parent):
        """
        Create a new comment instance. If the parent is submisison
        update comment_count field and save it.
        If parent is comment post it as child comment
        :param author: RedditUser instance
        :type author: RedditUser
        :param raw_comment: Raw comment text
        :type raw_comment: str
        :param parent: Comment or Submission that this comment is child of
        :type parent: Comment | Submission
        :return: New Comment instance
        :rtype: Comment
        """

        html_comment = mistune.markdown(raw_comment)
        # todo: any exceptions possible?
        comment = cls(author=author,
                      author_name=author.user.username,
                      raw_comment=raw_comment,
                      html_comment=html_comment)

        if isinstance(parent, Submission):
            submission = parent
            comment.submission = submission
        elif isinstance(parent, Comment):
            submission = parent.submission
            comment.submission = submission
            comment.parent = parent
        else:
            return
        submission.comment_count += 1
        submission.save()

        return comment 
Example #17
Source File: models.py    From django_reddit with Apache License 2.0 5 votes vote down vote up
def generate_html(self):
        if self.text:
            html = mistune.markdown(self.text)
            self.text_html = html 
Example #18
Source File: models.py    From django_reddit with Apache License 2.0 5 votes vote down vote up
def update_profile_data(self):
        self.about_html = mistune.markdown(self.about_text)
        if self.display_picture:
            self.gravatar_hash = md5(self.email.lower().encode('utf-8')).hexdigest()