ryshcate / ryshcate /

Full commit
# -*- coding: utf-8 -*-
This contains some utilities used by the rest of Ryshcate.

:copyright: 2010 Matthew "LeafStorm" Frazier
:license:   MIT/X11, see LICENSE for details
import re
from flask import Markup, flash, current_app, session
from itertools import chain
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name, get_all_lexers, ClassNotFound
from pygments.styles import get_all_styles
from ryshcate.locale import _

### Form helpers

BACKWARDS_PROFANITIES = set('nmad hctib tihs kcuf tnuc koog reggin hssa'

reverse = lambda s: ''.join(reversed(s))

def contains_profanities(text):
    return any(reverse(p) in text for p in BACKWARDS_PROFANITIES)

def flash_errors(form):
    for field, errors in form.errors.items():
        for error in errors:
            flash(_(u"Error in the %(field)s field - %(error)s",
                field=getattr(form, field).label.text, error=error
            ), 'error')

### Highlighting helpers

def highlight_code(code, lexer, formatter=HtmlFormatter, **formatter_opts):
    fmter = formatter(style=user_pygments_style(), **formatter_opts)
    if isinstance(lexer, basestring):
        lexer = get_lexer_by_name(lexer)
    return Markup(highlight(code, lexer, fmter))

def get_style_css(style, prefix='.highlight', **formatter_opts):
    fmter = HtmlFormatter(style=style, **formatter_opts)
    return fmter.get_style_defs(prefix)

LEXER_LIST = list(sorted((
    ((lexer[1][0] if 'bf' not in lexer[1] else 'bf'),
    lexer[0].replace('uck', '---'))
    for lexer in get_all_lexers()
), key=lambda l: l[0].lower()))


### Template helpers

def site_config(name, default=None):
    if not isinstance(name, basestring):
        raise TypeError("Configuration value name must be a string")
    key = 'SITE_' + name.upper()
    return current_app.config.get(key, default)

def user_pygments_style():
    default = current_app.config.get('DEFAULT_PYGMENTS_STYLE', 'default')
    return session.get('style', default)

def get_pygments_css():
    return get_style_css(user_pygments_style(), linenos='table')

TEMPLATE_GLOBALS = dict(site_config=site_config,