Skip to content

Commit

Permalink
Selective disable for one heading
Browse files Browse the repository at this point in the history
  • Loading branch information
fancsali committed Mar 24, 2020
1 parent d22847e commit 1b084ec
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,17 @@ MARKDOWN = {
...
```

You can selectively disable processing of a particular heading by adding the `headdown="0"` attribute to it:

```html
<h1 headdown="1">This will remain level 1!</h1>
```

... or using the `attr_list` extension:
```markdown
# This one stays at level 1 { headdown='0'}
```

## Credit

Thanks are owed to the author of [mdx_downheader][p2], whose code I examined for inspiration; and the contributers to the [default python-markdown extensions][pmdx], whose code I examined to get a better idea of what the [manual][pmdapi] was talking about.
Expand Down
16 changes: 12 additions & 4 deletions mdx_headdown/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
# Import relevant modules.
from markdown.extensions import Extension
from markdown.postprocessors import Postprocessor
from xml.etree import ElementTree as ET
import re

name = "mdx_headdown"
Expand All @@ -22,13 +23,20 @@ def run(self, text):
self.offset = abs(int(self.config['offset']))

# Match headings 1-6 case insensitively, and capture the heading number.
heading_pattern = re.compile(r'<h([1-6])>([^<]*)</h\1>', re.I)
heading_pattern = re.compile(r'<h([1-6])[^>]*>([^<]*)</h\1>', re.I)

return re.sub(heading_pattern, self.downgrade, text)

def downgrade(self, mo):
return '<h%(level)d>%(content)s</h%(level)d>' % \
{'level': min(6, int(mo.group(1)) + self.offset), 'content': mo.group(2) }
def downgrade(self, match):
element = ET.fromstring(match.group(0))

# Only process this heading if 'headdown="1"' (or missing...)
if element.attrib.get('headdown', 1) == 1:
# For all headings, increase their heading number by `offset`.
# If the new heading number is > 6, use 6 instead.
element.tag = 'h%d' % min(6, int(match.group(1))+self.offset)

return ET.tostring(element, encoding="unicode")

class DowngradeHeadingsExtension(Extension):
""" Setup the extension for usage. """
Expand Down

0 comments on commit 1b084ec

Please sign in to comment.