diff --git a/docs/extensions/toc.md b/docs/extensions/toc.md index 6db62226..33e0763a 100644 --- a/docs/extensions/toc.md +++ b/docs/extensions/toc.md @@ -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 `

` and `

` elements. + A trivial example: ```python diff --git a/markdown/extensions/toc.py b/markdown/extensions/toc.py index c92f928b..ea8e7062 100644 --- a/markdown/extensions/toc.py +++ b/markdown/extensions/toc.py @@ -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: @@ -466,6 +466,12 @@ def __init__(self, **kwargs): 'separated by a hyphen in between (`2-5`) defines the top (t) and the bottom (b) (..). ' '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. """ diff --git a/tests/test_syntax/extensions/test_toc.py b/tests/test_syntax/extensions/test_toc.py index 372ba09c..f5b6729e 100644 --- a/tests/test_syntax/extensions/test_toc.py +++ b/tests/test_syntax/extensions/test_toc.py @@ -555,6 +555,24 @@ def testAnchorLinkWithDoubleInlineCode(self): extensions=[TocExtension(anchorlink=True)] ) + def testAnchorLinkWithLinkDepth(self): + self.assertMarkdownRenders( + self.dedent( + ''' + # Header 1 + + ## Header *2* + ''' + ), + self.dedent( + ''' +

Header 1

+

Header 2

+ ''' + ), + extensions=[TocExtension(anchorlink=True, link_depth=1)] + ) + def testPermalink(self): self.assertMarkdownRenders( '# Header',