ext.py
This file
Path
src/jinja2/ext.py
844 lines · 30.4 KiB · Python
Last changed by
drop end of life python versions (#2096)David Lordbefore adoption49c48a0
History of this fileTake it
1"""Extension API for adding custom tags and behavior."""23import pprint4import re5import typing as t67from markupsafe import Markup89from . import defaults10from . import nodes11from .environment import Environment12from .exceptions import TemplateAssertionError13from .exceptions import TemplateSyntaxError14from .runtime import concat # type: ignore15from .runtime import Context16from .runtime import Undefined17from .utils import import_string18from .utils import pass_context1920if t.TYPE_CHECKING:21 import typing_extensions as te2223 from .lexer import Token24 from .lexer import TokenStream25 from .parser import Parser2627 class _TranslationsBasic(te.Protocol):28 def gettext(self, message: str) -> str: ...2930 def ngettext(self, singular: str, plural: str, n: int) -> str:31 pass3233 class _TranslationsContext(_TranslationsBasic):34 def pgettext(self, context: str, message: str) -> str: ...3536 def npgettext(37 self, context: str, singular: str, plural: str, n: int38 ) -> str: ...3940 _SupportedTranslations = _TranslationsBasic | _TranslationsContext414243# I18N functions available in Jinja templates. If the I18N library44# provides ugettext, it will be assigned to gettext.45GETTEXT_FUNCTIONS: tuple[str, ...] = (46 "_",47 "gettext",48 "ngettext",49 "pgettext",50 "npgettext",51)52_ws_re = re.compile(r"\s*\n\s*")535455class Extension:56 """Extensions can be used to add extra functionality to the Jinja template57 system at the parser level. Custom extensions are bound to an environment58 but may not store environment specific data on `self`. The reason for59 this is that an extension can be bound to another environment (for60 overlays) by creating a copy and reassigning the `environment` attribute.6162 As extensions are created by the environment they cannot accept any63 arguments for configuration. One may want to work around that by using64 a factory function, but that is not possible as extensions are identified65 by their import name. The correct way to configure the extension is66 storing the configuration values on the environment. Because this way the67 environment ends up acting as central configuration storage the68 attributes may clash which is why extensions have to ensure that the names69 they choose for configuration are not too generic. ``prefix`` for example70 is a terrible name, ``fragment_cache_prefix`` on the other hand is a good71 name as includes the name of the extension (fragment cache).72 """7374 identifier: t.ClassVar[str]7576 def __init_subclass__(cls) -> None:77 cls.identifier = f"{cls.__module__}.{cls.__name__}"7879 #: if this extension parses this is the list of tags it's listening to.80 tags: set[str] = set()8182 #: the priority of that extension. This is especially useful for83 #: extensions that preprocess values. A lower value means higher84 #: priority.85 #:86 #: .. versionadded:: 2.487 priority = 1008889 def __init__(self, environment: Environment) -> None:90 self.environment = environment9192 def bind(self, environment: Environment) -> "te.Self":93 """Create a copy of this extension bound to another environment."""94 rv = object.__new__(self.__class__)95 rv.__dict__.update(self.__dict__)96 rv.environment = environment97 return rv9899 def preprocess(100 self, source: str, name: str | None, filename: str | None = None101 ) -> str:102 """This method is called before the actual lexing and can be used to103 preprocess the source. The `filename` is optional. The return value104 must be the preprocessed source.105 """106 return source107108 def filter_stream(109 self, stream: "TokenStream"110 ) -> t.Union["TokenStream", t.Iterable["Token"]]:111 """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used112 to filter tokens returned. This method has to return an iterable of113 :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a114 :class:`~jinja2.lexer.TokenStream`.115 """116 return stream117118 def parse(self, parser: "Parser") -> nodes.Node | list[nodes.Node]:119 """If any of the :attr:`tags` matched this method is called with the120 parser as first argument. The token the parser stream is pointing at121 is the name token that matched. This method has to return one or a122 list of multiple nodes.123 """124 raise NotImplementedError()125126 def attr(self, name: str, lineno: int | None = None) -> nodes.ExtensionAttribute:127 """Return an attribute node for the current extension. This is useful128 to pass constants on extensions to generated template code.129130 ::131132 self.attr('_my_attribute', lineno=lineno)133 """134 return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)135136 def call_method(137 self,138 name: str,139 args: list[nodes.Expr] | None = None,140 kwargs: list[nodes.Keyword] | None = None,141 dyn_args: nodes.Expr | None = None,142 dyn_kwargs: nodes.Expr | None = None,143 lineno: int | None = None,144 ) -> nodes.Call:145 """Call a method of the extension. This is a shortcut for146 :meth:`attr` + :class:`jinja2.nodes.Call`.147 """148 if args is None:149 args = []150 if kwargs is None:151 kwargs = []152 return nodes.Call(153 self.attr(name, lineno=lineno),154 args,155 kwargs,156 dyn_args,157 dyn_kwargs,158 lineno=lineno,159 )160161162@pass_context163def _gettext_alias(164 __context: Context, *args: t.Any, **kwargs: t.Any165) -> t.Any | Undefined:166 return __context.call(__context.resolve("gettext"), *args, **kwargs)167168169def _make_new_gettext(func: t.Callable[[str], str]) -> t.Callable[..., str]:170 @pass_context171 def gettext(__context: Context, __string: str, **variables: t.Any) -> str:172 rv = __context.call(func, __string)173 if __context.eval_ctx.autoescape:174 rv = Markup(rv)175 # Always treat as a format string, even if there are no176 # variables. This makes translation strings more consistent177 # and predictable. This requires escaping178 return rv % variables # type: ignore179180 return gettext181182183def _make_new_ngettext(func: t.Callable[[str, str, int], str]) -> t.Callable[..., str]:184 @pass_context185 def ngettext(186 __context: Context,187 __singular: str,188 __plural: str,189 __num: int,190 **variables: t.Any,191 ) -> str:192 variables.setdefault("num", __num)193 rv = __context.call(func, __singular, __plural, __num)194 if __context.eval_ctx.autoescape:195 rv = Markup(rv)196 # Always treat as a format string, see gettext comment above.197 return rv % variables # type: ignore198199 return ngettext200201202def _make_new_pgettext(func: t.Callable[[str, str], str]) -> t.Callable[..., str]:203 @pass_context204 def pgettext(205 __context: Context, __string_ctx: str, __string: str, **variables: t.Any206 ) -> str:207 variables.setdefault("context", __string_ctx)208 rv = __context.call(func, __string_ctx, __string)209210 if __context.eval_ctx.autoescape:211 rv = Markup(rv)212213 # Always treat as a format string, see gettext comment above.214 return rv % variables # type: ignore215216 return pgettext217218219def _make_new_npgettext(220 func: t.Callable[[str, str, str, int], str],221) -> t.Callable[..., str]:222 @pass_context223 def npgettext(224 __context: Context,225 __string_ctx: str,226 __singular: str,227 __plural: str,228 __num: int,229 **variables: t.Any,230 ) -> str:231 variables.setdefault("context", __string_ctx)232 variables.setdefault("num", __num)233 rv = __context.call(func, __string_ctx, __singular, __plural, __num)234235 if __context.eval_ctx.autoescape:236 rv = Markup(rv)237238 # Always treat as a format string, see gettext comment above.239 return rv % variables # type: ignore240241 return npgettext242243244class InternationalizationExtension(Extension):245 """This extension adds gettext support to Jinja."""246247 tags = {"trans"}248249 # TODO: the i18n extension is currently reevaluating values in a few250 # situations. Take this example:251 # {% trans count=something() %}{{ count }} foo{% pluralize252 # %}{{ count }} fooss{% endtrans %}253 # something is called twice here. One time for the gettext value and254 # the other time for the n-parameter of the ngettext function.255256 def __init__(self, environment: Environment) -> None:257 super().__init__(environment)258 environment.globals["_"] = _gettext_alias259 environment.extend(260 install_gettext_translations=self._install,261 install_null_translations=self._install_null,262 install_gettext_callables=self._install_callables,263 uninstall_gettext_translations=self._uninstall,264 extract_translations=self._extract,265 newstyle_gettext=False,266 )267268 def _install(269 self, translations: "_SupportedTranslations", newstyle: bool | None = None270 ) -> None:271 # ugettext and ungettext are preferred in case the I18N library272 # is providing compatibility with older Python versions.273 gettext = getattr(translations, "ugettext", None)274 if gettext is None:275 gettext = translations.gettext276 ngettext = getattr(translations, "ungettext", None)277 if ngettext is None:278 ngettext = translations.ngettext279280 pgettext = getattr(translations, "pgettext", None)281 npgettext = getattr(translations, "npgettext", None)282 self._install_callables(283 gettext, ngettext, newstyle=newstyle, pgettext=pgettext, npgettext=npgettext284 )285286 def _install_null(self, newstyle: bool | None = None) -> None:287 import gettext288289 translations = gettext.NullTranslations()290 self._install_callables(291 gettext=translations.gettext,292 ngettext=translations.ngettext,293 newstyle=newstyle,294 pgettext=translations.pgettext,295 npgettext=translations.npgettext,296 )297298 def _install_callables(299 self,300 gettext: t.Callable[[str], str],301 ngettext: t.Callable[[str, str, int], str],302 newstyle: bool | None = None,303 pgettext: t.Callable[[str, str], str] | None = None,304 npgettext: t.Callable[[str, str, str, int], str] | None = None,305 ) -> None:306 if newstyle is not None:307 self.environment.newstyle_gettext = newstyle # type: ignore308 if self.environment.newstyle_gettext: # type: ignore309 gettext = _make_new_gettext(gettext)310 ngettext = _make_new_ngettext(ngettext)311312 if pgettext is not None:313 pgettext = _make_new_pgettext(pgettext)314315 if npgettext is not None:316 npgettext = _make_new_npgettext(npgettext)317318 self.environment.globals.update(319 gettext=gettext, ngettext=ngettext, pgettext=pgettext, npgettext=npgettext320 )321322 def _uninstall(self, translations: "_SupportedTranslations") -> None:323 for key in ("gettext", "ngettext", "pgettext", "npgettext"):324 self.environment.globals.pop(key, None)325326 def _extract(327 self,328 source: str | nodes.Template,329 gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,330 ) -> t.Iterator[tuple[int, str, str | None | tuple[str | None, ...]]]:331 if isinstance(source, str):332 source = self.environment.parse(source)333 return extract_from_ast(source, gettext_functions)334335 def parse(self, parser: "Parser") -> nodes.Node | list[nodes.Node]:336 """Parse a translatable tag."""337 lineno = next(parser.stream).lineno338339 context = None340 context_token = parser.stream.next_if("string")341342 if context_token is not None:343 context = context_token.value344345 # find all the variables referenced. Additionally a variable can be346 # defined in the body of the trans block too, but this is checked at347 # a later state.348 plural_expr: nodes.Expr | None = None349 plural_expr_assignment: nodes.Assign | None = None350 num_called_num = False351 variables: dict[str, nodes.Expr] = {}352 trimmed = None353 while parser.stream.current.type != "block_end":354 if variables:355 parser.stream.expect("comma")356357 # skip colon for python compatibility358 if parser.stream.skip_if("colon"):359 break360361 token = parser.stream.expect("name")362 if token.value in variables:363 parser.fail(364 f"translatable variable {token.value!r} defined twice.",365 token.lineno,366 exc=TemplateAssertionError,367 )368369 # expressions370 if parser.stream.current.type == "assign":371 next(parser.stream)372 variables[token.value] = var = parser.parse_expression()373 elif trimmed is None and token.value in ("trimmed", "notrimmed"):374 trimmed = token.value == "trimmed"375 continue376 else:377 variables[token.value] = var = nodes.Name(token.value, "load")378379 if plural_expr is None:380 if isinstance(var, nodes.Call):381 plural_expr = nodes.Name("_trans", "load")382 variables[token.value] = plural_expr383 plural_expr_assignment = nodes.Assign(384 nodes.Name("_trans", "store"), var385 )386 else:387 plural_expr = var388 num_called_num = token.value == "num"389390 parser.stream.expect("block_end")391392 plural = None393 have_plural = False394 referenced = set()395396 # now parse until endtrans or pluralize397 singular_names, singular = self._parse_block(parser, True)398 if singular_names:399 referenced.update(singular_names)400 if plural_expr is None:401 plural_expr = nodes.Name(singular_names[0], "load")402 num_called_num = singular_names[0] == "num"403404 # if we have a pluralize block, we parse that too405 if parser.stream.current.test("name:pluralize"):406 have_plural = True407 next(parser.stream)408 if parser.stream.current.type != "block_end":409 token = parser.stream.expect("name")410 if token.value not in variables:411 parser.fail(412 f"unknown variable {token.value!r} for pluralization",413 token.lineno,414 exc=TemplateAssertionError,415 )416 plural_expr = variables[token.value]417 num_called_num = token.value == "num"418 parser.stream.expect("block_end")419 plural_names, plural = self._parse_block(parser, False)420 next(parser.stream)421 referenced.update(plural_names)422 else:423 next(parser.stream)424425 # register free names as simple name expressions426 for name in referenced:427 if name not in variables:428 variables[name] = nodes.Name(name, "load")429430 if not have_plural:431 plural_expr = None432 elif plural_expr is None:433 parser.fail("pluralize without variables", lineno)434435 if trimmed is None:436 trimmed = self.environment.policies["ext.i18n.trimmed"]437 if trimmed:438 singular = self._trim_whitespace(singular)439 if plural:440 plural = self._trim_whitespace(plural)441442 node = self._make_node(443 singular,444 plural,445 context,446 variables,447 plural_expr,448 bool(referenced),449 num_called_num and have_plural,450 )451 node.set_lineno(lineno)452 if plural_expr_assignment is not None:453 return [plural_expr_assignment, node]454 else:455 return node456457 def _trim_whitespace(self, string: str, _ws_re: t.Pattern[str] = _ws_re) -> str:458 return _ws_re.sub(" ", string.strip())459460 def _parse_block(461 self, parser: "Parser", allow_pluralize: bool462 ) -> tuple[list[str], str]:463 """Parse until the next block tag with a given name."""464 referenced = []465 buf = []466467 while True:468 if parser.stream.current.type == "data":469 buf.append(parser.stream.current.value.replace("%", "%%"))470 next(parser.stream)471 elif parser.stream.current.type == "variable_begin":472 next(parser.stream)473 name = parser.stream.expect("name").value474 referenced.append(name)475 buf.append(f"%({name})s")476 parser.stream.expect("variable_end")477 elif parser.stream.current.type == "block_begin":478 next(parser.stream)479 block_name = (480 parser.stream.current.value481 if parser.stream.current.type == "name"482 else None483 )484 if block_name == "endtrans":485 break486 elif block_name == "pluralize":487 if allow_pluralize:488 break489 parser.fail(490 "a translatable section can have only one pluralize section"491 )492 elif block_name == "trans":493 parser.fail(494 "trans blocks can't be nested; did you mean `endtrans`?"495 )496 parser.fail(497 f"control structures in translatable sections are not allowed; "498 f"saw `{block_name}`"499 )500 elif parser.stream.eos:501 parser.fail("unclosed translation block")502 else:503 raise RuntimeError("internal parser error")504505 return referenced, concat(buf)506507 def _make_node(508 self,509 singular: str,510 plural: str | None,511 context: str | None,512 variables: dict[str, nodes.Expr],513 plural_expr: nodes.Expr | None,514 vars_referenced: bool,515 num_called_num: bool,516 ) -> nodes.Output:517 """Generates a useful node from the data provided."""518 newstyle = self.environment.newstyle_gettext # type: ignore519 node: nodes.Expr520521 # no variables referenced? no need to escape for old style522 # gettext invocations only if there are vars.523 if not vars_referenced and not newstyle:524 singular = singular.replace("%%", "%")525 if plural:526 plural = plural.replace("%%", "%")527528 func_name = "gettext"529 func_args: list[nodes.Expr] = [nodes.Const(singular)]530531 if context is not None:532 func_args.insert(0, nodes.Const(context))533 func_name = f"p{func_name}"534535 if plural_expr is not None:536 func_name = f"n{func_name}"537 func_args.extend((nodes.Const(plural), plural_expr))538539 node = nodes.Call(nodes.Name(func_name, "load"), func_args, [], None, None)540541 # in case newstyle gettext is used, the method is powerful542 # enough to handle the variable expansion and autoescape543 # handling itself544 if newstyle:545 for key, value in variables.items():546 # the function adds that later anyways in case num was547 # called num, so just skip it.548 if num_called_num and key == "num":549 continue550 node.kwargs.append(nodes.Keyword(key, value))551552 # otherwise do that here553 else:554 # mark the return value as safe if we are in an555 # environment with autoescaping turned on556 node = nodes.MarkSafeIfAutoescape(node)557 if variables:558 node = nodes.Mod(559 node,560 nodes.Dict(561 [562 nodes.Pair(nodes.Const(key), value)563 for key, value in variables.items()564 ]565 ),566 )567 return nodes.Output([node])568569570class ExprStmtExtension(Extension):571 """Adds a `do` tag to Jinja that works like the print statement just572 that it doesn't print the return value.573 """574575 tags = {"do"}576577 def parse(self, parser: "Parser") -> nodes.ExprStmt:578 node = nodes.ExprStmt(lineno=next(parser.stream).lineno)579 node.node = parser.parse_tuple()580 return node581582583class LoopControlExtension(Extension):584 """Adds break and continue to the template engine."""585586 tags = {"break", "continue"}587588 def parse(self, parser: "Parser") -> nodes.Break | nodes.Continue:589 token = next(parser.stream)590 if token.value == "break":591 return nodes.Break(lineno=token.lineno)592 return nodes.Continue(lineno=token.lineno)593594595class DebugExtension(Extension):596 """A ``{% debug %}`` tag that dumps the available variables,597 filters, and tests.598599 .. code-block:: html+jinja600601 <pre>{% debug %}</pre>602603 .. code-block:: text604605 {'context': {'cycler': <class 'jinja2.utils.Cycler'>,606 ...,607 'namespace': <class 'jinja2.utils.Namespace'>},608 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',609 ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],610 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',611 ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}612613 .. versionadded:: 2.11.0614 """615616 tags = {"debug"}617618 def parse(self, parser: "Parser") -> nodes.Output:619 lineno = parser.stream.expect("name:debug").lineno620 context = nodes.ContextReference()621 result = self.call_method("_render", [context], lineno=lineno)622 return nodes.Output([result], lineno=lineno)623624 def _render(self, context: Context) -> str:625 result = {626 "context": context.get_all(),627 "filters": sorted(self.environment.filters.keys()),628 "tests": sorted(self.environment.tests.keys()),629 }630631 # Set the depth since the intent is to show the top few names.632 return pprint.pformat(result, depth=3, compact=True)633634635def extract_from_ast(636 ast: nodes.Template,637 gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,638 babel_style: bool = True,639) -> t.Iterator[tuple[int, str, str | None | tuple[str | None, ...]]]:640 """Extract localizable strings from the given template node. Per641 default this function returns matches in babel style that means non string642 parameters as well as keyword arguments are returned as `None`. This643 allows Babel to figure out what you really meant if you are using644 gettext functions that allow keyword arguments for placeholder expansion.645 If you don't want that behavior set the `babel_style` parameter to `False`646 which causes only strings to be returned and parameters are always stored647 in tuples. As a consequence invalid gettext calls (calls without a single648 string parameter or string parameters after non-string parameters) are649 skipped.650651 This example explains the behavior:652653 >>> from jinja2 import Environment654 >>> env = Environment()655 >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')656 >>> list(extract_from_ast(node))657 [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]658 >>> list(extract_from_ast(node, babel_style=False))659 [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]660661 For every string found this function yields a ``(lineno, function,662 message)`` tuple, where:663664 * ``lineno`` is the number of the line on which the string was found,665 * ``function`` is the name of the ``gettext`` function used (if the666 string was extracted from embedded Python code), and667 * ``message`` is the string, or a tuple of strings for functions668 with multiple string arguments.669670 This extraction function operates on the AST and is because of that unable671 to extract any comments. For comment support you have to use the babel672 extraction interface or extract comments yourself.673 """674 out: str | None | tuple[str | None, ...]675676 for node in ast.find_all(nodes.Call):677 if (678 not isinstance(node.node, nodes.Name)679 or node.node.name not in gettext_functions680 ):681 continue682683 strings: list[str | None] = []684685 for arg in node.args:686 if isinstance(arg, nodes.Const) and isinstance(arg.value, str):687 strings.append(arg.value)688 else:689 strings.append(None)690691 for _ in node.kwargs:692 strings.append(None)693 if node.dyn_args is not None:694 strings.append(None)695 if node.dyn_kwargs is not None:696 strings.append(None)697698 if not babel_style:699 out = tuple(x for x in strings if x is not None)700701 if not out:702 continue703 else:704 if len(strings) == 1:705 out = strings[0]706 else:707 out = tuple(strings)708709 yield node.lineno, node.node.name, out710711712class _CommentFinder:713 """Helper class to find comments in a token stream. Can only714 find comments for gettext calls forwards. Once the comment715 from line 4 is found, a comment for line 1 will not return a716 usable value.717 """718719 def __init__(720 self, tokens: t.Sequence[tuple[int, str, str]], comment_tags: t.Sequence[str]721 ) -> None:722 self.tokens = tokens723 self.comment_tags = comment_tags724 self.offset = 0725 self.last_lineno = 0726727 def find_backwards(self, offset: int) -> list[str]:728 try:729 for _, token_type, token_value in reversed(730 self.tokens[self.offset : offset]731 ):732 if token_type in ("comment", "linecomment"):733 try:734 prefix, comment = token_value.split(None, 1)735 except ValueError:736 continue737 if prefix in self.comment_tags:738 return [comment.rstrip()]739 return []740 finally:741 self.offset = offset742743 def find_comments(self, lineno: int) -> list[str]:744 if not self.comment_tags or self.last_lineno > lineno:745 return []746 for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]):747 if token_lineno > lineno:748 return self.find_backwards(self.offset + idx)749 return self.find_backwards(len(self.tokens))750751752def babel_extract(753 fileobj: t.BinaryIO,754 keywords: t.Sequence[str],755 comment_tags: t.Sequence[str],756 options: dict[str, t.Any],757) -> t.Iterator[tuple[int, str, str | None | tuple[str | None, ...], list[str]]]:758 """Babel extraction method for Jinja templates.759760 .. versionchanged:: 2.3761 Basic support for translation comments was added. If `comment_tags`762 is now set to a list of keywords for extraction, the extractor will763 try to find the best preceding comment that begins with one of the764 keywords. For best results, make sure to not have more than one765 gettext call in one line of code and the matching comment in the766 same line or the line before.767768 .. versionchanged:: 2.5.1769 The `newstyle_gettext` flag can be set to `True` to enable newstyle770 gettext calls.771772 .. versionchanged:: 2.7773 A `silent` option can now be provided. If set to `False` template774 syntax errors are propagated instead of being ignored.775776 :param fileobj: the file-like object the messages should be extracted from777 :param keywords: a list of keywords (i.e. function names) that should be778 recognized as translation functions779 :param comment_tags: a list of translator tags to search for and include780 in the results.781 :param options: a dictionary of additional options (optional)782 :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.783 (comments will be empty currently)784 """785 extensions: dict[type[Extension], None] = {}786787 for extension_name in options.get("extensions", "").split(","):788 extension_name = extension_name.strip()789790 if not extension_name:791 continue792793 extensions[import_string(extension_name)] = None794795 if InternationalizationExtension not in extensions:796 extensions[InternationalizationExtension] = None797798 def getbool(options: t.Mapping[str, str], key: str, default: bool = False) -> bool:799 return options.get(key, str(default)).lower() in {"1", "on", "yes", "true"}800801 silent = getbool(options, "silent", True)802 environment = Environment(803 options.get("block_start_string", defaults.BLOCK_START_STRING),804 options.get("block_end_string", defaults.BLOCK_END_STRING),805 options.get("variable_start_string", defaults.VARIABLE_START_STRING),806 options.get("variable_end_string", defaults.VARIABLE_END_STRING),807 options.get("comment_start_string", defaults.COMMENT_START_STRING),808 options.get("comment_end_string", defaults.COMMENT_END_STRING),809 options.get("line_statement_prefix") or defaults.LINE_STATEMENT_PREFIX,810 options.get("line_comment_prefix") or defaults.LINE_COMMENT_PREFIX,811 getbool(options, "trim_blocks", defaults.TRIM_BLOCKS),812 getbool(options, "lstrip_blocks", defaults.LSTRIP_BLOCKS),813 defaults.NEWLINE_SEQUENCE,814 getbool(options, "keep_trailing_newline", defaults.KEEP_TRAILING_NEWLINE),815 tuple(extensions),816 cache_size=0,817 auto_reload=False,818 )819820 if getbool(options, "trimmed"):821 environment.policies["ext.i18n.trimmed"] = True822 if getbool(options, "newstyle_gettext"):823 environment.newstyle_gettext = True # type: ignore824825 source = fileobj.read().decode(options.get("encoding", "utf-8"))826 try:827 node = environment.parse(source)828 tokens = list(environment.lex(environment.preprocess(source)))829 except TemplateSyntaxError:830 if not silent:831 raise832 # skip templates with syntax errors833 return834835 finder = _CommentFinder(tokens, comment_tags)836 for lineno, func, message in extract_from_ast(node, keywords):837 yield lineno, func, message, finder.find_comments(lineno)838839840#: nicer import names841i18n = InternationalizationExtension842do = ExprStmtExtension843loopcontrols = LoopControlExtension844debug = DebugExtension