`Index </index.txt>`_

====================
package ``cssutils``
====================
:version: $Id: cssutils.txt 1263 2008-05-28 16:23:50Z cthedot $

.. contents::

overview
========
Contains tokenizer, parser and helper classes used by subpackages ``css`` and ``stylesheets``.
Implemented is also the interface `DOMImplementationCSS <http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-DOMImplementationCSS>`_.

:codec_: A CSS codec registered at standard module ``codecs``
:CSSParser_: A CSS parser
:CSSSerializer_: A configurable CSS serializer
:functions_: Utility functions ``getUrls`` and ``replaceUrls`` for now
:log_: A configurable ``cssutils.errorhandler.ErrorHandler()`` logger
:DOMImplementationCSS: Registers cssutils at standard package ``xml.dom``

.. _codec:

CSS codec
=========
You may use the provided CSS codec to read or write a CSS stylesheet. Handling is similar to other codecs. The codec handles the text encoding of the file automatically (regarding BOM or @charset rules in the stylesheet).

Example::

    import codecs
    import cssutils

    cssText = codecs.open('sheets/test-unicode.css', encoding='css').read()
    sheet = cssutils.parseString(cssText)


.. _CSSParser:

parsing CSS
===========
Options to parse a given stylesheet:

* use the helper functions:

  - ``cssutils.parseString(cssText, encoding=None, href=None, media=None, title=None)``
  - ``cssutils.parseFile(filename, encoding=None, href=None, media=None, title=None)``
  - ``cssutils.parseUrl(href, encoding=None, media=None, title=None)``

  parameter ``encoding``
        Value ``None`` defaults to encoding detection via HTTP, BOM or an
        @charset rule.
        Other values override detected encoding for the sheet at ``href``
        including any imported sheets.

        Additionally parameter ``encoding`` for ``parseString`` is used to decode the string if the given string is a byte string (not a unicode).

