Index: includemacro/macros.py
===================================================================
--- includemacro/macros.py	(revision 16425)
+++ includemacro/macros.py	(working copy)
@@ -10,6 +10,7 @@
 #
 
 import urllib2
+import re
 from StringIO import StringIO
 
 from genshi.filters.html import HTMLSanitizer
@@ -30,6 +31,11 @@
 from trac.wiki.model import WikiPage
 
 
+class IncludeException(Exception):
+    def __init__(self, s):
+        self.s = s
+
+
 class IncludeMacro(WikiMacroBase):
     """A macro to include other resources in wiki pages.
 
@@ -43,6 +49,74 @@
         'wiki': 'text/x-trac-wiki',
     }
 
+    def _extract_section(self, s, section):
+        try:
+            mStart = re.search(r'^(=+)\s+{}\s+\1'.format(re.escape(section)), s, re.M)
+            depthStart = len(mStart.group(1))
+
+            rxSection = re.compile(r'^(=+)\s+\S.*\s+\1', re.M)
+            ichMac = len(s)
+            for m in rxSection.finditer(s, mStart.end()):
+                if len(m.group(1)) <= depthStart:
+                    ichMac = m.start()
+                    break
+            return s[mStart.end():ichMac]
+        except:
+            return None
+
+    def _include_wiki(self, source_obj, formatter):
+        try:
+            source_obj, source_section = source_obj.split('#', 1)
+        except ValueError: # If no # is present, assume its a wiki page
+            source_obj, source_section = source_obj, None
+
+        # XXX: Check for recursion in page includes. <NPK>
+        page_name, page_version = _split_path(source_obj)
+        # Relative link resolution adapted from Trac 1.1.2dev.
+        # Hint: Only attempt this in wiki rendering context.
+        if formatter.resource and formatter.resource.realm == 'wiki':
+            referrer = formatter.resource.id
+            ws = WikiSystem(self.env)
+            if page_name.startswith('/'):
+                page_name = page_name.lstrip('/')
+            elif page_name.startswith(('./', '../')) or \
+                    page_name in ('.', '..'):
+                try:
+                    # Trac 1.2
+                    page_name = ws.resolve_relative_name(page_name,
+                                                         referrer)
+                except AttributeError:
+                    page_name = _resolve_relative_name(page_name,
+                                                       referrer)
+            else:
+                page_name = _resolve_scoped_name(ws, page_name, referrer)
+        try:
+            page = WikiPage(self.env, page_name, page_version)
+        except (TypeError, ValueError):  # Trac < 1.2 (Trac:#11544)
+            msg = _('"%(version)s" is not a valid wiki page version.',
+                    version=page_version)
+            raise IncludeException(system_message(msg))
+        except TracError, e:
+            raise IncludeException(system_message(e))
+        if 'WIKI_VIEW' not in formatter.perm(page.resource):
+            raise IncludeException('')
+        if not page.exists:
+            if page_version:
+                raise IncludeException(system_message('No version "%s" for wiki page "%s"'
+                                      % (page_version, page_name)))
+            else:
+                raise IncludeException(system_message('Wiki page "%s" does not exist'
+                                      % page_name))
+
+        out = page.text
+        if source_section:
+            out = self._extract_section(out, source_section)
+            if out is None:
+                raise IncludeException(system_message('Section "%s" not found in wiki page "%s"'
+                        % (source_section, page_name)))
+        return out
+
+
     # IWikiMacroProvider methods
 
     def expand_macro(self, formatter, name, content):
@@ -85,44 +159,10 @@
                 return system_message("Error while previewing", str(e))
             ctxt = Context.from_request(formatter.req)
         elif source_format == 'wiki':
-            # XXX: Check for recursion in page includes. <NPK>
-            page_name, page_version = _split_path(source_obj)
-            # Relative link resolution adapted from Trac 1.1.2dev.
-            # Hint: Only attempt this in wiki rendering context.
-            if formatter.resource and formatter.resource.realm == 'wiki':
-                referrer = formatter.resource.id
-                ws = WikiSystem(self.env)
-                if page_name.startswith('/'):
-                    page_name = page_name.lstrip('/')
-                elif page_name.startswith(('./', '../')) or \
-                        page_name in ('.', '..'):
-                    try:
-                        # Trac 1.2
-                        page_name = ws.resolve_relative_name(page_name,
-                                                             referrer)
-                    except AttributeError:
-                        page_name = _resolve_relative_name(page_name,
-                                                           referrer)
-                else:
-                    page_name = _resolve_scoped_name(ws, page_name, referrer)
             try:
-                page = WikiPage(self.env, page_name, page_version)
-            except (TypeError, ValueError):  # Trac < 1.2 (Trac:#11544)
-                msg = _('"%(version)s" is not a valid wiki page version.',
-                        version=page_version)
-                return system_message(msg)
-            except TracError, e:
-                return system_message(e)
-            if 'WIKI_VIEW' not in formatter.perm(page.resource):
-                return ''
-            if not page.exists:
-                if page_version:
-                    return system_message('No version "%s" for wiki page "%s"'
-                                          % (page_version, page_name))
-                else:
-                    return system_message('Wiki page "%s" does not exist'
-                                          % page_name)
-            out = page.text
+                out = self._include_wiki(source_obj, formatter)
+            except IncludeException, e:
+                return e.s
             ctxt = Context.from_request(formatter.req, 'wiki', source_obj)
         elif source_format in ('source', 'browser', 'repos'):
             if 'FILE_VIEW' not in formatter.perm:
