Unicode support for wordcount.
[jinja2.git] / jinja2 / filters.py
index 0b55760169ef60683e17bd9f4c406c64448d2b4e..676627f34d1c843961e54adb1d73e43603b33fae 100644 (file)
@@ -5,29 +5,25 @@
 
     Bundled jinja filters.
 
-    :copyright: 2008 by Armin Ronacher, Christoph Hack.
+    :copyright: (c) 2009 by the Jinja Team.
     :license: BSD, see LICENSE for more details.
 """
 import re
 import math
 from random import choice
-try:
-    from operator import itemgetter
-except ImportError:
-    itemgetter = lambda a: lambda b: b[a]
-from urllib import urlencode, quote
+from operator import itemgetter
 from itertools import imap, groupby
 from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode
 from jinja2.runtime import Undefined
-from jinja2.exceptions import FilterArgumentError
+from jinja2.exceptions import FilterArgumentError, SecurityError
 
 
-_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
+_word_re = re.compile(r'\w+(?u)')
 
 
 def contextfilter(f):
-    """Decorator for marking context dependent filters. The current context
-    argument will be passed as first argument.
+    """Decorator for marking context dependent filters. The current
+    :class:`Context` will be passed as first argument.
     """
     if getattr(f, 'environmentfilter', False):
         raise TypeError('filter already marked as environment filter')
@@ -36,8 +32,8 @@ def contextfilter(f):
 
 
 def environmentfilter(f):
-    """Decorator for marking evironment dependent filters.  The environment
-    used for the template is passed to the filter as first argument.
+    """Decorator for marking evironment dependent filters.  The current
+    :class:`Environment` is passed to the filter as first argument.
     """
     if getattr(f, 'contextfilter', False):
         raise TypeError('filter already marked as context filter')
@@ -77,7 +73,7 @@ def do_replace(environment, s, old, new, count=None):
         s = escape(s)
     else:
         s = soft_unicode(s)
-    return s.replace(old, new, count)
+    return s.replace(soft_unicode(old), soft_unicode(new), count)
 
 
 def do_upper(s):
@@ -98,7 +94,7 @@ def do_xmlattr(_environment, d, autospace=True):
 
     .. sourcecode:: html+jinja
 
-        <ul{{ {'class': 'my_list', 'missing': None,
+        <ul{{ {'class': 'my_list', 'missing': none,
                 'id': 'list-%d'|format(variable)}|xmlattr }}>
         ...
         </ul>
@@ -112,11 +108,11 @@ def do_xmlattr(_environment, d, autospace=True):
         </ul>
 
     As you can see it automatically prepends a space in front of the item
-    if the filter returned something unless the second parameter is `False`.
+    if the filter returned something unless the second parameter is false.
     """
     rv = u' '.join(
         u'%s="%s"' % (escape(key), escape(value))
-        for key, value in dict(*args, **kwargs).iteritems()
+        for key, value in d.iteritems()
         if value is not None and not isinstance(value, Undefined)
     )
     if autospace and rv:
@@ -141,7 +137,7 @@ def do_title(s):
 
 
 def do_dictsort(value, case_sensitive=False, by='key'):
-    """ Sort a dict and yield (key, value) pairs. Because python dicts are
+    """Sort a dict and yield (key, value) pairs. Because python dicts are
     unsorted you may want to use this function to order them by either
     key or value:
 
@@ -166,15 +162,34 @@ def do_dictsort(value, case_sensitive=False, by='key'):
                                   '"key" or "value"')
     def sort_func(item):
         value = item[pos]
-        if isinstance(value, basestring):
-            value = unicode(value)
-            if not case_sensitive:
-                value = value.lower()
+        if isinstance(value, basestring) and not case_sensitive:
+            value = value.lower()
         return value
 
     return sorted(value.items(), key=sort_func)
 
 
+def do_sort(value, case_sensitive=False):
+    """Sort an iterable.  If the iterable is made of strings the second
+    parameter can be used to control the case sensitiveness of the
+    comparison which is disabled by default.
+
+    .. sourcecode:: jinja
+
+        {% for item in iterable|sort %}
+            ...
+        {% endfor %}
+    """
+    if not case_sensitive:
+        def sort_func(item):
+            if isinstance(item, basestring):
+                item = item.lower()
+            return item
+    else:
+        sort_func = None
+    return sorted(seq, key=sort_func)
+
+
 def do_default(value, default_value=u'', boolean=False):
     """If the value is undefined it will return the passed default value,
     otherwise the value of the variable:
@@ -201,7 +216,7 @@ def do_default(value, default_value=u'', boolean=False):
 def do_join(environment, value, d=u''):
     """Return a string which is the concatenation of the strings in the
     sequence. The separator between elements is an empty string per
-    default, you can define ith with the optional parameter:
+    default, you can define it with the optional parameter:
 
     .. sourcecode:: jinja
 
@@ -242,7 +257,7 @@ def do_center(value, width=80):
 
 @environmentfilter
 def do_first(environment, seq):
-    """Return the frist item of a sequence."""
+    """Return the first item of a sequence."""
     try:
         return iter(seq).next()
     except StopIteration:
@@ -267,23 +282,22 @@ def do_random(environment, seq):
         return environment.undefined('No random item, sequence was empty.')
 
 
-def do_filesizeformat(value):
+def do_filesizeformat(value, binary=False):
     """Format the value like a 'human-readable' file size (i.e. 13 KB,
-    4.1 MB, 102 bytes, etc).
+    4.1 MB, 102 bytes, etc).  Per default decimal prefixes are used (mega,
+    giga, etc.), if the second parameter is set to `True` the binary
+    prefixes are used (mebi, gibi).
     """
-    # fail silently
-    try:
-        bytes = float(value)
-    except TypeError:
-        bytes = 0
-
-    if bytes < 1024:
+    bytes = float(value)
+    base = binary and 1024 or 1000
+    middle = binary and 'i' or ''
+    if bytes < base:
         return "%d Byte%s" % (bytes, bytes != 1 and 's' or '')
-    elif bytes < 1024 * 1024:
-        return "%.1f KB" % (bytes / 1024)
-    elif bytes < 1024 * 1024 * 1024:
-        return "%.1f MB" % (bytes / (1024 * 1024))
-    return "%.1f GB" % (bytes / (1024 * 1024 * 1024))
+    elif bytes < base * base:
+        return "%.1f K%sB" % (bytes / base, middle)
+    elif bytes < base * base * base:
+        return "%.1f M%sB" % (bytes / (base * base), middle)
+    return "%.1f G%sB" % (bytes / (base * base * base), middle)
 
 
 def do_pprint(value, verbose=False):
@@ -295,7 +309,8 @@ def do_pprint(value, verbose=False):
     return pformat(value, verbose=verbose)
 
 
-def do_urlize(value, trim_url_limit=None, nofollow=False):
+@environmentfilter
+def do_urlize(environment, value, trim_url_limit=None, nofollow=False):
     """Converts URLs in plain text into clickable links.
 
     If you pass the filter an additional integer it will shorten the urls
@@ -304,10 +319,13 @@ def do_urlize(value, trim_url_limit=None, nofollow=False):
 
     .. sourcecode:: jinja
 
-        {{ mytext|urlize(40, True) }}
+        {{ mytext|urlize(40, true) }}
             links are shortened to 40 chars and defined with rel="nofollow"
     """
-    return urlize(soft_unicode(value), trim_url_limit, nofollow)
+    rv = urlize(value, trim_url_limit, nofollow)
+    if environment.autoescape:
+        rv = Markup(rv)
+    return rv
 
 
 def do_indent(s, width=4, indentfirst=False):
@@ -318,13 +336,14 @@ def do_indent(s, width=4, indentfirst=False):
 
     .. sourcecode:: jinja
 
-        {{ mytext|indent(2, True) }}
+        {{ mytext|indent(2, true) }}
             indent by two spaces and indent the first line too.
     """
-    indention = ' ' * width
+    indention = u' ' * width
+    rv = (u'\n' + indention).join(s.splitlines())
     if indentfirst:
-        return u'\n'.join(indention + line for line in s.splitlines())
-    return s.replace('\n', '\n' + indention)
+        rv = indention + rv
+    return rv
 
 
 def do_truncate(s, length=255, killwords=False, end='...'):
@@ -358,31 +377,22 @@ def do_truncate(s, length=255, killwords=False, end='...'):
     return u' '.join(result)
 
 
-def do_wordwrap(s, pos=79, hard=False):
+def do_wordwrap(s, width=79, break_long_words=True):
     """
     Return a copy of the string passed to the filter wrapped after
-    ``79`` characters. You can override this default using the first
-    parameter. If you set the second parameter to `true` Jinja will
-    also split words apart (usually a bad idea because it makes
-    reading hard).
+    ``79`` characters.  You can override this default using the first
+    parameter.  If you set the second parameter to `false` Jinja will not
+    split words apart if they are longer than `width`.
     """
-    if len(s) < pos:
-        return s
-    if hard:
-        return u'\n'.join(s[idx:idx + pos] for idx in
-                          xrange(0, len(s), pos))
-
-    # TODO: switch to wordwrap.wrap
-    # code from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061
-    return reduce(lambda line, word, pos=pos: u'%s%s%s' %
-                  (line, u' \n'[(len(line)-line.rfind('\n') - 1 +
-                                len(word.split('\n', 1)[0]) >= pos)],
-                   word), s.split(' '))
+    import textwrap
+    return u'\n'.join(textwrap.wrap(s, width=width, expand_tabs=False,
+                                   replace_whitespace=False,
+                                   break_long_words=break_long_words))
 
 
 def do_wordcount(s):
     """Count the words in that string."""
-    return len(s.split())
+    return len(_word_re.findall(s))
 
 
 def do_int(value, default=0):
@@ -420,10 +430,10 @@ def do_format(value, *args, **kwargs):
         {{ "%s - %s"|format("Hello?", "Foo!") }}
             -> Hello? - Foo!
     """
-    if kwargs:
-        kwargs.update(idx, arg in enumerate(args))
-        args = kwargs
-    return soft_unicode(value) % args
+    if args and kwargs:
+        raise FilterArgumentError('can\'t handle positional and keyword '
+                                  'arguments at the same time')
+    return soft_unicode(value) % (kwargs or args)
 
 
 def do_trim(value):
@@ -436,13 +446,13 @@ def do_striptags(value):
     """
     if hasattr(value, '__html__'):
         value = value.__html__()
-    return u' '.join(_striptags_re.sub('', value).split())
+    return Markup(unicode(value)).striptags()
 
 
 def do_slice(value, slices, fill_with=None):
     """Slice an iterator and return a list of lists containing
     those items. Useful if you want to create a div containing
-    three div tags that represent columns:
+    three ul tags that represent columns:
 
     .. sourcecode:: html+jinja
 
@@ -488,7 +498,7 @@ def do_batch(value, linecount, fill_with=None):
         {%- for row in items|batch(3, '&nbsp;') %}
           <tr>
           {%- for column in row %}
-            <tr>{{ column }}</td>
+            <td>{{ column }}</td>
           {%- endfor %}
           </tr>
         {%- endfor %}
@@ -541,7 +551,7 @@ def do_round(value, precision=0, method='common'):
 
 def do_sort(value, reverse=False):
     """Sort a sequence. Per default it sorts ascending, if you pass it
-    `True` as first argument it will reverse the sorting.
+    true as first argument it will reverse the sorting.
     """
     return sorted(value, reverse=reverse)
 
@@ -581,7 +591,7 @@ def do_groupby(environment, value, attribute):
     attribute and the `list` contains all the objects that have this grouper
     in common.
     """
-    expr = lambda x: environment.subscribe(x, attribute)
+    expr = lambda x: environment.getitem(x, attribute)
     return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)))
 
 
@@ -608,6 +618,11 @@ def do_mark_safe(value):
     return Markup(value)
 
 
+def do_mark_unsafe(value):
+    """Mark a value as unsafe.  This is the reverse operation for :func:`safe`."""
+    return unicode(value)
+
+
 def do_reverse(value):
     """Reverse the object or return an iterator the iterates over it the other
     way round.
@@ -625,7 +640,33 @@ def do_reverse(value):
             raise FilterArgumentError('argument must be iterable')
 
 
+@environmentfilter
+def do_attr(environment, obj, name):
+    """Get an attribute of an object.  ``foo|attr("bar")`` works like
+    ``foo["bar"]`` just that always an attribute is returned and items are not
+    looked up.
+
+    See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
+    """
+    try:
+        name = str(name)
+    except UnicodeError:
+        pass
+    else:
+        try:
+            value = getattr(obj, name)
+        except AttributeError:
+            pass
+        else:
+            if environment.sandboxed and not \
+               environment.is_safe_attribute(obj, name, value):
+                return environment.unsafe_undefined(obj, name)
+            return value
+    return environment.undefined(obj=obj, name=name)
+
+
 FILTERS = {
+    'attr':                 do_attr,
     'replace':              do_replace,
     'upper':                do_upper,
     'lower':                do_lower,
@@ -639,6 +680,7 @@ FILTERS = {
     'join':                 do_join,
     'count':                len,
     'dictsort':             do_dictsort,
+    'sort':                 do_sort,
     'length':               len,
     'reverse':              do_reverse,
     'center':               do_center,