mdx_image.py 2.03 KB
Newer Older
Piotr Mitros committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#!/usr/bin/env python
'''
Image Embedding Extension for Python-Markdown
======================================

Converts lone links to embedded images, provided the file extension is allowed.

Ex:
    http://www.ericfehse.net/media/img/ef/blog/django-pony.jpg
    becomes
    <img src="http://www.ericfehse.net/media/img/ef/blog/django-pony.jpg">

    mypic.jpg   becomes    <img src="/MEDIA_PATH/mypic.jpg">

Requires Python-Markdown 1.6+
'''

import simplewiki.settings as settings
19

Piotr Mitros committed
20
import markdown
21 22 23 24 25 26 27
try:
    # Markdown 2.1.0 changed from 2.0.3. We try importing the new version first,
    # but import the 2.0.3 version if it fails
    from markdown.util import etree
except:
    from markdown import etree

Piotr Mitros committed
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

class ImageExtension(markdown.Extension):
    def __init__(self, configs):
        for key, value in configs :
            self.setConfig(key, value)
    
    def add_inline(self, md, name, klass, re):
        pattern = klass(re)
        pattern.md = md
        pattern.ext = self
        md.inlinePatterns.add(name, pattern, "<reference")
    
    def extendMarkdown(self, md, md_globals):
        self.add_inline(md, 'image', ImageLink, 
        r'^(?P<proto>([^:/?#])+://)?(?P<domain>([^/?#]*)/)?(?P<path>[^?#]*\.(?P<ext>[^?#]{3,4}))(?:\?([^#]*))?(?:#(.*))?$')

class ImageLink(markdown.inlinepatterns.Pattern):
    def handleMatch(self, m):
46
        img = etree.Element('img')
Piotr Mitros committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
        proto  = m.group('proto') or "http://"
        domain = m.group('domain')
        path   = m.group('path')
        ext    = m.group('ext')
        
        # A fixer upper
        if ext.lower() in settings.WIKI_IMAGE_EXTENSIONS:
            if domain:
                src = proto+domain+path
            elif path:
                # We need a nice way to source local attachments...
                src = "/wiki/media/" + path + ".upload"
            else:
                src = ''
            img.set('src', src)
        return img
    
def makeExtension(configs=None) :
    return ImageExtension(configs=configs)

if __name__ == "__main__":
    import doctest
    doctest.testmod()