* parsing a stylesheet this way does not raise any exceptions if an error occurs but parses CSS as defined in the specifications. Setting explicit properties (e.g. ``CSSStyleSheet.cssText`` with a syntactically incorrect sheet raises the relevant exeptions.

* or get an instance of ``cssutils.CSSParser`` and use the provided ``parse*`` methods which are the same as the helper functions. The parser is reusable. With parameter ``raiseExceptions=False`` it is possible to define how the parser should cope with encountered errors.

Custom URL Fetcher
------------------
If you want to control how imported stylesheets are read you may define a custom URL fetcher (e.g. needed on Google AppEngine as urllib2 which is normally used is not available, a GA helper method may be added to cssutils soon.)

A custom URL fetcher may be used during parsing via ``CSSParser.setFetcher(fetcher)`` (or as an init parameter). The so customized parser is reusable. The fetcher is called when an ``@import`` rule is found and the referenced stylesheet is about to be retrieved.

      The function gets a single parameter

      ``url``
          the URL to read

      and returns ``(encoding, content)`` where ``encoding`` is the HTTP charset normally given via the Content-Type header (which may simply omit the charset) and ``content`` being the (byte) string content. The Mimetype should be 'text/css' but this has to be checked by the fetcher itself (the default fetcher emits a warning if encountering a different mimetype).
      The content is then decoded by cssutils using all encoding related data available.

        Example::

            def fetcher(url):
                return 'ascii', '/*test*/'

            parser = cssutils.CSSParser(fetcher=fetcher)
            parser.parse...

      To omit parsing of imported sheets just define a fetcher like ``lambda url: None`` (A single None is sufficient but returning ``None, None`` would be clearer).

      You may also define the encoding for each imported sheet with a fetcher which returns a (normally HTTP) encoding depending in URL.



.. _CSSSerializer:

serializing CSS
===============

Serializer
----------
There is a single global serializer used throughout the library. You may configure it by setting specific Preferences_ or completely replace it with your own.

A custom serializer must implement all methods the default one provides. Easiest would be to subclass ``cssutils.serialize.Serializer``.

To set a new serializer, use::

    sheet = CSSStyleSheet()
    sheet.setSerializer(newser)

You may also set ``cssutils.ser`` directly but the above method is the preferred one.


.. _Preferences:

Preferences
-----------
Quite a few preferences of the cssutils serializer may be tweaked.

To set a preference use::

    sheet = CSSStyleSheet()
    sheet.setSerializerPref(pref, value)

You may also set ``cssutils.ser.prefs.pref = value`` directly.

Preferences are always used *globally*, so for all stylesheets until preferences are set again.

group settings
~~~~~~~~~~~~~~
Two methods are available to use a predefined set of settings:

useDefaults()
    reset all preference options to the default values
useMinified()
    sets options to achieve a minified stylesheet


individual settings
~~~~~~~~~~~~~~~~~~~
The following preferences are currently available (name = default value):

defaultAtKeyword = True
    Should the literal @keyword from src CSS be used or the default
    form, e.g. if ``True``: ``@import`` else e.g.: ``@i\mport``
defaultPropertyName = True
    Should the normalized propertyname be used or the one given in
    the src file, e.g. if ``True``: ``color`` else e.g.: ``c\olor``

    Only used if ``keepAllProperties==False``.

defaultPropertyPriority = True
    Should the normalized or literal priority be used, e.g. '!important'
    or u'!Im\portant'
importHrefFormat = None
    Uses hreftype if ``None`` or explicit ``'string'`` or ``'uri'``
indent = 4 * ' '
    Indentation of e.g Properties inside a CSSStyleDeclaration
keepAllProperties = True
    If ``True`` all properties set in the original CSSStylesheet
    are kept meaning even properties set twice with the exact same
    same name are kept!
keepComments = True
    If ``False`` removes all CSSComments
keepEmptyRules = False
    defines if empty rules like e.g. ``a {}`` are kept in the resulting
    serialized sheet
keepUsedNamespaceRulesOnly = False
    if True only namespace rules which are actually used are kept
lineNumbers = False
    Only used for serializing CSSStyleSheet, not individual rules or properties etc.
lineSeparator = u'\\n'
    How to end a line. This may be set to e.g. u'' for serializing of
    CSSStyleDeclarations usable in HTML style attribute.
listItemSpacer = u' '
    String which is used in ``css.SelectorList``, ``css.CSSValue`` and
    ``stylesheets.MediaList`` after the comma, minifier sets this to the empty string.
omitLastSemicolon = True
    If ``True`` omits ; after last property of CSSStyleDeclaration
paranthesisSpacer = u' '
    String which is used before an opening paranthesis like in a
    ``css.CSSMediaRule`` or ``css.CSSStyleRule``, minifier sets this to the empty string.
propertyNameSpacer = u' '
    String which is used after a Property name colon, minifier sets this to the empty string.
selectorCombinatorSpacer = u' '
    String which is used before and after a Selector combinator like +, > or ~.
    CSSOM defines a single space for this which is also the default in cssutils.
spacer = u' '
    general spacer, used e.g. by CSSUnknownRule

validOnly = False
    If ``True`` only valid (currently Properties) are kept.

    A Property is valid if it is a known Property with a valid value.
    Currently CSS 2.1 values as defined in cssproperties.py would be
    valid.

.. _functions:

helper functions
================

.. _getUrls:

def getUrls(sheet):
    Utility function to get all ``url(value)`` values in
    ``CSSImportRules`` and ``CSSStyleDeclaration`` objects (properties)
    of given CSSStyleSheet ``sheet``.

    This function is a generator. The url values exclude ``url(`` and ``)`` and surrounding single or double quotes.

.. _replaceUrls:

replaceUrls(sheet, replacer)
    Utility function to replace all ``url(urlstring)`` values in
    ``CSSImportRules`` and ``CSSStyleDeclaration`` objects (properties)
    of given CSSStyleSheet ``sheet``.

    ``replacer`` must be a function which is called with a single
    argument ``urlstring`` which is the current value of url()
    excluding ``url(`` and ``)`` and surrounding single or double quotes.

.. _log:

logging
=======
A global logger is used throughout the library. You may configure it or even replace it with your own. Customizing the default log should be sufficient for most purposes though.

The default logger is available as ``cssutils.log``. It has the following methods:

* ``log.setlog(newlog)``: To redirect logging output, the default output is sent to ``stderr``
* ``log.setloglevel(level)``: To change the log level. This should be a level defined by the ``logging`` module, e.g.::

    import logging
    cssutils.log.setloglevel(logging.FATAL)


