Index: tractags/macros.py
===================================================================
--- tractags/macros.py	(revision 12375)
+++ tractags/macros.py	(working copy)
@@ -10,7 +10,7 @@
 
 import re
 
-from genshi.builder import Markup, tag as builder
+from genshi.builder import tag as builder
 from pkg_resources import resource_filename
 
 from trac.config import BoolOption, ListOption, Option
@@ -20,7 +20,7 @@
 from trac.ticket.api import TicketSystem
 from trac.ticket.model import Ticket
 from trac.util import embedded_numbers
-from trac.util.compat import sorted, set
+from trac.util.compat import sorted, set, partial
 from trac.util.presentation import Paginator
 from trac.util.text import shorten_line, to_unicode
 from trac.web.chrome import Chrome, ITemplateProvider, \
@@ -156,17 +156,17 @@
         tag_system = TagSystem(env)
         all_realms = [p.get_taggable_realm()
                       for p in tag_system.tag_providers]
-        self.all_realms = all_realms
-        self.realms = realms
 
         if name == 'TagCloud':
             args.append(' or '.join(['realm:%s' % r for r in realms]))
             all_tags = tag_system.get_all_tags(req, ' '.join(args))
             mincount = 'mincount' in kw and kw['mincount'] or None
-            return self.render_cloud(req, all_tags,
+            get_href = partial(self.get_href, req, realms, None)
+            return self.render_cloud(req, all_tags, get_href,
                                      caseless_sort=self.caseless_sort,
                                      mincount=mincount)
-        elif name == 'ListTagged':
+
+        if name == 'ListTagged':
             if _OBSOLETE_ARGS_RE.search(content):
                 data = {'warning': 'obsolete_args'}
             else:
@@ -186,20 +186,17 @@
                     realms = list(set(all_realms)-set(self.exclude_realms))
             if not realms:
                 return ''
-            else:
-                self.query = query
-                self.realms = realms
-            query = '(%s) (%s)' % (query, ' or '.join(['realm:%s' % (r)
-                                                       for r in realms]))
-            env.log.debug('LISTTAGGED_QUERY: ' + query)
-            query_result = tag_system.query(req, query)
+            get_href = partial(self.get_href, req, realms, query)
+            tag_query = '(%s) (%s)' % (query, ' or '.join(['realm:%s' % (r)
+                                                           for r in realms]))
+            self.log.debug('LISTTAGGED_QUERY: %s', tag_query)
+            query_result = tag_system.query(req, tag_query)
 
             def _link(resource):
                 if resource.realm == 'tag':
                     # Keep realm selection in tag links.
                     #if context.resource.realm == 'tag':
-                    return builder.a(resource.id,
-                                     href=self.get_href(req, tag=resource))
+                    return builder.a(resource.id, href=get_href(tag=resource))
                     #else:
                 elif resource.realm == 'ticket':
                     # Return resource link including ticket status dependend
@@ -230,7 +227,8 @@
 
             results = sorted(query_result, key=lambda r: \
                              embedded_numbers(to_unicode(r[0].id)))
-            results = self._paginate(req, results)
+            get_href = partial(self.get_href, req, realms, req.args.get('q'))
+            results = self._paginate(req, results, get_href)
             rows = []
             for resource, tags in results:
                 desc = tag_system.describe_tagged_resource(req, resource)
@@ -279,22 +277,14 @@
             return Chrome(env).render_template(
                 req, 'listtagged_results.html', data, 'text/html', True)
 
-    def get_href(self, req, per_page=None, page=None, tag=None, **kwargs):
+    def get_href(self, req, realms, query, per_page=None, page=None, tag=None,
+                 **kwargs):
         """Prepare href objects for tag links and pager navigation.
 
         Generate form-related arguments, strip arguments with default values.
         """
-#        form_realms = None
-#        if req.path_info == '/tags':
-        form_realms = {}
         # Prepare realm arguments to keep form data consistent.
-        for realm in self.realms:
-            form_realms[realm] = 'on'
-#        realms = None
-#        elif set(self.realms) == set(self.all_realms):
-#            realms = None
-#        else:
-        realms = self.realms
+        form_realms = dict((realm, 'on') for realm in realms)
         if not page and not per_page:
             # We're not serving pager navigation here.
             return get_resource_url(self.env, tag, req.href,
@@ -303,12 +293,12 @@
             page = None
         if per_page == self.items_per_page:
             per_page = None
-        return req.href(req.path_info, form_realms, q=self.query,
+        return req.href(req.path_info, form_realms, q=query,
                         realms=realms, listtagged_per_page=per_page,
                         listtagged_page=page, **kwargs)
 
-    def render_cloud(self, req, cloud, renderer=None, caseless_sort=False,
-                     mincount=None):
+    def render_cloud(self, req, cloud, get_href, renderer=None,
+                     caseless_sort=False, mincount=None):
         """Render a tag cloud.
 
         :cloud: Dictionary of {object: count} representing the cloud.
@@ -324,7 +314,7 @@
 
         if renderer is None:
             def default_renderer(tag, count, percent):
-                href = self.get_href(req, tag=Resource('tag', tag))
+                href = get_href(tag=Resource('tag', tag))
                 return builder.a(tag, rel='tag', title='%i' % count,
                                  href=href, style='font-size: %ipx'
                                  % int(min_px + percent * (max_px - min_px)))
@@ -362,8 +352,7 @@
             ul('\n', li, '\n')
         return ul and ul or _("No tags found")
 
-    def _paginate(self, req, results):
-        self.query = req.args.get('q', None)
+    def _paginate(self, req, results, get_href):
         current_page = as_int(req.args.get('listtagged_page'), 1)
         items_per_page = as_int(req.args.get('listtagged_per_page'), None)
         if items_per_page is None:
@@ -373,7 +362,7 @@
         pagedata = []
         shown_pages = result.get_shown_pages(21)
         for page in shown_pages:
-            page_href = self.get_href(req, items_per_page, page)
+            page_href = get_href(items_per_page, page)
             pagedata.append([page_href, None, str(page),
                              _("Page %(num)d", num=page)])
 
@@ -384,11 +373,11 @@
                                'string': str(result.page + 1), 'title': None}
 
         if result.has_next_page:
-            next_href = self.get_href(req, items_per_page, current_page + 1)
+            next_href = get_href(items_per_page, current_page + 1)
             add_link(req, 'next', next_href, _('Next Page'))
 
         if result.has_previous_page:
-            prev_href = self.get_href(req, items_per_page, current_page - 1)
+            prev_href = get_href(items_per_page, current_page - 1)
             add_link(req, 'prev', prev_href, _('Previous Page'))
         return result
 
