Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor as last post-processor #3

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Copyright 2018, Sascha Cowley.
Copyright 2018-2020, Sascha Cowley and contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
Expand All @@ -16,4 +16,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
OTHER DEALINGS IN THE SOFTWARE.
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,31 @@ 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' }
```
**Note**: This is analogous to how the [Markdown in HTML][pmd_mdinhtml] extension &ndash; within Python-Markdown Extra, that comes with Python-Markdown itself &ndash; would allow you to enable markdown processing inside raw HTML blocks by inlcuding `markdown="1"`.

## 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.

This project is copyright 2018 by Sascha Cowley under the [MIT License](LICENSE).
This project is copyright 2018-2020 by Sascha Cowley and contributors [MIT License](LICENSE).


[pmd]: https://python-markdown.github.io/
[pmd_mdinhtml]: https://python-markdown.github.io/extensions/md_in_html/
[pelican]: https://getpelican.com/
[p1]: https://code.google.com/archive/p/markdown-downheader/
[p2]: https://github.com/cprieto/mdx_downheader
[pmdx]: https://python-markdown.github.io/extensions/
[pmdapi]: https://python-markdown.github.io/extensions/
[pelicanconf]: http://docs.getpelican.com/en/stable/settings.html
[3ppmdx]: https://github.com/Python-Markdown/markdown/wiki/third-party-extensions
[3ppmdx]: https://github.com/Python-Markdown/markdown/wiki/third-party-extensions
52 changes: 28 additions & 24 deletions mdx_headdown/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,38 @@
heading levels to offset by. This will automatically be absolutised and
integerised.

(c) 2018, Sascha Cowley under the MIT Licence.
(c) 2018-2020, Sascha Cowley and contributors under the MIT Licence.
"""

# Import relevant modules.
from markdown.extensions import Extension
from markdown.treeprocessors import Treeprocessor
from markdown.postprocessors import Postprocessor
from xml.etree import ElementTree as ET
import re

name = "mdx_headdown"

class DowngradeHeadingsTreeprocessor(Treeprocessor):
""" Downgrade headings via the Treeprocessor interface. """
def run(self, root):
class DowngradeHeadingsPostprocessor(Postprocessor):
""" Downgrade headings via the Preprocessor interface. """
def run(self, text):
# Ensure the offset value is a positive (or zero) integer.
offset = abs(int(self.config['offset']))

# Match headings 1-6 case insensitively if they're the entirety of the
# string, and capture the heading number.
heading_pattern = re.compile('^h([1-6])$', re.I)

for element in root:
# Attempt matching each tag against the heading pattern.
match = heading_pattern.match(element.tag)
if match:
# 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))+offset)
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)

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

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 All @@ -45,15 +49,15 @@ def __init__(self, **kwargs):
super(DowngradeHeadingsExtension, self).__init__(**kwargs)

def extendMarkdown(self, md):
# Register the plugin as a Treeprocessor. """
md.treeprocessors.register(
DowngradeHeadingsTreeprocessor(md),
'downgradeheadings', 200
# Register the plugin as a Postprocessor. """
md.postprocessors.register(
DowngradeHeadingsPostprocessor(md),
'downgradeheadings', 5
)
# And give the actual processor access to the configuration.
DowngradeHeadingsTreeprocessor.config = self.getConfigs()
DowngradeHeadingsPostprocessor.config = self.getConfigs()


def makeExtension(*args, **kwargs):
# Tell Markdown to make this an extension.
return DowngradeHeadingsExtension(*args, **kwargs)
return DowngradeHeadingsExtension(*args, **kwargs)