trentm / python-markdown2

markdown2: A fast and complete implementation of Markdown in Python
Other
2.64k stars 431 forks source link

Add the possibility to allow some HTML tags #334

Open savelmtr opened 4 years ago

savelmtr commented 4 years ago

Hello! It would be great if we could add this possibility to the markdown2. For example, users of my forum need the <font color='red'> tag. Also <small>. I think it would be very cool if we can determine the list of such tags in settings of the markdown2. Like this, may be: safe_mode=True, allowed_tags=['font','small'] What do you think about this?

icyphox commented 4 years ago

This would be fantastic to have, really.

savelmtr commented 4 years ago

@icyphox, for my forum, I've made an extention for markdown2 in which I've incorporate some BB-codes for in the same time keep the security and also add some features which markdown doesn't have. I could propose this as PR for example.

For now it looks like this: self.bbcodes = ['.color', 'small', 'big', 'del', 'sup'] text = self.make_bbcodes(text)

and also the function:

    def make_bbcodes(self, text):
        # decode some bbcodes in text

        def bbcodes_helper(obj):
            tag = obj.group(1)
            innerHTML = obj.group(2).replace('\n\n', '</{0}>\n\n<{0}>'.format(tag))
            return r'<{0}>{1}</{0}>'.format(tag, innerHTML)

        color_pattern = re.compile(r'\w+|\#[\w\d]+')
        def bbcodes_font_helper(obj):
            style_option = obj.group(1)
            style_option_setting = obj.group(2)
            innerHTML = obj.group(3)
            if not color_pattern.fullmatch(style_option_setting):
                return '{0}{1}{0}'.format(self.html_removed_text, innerHTML)
            else:
                innerHTML = innerHTML.replace('\n\n', '</span>\n\n<span style="{0}: {1}">'.format(style_option, style_option_setting))
            return r'<span style="{0}: {1}">{2}</span>'.format(style_option, style_option_setting, innerHTML)

        for code in self.bbcodes:

            if '.' in code:
                pattrn = re.compile(r'\[({0})\=[\"\']?(.+?)[\"\']?\]([\S\s]*?)\[\/{0}\]'.format(code.replace('.', '')))
                text = pattrn.sub(bbcodes_font_helper, text)

            else:
                pattrn = re.compile(r'\[({0})\]([\S\s]*?)\[\/{0}\]'.format(code))
                text = pattrn.sub(bbcodes_helper, text)

        return text