[svn] moved some of the documentation into docstrings
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent 1f57be8 · Browse files · 13 files·+358 added−135 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+358 added−135 removed
- other:+358 added−135 removed
Provenance
- Commit
5a8e497- Tree
804008d- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
1f57be8
13 files changed+358 added−135 removed
modified:docs/src/devintro.txt+2 added-62 removed
25 unmodified lines26 27 The Environment28 ===============29 30-The core component of Jinja is the `Environment`. It contains important shared31-variables like configuration, filters, tests, globals and other stuff.30+[[environment_doc]]31 33-Here the possible initialization parameters:34-35-========================= ==================================================36-`block_start_string` * the string marking the begin of a block. this37- defaults to ``'{%'``.38-`block_end_string` * the string marking the end of a block. defaults39- to ``'%}'``.40-`variable_start_string` * the string marking the begin of a print41- statement. defaults to ``'{{'``.42-`comment_start_string` * the string marking the begin of a43- comment. defaults to ``'{#'``.44-`comment_end_string` * the string marking the end of a comment.45- defaults to ``'#}'``.46-`trim_blocks` * If this is set to ``True`` the first newline47- after a block is removed (block, not48- variable tag!). Defaults to ``False``.49-`auto_escape` If this is set to ``True`` Jinja will50- automatically escape all variables using xml51- escaping methods. If you don't want to escape a52- string you have to wrap it in a ``Markup``53- object from the ``jinja.datastructure`` module.54- If `auto_escape` is ``True`` there will be also55- a ``Markup`` object in the template namespace56- to define partial html fragments. Note that we do57- not recomment this feature, see also the comment58- below.59-`default_filters` list of tuples in the form (``filter_name``,60- ``arguments``) where ``filter_name`` is the61- name of a registered filter and ``arguments``62- a tuple with the filter arguments. The filters63- specified here will always be applied when64- printing data to the template.65- *new in jinja 1.1*66-`template_charset` The charset of the templates. Defaults67- to ``'utf-8'``.68-`charset` Charset of all string input data. Defaults69- to ``'utf-8'``.70-`namespace` Global namespace for all templates.71-`loader` Specify a template loader.72-`filters` dict of filters or the default filters if not73- defined.74-`tests` dict of tests of the default tests if not defined.75-`context_class` the context class this template should use. See76- the `context documentation`_ for more details.77-`silent` set this to `False` if you want to receive errors78- for missing template variables or attributes.79- Defaults to `False`. *new in Jinja 1.1*80-`friendly_traceback` Set this to `False` to disable the developer81- friendly traceback rewriting. Whenever an82- runtime or syntax error occours jinja will try83- to make a developer friendly traceback that shows84- the error in the template line. This however can85- be annoying when debugging broken functions which86- are called from the template. *new in Jinja 1.1*87-========================= ==================================================88-89-All of these variables except those marked with a star (*) are modifiable after90-environment initialization.91-32 The environment provides the following useful functions and properties in33 addition to the initialization values:34 35 =========================== ==================================================77 unmodified lines113 114 115 .. _installation: installation.txt116 .. _context documentation: contextenv.txt177-.. _translators: translators.txt117 .. _loader: loaders.txt118+.. _translators: translators.txt119 .. _filter development: filters.txt120 .. _test development: tests.txtmodified:docs/generate.py+10 added-1 removed
99 unmodified lines100 result.append('`%s`\n%s' % (loader.__name__, '\n'.join(doclines)))101 102 return '\n\n'.join(result)103 104+def generate_environment_doc():105+ from jinja.environment import Environment106+ return '%s\n\n%s' % (107+ inspect.getdoc(Environment),108+ inspect.getdoc(Environment.__init__)109+ )110+111 e = Environment()112 113 PYGMENTS_FORMATTER = HtmlFormatter(style='pastie', cssclass='syntax')114 115 LIST_OF_FILTERS = generate_list_of_filters()116 LIST_OF_TESTS = generate_list_of_tests()117 LIST_OF_LOADERS = generate_list_of_loaders()118+ENVIRONMENT_DOC = generate_environment_doc()119 120 FULL_TEMPLATE = e.from_string('''\121 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"122 "http://www.w3.org/TR/html4/strict.dtd">113 unmodified lines236 def generate_documentation(data, link_style):237 writer = DocumentationWriter(link_style)238 data = data.replace('[[list_of_filters]]', LIST_OF_FILTERS)\239 .replace('[[list_of_tests]]', LIST_OF_TESTS)\232- .replace('[[list_of_loaders]]', LIST_OF_LOADERS)240+ .replace('[[list_of_loaders]]', LIST_OF_LOADERS)\241+ .replace('[[environment_doc]]', ENVIRONMENT_DOC)242 parts = publish_parts(243 data,244 writer=writer,245 settings_overrides={50 unmodified linesmodified:jinja/translators/__init__.py+1 added-2 removed
1 unmodified line2 """3 jinja.translators4 ~~~~~~~~~~~~~~~~~5 6- The submodules of this module provide translators for the jinja ast7- which basically just is the python ast with a few more nodes.6+ The submodules of this module provide translators for the jinja ast.7 8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """19 unmodified linesmodified:jinja/translators/python.py+67 added-16 removed
3 unmodified lines4 ~~~~~~~~~~~~~~~~~~~~~~~~5 6 This module translates a jinja ast into python code.7 8+ This translator tries hard to keep Jinja sandboxed. All security9+ relevant calls are wrapped by methods defined in the environment.10+ This affects:11+12+ - method calls13+ - attribute access14+ - name resolution15+16+ It also adds debug symbols used by the traceback toolkit implemented17+ in `jinja.utils`.18+19 :copyright: 2007 by Armin Ronacher.20 :license: BSD, see LICENSE for more details.21 """22 import re95 unmodified lines118 def __init__(self, environment, node):119 self.environment = environment120 self.node = node121 122+ #: mapping to constants in the environment that are not123+ #: converted to context lookups. this should improve124+ #: performance and avoid accidentally screwing things up125+ #: by rebinding essential constants.126 self.constants = {127 'true': 'True',128 'false': 'False',129 'none': 'None',130 'undefined': 'Undefined'131 }132 133+ #: bind the nodes to the callback functions. There are134+ #: some missing! A few are specified in the `unhandled`135+ #: mapping in order to disallow their usage, some of them136+ #: will not appear in the jinja parser output because137+ #: they are filtered out.138 self.handlers = {139 # jinja nodes140 nodes.Template: self.handle_template,141 nodes.Text: self.handle_template_text,7 unmodified lines149 nodes.Filter: self.handle_filter,150 nodes.Block: self.handle_block,151 nodes.Include: self.handle_include,152 nodes.Trans: self.handle_trans,133- # used python nodes153+ # python nodes154 ast.Name: self.handle_name,155 ast.AssName: self.handle_name,156 ast.Compare: self.handle_compare,157 ast.Const: self.handle_const,19 unmodified lines177 ast.Slice: self.handle_slice,178 ast.Sliceobj: self.handle_sliceobj179 }180 181+ #: mapping of unsupported syntax elements.182+ #: the value represents the feature name that appears183+ #: in the exception.184 self.unsupported = {185 ast.ListComp: 'list comprehensions',186 ast.From: 'imports',187 ast.Import: 'imports',188 }189+190+ #: because of python2.3 compatibility add generator191+ #: expressions only to the list of unused features192+ #: if it exists.193 if hasattr(ast, 'GenExpr'):194 self.unsupported.update({195 ast.GenExpr: 'generator expressions'196 })197 171- self.require_translations = False172-198 # -- public methods199 200 def process(environment, node):201+ """202+ The only public method. Creates a translator instance,203+ translates the code and returns it in form of an204+ `Template` instance.205+ """206 translator = PythonTranslator(environment, node)207 filename = node.filename or '<template>'208 source = translator.translate()179- return Template(environment,180- compile(source, filename, 'exec'))209+ return Template(environment, compile(source, filename, 'exec'))210 process = staticmethod(process)211 212 # -- private helper methods213 214 def indent(self, text):215 """187- Indent the current text.216+ Indent the current text. This does only indent the217+ first line.218 """219 return (' ' * (self.indention * 4)) + text220 221 def nodeinfo(self, node, force=False):43 unmodified lines265 return 'apply_filters(%s, context, %s)' % (s, _to_tuple(filters))266 267 def handle_node(self, node):268 """239- Handle one node269+ Handle one node. Resolves the correct callback functions defined270+ in the callback mapping. This also raises the `TemplateSyntaxError`271+ for unsupported syntax elements such as list comprehensions.272 """273 if node.__class__ in self.handlers:274 out = self.handlers[node.__class__](node)275 elif node.__class__ in self.unsupported:4 unmodified lines280 raise AssertionError('unhandled node %r' % node.__class__)281 return out282 283 def reset(self):284+ """285+ Reset translation variables such as indention, cycle id286+ or the require_translations flag.287+ """288 self.indention = 0289 self.last_cycle_id = 0290+ self.require_translations = False291 292 def translate(self):293+ """294+ Translate the node defined in the constructor after295+ resetting the translator.296+ """297 self.reset()298 return self.handle_node(self.node)299 300 # -- jinja nodes116 unmodified lines417 dict_lines.append(' %r: %s' % (418 str(name),419 _to_tuple(tmp)420 ))421+422+ # blocks must always be defined. even if it's empty. some423+ # features depend on it424 lines.append('\nblocks = {\n%s\n}' % ',\n'.join(dict_lines))425 426 # now get the real source lines and map the debugging symbols427 debug_mapping = []54 unmodified lines482 )483 484 # simple loops485 else:442- write('context[\'loop\'] = loop = LoopContext(%s, context[\'loop\'], None)' %443- self.handle_node(node.seq))486+ write('context[\'loop\'] = loop = LoopContext(%s, '487+ 'context[\'loop\'], None)' % self.handle_node(node.seq))488 write('for %s in loop:' %489 self.handle_node(node.item)490 )491 20 unmodified lines512 write('if False:')513 self.indention += 1514 write('yield None')515 self.indention -= 2472- write('context[\'loop\'] = LoopContext(None, context[\'loop\'], buffereater(forloop))')516+ write('context[\'loop\'] = LoopContext(None, context[\'loop\'], '517+ 'buffereater(forloop))')518 write('for item in forloop(%s):' % self.handle_node(node.seq))519 self.indention += 1520 write('yield item')521 self.indention -= 148 unmodified lines570 hardcoded = False571 self.indention -= 1572 573 if hardcoded:529- write('yield finish_var(context.current[%r].cycle(), context)' % name)574+ write('yield finish_var(context.current[%r].cycle(), '575+ 'context)' % name)576 else:531- write('yield finish_var(context.current[%r].cycle(%s), context)' % (577+ write('yield finish_var(context.current[%r].cycle(%s), '578+ 'context)' % (579 name,580 self.handle_node(node.seq)581 ))582 21 unmodified lines604 if node.arguments:605 write('argcount = len(args)')606 tmp = []607 for idx, (name, n) in enumerate(node.arguments):561- tmp.append('\'%s\': (argcount > %d and (args[%d],) or (%s,))[0]' % (608+ tmp.append('\'%s\': (argcount > %d and (args[%d],) '609+ 'or (%s,))[0]' % (610 name,611 idx,612 idx,613 n is None and 'Undefined' or self.handle_node(n)8 unmodified lines622 write('if False:')623 self.indention += 1624 write('yield False')625 self.indention -= 2578- buf.append(self.indent('context[%r] = buffereater(macro)' % node.name))626+ buf.append(self.indent('context[%r] = buffereater(macro)' %627+ node.name))628 629 return '\n'.join(buf)630 631 def handle_set(self, node):21 unmodified lines653 write('if False:')654 self.indention += 1655 write('yield None')656 self.indention -= 2608- write('yield %s' % self.filter('u\'\'.join(filtered())', node.filters))657+ write('yield %s' % self.filter('u\'\'.join(filtered())',658+ node.filters))659 return '\n'.join(buf)660 661 def handle_block(self, node, level=0):662 """176 unmodified lines839 kwargs[arg.name] = self.handle_node(arg.expr)840 else:841 args.append(self.handle_node(arg))842 if not (args or kwargs or star_args or dstar_args):793- return 'call_function_simple(%s, context)' % self.handle_node(node.node)843+ return 'call_function_simple(%s, context)' % \844+ self.handle_node(node.node)845 return 'call_function(%s, context, %s, {%s}, %s, %s)' % (846 self.handle_node(node.node),847 _to_tuple(args),848 ', '.join(['%r: %s' % i for i in kwargs.iteritems()]),138 unmodified linesmodified:jinja/datastructure.py+72 added-20 removed
42 unmodified lines43 """44 __slots__ = ()45 46 def __init__(self):47- try:48- Undefined49- except NameError:50- pass51- else:52- raise TypeError('cannot create %r instances' %53- self.__class__.__name__)47+ raise TypeError('cannot create %r instances' %48+ self.__class__.__name__)49 50+ def __add__(self, other):51+ """Any operator returns the operand."""52+ return other55- __sub__ = __mul__ = __div__ = __rsub__ = __rmul__ = __div__ = __radd__ = \56- __add__ = lambda self, other: other53+ __sub__ = __mul__ = __div__ = __rsub__ = __rmul__ = __div__ = __mod__ =\54+ __radd__ = __rmod__ = __add__55 56 def __getitem__(self, arg):57+ """Getting any item returns `Undefined`"""58 return self59 60 def __iter__(self):61+ """Iterating over `Undefined` returns an empty iterator."""62 if False:63 yield None64 65 def __getattr__(self, arg):66+ """Getting any attribute returns `Undefined`"""67 return self68 69 def __nonzero__(self):70+ """`Undefined` is considered boolean `False`"""71 return False72 73 def __len__(self):74+ """`Undefined` is an empty sequence"""75 return 076 77 def __str__(self):78+ """The string representation is empty."""79 return ''80 81 def __unicode__(self):82+ """The unicode representation is empty."""83 return u''84 85+ def __repr__(self):86+ """The representation is ``'Undefined'``"""87+ return 'Undefined'88+89 def __int__(self):90+ """Converting `Undefined` to an integer ends up in ``0``"""91 return 092 93 def __float__(self):94+ """Converting `Undefined` to an float ends up in ``0.0``"""95 return 0.096 97 def __eq__(self, other):98+ """`Undefined` is not equal to anything else."""99 return False100 101 def __ne__(self, other):102+ """`Undefined` is not equal to anything else."""103 return True104 105 def __call__(self, *args, **kwargs):106+ """Calling `Undefined` returns `Undefined`"""107 return self108 109+ def __copy__(self):110+ """Return a copy."""111+ return self112 96-Undefined = UndefinedType()113+ def __deepcopy__(self, memo):114+ """Return a deepcopy."""115+ return self116 117+ def __reduce__(self):118+ """Helper for pickle."""119+ return 'Undefined'120 121+122+#: the singleton instance of UndefinedType123+Undefined = object.__new__(UndefinedType)124+125+126 class FakeTranslator(object):127 """128 Default null translator.129 """130 131 def gettext(self, s):132+ """133+ Translate a singular string.134+ """135 return s136 137 def ngettext(self, s, p, n):138+ """139+ Translate a plural string.140+ """141 if n == 1:142 return s143 return p144 40 unmodified lines185 # cache object used for filters and tests186 self.cache = {}187 188 def pop(self):156- """Pop the last layer from the stack and return it."""189+ """190+ Pop the last layer from the stack and return it.191+ """192 rv = self._stack.pop()193 self.current = self._stack[-1]194 return rv195 196 def push(self, data=None):162- """Push a new dict or empty layer to the stack and return that layer"""197+ """198+ Push a new dict or empty layer to the stack and return that layer199+ """200 data = data or {}201 self._stack.append(data)202 self.current = self._stack[-1]203 return data204 205 def to_dict(self):169- """Convert the context into a dict. This skips the globals."""206+ """207+ Convert the context into a dict. This skips the globals.208+ """209 result = {}210 for layer in self._stack[1:]:211 for key, value in layer.iteritems():212 if key.startswith('::'):1 unmodified line214 result[key] = value215 return result216 217 def __getitem__(self, name):218+ """219+ Resolve one item. Restrict the access to internal variables220+ such as ``'::cycle1'``. Resolve deferreds.221+ """222 if not name.startswith('::'):223 # because the stack is usually quite small we better use [::-1]224 # which is faster than reversed() somehow.225 for d in self._stack[::-1]:11 unmodified lines237 return Undefined238 raise TemplateRuntimeError('%r is not defined' % name)239 240 def __setitem__(self, name, value):241+ """242+ Set a variable in the outermost layer.243+ """244 self.current[name] = value245 246 def __delitem__(self, name):247+ """248+ Delete an variable in the outermost layer.249+ """250 if name in self.current:251 del self.current[name]252 253 def __contains__(self, name):254+ """255+ Check if the context contains a given variable.256+ """257 for layer in self._stack:258 if name in layer:259 return True260 return False261 262 def __repr__(self):211- tmp = {}212- for d in self._stack:213- for key, value in d.iteritems():214- tmp[key] = value215- return 'Context(%s)' % repr(tmp)263+ """264+ String representation of the context.265+ """266+ return 'Context(%r)' % self.to_dict()267 268 269 class LoopContext(object):270 """128 unmodified lines399 it supports pushing tokens back to the stream.400 """401 402 def __init__(self, generator):352- self._generator = generator403+ self._next = generator.next404 self._pushed = []405 self.last = (1, 'initial', '')406 407 def __iter__(self):408+ """Return self in order to mark this is iterator."""409 return self410 411 def __nonzero__(self):412 """Are we at the end of the tokenstream?"""11 unmodified lines424 """Return the next token from the stream."""425 if self._pushed:426 rv = self._pushed.pop()427 else:376- rv = self._generator.next()428+ rv = self._next()429 self.last = rv430 return rv431 432 def look(self):28 unmodified linesmodified:jinja/defaults.py+3 added
12 unmodified lines13 from jinja.utils import debug_context, safe_range, generate_lorem_ipsum, \14 watch_changes15 16 17+__all__ = ['DEFAULT_FILTERS', 'DEFAULT_TESTS', 'DEFAULT_NAMESPACE']18+19+20 DEFAULT_NAMESPACE = {21 'range': safe_range,22 'debug': debug_context,23 'lipsum': generate_lorem_ipsum,2 unmodified linesmodified:jinja/environment.py+88 added-5 removed
17 unmodified lines18 SecurityException, TemplateSyntaxError, TemplateRuntimeError19 from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE20 21 22+__all__ = ['Environment']23+24+25 class Environment(object):26 """27 The jinja environment.28+29+ The core component of Jinja is the `Environment`. It contains30+ important shared variables like configuration, filters, tests,31+ globals and others.32 """33 34 def __init__(self,35 block_start_string='{%',13 unmodified lines49 tests=None,50 context_class=Context,51 silent=True,52 friendly_traceback=True):53+ """54+ Here the possible initialization parameters:55 56+ ========================= ============================================57+ `block_start_string` * the string marking the begin of a block.58+ this defaults to ``'{%'``.59+ `block_end_string` * the string marking the end of a block.60+ defaults to ``'%}'``.61+ `variable_start_string` * the string marking the begin of a print62+ statement. defaults to ``'{{'``.63+ `comment_start_string` * the string marking the begin of a64+ comment. defaults to ``'{#'``.65+ `comment_end_string` * the string marking the end of a comment.66+ defaults to ``'#}'``.67+ `trim_blocks` * If this is set to ``True`` the first newline68+ after a block is removed (block, not69+ variable tag!). Defaults to ``False``.70+ `auto_escape` If this is set to ``True`` Jinja will71+ automatically escape all variables using xml72+ escaping methods. If you don't want to73+ escape a string you have to wrap it in a74+ ``Markup`` object from the75+ ``jinja.datastructure`` module. If76+ `auto_escape` is ``True`` there will be also77+ a ``Markup`` object in the template78+ namespace to define partial html fragments.79+ Note that we do not recomment this feature.80+ `default_filters` list of tuples in the form (``filter_name``,81+ ``arguments``) where ``filter_name`` is the82+ name of a registered filter and83+ ``arguments`` a tuple with the filter84+ arguments. The filters specified here will85+ always be applied when printing data to the86+ template. *new in Jinja 1.1*87+ `template_charset` The charset of the templates. Defaults88+ to ``'utf-8'``.89+ `charset` Charset of all string input data. Defaults90+ to ``'utf-8'``.91+ `namespace` Global namespace for all templates.92+ `loader` Specify a template loader.93+ `filters` dict of filters or the default filters if94+ not defined.95+ `tests` dict of tests of the default tests if not96+ defined.97+ `context_class` the context class this template should use.98+ See the `Context` documentation for more99+ details.100+ `silent` set this to `False` if you want to receive101+ errors for missing template variables or102+ attributes. Defaults to `False`. *new in103+ Jinja 1.1*104+ `friendly_traceback` Set this to `False` to disable the developer105+ friendly traceback rewriting. Whenever an106+ runtime or syntax error occours jinja will107+ try to make a developer friendly traceback108+ that shows the error in the template line.109+ This however can be annoying when debugging110+ broken functions that are called from the111+ template. *new in Jinja 1.1*112+ ========================= ============================================113+114+ All of these variables except those marked with a star (*) are115+ modifiable after environment initialization.116+ """117+118 # lexer / parser information119 self.block_start_string = block_start_string120 self.block_end_string = block_end_string121 self.variable_start_string = variable_start_string29 unmodified lines151 """152 Get or set the template loader.153 """154 self._loader = LoaderWrapper(self, value)84- loader = property(lambda s: s._loader, loader, loader.__doc__)155+ loader = property(lambda s: s._loader, loader, doc=loader.__doc__)156 157 def parse(self, source, filename=None):87- """Function that creates a new parser and parses the source."""158+ """159+ Parse the sourcecode and return the abstract syntax tree. This tree160+ of nodes is used by the `translators`_ to convert the template into161+ executable source- or bytecode.162+163+ .. _translators: translators.txt164+ """165 parser = Parser(self, source, filename)166 return parser.parse()167 168 def from_string(self, source):92- """Load a template from a string."""169+ """170+ Load and parse a template source and translate it into eval-able171+ Python code. This code is wrapped within a `Template` class that172+ allows you to render it.173+ """174 from jinja.parser import Parser175 from jinja.translators.python import PythonTranslator176 try:177 rv = PythonTranslator.process(self, Parser(self, source).parse())10 unmodified lines188 rv._source = source189 return rv190 191 def get_template(self, filename):111- """Load a template from a filename. Only works112- if a proper loader is set."""192+ """193+ Load a template from a loader. If the template does not exist, you194+ will get a `TemplateNotFound` exception.195+ """196 return self._loader.load(filename)197 198 def to_unicode(self, value):199 """127 unmodified linesmodified:jinja/filters.py+11 added-5 removed
267 unmodified lines268 def wrapped(env, context, seq):269 try:270 return iter(seq).next()271 except StopIteration:272+ if env.silent:272- return Undefined273+ return Undefined274+ raise TemplateRuntimeError('%r is empty' % seq)275 return wrapped276 277 278 def do_last():2 unmodified lines281 """282 def wrapped(env, context, seq):283 try:284 return iter(_reversed(seq)).next()283- except (TypeError, StopIteration):284- return Undefined285+ except StopIteration:286+ if env.silent:287+ return Undefined288+ raise TemplateRuntimeError('%r is empty' % seq)289 return wrapped290 291 292 def do_random():2 unmodified lines295 """296 def wrapped(env, context, seq):297 try:298 return choice(seq)295- except:296- return Undefined299+ except IndexError:300+ if env.silent:301+ return Undefined302+ raise TemplateRuntimeError('%r is empty' % seq)303 return wrapped304 305 306 def do_urlencode():350 unmodified linesmodified:jinja/lexer.py+22 added-3 removed
1 unmodified line2 """3 jinja.lexer4 ~~~~~~~~~~~5 6+ This module implements a Jinja / Python combination lexer. The7+ `Lexer` class provided by this module is used to do some preprocessing8+ for Jinja.9+10+ On the one hand it filters out invalid operators like the bitshift11+ operators we don't allow in templates. On the other hand it separates12+ template code and python code in expressions.13+14+ Because of some limitations in the compiler package which are just15+ natural but annoying for Jinja, the lexer also "escapes" non names that16+ are not keywords. The Jinja parser then removes those escaping marks17+ again.18+19+ This is required in order to make "class" and some other python keywords20+ we don't use valid identifiers.21+22 :copyright: 2007 by Armin Ronacher.23 :license: BSD, see LICENSE for more details.24 """25 import re5 unmodified lines31 except NameError:32 from sets import Set as set33 34 35+__all__ = ['Lexer', 'Failure', 'keywords']36+37+38 # static regular expressions39 whitespace_re = re.compile(r'\s+(?m)')40 name_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*')41 string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"131 unmodified lines173 back to the stream. That's for example done by the parser.174 175 Additionally non keywords are escaped.176 """158- def filter():177+ def generate():178 for lineno, token, value in self.tokeniter(source):179 if token == 'name' and value not in keywords:180 value += '_'181 yield lineno, token, value163- return TokenStream(filter())182+ return TokenStream(generate())183 184 def tokeniter(self, source):185 """186 This method tokenizes the text and returns the tokens in a generator.1 unmodified line188 you get is not compatible with the input the jinja parser wants. The189 parser uses the `tokenize` function with returns a `TokenStream` with190 some escaped tokens.191 """173- source = type(source)('\n').join(source.splitlines())192+ source = '\n'.join(source.splitlines())193 pos = 0194 lineno = 1195 stack = ['root']196 statetokens = self.rules['root']89 unmodified linesmodified:jinja/nodes.py+5 added-1 removed
1 unmodified line2 """3 jinja.nodes4 ~~~~~~~~~~~5 6- Additional nodes for Jinja. Look like nodes from the ast.6+ This module implements additional nodes derived from the ast base node.7 8+ It also provides some node tree helper functions like `in_lineno` and9+ `get_nodes` used by the parser and translator in order to normalize10+ python and jinja nodes.11+12 :copyright: 2007 by Armin Ronacher.13 :license: BSD, see LICENSE for more details.14 """15 from compiler import ast338 unmodified linesmodified:jinja/parser.py+12 added-18 removed
3 unmodified lines4 ~~~~~~~~~~~~5 6 Implements the template parser.7 8+ The Jinja template parser is not a real parser but a combination of the9+ python compiler package and some postprocessing. The tokens yielded by10+ the lexer are used to separate template data and expressions. The11+ expression tokens are then converted into strings again and processed12+ by the python parser.13+14 :copyright: 2007 by Armin Ronacher.15 :license: BSD, see LICENSE for more details.16 """17 import re7 unmodified lines25 except NameError:26 from sets import Set as set27 28 29+__all__ = ['Parser']30+31+32 # callback functions for the subparse method33 end_of_block = lambda p, t, d: t == 'block_end'34 end_of_variable = lambda p, t, d: t == 'variable_end'35 end_of_comment = lambda p, t, d: t == 'comment_end'6 unmodified lines42 end_of_block_tag = lambda p, t, d: t == 'name' and d == 'endblock'43 end_of_trans = lambda p, t, d: t == 'name' and d == 'endtrans'44 45 37-string_inc_re = re.compile(r'(?:[^\d]*(\d+)[^\d]*)+')38-39-40-def inc_string(s):41- """42- Increment a string43- """44- m = string_inc_re.search(s)45- if m:46- next = str(int(m.group(1)) + 1)47- start, end = m.span(1)48- s = s[:max(end - len(next), start)] + next + s[end:]49- else:50- name, ext = s.rsplit('.', 1)51- return '%s2.%s' % (name, ext)52- return s53-54-46 class Parser(object):47 """48 The template parser class.49 7 unmodified lines57 self.source = source58 self.filename = filename59 self.tokenstream = environment.lexer.tokenize(source)60 61+ #: if this template has a parent template it's stored here62+ #: after parsing63 self.extends = None64+ #: set for blocks in order to keep them unique65 self.blocks = set()66 67 self.directives = {68 'raw': self.handle_raw_directive,569 unmodified linesmodified:jinja/utils.py+58 added-1 removed
19 unmodified lines20 from jinja.nodes import Trans21 from jinja.datastructure import Context, TemplateData22 from jinja.exceptions import SecurityException, TemplateNotFound23 24+#: the python2.4 version of deque is missing the remove method25+#: because a for loop with a lookup for the missing value written26+#: in python is slower we just use deque if we have python2.5 or higher27 if sys.version_info >= (2, 5):28 from collections import deque29 else:30 deque = None287 unmodified lines318 319 320 def collect_translations(ast):321 """319- Collect all translatable strings for the given ast.322+ Collect all translatable strings for the given ast. The323+ return value is a list of tuples in the form ``(lineno, singular,324+ plural)``. If a translation doesn't require a plural form the325+ third item is `None`.326 """327 todo = [ast]328 result = []329 while todo:103 unmodified lines433 self._remove = self._queue.remove434 self._append = self._queue.append435 436 def copy(self):437+ """438+ Return an shallow copy of the instance.439+ """440 rv = CacheDict(self.capacity)441 rv._mapping.update(self._mapping)442 rv._queue = self._queue[:]443 return rv444 445 def get(self, key, default=None):446+ """447+ Return an item from the cache dict or `default`448+ """449 if key in self:450 return self[key]451 return default452 453 def setdefault(self, key, default=None):454+ """455+ Set `default` if the key is not in the cache otherwise456+ leave unchanged. Return the value of this key.457+ """458 if key in self:459 return self[key]460 self[key] = default461 return default462 463 def clear(self):464+ """465+ Clear the cache dict.466+ """467 self._mapping.clear()468 try:469 self._queue.clear()470 except AttributeError:471 del self._queue[:]472 473 def __contains__(self, key):474+ """475+ Check if a key exists in this cache dict.476+ """477 return key in self._mapping478 479 def __len__(self):480+ """481+ Return the current size of the cache dict.482+ """483 return len(self._mapping)484 485 def __repr__(self):486 return '<%s %r>' % (1 unmodified line488 self._mapping489 )490 491 def __getitem__(self, key):492+ """493+ Get an item from the cache dict. Moves the item up so that494+ it has the highest priority then.495+496+ Raise an `KeyError` if it does not exist.497+ """498 rv = self._mapping[key]499 if self._queue[-1] != key:500 self._remove(key)501 self._append(key)502 return rv503 504 def __setitem__(self, key, value):505+ """506+ Sets the value for an item. Moves the item up so that it507+ has the highest priority then.508+ """509 if key in self._mapping:510 self._remove(key)511 elif len(self._mapping) == self.capacity:512 del self._mapping[self._popleft()]513 self._append(key)514 self._mapping[key] = value515 516 def __delitem__(self, key):517+ """518+ Remove an item from the cache dict.519+ Raise an `KeyError` if it does not exist.520+ """521 del self._mapping[key]522 self._remove(key)523 524 def __iter__(self):525+ """526+ Iterate over all values in the cache dict, ordered by527+ the most recent usage.528+ """529 try:530 return reversed(self._queue)531 except NameError:532 return iter(self._queue[::-1])533 534 def __reversed__(self):535+ """536+ Iterate over the values in the cache dict, oldest items537+ coming first.538+ """539 return iter(self._queue)540 541 __copy__ = copy542+543+ def __deepcopy__(self):544+ """545+ Return a deep copy of the cache dict.546+ """547+ from copy import deepcopy548+ rv = CacheDict(self.capacity)549+ rv._mapping = deepcopy(self._mapping)550+ rv._queue = deepcopy(self._queue)551+ return rvmodified:CHANGES+7 added-1 removed
13 unmodified lines14 - some small bugfixes.15 16 - improved security system regarding function calls.17 18-- added `lipsum` function18+- added `lipsum` function to generate random text.19 20 - strings without unicode characters are processed as binary strings now21 to workaround problems with `datetime.strftime` which only accepts22 binary strings.1 unmodified line24 - developer friendly traceback is now toggleable25 26 - silent variable name failure is now toggleable27 28+- fixed issue with old-style classes not implementing `__getitem__`29+ (thanks to Axel Böhm for discovering that bug)30 31+- added a bunch of new docstrings to the Jinja classes. Makes fun now to32+ use pydoc :-)33+34+35 Version 1.036 -----------37 (released Mar 23, 2007)38 1 unmodified line