Skip to content
Closed
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
6 changes: 6 additions & 0 deletions docs/extensions/toc.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,12 @@ The following options are provided to configure the output:
included in the Table of Contents. To exclude this first level, you
have to set `toc_depth` to `"4-6"`.

* **`link_depth`**
Add anchors/permalinks only to headings up to this depth (`h1`–`hN`).
Defaults to `6`.

For example, setting `link_depth` to `2` adds anchors only to `<h1>` and `<h2>` elements.

A trivial example:

```python
Expand Down
8 changes: 7 additions & 1 deletion markdown/extensions/toc.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ def __init__(self, md: Markdown, config: dict[str, Any]):
self.permalink_class: str = config["permalink_class"]
self.permalink_title: str = config["permalink_title"]
self.permalink_leading: bool | None = parseBoolValue(config["permalink_leading"], False)
self.header_rgx = re.compile("[Hh][123456]")
self.header_rgx = re.compile(f'[Hh][1-{config["link_depth"]}]')
if isinstance(config["toc_depth"], str) and '-' in config["toc_depth"]:
self.toc_top, self.toc_bottom = [int(x) for x in config["toc_depth"].split('-')]
else:
Expand Down Expand Up @@ -466,6 +466,12 @@ def __init__(self, **kwargs):
'separated by a hyphen in between (`2-5`) defines the top (t) and the bottom (b) (<ht>..<hb>). '
'Default: `6` (bottom).'
],
'link_depth': [
6,
'Add anchors/permalinks only to headings up to this depth (`h1`–`hN`). '
'For example, `link_depth: 2` adds them to `h1` and `h2` only. '
'Default: `6`'
]
}
""" Default configuration options. """

Expand Down
18 changes: 18 additions & 0 deletions tests/test_syntax/extensions/test_toc.py
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,24 @@ def testAnchorLinkWithDoubleInlineCode(self):
extensions=[TocExtension(anchorlink=True)]
)

def testAnchorLinkWithLinkDepth(self):
self.assertMarkdownRenders(
self.dedent(
'''
# Header 1

## Header *2*
'''
),
self.dedent(
'''
<h1 id="header-1"><a class="toclink" href="#header-1">Header 1</a></h1>
<h2>Header <em>2</em></h2>
'''
),
extensions=[TocExtension(anchorlink=True, link_depth=1)]
)

def testPermalink(self):
self.assertMarkdownRenders(
'# Header',
Expand Down
Loading