Index: genshi/template/base.py
===================================================================
--- genshi/template/base.py	(revision 806)
+++ genshi/template/base.py	(working copy)
@@ -254,7 +254,7 @@
         """Pop the top-most scope from the stack."""
 
 
-def _apply_directives(stream, ctxt, directives):
+def _apply_directives(stream, directives, ctxt, **bind):
     """Apply the given directives to the stream.
     
     :param stream: the stream the directives should be applied to
@@ -263,7 +263,7 @@
     :return: the stream with the given directives applied
     """
     if directives:
-        stream = directives[0](iter(stream), ctxt, directives[1:])
+        stream = directives[0](iter(stream), directives[1:], ctxt, **bind)
     return stream
 
 
@@ -426,21 +426,24 @@
         :return: a markup event stream representing the result of applying
                  the template to the context data.
         """
+        bind = {}
         if args:
             assert len(args) == 1
             ctxt = args[0]
             if ctxt is None:
                 ctxt = Context(**kwargs)
+            else:
+                bind = kwargs
             assert isinstance(ctxt, Context)
         else:
             ctxt = Context(**kwargs)
 
         stream = self.stream
         for filter_ in self.filters:
-            stream = filter_(iter(stream), ctxt)
+            stream = filter_(iter(stream), ctxt, **bind)
         return Stream(stream, self.serializer)
 
-    def _eval(self, stream, ctxt):
+    def _eval(self, stream, ctxt, **bind):
         """Internal stream filter that evaluates any expressions in `START` and
         `TEXT` events.
         """
@@ -460,7 +463,8 @@
                     else:
                         values = []
                         for subkind, subdata, subpos in self._eval(substream,
-                                                                   ctxt):
+                                                                   ctxt,
+                                                                   **bind):
                             if subkind is TEXT:
                                 values.append(subdata)
                         value = [x for x in values if x is not None]
@@ -470,7 +474,9 @@
                 yield kind, (tag, Attrs(new_attrs)), pos
 
             elif kind is EXPR:
+                if bind: ctxt.push(bind)
                 result = data.evaluate(ctxt)
+                if bind: ctxt.pop()
                 if result is not None:
                     # First check for a string, otherwise the iterable test
                     # below succeeds, and the string will be chopped up into
@@ -482,7 +488,7 @@
                     elif hasattr(result, '__iter__'):
                         substream = _ensure(result)
                         for filter_ in filters:
-                            substream = filter_(substream, ctxt)
+                            substream = filter_(substream, ctxt, **bind)
                         for event in substream:
                             yield event
                     else:
@@ -491,28 +497,31 @@
             else:
                 yield kind, data, pos
 
-    def _exec(self, stream, ctxt):
+    def _exec(self, stream, ctxt, **bind):
         """Internal stream filter that executes Python code blocks."""
         for event in stream:
             if event[0] is EXEC:
+                if bind: ctxt.push(bind)
                 event[1].execute(_ctxt2dict(ctxt))
+                if bind: ctxt.pop()
             else:
                 yield event
 
-    def _flatten(self, stream, ctxt):
+    def _flatten(self, stream, ctxt, **bind):
         """Internal stream filter that expands `SUB` events in the stream."""
         for event in stream:
             if event[0] is SUB:
                 # This event is a list of directives and a list of nested
                 # events to which those directives should be applied
                 directives, substream = event[1]
-                substream = _apply_directives(substream, ctxt, directives)
-                for event in self._flatten(substream, ctxt):
+                substream = _apply_directives(substream, directives, ctxt,
+                                              **bind)
+                for event in self._flatten(substream, ctxt, **bind):
                     yield event
             else:
                 yield event
 
-    def _include(self, stream, ctxt):
+    def _include(self, stream, ctxt, **bind):
         """Internal stream filter that performs inclusion of external
         template files.
         """
@@ -523,20 +532,21 @@
                 href, cls, fallback = event[1]
                 if not isinstance(href, basestring):
                     parts = []
-                    for subkind, subdata, subpos in self._eval(href, ctxt):
+                    for subkind, subdata, subpos in self._eval(href, ctxt,
+                                                               **bind):
                         if subkind is TEXT:
                             parts.append(subdata)
                     href = u''.join([x for x in parts if x is not None])
                 try:
                     tmpl = self.loader.load(href, relative_to=event[2][0],
                                             cls=cls or self.__class__)
-                    for event in tmpl.generate(ctxt):
+                    for event in tmpl.generate(ctxt, **bind):
                         yield event
                 except TemplateNotFound:
                     if fallback is None:
                         raise
                     for filter_ in self.filters:
-                        fallback = filter_(iter(fallback), ctxt)
+                        fallback = filter_(iter(fallback), ctxt, **bind)
                     for event in fallback:
                         yield event
             else:
Index: genshi/template/tests/directives.py
===================================================================
--- genshi/template/tests/directives.py	(revision 806)
+++ genshi/template/tests/directives.py	(working copy)
@@ -631,6 +631,32 @@
           </body>
         </html>""", str(tmpl.generate()))
 
