Skip to content

Instantly share code, notes, and snippets.

@gabrielfalcao
Created April 6, 2011 19:33
Show Gist options
  • Save gabrielfalcao/906357 to your computer and use it in GitHub Desktop.
Save gabrielfalcao/906357 to your computer and use it in GitHub Desktop.
small tornado server that translate a few parts of markdown syntax to mediawiki, not 100% functional but helps a lot
# #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) <2011> Gabriel Falcão <[email protected]>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
import re
class Markdown2MediaWiki(object):
"""
>>> cv = Markdown2MediaWiki('# foobar')
>>> cv.convert()
u'= foobar =\\n'
>>> cv = Markdown2MediaWiki('###### iasydlasdaskdakdu @#$%)(*&&')
>>> cv.convert()
u'====== iasydlasdaskdakdu @#$%)(*&& ======\\n'
>>> cv = Markdown2MediaWiki('[name of the link](http://actual.link.com?with=query%20strings)')
>>> cv.convert()
u'[http://actual.link.com?with=query%20strings name of the link]'
>>> cv = Markdown2MediaWiki('something with `code` inline')
>>> cv.convert()
u'something with <pre>code</pre> inline'
>>> cv = Markdown2MediaWiki(' something with `code` inline ')
>>> cv.convert()
u'<pre> something with `code` inline </pre>'
>>> cv = Markdown2MediaWiki('*blabla*')
>>> cv.convert()
u"''blabla''"
>>> cv = Markdown2MediaWiki('**blabla**')
>>> cv.convert()
u"'''blabla'''"
>>> cv = Markdown2MediaWiki('*blabla* **foobar**')
>>> cv.convert()
u"''blabla'' '''foobar'''"
"""
def __init__(self, string):
self.string = string
def _filter_headings(self, string):
regex = re.compile(ur'^(?P<char>[#]+)\s*(?P<title>.*)', re.U)
found = regex.findall(string)
for char, title in found:
string = regex.sub(ur'{0} \g<title> {0}'.format('=' * len(char)), string, 1)
return string
def _filter_links(self, string):
regex = re.compile(ur'[[](?P<name>[^]]+)[]][(](?P<link>https?[:][/]{2}[^)]+)[)]', re.U)
return regex.sub(ur'[\g<link> \g<name>]', string)
def _filter_inline_code(self, string):
regex = re.compile(ur'^(?P<start>[^<]|[<][^p]|[<]p[^r]|[<]pr[^e]|[<]pre[^>])(?P<any1>[^`]*)[`](?P<code>[^`]*)[`](?P<any2>[^`]*)$')
return regex.sub(ur'\g<start>\g<any1><pre>\g<code></pre>\g<any2>', string)
def _filter_indented_code(self, string):
regex = re.compile(ur'^\s{4}(?P<code>.*)$')
return regex.sub(ur'<pre>\g<code></pre>', string)
def _filter_bold_and_italic(self, string):
regex = re.compile(ur'(?P<char>[*]{1,2})\s*(?P<title>[^*]*)\s*(?P=char)', re.U)
found = regex.findall(string)
for char, title in found:
string = regex.sub(ur'{0}\g<title>{0}'.format("'" * (len(char)+1)), string, 1)
return string
def convert(self):
lines = self.string.splitlines()
transformers = [getattr(self, x) for x in sorted(dir(self)) \
if x.startswith("_filter")]
res = []
for line in lines:
for transform in transformers:
line = transform(line)
res.append(line)
string = '\n'.join(map(unicode.strip, res))
return re.sub(r'[=]$', '=\n', string)
if __name__ == "__main__":
import doctest
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def post(self):
cv = Markdown2MediaWiki(self.get_argument('md', ''))
self.set_header('Content-Type', 'text/plain')
self.write(cv.convert())
def get(self):
self.write(self.render_index())
def render_index(self, top=""):
return ur'''
<html>
<head>
<title>Markdown2MediaWiki</title>
</head>
<body>
{0}
<form method="POST">
<textarea name="md" style="width:640px;height:480px">
# Put
## some
markdown
*right* **here**
</textarea>
<input type="submit" value="convert to media wiki" />
</form>
</body>
</html>
'''.format(top)
application = tornado.web.Application([
(r"/", MainHandler),
])
result = doctest.testmod()
if not result.failed:
print "all tests passed, running on http://localhost:9099/"
application.listen(9099)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment