moved environment defaults to jinja2.defaults
[jinja2.git] / jinja2 / ext.py
1 # -*- coding: utf-8 -*-
2 """
3     jinja2.ext
4     ~~~~~~~~~~
5
6     Jinja extensions allow to add custom tags similar to the way django custom
7     tags work.  By default two example extensions exist: an i18n and a cache
8     extension.
9
10     :copyright: Copyright 2008 by Armin Ronacher.
11     :license: BSD.
12 """
13 from collections import deque
14 from jinja2 import nodes
15 from jinja2.defaults import *
16 from jinja2.environment import get_spontaneous_environment
17 from jinja2.runtime import Undefined, concat
18 from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError
19 from jinja2.utils import contextfunction, import_string, Markup
20
21
22 # the only real useful gettext functions for a Jinja template.  Note
23 # that ugettext must be assigned to gettext as Jinja doesn't support
24 # non unicode strings.
25 GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')
26
27
28 class ExtensionRegistry(type):
29     """Gives the extension an unique identifier."""
30
31     def __new__(cls, name, bases, d):
32         rv = type.__new__(cls, name, bases, d)
33         rv.identifier = rv.__module__ + '.' + rv.__name__
34         return rv
35
36
37 class Extension(object):
38     """Extensions can be used to add extra functionality to the Jinja template
39     system at the parser level.  Custom extensions are bound to an environment
40     but may not store environment specific data on `self`.  The reason for
41     this is that an extension can be bound to another environment (for
42     overlays) by creating a copy and reassigning the `environment` attribute.
43
44     As extensions are created by the environment they cannot accept any
45     arguments for configuration.  One may want to work around that by using
46     a factory function, but that is not possible as extensions are identified
47     by their import name.  The correct way to configure the extension is
48     storing the configuration values on the environment.  Because this way the
49     environment ends up acting as central configuration storage the
50     attributes may clash which is why extensions have to ensure that the names
51     they choose for configuration are not too generic.  ``prefix`` for example
52     is a terrible name, ``fragment_cache_prefix`` on the other hand is a good
53     name as includes the name of the extension (fragment cache).
54     """
55     __metaclass__ = ExtensionRegistry
56
57     #: if this extension parses this is the list of tags it's listening to.
58     tags = set()
59
60     def __init__(self, environment):
61         self.environment = environment
62
63     def bind(self, environment):
64         """Create a copy of this extension bound to another environment."""
65         rv = object.__new__(self.__class__)
66         rv.__dict__.update(self.__dict__)
67         rv.environment = environment
68         return rv
69
70     def parse(self, parser):
71         """If any of the :attr:`tags` matched this method is called with the
72         parser as first argument.  The token the parser stream is pointing at
73         is the name token that matched.  This method has to return one or a
74         list of multiple nodes.
75         """
76         raise NotImplementedError()
77
78     def attr(self, name, lineno=None):
79         """Return an attribute node for the current extension.  This is useful
80         to pass constants on extensions to generated template code::
81
82             self.attr('_my_attribute', lineno=lineno)
83         """
84         return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
85
86     def call_method(self, name, args=None, kwargs=None, dyn_args=None,
87                     dyn_kwargs=None, lineno=None):
88         """Call a method of the extension.  This is a shortcut for
89         :meth:`attr` + :class:`jinja2.nodes.Call`.
90         """
91         if args is None:
92             args = []
93         if kwargs is None:
94             kwargs = []
95         return nodes.Call(self.attr(name, lineno=lineno), args, kwargs,
96                           dyn_args, dyn_kwargs, lineno=lineno)
97
98
99 @contextfunction
100 def _gettext_alias(context, string):
101     return context.resolve('gettext')(string)
102
103
104 class InternationalizationExtension(Extension):
105     """This extension adds gettext support to Jinja2."""
106     tags = set(['trans'])
107
108     def __init__(self, environment):
109         Extension.__init__(self, environment)
110         environment.globals['_'] = _gettext_alias
111         environment.extend(
112             install_gettext_translations=self._install,
113             install_null_translations=self._install_null,
114             uninstall_gettext_translations=self._uninstall,
115             extract_translations=self._extract
116         )
117
118     def _install(self, translations):
119         self.environment.globals.update(
120             gettext=translations.ugettext,
121             ngettext=translations.ungettext
122         )
123
124     def _install_null(self):
125         self.environment.globals.update(
126             gettext=lambda x: x,
127             ngettext=lambda s, p, n: (n != 1 and (p,) or (s,))[0]
128         )
129
130     def _uninstall(self, translations):
131         for key in 'gettext', 'ngettext':
132             self.environment.globals.pop(key, None)
133
134     def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):
135         if isinstance(source, basestring):
136             source = self.environment.parse(source)
137         return extract_from_ast(source, gettext_functions)
138
139     def parse(self, parser):
140         """Parse a translatable tag."""
141         lineno = parser.stream.next().lineno
142
143         # find all the variables referenced.  Additionally a variable can be
144         # defined in the body of the trans block too, but this is checked at
145         # a later state.
146         plural_expr = None
147         variables = {}
148         while parser.stream.current.type is not 'block_end':
149             if variables:
150                 parser.stream.expect('comma')
151
152             # skip colon for python compatibility
153             if parser.stream.skip_if('colon'):
154                 break
155
156             name = parser.stream.expect('name')
157             if name.value in variables:
158                 parser.fail('translatable variable %r defined twice.' %
159                             name.value, name.lineno,
160                             exc=TemplateAssertionError)
161
162             # expressions
163             if parser.stream.current.type is 'assign':
164                 parser.stream.next()
165                 variables[name.value] = var = parser.parse_expression()
166             else:
167                 variables[name.value] = var = nodes.Name(name.value, 'load')
168             if plural_expr is None:
169                 plural_expr = var
170
171         parser.stream.expect('block_end')
172
173         plural = plural_names = None
174         have_plural = False
175         referenced = set()
176
177         # now parse until endtrans or pluralize
178         singular_names, singular = self._parse_block(parser, True)
179         if singular_names:
180             referenced.update(singular_names)
181             if plural_expr is None:
182                 plural_expr = nodes.Name(singular_names[0], 'load')
183
184         # if we have a pluralize block, we parse that too
185         if parser.stream.current.test('name:pluralize'):
186             have_plural = True
187             parser.stream.next()
188             if parser.stream.current.type is not 'block_end':
189                 plural_expr = parser.parse_expression()
190             parser.stream.expect('block_end')
191             plural_names, plural = self._parse_block(parser, False)
192             parser.stream.next()
193             referenced.update(plural_names)
194         else:
195             parser.stream.next()
196
197         # register free names as simple name expressions
198         for var in referenced:
199             if var not in variables:
200                 variables[var] = nodes.Name(var, 'load')
201
202         # no variables referenced?  no need to escape
203         if not referenced:
204             singular = singular.replace('%%', '%')
205             if plural:
206                 plural = plural.replace('%%', '%')
207
208         if not have_plural:
209             plural_expr = None
210         elif plural_expr is None:
211             parser.fail('pluralize without variables', lineno)
212
213         if variables:
214             variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)
215                                     for x, y in variables.items()])
216         else:
217             variables = None
218
219         node = self._make_node(singular, plural, variables, plural_expr)
220         node.set_lineno(lineno)
221         return node
222
223     def _parse_block(self, parser, allow_pluralize):
224         """Parse until the next block tag with a given name."""
225         referenced = []
226         buf = []
227         while 1:
228             if parser.stream.current.type is 'data':
229                 buf.append(parser.stream.current.value.replace('%', '%%'))
230                 parser.stream.next()
231             elif parser.stream.current.type is 'variable_begin':
232                 parser.stream.next()
233                 name = parser.stream.expect('name').value
234                 referenced.append(name)
235                 buf.append('%%(%s)s' % name)
236                 parser.stream.expect('variable_end')
237             elif parser.stream.current.type is 'block_begin':
238                 parser.stream.next()
239                 if parser.stream.current.test('name:endtrans'):
240                     break
241                 elif parser.stream.current.test('name:pluralize'):
242                     if allow_pluralize:
243                         break
244                     parser.fail('a translatable section can have only one '
245                                 'pluralize section')
246                 parser.fail('control structures in translatable sections are '
247                             'not allowed')
248             else:
249                 assert False, 'internal parser error'
250
251         return referenced, concat(buf)
252
253     def _make_node(self, singular, plural, variables, plural_expr):
254         """Generates a useful node from the data provided."""
255         # singular only:
256         if plural_expr is None:
257             gettext = nodes.Name('gettext', 'load')
258             node = nodes.Call(gettext, [nodes.Const(singular)],
259                               [], None, None)
260
261         # singular and plural
262         else:
263             ngettext = nodes.Name('ngettext', 'load')
264             node = nodes.Call(ngettext, [
265                 nodes.Const(singular),
266                 nodes.Const(plural),
267                 plural_expr
268             ], [], None, None)
269
270         # mark the return value as safe if we are in an
271         # environment with autoescaping turned on
272         if self.environment.autoescape:
273             node = nodes.MarkSafe(node)
274
275         if variables:
276             node = nodes.Mod(node, variables)
277         return nodes.Output([node])
278
279
280 class ExprStmtExtension(Extension):
281     """Adds a `do` tag to Jinja2 that works like the print statement just
282     that it doesn't print the return value.
283     """
284     tags = set(['do'])
285
286     def parse(self, parser):
287         node = nodes.ExprStmt(lineno=parser.stream.next().lineno)
288         node.node = parser.parse_tuple()
289         return node
290
291
292 class LoopControlExtension(Extension):
293     """Adds break and continue to the template engine."""
294     tags = set(['break', 'continue'])
295
296     def parse(self, parser):
297         token = parser.stream.next()
298         if token.value == 'break':
299             return nodes.Break(lineno=token.lineno)
300         return nodes.Continue(lineno=token.lineno)
301
302
303 def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS):
304     """Extract localizable strings from the given template node.
305
306     For every string found this function yields a ``(lineno, function,
307     message)`` tuple, where:
308
309     * ``lineno`` is the number of the line on which the string was found,
310     * ``function`` is the name of the ``gettext`` function used (if the
311       string was extracted from embedded Python code), and
312     *  ``message`` is the string itself (a ``unicode`` object, or a tuple
313        of ``unicode`` objects for functions with multiple string arguments).
314     """
315     for node in node.find_all(nodes.Call):
316         if not isinstance(node.node, nodes.Name) or \
317            node.node.name not in gettext_functions:
318             continue
319
320         strings = []
321         for arg in node.args:
322             if isinstance(arg, nodes.Const) and \
323                isinstance(arg.value, basestring):
324                 strings.append(arg.value)
325             else:
326                 strings.append(None)
327
328         if len(strings) == 1:
329             strings = strings[0]
330         else:
331             strings = tuple(strings)
332         yield node.lineno, node.node.name, strings
333
334
335 def babel_extract(fileobj, keywords, comment_tags, options):
336     """Babel extraction method for Jinja templates.
337
338     :param fileobj: the file-like object the messages should be extracted from
339     :param keywords: a list of keywords (i.e. function names) that should be
340                      recognized as translation functions
341     :param comment_tags: a list of translator tags to search for and include
342                          in the results.  (Unused)
343     :param options: a dictionary of additional options (optional)
344     :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
345              (comments will be empty currently)
346     """
347     extensions = set()
348     for extension in options.get('extensions', '').split(','):
349         extension = extension.strip()
350         if not extension:
351             continue
352         extensions.add(import_string(extension))
353     if InternationalizationExtension not in extensions:
354         extensions.add(InternationalizationExtension)
355
356     environment = get_spontaneous_environment(
357         options.get('block_start_string', BLOCK_START_STRING),
358         options.get('block_end_string', BLOCK_END_STRING),
359         options.get('variable_start_string', VARIABLE_START_STRING),
360         options.get('variable_end_string', VARIABLE_END_STRING),
361         options.get('comment_start_string', COMMENT_START_STRING),
362         options.get('comment_end_string', COMMENT_END_STRING),
363         options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
364         str(options.get('trim_blocks', TRIM_BLOCKS)).lower() in \
365             ('1', 'on', 'yes', 'true'),
366         NEWLINE_SEQUENCE, frozenset(extensions),
367         # fill with defaults so that environments are shared
368         # with other spontaneus environments.  The rest of the
369         # arguments are optimizer, undefined, finalize, autoescape,
370         # loader, cache size and auto reloading setting
371         True, Undefined, None, False, None, 0, False
372     )
373
374     source = fileobj.read().decode(options.get('encoding', 'utf-8'))
375     node = environment.parse(source)
376     for lineno, func, message in extract_from_ast(node, keywords):
377         yield lineno, func, message, []
378
379
380 #: nicer import names
381 i18n = InternationalizationExtension
382 do = ExprStmtExtension
383 loopcontrols = LoopControlExtension