We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Links in headings are broken on docs
For example:
https://dev.ocf.berkeley.edu/docs/faq/
![](http://i.fluffy.cc/RDF2Pq9B402fmfJp1ghVd3p9pzvKSlmc.png)

I think this is a side-effect of overreaching CSS rules intended for the link icons.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `ocfweb/component/markdown.py`
Content:
```
1 import re
2 
3 import mistune
4 from django.core.urlresolvers import reverse
5 
6 from ocfweb.caching import lru_cache
7 
8 # tags of a format like: [[!meta title="Backups"]]
9 META_REGEX = re.compile('\[\[!meta ([a-z]+)="([^"]*)"\]\]')
10 
11 
12 class HtmlCommentsInlineLexerMixin:
13     """Strip HTML comments inside lines."""
14 
15     def enable_html_comments(self):
16         self.rules.html_comment = re.compile(
17             '^<!--(.*?)-->'
18         )
19         self.default_rules.insert(0, 'html_comment')
20 
21     def output_html_comment(self, m):
22         return ''
23 
24 
25 class HtmlCommentsBlockLexerMixin:
26     """Strip blocks which consist entirely of HTML comments."""
27 
28     def enable_html_comments(self):
29         self.rules.html_comment = re.compile(
30             '^<!--(.*?)-->'
31         )
32         self.default_rules.insert(0, 'html_comment')
33 
34     def parse_html_comment(self, m):
35         pass
36 
37 
38 class DjangoLinkInlineLexerMixin:
39     """Turn special Markdown link syntax into Django links.
40 
41     In Django templates, we can use `url` tags, such as:
42         {% url 'staff-hours' %}
43         {% url 'doc' 'staff/backend/backups' %}
44 
45     In Markdown, we use the following fake syntax to generate Django links:
46         [[human readable name|staff-hours]]
47         [[human readable name|doc staff/backend/backups]]
48 
49     You can link to fragments with a # at the very end:
50         [[human readable name|staff-hours#something]]
51         [[human readable name|doc staff/backend/backups#something]]
52     """
53 
54     split_words = re.compile('((?:\S|\\\\ )+)')
55 
56     def enable_django_links(self):
57         self.rules.django_link = re.compile(
58             '^\[\[(?!\!)'
59             '([\s\S]+?)'
60             '\|'
61             '([^#]+?)'
62             '(?:#(.*?))?'
63             '\]\]'
64         )
65         self.default_rules.insert(0, 'django_link')
66 
67     def output_django_link(self, m):
68         text, target, fragment = m.group(1), m.group(2), m.group(3)
69 
70         def href(link, fragment):
71             if fragment:
72                 return link + '#' + fragment
73             return link
74 
75         words = DjangoLinkInlineLexerMixin.split_words.findall(target)
76         name, *params = words
77         return self.renderer.link(
78             link=href(reverse(name, args=params), fragment),
79             title=None,
80             text=text,
81         )
82 
83 
84 class HeaderRendererMixin:
85     """Mixin to render headers with auto-generated IDs (or provided IDs).
86 
87     If headers are written as usual, they'll be given automatically-generated
88     IDs based on their header level and text.
89 
90     Headers can also be specified with an ID at the end wrapped in curly braces:
91 
92         ### My Header    {my_id}
93 
94     This ID will be used directly without further manipulation, and can be
95     relied on for linking.
96 
97     Custom IDs can consist only of lowercase a-z, 0-9, dash, and underscore.
98 
99     IDs are tracked into a table of contents which should be reset before
100     rendering a document and read afterwards.
101     """
102 
103     def reset_toc(self):
104         self.toc = []
105         self.toc_ids = set()
106 
107     def get_toc(self):
108         return self.toc
109 
110     def header(self, text, level, raw=None):
111         custom_id_match = re.match(r'^(.*?)\s+{([a-z0-9\-_]+)}\s*$', text)
112         if custom_id_match:
113             text = custom_id_match.group(1)
114             id = custom_id_match.group(2)
115 
116             if id in self.toc_ids:
117                 raise ValueError('Duplicate header ID in Markdown: "{}"'.format(id))
118         else:
119             id = 'h{level}_{title}'.format(
120                 level=level,
121                 title=re.sub('[^a-z0-9\-_ ]', '', text.lower()).strip().replace(' ', '-'),
122             )
123 
124             # dumb collision avoidance
125             while id in self.toc_ids:
126                 id += '_'
127 
128         self.toc.append((level, text, id))
129         self.toc_ids.add(id)
130         return '<h{level} id="{id}">{text} <a class="" href="#{id}"><span></span></a></h{level}>\n'.format(
131             level=level,
132             id=id,
133             text=text,
134         )
135 
136 
137 class OcfMarkdownRenderer(
138     HeaderRendererMixin,
139     mistune.Renderer,
140 ):
141     pass
142 
143 
144 class OcfMarkdownInlineLexer(
145     mistune.InlineLexer,
146     DjangoLinkInlineLexerMixin,
147     HtmlCommentsInlineLexerMixin,
148 ):
149     pass
150 
151 
152 class OcfMarkdownBlockLexer(
153     mistune.BlockLexer,
154     HtmlCommentsBlockLexerMixin,
155 ):
156     pass
157 
158 
159 _renderer = OcfMarkdownRenderer(
160     escape=True,
161     hard_wrap=False,
162 )
163 
164 _inline = OcfMarkdownInlineLexer(_renderer)
165 _inline.enable_html_comments()
166 _inline.enable_django_links()
167 
168 _block = OcfMarkdownBlockLexer(mistune.BlockGrammar())
169 _block.enable_html_comments()
170 
171 _markdown = mistune.Markdown(
172     renderer=_renderer,
173     inline=_inline,
174     block=_block,
175 )
176 
177 
178 def markdown(text):
179     _renderer.reset_toc()
180     return _markdown(text)
181 
182 
183 def text_and_meta(f):
184     """Return tuple (text, meta dict) for the given file.
185 
186     Meta tags are stripped from the Markdown source, but the Markdown is
187     not rendered.
188     """
189     text = f.read()
190     meta = {}
191 
192     def repl(match):
193         meta[match.group(1)] = match.group(2)
194         return ''
195 
196     text = META_REGEX.sub(repl, text)
197     return text, meta
198 
199 
200 @lru_cache()
201 def markdown_and_toc(text):
202     """Return tuple (html, toc) for the given text."""
203     html = markdown(text)
204     return html, _renderer.get_toc()
205
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/ocfweb/component/markdown.py b/ocfweb/component/markdown.py
--- a/ocfweb/component/markdown.py
+++ b/ocfweb/component/markdown.py
@@ -127,7 +127,7 @@
 
         self.toc.append((level, text, id))
         self.toc_ids.add(id)
-        return '<h{level} id="{id}">{text} <a class="" href="#{id}"><span></span></a></h{level}>\n'.format(
+        return '<h{level} id="{id}">{text} <a class="anchor" href="#{id}"><span></span></a></h{level}>\n'.format(
             level=level,
             id=id,
             text=text,

{"golden_diff": "diff --git a/ocfweb/component/markdown.py b/ocfweb/component/markdown.py\n--- a/ocfweb/component/markdown.py\n+++ b/ocfweb/component/markdown.py\n@@ -127,7 +127,7 @@\n \n         self.toc.append((level, text, id))\n         self.toc_ids.add(id)\n-        return '<h{level} id=\"{id}\">{text} <a class=\"\" href=\"#{id}\"><span></span></a></h{level}>\\n'.format(\n+        return '<h{level} id=\"{id}\">{text} <a class=\"anchor\" href=\"#{id}\"><span></span></a></h{level}>\\n'.format(\n             level=level,\n             id=id,\n             text=text,\n", "issue": "Links in headings are broken on docs\nFor example:\nhttps://dev.ocf.berkeley.edu/docs/faq/\n![](http://i.fluffy.cc/RDF2Pq9B402fmfJp1ghVd3p9pzvKSlmc.png)\n\nI think this is a side-effect of overreaching CSS rules intended for the link icons.\n\n", "before_files": [{"content": "import re\n\nimport mistune\nfrom django.core.urlresolvers import reverse\n\nfrom ocfweb.caching import lru_cache\n\n# tags of a format like: [[!meta title=\"Backups\"]]\nMETA_REGEX = re.compile('\\[\\[!meta ([a-z]+)=\"([^\"]*)\"\\]\\]')\n\n\nclass HtmlCommentsInlineLexerMixin:\n    \"\"\"Strip HTML comments inside lines.\"\"\"\n\n    def enable_html_comments(self):\n        self.rules.html_comment = re.compile(\n            '^<!--(.*?)-->'\n        )\n        self.default_rules.insert(0, 'html_comment')\n\n    def output_html_comment(self, m):\n        return ''\n\n\nclass HtmlCommentsBlockLexerMixin:\n    \"\"\"Strip blocks which consist entirely of HTML comments.\"\"\"\n\n    def enable_html_comments(self):\n        self.rules.html_comment = re.compile(\n            '^<!--(.*?)-->'\n        )\n        self.default_rules.insert(0, 'html_comment')\n\n    def parse_html_comment(self, m):\n        pass\n\n\nclass DjangoLinkInlineLexerMixin:\n    \"\"\"Turn special Markdown link syntax into Django links.\n\n    In Django templates, we can use `url` tags, such as:\n        {% url 'staff-hours' %}\n        {% url 'doc' 'staff/backend/backups' %}\n\n    In Markdown, we use the following fake syntax to generate Django links:\n        [[human readable name|staff-hours]]\n        [[human readable name|doc staff/backend/backups]]\n\n    You can link to fragments with a # at the very end:\n        [[human readable name|staff-hours#something]]\n        [[human readable name|doc staff/backend/backups#something]]\n    \"\"\"\n\n    split_words = re.compile('((?:\\S|\\\\\\\\ )+)')\n\n    def enable_django_links(self):\n        self.rules.django_link = re.compile(\n            '^\\[\\[(?!\\!)'\n            '([\\s\\S]+?)'\n            '\\|'\n            '([^#]+?)'\n            '(?:#(.*?))?'\n            '\\]\\]'\n        )\n        self.default_rules.insert(0, 'django_link')\n\n    def output_django_link(self, m):\n        text, target, fragment = m.group(1), m.group(2), m.group(3)\n\n        def href(link, fragment):\n            if fragment:\n                return link + '#' + fragment\n            return link\n\n        words = DjangoLinkInlineLexerMixin.split_words.findall(target)\n        name, *params = words\n        return self.renderer.link(\n            link=href(reverse(name, args=params), fragment),\n            title=None,\n            text=text,\n        )\n\n\nclass HeaderRendererMixin:\n    \"\"\"Mixin to render headers with auto-generated IDs (or provided IDs).\n\n    If headers are written as usual, they'll be given automatically-generated\n    IDs based on their header level and text.\n\n    Headers can also be specified with an ID at the end wrapped in curly braces:\n\n        ### My Header    {my_id}\n\n    This ID will be used directly without further manipulation, and can be\n    relied on for linking.\n\n    Custom IDs can consist only of lowercase a-z, 0-9, dash, and underscore.\n\n    IDs are tracked into a table of contents which should be reset before\n    rendering a document and read afterwards.\n    \"\"\"\n\n    def reset_toc(self):\n        self.toc = []\n        self.toc_ids = set()\n\n    def get_toc(self):\n        return self.toc\n\n    def header(self, text, level, raw=None):\n        custom_id_match = re.match(r'^(.*?)\\s+{([a-z0-9\\-_]+)}\\s*$', text)\n        if custom_id_match:\n            text = custom_id_match.group(1)\n            id = custom_id_match.group(2)\n\n            if id in self.toc_ids:\n                raise ValueError('Duplicate header ID in Markdown: \"{}\"'.format(id))\n        else:\n            id = 'h{level}_{title}'.format(\n                level=level,\n                title=re.sub('[^a-z0-9\\-_ ]', '', text.lower()).strip().replace(' ', '-'),\n            )\n\n            # dumb collision avoidance\n            while id in self.toc_ids:\n                id += '_'\n\n        self.toc.append((level, text, id))\n        self.toc_ids.add(id)\n        return '<h{level} id=\"{id}\">{text} <a class=\"\" href=\"#{id}\"><span></span></a></h{level}>\\n'.format(\n            level=level,\n            id=id,\n            text=text,\n        )\n\n\nclass OcfMarkdownRenderer(\n    HeaderRendererMixin,\n    mistune.Renderer,\n):\n    pass\n\n\nclass OcfMarkdownInlineLexer(\n    mistune.InlineLexer,\n    DjangoLinkInlineLexerMixin,\n    HtmlCommentsInlineLexerMixin,\n):\n    pass\n\n\nclass OcfMarkdownBlockLexer(\n    mistune.BlockLexer,\n    HtmlCommentsBlockLexerMixin,\n):\n    pass\n\n\n_renderer = OcfMarkdownRenderer(\n    escape=True,\n    hard_wrap=False,\n)\n\n_inline = OcfMarkdownInlineLexer(_renderer)\n_inline.enable_html_comments()\n_inline.enable_django_links()\n\n_block = OcfMarkdownBlockLexer(mistune.BlockGrammar())\n_block.enable_html_comments()\n\n_markdown = mistune.Markdown(\n    renderer=_renderer,\n    inline=_inline,\n    block=_block,\n)\n\n\ndef markdown(text):\n    _renderer.reset_toc()\n    return _markdown(text)\n\n\ndef text_and_meta(f):\n    \"\"\"Return tuple (text, meta dict) for the given file.\n\n    Meta tags are stripped from the Markdown source, but the Markdown is\n    not rendered.\n    \"\"\"\n    text = f.read()\n    meta = {}\n\n    def repl(match):\n        meta[match.group(1)] = match.group(2)\n        return ''\n\n    text = META_REGEX.sub(repl, text)\n    return text, meta\n\n\n@lru_cache()\ndef markdown_and_toc(text):\n    \"\"\"Return tuple (html, toc) for the given text.\"\"\"\n    html = markdown(text)\n    return html, _renderer.get_toc()\n", "path": "ocfweb/component/markdown.py"}], "after_files": [{"content": "import re\n\nimport mistune\nfrom django.core.urlresolvers import reverse\n\nfrom ocfweb.caching import lru_cache\n\n# tags of a format like: [[!meta title=\"Backups\"]]\nMETA_REGEX = re.compile('\\[\\[!meta ([a-z]+)=\"([^\"]*)\"\\]\\]')\n\n\nclass HtmlCommentsInlineLexerMixin:\n    \"\"\"Strip HTML comments inside lines.\"\"\"\n\n    def enable_html_comments(self):\n        self.rules.html_comment = re.compile(\n            '^<!--(.*?)-->'\n        )\n        self.default_rules.insert(0, 'html_comment')\n\n    def output_html_comment(self, m):\n        return ''\n\n\nclass HtmlCommentsBlockLexerMixin:\n    \"\"\"Strip blocks which consist entirely of HTML comments.\"\"\"\n\n    def enable_html_comments(self):\n        self.rules.html_comment = re.compile(\n            '^<!--(.*?)-->'\n        )\n        self.default_rules.insert(0, 'html_comment')\n\n    def parse_html_comment(self, m):\n        pass\n\n\nclass DjangoLinkInlineLexerMixin:\n    \"\"\"Turn special Markdown link syntax into Django links.\n\n    In Django templates, we can use `url` tags, such as:\n        {% url 'staff-hours' %}\n        {% url 'doc' 'staff/backend/backups' %}\n\n    In Markdown, we use the following fake syntax to generate Django links:\n        [[human readable name|staff-hours]]\n        [[human readable name|doc staff/backend/backups]]\n\n    You can link to fragments with a # at the very end:\n        [[human readable name|staff-hours#something]]\n        [[human readable name|doc staff/backend/backups#something]]\n    \"\"\"\n\n    split_words = re.compile('((?:\\S|\\\\\\\\ )+)')\n\n    def enable_django_links(self):\n        self.rules.django_link = re.compile(\n            '^\\[\\[(?!\\!)'\n            '([\\s\\S]+?)'\n            '\\|'\n            '([^#]+?)'\n            '(?:#(.*?))?'\n            '\\]\\]'\n        )\n        self.default_rules.insert(0, 'django_link')\n\n    def output_django_link(self, m):\n        text, target, fragment = m.group(1), m.group(2), m.group(3)\n\n        def href(link, fragment):\n            if fragment:\n                return link + '#' + fragment\n            return link\n\n        words = DjangoLinkInlineLexerMixin.split_words.findall(target)\n        name, *params = words\n        return self.renderer.link(\n            link=href(reverse(name, args=params), fragment),\n            title=None,\n            text=text,\n        )\n\n\nclass HeaderRendererMixin:\n    \"\"\"Mixin to render headers with auto-generated IDs (or provided IDs).\n\n    If headers are written as usual, they'll be given automatically-generated\n    IDs based on their header level and text.\n\n    Headers can also be specified with an ID at the end wrapped in curly braces:\n\n        ### My Header    {my_id}\n\n    This ID will be used directly without further manipulation, and can be\n    relied on for linking.\n\n    Custom IDs can consist only of lowercase a-z, 0-9, dash, and underscore.\n\n    IDs are tracked into a table of contents which should be reset before\n    rendering a document and read afterwards.\n    \"\"\"\n\n    def reset_toc(self):\n        self.toc = []\n        self.toc_ids = set()\n\n    def get_toc(self):\n        return self.toc\n\n    def header(self, text, level, raw=None):\n        custom_id_match = re.match(r'^(.*?)\\s+{([a-z0-9\\-_]+)}\\s*$', text)\n        if custom_id_match:\n            text = custom_id_match.group(1)\n            id = custom_id_match.group(2)\n\n            if id in self.toc_ids:\n                raise ValueError('Duplicate header ID in Markdown: \"{}\"'.format(id))\n        else:\n            id = 'h{level}_{title}'.format(\n                level=level,\n                title=re.sub('[^a-z0-9\\-_ ]', '', text.lower()).strip().replace(' ', '-'),\n            )\n\n            # dumb collision avoidance\n            while id in self.toc_ids:\n                id += '_'\n\n        self.toc.append((level, text, id))\n        self.toc_ids.add(id)\n        return '<h{level} id=\"{id}\">{text} <a class=\"anchor\" href=\"#{id}\"><span></span></a></h{level}>\\n'.format(\n            level=level,\n            id=id,\n            text=text,\n        )\n\n\nclass OcfMarkdownRenderer(\n    HeaderRendererMixin,\n    mistune.Renderer,\n):\n    pass\n\n\nclass OcfMarkdownInlineLexer(\n    mistune.InlineLexer,\n    DjangoLinkInlineLexerMixin,\n    HtmlCommentsInlineLexerMixin,\n):\n    pass\n\n\nclass OcfMarkdownBlockLexer(\n    mistune.BlockLexer,\n    HtmlCommentsBlockLexerMixin,\n):\n    pass\n\n\n_renderer = OcfMarkdownRenderer(\n    escape=True,\n    hard_wrap=False,\n)\n\n_inline = OcfMarkdownInlineLexer(_renderer)\n_inline.enable_html_comments()\n_inline.enable_django_links()\n\n_block = OcfMarkdownBlockLexer(mistune.BlockGrammar())\n_block.enable_html_comments()\n\n_markdown = mistune.Markdown(\n    renderer=_renderer,\n    inline=_inline,\n    block=_block,\n)\n\n\ndef markdown(text):\n    _renderer.reset_toc()\n    return _markdown(text)\n\n\ndef text_and_meta(f):\n    \"\"\"Return tuple (text, meta dict) for the given file.\n\n    Meta tags are stripped from the Markdown source, but the Markdown is\n    not rendered.\n    \"\"\"\n    text = f.read()\n    meta = {}\n\n    def repl(match):\n        meta[match.group(1)] = match.group(2)\n        return ''\n\n    text = META_REGEX.sub(repl, text)\n    return text, meta\n\n\n@lru_cache()\ndef markdown_and_toc(text):\n    \"\"\"Return tuple (html, toc) for the given text.\"\"\"\n    html = markdown(text)\n    return html, _renderer.get_toc()\n", "path": "ocfweb/component/markdown.py"}]}