+    def test_recursive_match_3(self):
+        tmpl = MarkupTemplate("""<test xmlns:py="http://genshi.edgewall.org/">
+          <py:match path="b[@type='bullet']">
+            <bullet>${select('*|text()')}</bullet>
+          </py:match>
+          <py:match path="group[@type='bullet']">
+            <ul>${select('*')}</ul>
+          </py:match>
+          <py:match path="b">
+            <generic>${select('*|text()')}</generic>
+          </py:match>
+
+          <b>
+            <group type="bullet">
+              <b type="bullet">1</b>
+              <b type="bullet">2</b>
+            </group>
+          </b>
+        </test>
+        """)
+        self.assertEqual("""<test>
+            <generic>
+            <ul><bullet>1</bullet><bullet>2</bullet></ul>
+          </generic>
+        </test>""", str(tmpl.generate()))
+
     def test_not_match_self(self):
         """
         See http://genshi.edgewall.org/ticket/77
Index: genshi/template/markup.py
===================================================================
--- genshi/template/markup.py	(revision 806)
+++ genshi/template/markup.py	(working copy)
@@ -225,7 +225,7 @@
         assert len(streams) == 1
         return streams[0]
 
-    def _match(self, stream, ctxt, match_templates=None):
+    def _match(self, stream, ctxt, match_templates=None, **bind):
         """Internal stream filter that applies any defined match templates
         to the stream.
         """
@@ -272,11 +272,15 @@
                     # Consume and store all events until an end event
                     # corresponding to this start event is encountered
                     inner = _strip(stream)
-                    if 'match_once' not in hints \
-                            and 'not_recursive' not in hints:
-                        inner = self._match(inner, ctxt, [match_templates[idx]])
-                    content = list(self._include(chain([event], inner, tail),
-                                                 ctxt))
+                    pre_match_templates = match_templates[:idx + 1]
+                    if 'match_once' not in hints and 'not_recursive' in hints:
+                        pre_match_templates.pop()
+                    inner = self._match(inner, ctxt, pre_match_templates,
+                                        **bind)
+                    content = self._include(chain([event], inner, tail),
+                                            ctxt, **bind)
+                    if 'not_buffered' not in hints:
+                        content = list(content)
 
                     for test in [mt[0] for mt in match_templates]:
                         test(tail[0], namespaces, ctxt, updateonly=True)
@@ -285,19 +289,21 @@
                     # match template
                     def select(path):
                         return Stream(content).select(path, namespaces, ctxt)
-                    ctxt.push(dict(select=select))
+                    bind = dict(select=select)
 
                     # Recursively process the output
-                    template = _apply_directives(template, ctxt, directives)
+                    template = _apply_directives(template, directives, ctxt,
+                                                 **bind)
                     remaining = match_templates
-                    if 'match_once' not in hints:
-                        remaining = remaining[:idx] + remaining[idx + 1:]
-                    for event in self._match(self._exec(
-                                    self._eval(self._flatten(template, ctxt),
-                                    ctxt), ctxt), ctxt, remaining):
+                    for event in self._match(
+                            self._exec(
+                                self._eval(
+                                    self._flatten(template, ctxt, **bind),
+                                    ctxt, **bind),
+                                ctxt, **bind),
+                            ctxt, match_templates[idx + 1:], **bind):
                         yield event
 
-                    ctxt.pop()
                     break
 
             else: # no matches
Index: genshi/template/directives.py
===================================================================
--- genshi/template/directives.py	(revision 806)
+++ genshi/template/directives.py	(working copy)
@@ -88,13 +88,13 @@
         return cls(value, template, namespaces, *pos[1:]), stream
     attach = classmethod(attach)
 
-    def __call__(self, stream, ctxt, directives):
+    def __call__(self, stream, directives, ctxt, **bind):
         """Apply the directive to the given stream.
         
         :param stream: the event stream
-        :param ctxt: the context data
         :param directives: a list of the remaining directives that should
                            process the stream
+        :param ctxt: the context data
         """
         raise NotImplementedError
 
@@ -167,10 +167,12 @@
     """
     __slots__ = []
 
-    def __call__(self, stream, ctxt, directives):
+    def __call__(self, stream, directives, ctxt, **bind):
         def _generate():
             kind, (tag, attrib), pos  = stream.next()
+            if bind: ctxt.push(bind)
             attrs = self.expr.evaluate(ctxt)
+            if bind: ctxt.pop()
             if attrs:
                 if isinstance(attrs, Stream):
                     try:
@@ -186,7 +188,7 @@
             for event in stream:
                 yield event
 
-        return _apply_directives(_generate(), ctxt, directives)
+        return _apply_directives(_generate(), directives, ctxt, **bind)
 
 
 class ContentDirective(Directive):
@@ -291,11 +293,12 @@
                                                namespaces, pos)
     attach = classmethod(attach)
 
-    def __call__(self, stream, ctxt, directives):
+    def __call__(self, stream, directives, ctxt, **bind):
         stream = list(stream)
 
         def function(*args, **kwargs):
             scope = {}
+            if bind: ctxt.push(bind)
             args = list(args) # make mutable
             for name in self.args:
                 if args:
@@ -306,12 +309,13 @@
                     else:
                         val = self.defaults.get(name).evaluate(ctxt)
                     scope[name] = val
+            if bind: ctxt.pop()
             if not self.star_args is None:
                 scope[self.star_args] = args
             if not self.dstar_args is None:
                 scope[self.dstar_args] = kwargs
             ctxt.push(scope)
-            for event in _apply_directives(stream, ctxt, directives):
+            for event in _apply_directives(stream, directives, ctxt, **bind):
                 yield event
             ctxt.pop()
         try:
@@ -364,8 +368,10 @@
                                                namespaces, pos)
     attach = classmethod(attach)
 
-    def __call__(self, stream, ctxt, directives):
+    def __call__(self, stream, directives, ctxt, **bind):
+        if bind: ctxt.push(bind)
         iterable = self.expr.evaluate(ctxt)
+        if bind: ctxt.pop()
         if iterable is None:
             return
 
@@ -375,7 +381,7 @@
         for item in iterable:
             assign(scope, item)
             ctxt.push(scope)
-            for event in _apply_directives(stream, ctxt, directives):
+            for event in _apply_directives(stream, directives, ctxt, **bind):
                 yield event
             ctxt.pop()
 
@@ -405,9 +411,12 @@
                                               namespaces, pos)
     attach = classmethod(attach)
 
-    def __call__(self, stream, ctxt, directives):
-        if self.expr.evaluate(ctxt):
-            return _apply_directives(stream, ctxt, directives)
+    def __call__(self, stream, directives, ctxt, **bind):
+        if bind: ctxt.push(bind)
+        value = self.expr.evaluate(ctxt)
+        if bind: ctxt.pop()
+        if value:
+            return _apply_directives(stream, directives, ctxt, **bind)
         return []
 
 
@@ -440,6 +449,8 @@
     def attach(cls, template, stream, value, namespaces, pos):
         hints = []
         if type(value) is dict:
+            if value.get('buffer', '').lower() == 'false':
+                hints.append('not_buffered')
             if value.get('once', '').lower() == 'true':
                 hints.append('match_once')
             if value.get('recursive', '').lower() == 'false':
@@ -449,7 +460,7 @@
                stream
     attach = classmethod(attach)
 
-    def __call__(self, stream, ctxt, directives):
+    def __call__(self, stream, directives, ctxt, **bind):
         ctxt._match_templates.append((self.path.test(ignore_context=True),
                                       self.path, list(stream), self.hints,
                                       self.namespaces, directives))
@@ -531,7 +542,7 @@
     """
     __slots__ = []
 
-    def __call__(self, stream, ctxt, directives):
+    def __call__(self, stream, directives, ctxt, **bind):
         def _generate():
             if self.expr.evaluate(ctxt):
                 stream.next() # skip start tag
@@ -542,7 +553,7 @@
             else:
                 for event in stream:
                     yield event
-        return _apply_directives(_generate(), ctxt, directives)
+        return _apply_directives(_generate(), directives, ctxt, **bind)
 
     def attach(cls, template, stream, value, namespaces, pos):
         if not value:
@@ -600,12 +611,14 @@
                                                   namespaces, pos)
     attach = classmethod(attach)
 
-    def __call__(self, stream, ctxt, directives):
+    def __call__(self, stream, directives, ctxt, **bind):
         info = [False, bool(self.expr), None]
         if self.expr:
+            if bind: ctxt.push(bind)
             info[2] = self.expr.evaluate(ctxt)
+            if bind: ctxt.pop()
         ctxt._choice_stack.append(info)
-        for event in _apply_directives(stream, ctxt, directives):
+        for event in _apply_directives(stream, directives, ctxt, **bind):
             yield event
         ctxt._choice_stack.pop()
 
@@ -629,7 +642,7 @@
                                                 namespaces, pos)
     attach = classmethod(attach)
 
-    def __call__(self, stream, ctxt, directives):
+    def __call__(self, stream, directives, ctxt, **bind):
         info = ctxt._choice_stack and ctxt._choice_stack[-1]
         if not info:
             raise TemplateRuntimeError('"when" directives can only be used '
@@ -644,7 +657,9 @@
         if info[1]:
             value = info[2]
             if self.expr:
+                if bind: ctxt.push(bind)
                 matched = value == self.expr.evaluate(ctxt)
+                if bind: ctxt.pop()
             else:
                 matched = bool(value)
         else:
@@ -653,7 +668,7 @@
         if not matched:
             return []
 
-        return _apply_directives(stream, ctxt, directives)
+        return _apply_directives(stream, directives, ctxt, **bind)
 
 
 class OtherwiseDirective(Directive):
@@ -668,7 +683,7 @@
         Directive.__init__(self, None, template, namespaces, lineno, offset)
         self.filename = template.filepath
 
-    def __call__(self, stream, ctxt, directives):
+    def __call__(self, stream, directives, ctxt, **bind):
         info = ctxt._choice_stack and ctxt._choice_stack[-1]
         if not info:
             raise TemplateRuntimeError('an "otherwise" directive can only be '
@@ -678,7 +693,7 @@
             return []
         info[0] = True
 
-        return _apply_directives(stream, ctxt, directives)
+        return _apply_directives(stream, directives, ctxt, **bind)
 
 
 class WithDirective(Directive):
@@ -722,11 +737,13 @@
                                                 namespaces, pos)
     attach = classmethod(attach)
 
-    def __call__(self, stream, ctxt, directives):
+    def __call__(self, stream, directives, ctxt, **bind):
         frame = {}
         ctxt.push(frame)
+        if bind: ctxt.push(bind)
         self.suite.execute(_ctxt2dict(ctxt))
-        for event in _apply_directives(stream, ctxt, directives):
+        if bind: ctxt.pop()
+        for event in _apply_directives(stream, directives, ctxt, **bind):
             yield event
         ctxt.pop()
 
Index: genshi/template/text.py
===================================================================
--- genshi/template/text.py	(revision 809)
+++ genshi/template/text.py	(working copy)
@@ -33,7 +33,7 @@
                                  TemplateSyntaxError, EXEC, INCLUDE, SUB
 from genshi.template.eval import Suite
 from genshi.template.directives import *
-from genshi.template.directives import Directive, _apply_directives
+from genshi.template.directives import Directive
 from genshi.template.interpolation import interpolate
 
 __all__ = ['NewTextTemplate', 'OldTextTemplate', 'TextTemplate']
