Source

pygments-main-2 / pygments / formatters / __init__.py

# -*- coding: utf-8 -*-
"""
    pygments.formatters
    ~~~~~~~~~~~~~~~~~~~

    Pygments formatters.

    :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""
import fnmatch
import sys
import types
from os.path import basename

from pygments.formatters._mapping import FORMATTERS
from pygments.plugin import find_plugin_formatters
from pygments.util import ClassNotFound

__all__ = ['get_formatter_by_name', 'get_formatter_for_filename',
           'get_all_formatters'] + FORMATTERS.keys()

_formatter_cache = {}

def _load_formatters(module_name):
    """
    Load a formatter (and all others in the module too).
    """
    mod = __import__(module_name, None, None, ['__all__'])
    for formatter_name in mod.__all__:
        cls = getattr(mod, formatter_name)
        _formatter_cache[cls.name] = cls

def get_all_formatters():
    """
    Return a generator of all know formatters.
    """
    for item in FORMATTERS.itervalues():
        yield item[1:]
    for _, formatter in find_plugin_formatters():
        yield formatter


def get_formatter_by_name(_alias, **options):
    """
    Get a formatter by an alias.
    """
    # lookup builtin formatters
    for module_name, name, aliases, _, _ in FORMATTERS.itervalues():
        if _alias in aliases:
            if name not in _formatter_cache:
                _load_formatters(module_name)
            return _formatter_cache[name](**options)
    # continue with formatters from setuptools entrypoints
    for _, cls in find_plugin_formatters():
        if _alias in cls.aliases:
            return cls(**options)
    raise ClassNotFound('no formatter for alias %r found' % _alias)

def get_formatter_for_filename(_fn, **options):
    """
    Get a formatter for a filename.
    """
    matches = []
    fn = basename(_fn)
    print fn
    for modname, name, _, filenames, _ in FORMATTERS.itervalues():
        for filename in filenames:
            if fnmatch.fnmatch(fn, filename):
                if name not in _formatter_cache:
                    _load_formatters(modname)
                return _formatter_cache[name]
    for _, cls in find_plugin_formatters():
        for filename in cls.filenames:
            if fnmatch.fnmatch(fn, filename):
                return cls
    raise ClassNotFound("No formatter found for file name %r" % fn)

class _automodule(types.ModuleType):
    """Automatically import formatters."""

    def __getattr__(self, name):
        info = FORMATTERS.get(name)
        if info:
            _load_formatters(info[0])
            cls = _formatter_cache[info[1]]
            setattr(self, name, cls)
            return cls
        raise AttributeError(name)


oldmod = sys.modules['pygments.formatters']
newmod = _automodule('pygments.formatter')
newmod.__dict__.update(oldmod.__dict__)
sys.modules['pygments.formatters'] = newmod
del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types