Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Emoji Grammar #12

Open
sh4nks opened this issue Feb 9, 2017 · 0 comments
Open

Emoji Grammar #12

sh4nks opened this issue Feb 9, 2017 · 0 comments

Comments

@sh4nks
Copy link

sh4nks commented Feb 9, 2017

Hey,

I have been trying to add a 'emoji' grammar to mistune but unfortunately I have been not so successful and have already spent more time on it than I'd like to admit. I am not that experienced with regex'es so there might be something wrong with mine but I just can't figure out what. The problem is, that mistune will only match the first pattern (like, literally the first in a block) and every emoji pattern after the first match is handled as a normal text. This is the code I've come up with:

import re
import mistune

class EmojiRenderer(object):
    def emoji(self, text):
        return "<emoji>%s</emoji>" % text


class EmojiInlineLexer(mistune.InlineLexer):
    def __init__(self, **kwargs):
        super(EmojiInlineLexer, self).__init__(**kwargs)
        self.default_rules.insert(0, "emoji")
        self.rules.emoji = re.compile(r'^:([a-zA-Z0-9\+\-_]+):', re.I)

    def output_emoji(self, m):
        text = self.output(m.group(1))
        return self.renderer.emoji(text)


class MarkdownRenderer(mistune.Renderer, EmojiRenderer):
    def __init__(self, **kwargs):
        super(MarkdownRenderer, self).__init__(**kwargs)


renderer = MarkdownRenderer()
inline = EmojiInlineLexer(renderer=renderer)
markdown = mistune.Markdown(renderer=renderer, inline=inline)
demo_text = """
:thumbs_up: *this works*

this doesn't work :thumbs_down:

:smile: :cry:
"""
print(markdown(demo_text))

and this is the output:

<p><emoji>thumbs_up</emoji> <em>this works</em></p>
<p>this doesn't work :thumbs_down:</p>
<p><emoji>smile</emoji> :cry:</p>

I would really appreciate any input/help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant