diff options
-rw-r--r-- | pastepy.py | 43 |
1 files changed, 22 insertions, 21 deletions
@@ -14,12 +14,16 @@ try: has_markdown = True except ImportError: has_markdown = False +import pygments from pygments import highlight from pygments.lexers import get_all_lexers, get_lexer_by_name from pygments.formatters import HtmlFormatter base62_alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' +class PasteError(Exception): pass +class UnknownSyntaxError(PasteError): pass + class CustomHtmlFormatter(HtmlFormatter): def wrap(self, source, outfile): yield 0, '<pre>' @@ -82,16 +86,10 @@ class Paste(object): }))] def preview(self, mp): - if mp['syntax'].value == 'md-render' and has_markdown: - text = markdown.markdown(mp['text'].value) - lexername = 'Rendered markdown' - else: - try: - lex = get_lexer_by_name(mp['syntax'].value.decode('utf8')) - lexername = lex.name - text = highlight(mp['text'].value.decode('utf8'), lex, self.formatter) - except: - return self.message('Could not find the lexer "%s".' % mp['syntax'].value, 'Error') + try: + lexername, text = self.get_formatted(mp['syntax'].value.decode('utf8'), mp['text'].value.decode('utf8')) + except UnknownSyntaxError: + return self.message('Could not find lexer "%s".' % mp['syntax'].value, 'Error') self.start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')]) return [str(templates.view(searchList = { @@ -131,17 +129,20 @@ class Paste(object): self.start_response('302 Found', headers) return [] - def view(self): - def get_formatted(syntax, text): - if syntax == 'md-render' and has_markdown: - text = markdown.markdown(text) - lexername = 'Rendered markdown' - else: + def get_formatted(self, syntax, text): + if syntax == 'md-render' and has_markdown: + text = markdown.markdown(text) + lexername = 'Rendered markdown' + else: + try: lex = get_lexer_by_name(syntax or 'text') - lexername = lex.name - text = highlight(text, lex, self.formatter) - return (lexername, text) + except pygments.util.ClassNotFound: + raise UnknownSyntaxError(syntax) + lexername = lex.name + text = highlight(text, lex, self.formatter) + return (lexername, text) + def view(self): hash = self.path[1] try: @@ -156,8 +157,8 @@ class Paste(object): self.start_response('404 Not Found', []) return [] try: - lexername, text = get_formatted(paste.syntax, paste.text if type(paste.text) == unicode else paste.text.decode('utf8')) - except: + lexername, text = self.get_formatted(paste.syntax, paste.text if type(paste.text) == unicode else paste.text.decode('utf8')) + except UnknownSyntaxError: return self.message('Could not find the lexer "%s".' % paste.syntax, 'Error') cache = db.Cache(hash, lexername, text) session.add(cache) |