Skip to content

Commit 848c502

Browse files
committed
Add title mode configuration to SuperFences and Highlight
This allows titles to be specified in HTML mode allowing for styled titles.
1 parent 881c052 commit 848c502

9 files changed

Lines changed: 204 additions & 22 deletions

File tree

‎.pyspelling.yml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ matrix:
77
- title
88
- alt
99
ignores:
10-
- ':matches(code, pre)'
11-
- 'a:matches(.magiclink-compare, .magiclink-commit, .magiclink-repository)'
10+
- 'code, pre'
11+
- 'a:is(.magiclink-compare, .magiclink-commit, .magiclink-repository)'
1212
- '.md-social__link'
1313
- 'span.keys'
1414
- '.arithmatex, .md-nav__link, .md-footer-custom-text, .md-source__repository, .headerlink, .md-icon'

‎docs/src/markdown/about/changelog.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,11 @@ icon: lucide/scroll-text
1010
superscript is disabled in the respective extension, CommonMark rules will be honored again. A new `punctuation`
1111
rule has been added to force CommonMark rules. When done, people will need to be aware of punctuation in when
1212
subscript or superscript is enabled and escape any that violates CommonMark rules.
13+
- **NEW**: Highlight: Highlight now allows in the `auto_title_map` specifying the title as a simple string or a
14+
dictionary containing the title and the title mode: either `text` or `html`, with `text` being the default. This
15+
allows a title title to be specified and treated as HTML when the mode is `html`.
16+
- **NEW**: SuperFences: Add new `title_mode` option for Pygments fenced blocks that allows a user to specify a title
17+
to be treated as HTML via `title_mode="html"`.
1318

1419
## 12.1
1520

‎docs/src/markdown/extensions/highlight.md‎

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -149,27 +149,26 @@ Option | Type | Default | Description
149149
`language_prefix` | string | `#!py3 'language-'` | Controls the prefix applied to the language class when Pygments is not used. By default, uses the HTML5 prefix of `language-`.
150150
`code_attr_on_pre` | bool | `#!py3 False` | By default, the language class and all attributes added via the [`attr_list`][attr-list] extension are attached to the `#!html <code>` element. This forces them to be attached to the `#!html <pre>` element.
151151
`auto_title` | bool | `#!py3 False` | When using Pygments, for all code blocks generate a title header with the name of the lexer being used. The lexer name is pulled directly from Pygments and title cased appropriately.
152-
`auto_title_map` | dict | `#!py3 {}` | A dictionary used to override certain titles returned by `auto_title`. Simply specify the title to override as the key and the desired title as the value.
152+
`auto_title_map` | dict | `#!py3 {}` | A dictionary used to override certain titles returned by `auto_title`. Simply specify the title to override as the key and the desired title as the value. If you desire the title to be treated as HTML, specify the title as a dictionary `#!py {"title": "My Title", "mode": "html"}`.
153153
`line_spans` | string | `#!py3 ''` | Controls the Pygments option of a similar name. If set to a nonempty string, e.g. `foo`, the formatter will wrap each output line in a `#!html <span>` tag with an id of `foo-<code_block_number>-<line_number>`.
154154
`anchor_linenums` | bool | `#!py3 False` | Enables the Pygments option of a similar name. If set to `#!py True`, will wrap line numbers in `#!html <a>` tags. Used in combination with `linenums` and `line_anchors`. If `line_anchors` is not configured, `__codelineno` will be assumed as the ID prefix.
155155
`line_anchors` | bool | `#!py3 False` | Controls the Pygments option of a similar name. If set to a nonempty string, e.g. `foo`, the formatter will insert an anchor tag with an id (and name) of `foo-<code_block_number>-<line_number>`.
156156
`pygments_lang_class` | bool | `#!py3 False` | If set to True, the language name used will be included as a class attached to the element with the associated `language_prefix`.
157157
`stripnl` | bool | `#!py3 True` | Strips leading and trailing newlines from code blocks. This is Pygments default behavior. Setting this to `#!py False` disables this and will retain leading and trailing newlines. This has no affect on inline code.
158158

159-
/// new | New 7.1
160-
`linenums_class` was added in `7.1`.
161-
///
159+
> [!new] New 7.1
160+
> `linenums_class` was added in `7.1`.
162161
163-
/// new | New 7.2
164-
`linenums` now accepts `#!py3 None` as the default for allow line numbers to be enabled per code block.
165-
`#!py3 False` now disables line numbers globally preventing line numbers even if specified per code block. `True`
166-
still enables globally.
167-
///
162+
> [!new] New 7.2
163+
> `linenums` now accepts `#!py3 None` as the default for allow line numbers to be enabled per code block.
164+
> `#!py3 False` now disables line numbers globally preventing line numbers even if specified per code block. `True`
165+
> still enables globally.
168166
169-
/// new | New 9.0
170-
`auto_title`, `auto_title_map`, `line_spans`, `anchor_linenums`, and `line_anchors` were all added in `9.0`.
171-
///
167+
> [!new] New 9.0
168+
> `auto_title`, `auto_title_map`, `line_spans`, `anchor_linenums`, and `line_anchors` were all added in `9.0`.
172169
173-
/// new | New 10.7
174-
`default_lang` added in 10.7.
175-
///
170+
> [!new] New 10.7
171+
> `default_lang` added in 10.7.
172+
173+
> [!new] New 12.2
174+
> Added the ability to specify the title mode as `html` in the `auto_title_map`.

‎docs/src/markdown/extensions/superfences.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,6 +548,53 @@ extension_configs:
548548
```
549549
````
550550

551+
Lastly, it may be desirable to utilize raw HTML in titles, if so, `title_mode` can be used to enable HTML mode.
552+
553+
````text title="Undesired Automatic Title"
554+
```py title="HTML <em>example</em>" title_mode="html"
555+
>>> 3 + 3
556+
6
557+
```
558+
````
559+
560+
/// html | div.result
561+
````md-render
562+
---
563+
extensions:
564+
- pymdownx.highlight
565+
- pymdownx.superfences
566+
567+
extension_configs:
568+
pymdownx.highlight:
569+
auto_title: true
570+
line_spans: __codeline_b
571+
line_anchors: __codelineno_b
572+
anchor_linenums: True
573+
---
574+
```py title="HTML <em>example</em>" title_mode="html"
575+
>>> 3 + 3
576+
6
577+
```
578+
````
579+
///
580+
581+
This can also be applied to `auto_title_map`. If HTML mode is desired, just specify the title as a dictionary specifying
582+
the title and the mode:
583+
584+
```py3
585+
extension_configs = {
586+
"pymdownx.highlight": {
587+
"auto_title": True,
588+
"auto_title_map": {
589+
"Python Console Session": {"title": "<strong>Python</strong>", "mode": "html"}
590+
}
591+
}
592+
}
593+
```
594+
595+
> [!new] 12.2
596+
> HTML mode for titles was added in 12.2.
597+
551598
## Pygments Line Anchors and Spans
552599

553600
/// new | New 9.0

‎pymdownx/highlight.py‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -234,15 +234,16 @@ class Highlight:
234234
"""Highlight class."""
235235

236236
def __init__(
237-
self, guess_lang=False, pygments_style='default', use_pygments=True,
237+
self, md, guess_lang=False, pygments_style='default', use_pygments=True,
238238
noclasses=False, extend_pygments_lang=None, linenums=None, linenums_special=-1,
239239
linenums_style='table', linenums_class='linenums', language_prefix='language-',
240240
code_attr_on_pre=False, auto_title=False, auto_title_map=None, line_spans='',
241241
anchor_linenums=False, line_anchors='', pygments_lang_class=False, stripnl=True,
242-
default_lang=''
242+
default_lang='', title_mode='text'
243243
):
244244
"""Initialize."""
245245

246+
self.md = md
246247
self.guess_lang = guess_lang
247248
self.pygments_style = pygments_style
248249
self.use_pygments = use_pygments
@@ -260,6 +261,7 @@ def __init__(
260261
self.pygments_lang_class = pygments_lang_class
261262
self.stripnl = stripnl
262263
self.default_lang = default_lang
264+
self.title_mode=title_mode
263265

264266
if self.anchor_linenums and not self.line_anchors:
265267
self.line_anchors = '__codelineno'
@@ -343,6 +345,7 @@ def highlight(
343345
# Convert with Pygments.
344346
if pygments and self.use_pygments:
345347

348+
title_mode = self.title_mode
346349
if p_ver < (2, 12): # pragma: no cover
347350
raise RuntimeError('Pymdownx Highlight requires at least Pygments 2.12+ if enabling Pygments')
348351

@@ -391,12 +394,23 @@ def highlight(
391394

392395
if title is None and self.auto_title:
393396
name = " ".join([w.title() if w.islower() else w for w in lexer.name.split()])
394-
title = self.auto_title_map.get(name, name)
397+
result = self.auto_title_map.get(name, name)
398+
if isinstance(result, dict):
399+
title = result.get('title', '')
400+
title_mode = result.get('mode', 'text').lower()
401+
else:
402+
title = result
403+
title_mode = 'text'
404+
if title_mode not in ('text', 'html'):
405+
title_mode = 'text'
395406
if title:
396407
title = title.strip()
397408
if title is None:
398409
title = ''
399410

411+
if title and title_mode == 'html':
412+
title = self.md.htmlStash.store(title)
413+
400414
# Setup formatter
401415
html_formatter = InlineHtmlFormatter if inline else BlockHtmlFormatter
402416
formatter = html_formatter(
@@ -508,6 +522,7 @@ def run(self, root):
508522

509523
self.ext.pygments_code_block += 1
510524
code = Highlight(
525+
self.md,
511526
guess_lang=self.config['guess_lang'],
512527
pygments_style=self.config['pygments_style'],
513528
use_pygments=self.config['use_pygments'],

‎pymdownx/inlinehilite.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ def highlight_code(self, src='', language='', classname=None, md=None):
136136

137137
if process_text:
138138
el = self.highlighter(
139+
self.md,
139140
guess_lang=self.guess_lang,
140141
pygments_style=self.pygments_style,
141142
use_pygments=self.use_pygments,

‎pymdownx/superfences.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,14 +172,15 @@ def highlight_validator(language, inputs, options, attrs, md):
172172
"""Highlight validator."""
173173

174174
use_pygments = md.preprocessors['fenced_code_block'].use_pygments
175+
opts = (('hl_lines', RE_HL_LINES), ('linenums', RE_LINENUMS), ('title', None), ('title_mode', None))
175176

176177
for k, v in inputs.items():
177178
matched = False
178179
if use_pygments:
179180
if k.startswith('data-'):
180181
attrs[k] = v
181182
continue
182-
for opt, validator in (('hl_lines', RE_HL_LINES), ('linenums', RE_LINENUMS), ('title', None)):
183+
for opt, validator in opts:
183184
if k == opt:
184185
if v is not True and (validator is None or validator.match(v) is not None):
185186
options[k] = v
@@ -433,6 +434,7 @@ def get_hl_settings(self):
433434
self.pygments_lang_class = config.get('pygments_lang_class', False)
434435
self.stripnl = config.get('stripnl', True)
435436
self.default_lang = config.get('default_lang', True)
437+
self.title_mode = config.get('title_mode', 'text')
436438

437439
def clear(self):
438440
"""Reset the class variables."""
@@ -852,6 +854,7 @@ def highlight(self, src="", language="", options=None, md=None, **kwargs):
852854
linespecial = None
853855
hl_lines = None
854856
title = None
857+
title_mode = self.title_mode
855858

856859
if self.use_pygments:
857860
if 'hl_lines' in options:
@@ -867,6 +870,8 @@ def highlight(self, src="", language="", options=None, md=None, **kwargs):
867870
if 'title' in options:
868871
title = options['title']
869872
del options['title']
873+
if 'title_mode' in options:
874+
title_mode = options['title_mode']
870875

871876
linestep = self.parse_line_step(linestep)
872877
linestart = self.parse_line_start(linestart)
@@ -876,6 +881,7 @@ def highlight(self, src="", language="", options=None, md=None, **kwargs):
876881
self.highlight_ext.pygments_code_block += 1
877882

878883
el = self.highlighter(
884+
self.md,
879885
guess_lang=self.guess_lang,
880886
pygments_style=self.pygments_style,
881887
use_pygments=self.use_pygments,
@@ -894,7 +900,8 @@ def highlight(self, src="", language="", options=None, md=None, **kwargs):
894900
anchor_linenums=self.anchor_linenums,
895901
pygments_lang_class=self.pygments_lang_class,
896902
stripnl=self.stripnl,
897-
default_lang=self.default_lang
903+
default_lang=self.default_lang,
904+
title_mode=title_mode
898905
).highlight(
899906
src,
900907
language,

‎tests/test_extensions/test_highlight.py‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,66 @@ def test_auto_tile_map(self):
129129
)
130130

131131

132+
class TestHighlightAutoTitleMapHTML(util.MdCase):
133+
"""Test title cases."""
134+
135+
extension = ['pymdownx.highlight', 'pymdownx.superfences']
136+
extension_configs = {
137+
'pymdownx.highlight': {
138+
'auto_title': True,
139+
"auto_title_map": {
140+
"Python Console Session": {"title": "<strong>Python</strong>", "mode": "html"}
141+
}
142+
}
143+
}
144+
145+
def test_auto_tile_map(self):
146+
"""Test auto title."""
147+
148+
self.check_markdown(
149+
r'''
150+
```pycon
151+
>>> import test
152+
```
153+
''',
154+
r'''
155+
<div class="highlight"><span class="filename"><strong>Python</strong></span><pre><span></span><code><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span><span class="w"> </span><span class="nn">test</span>
156+
</code></pre></div>
157+
''', # noqa: E501
158+
True
159+
)
160+
161+
162+
class TestHighlightAutoTitleMapBadTitleMode(util.MdCase):
163+
"""Test title cases."""
164+
165+
extension = ['pymdownx.highlight', 'pymdownx.superfences']
166+
extension_configs = {
167+
'pymdownx.highlight': {
168+
'auto_title': True,
169+
"auto_title_map": {
170+
"Python Console Session": {"title": "<strong>Python</strong>", "mode": "bad"}
171+
}
172+
}
173+
}
174+
175+
def test_auto_tile_map(self):
176+
"""Test auto title."""
177+
178+
self.check_markdown(
179+
r'''
180+
```pycon
181+
>>> import test
182+
```
183+
''',
184+
r'''
185+
<div class="highlight"><span class="filename">&lt;strong&gt;Python&lt;/strong&gt;</span><pre><span></span><code><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span><span class="w"> </span><span class="nn">test</span>
186+
</code></pre></div>
187+
''', # noqa: E501
188+
True
189+
)
190+
191+
132192
class TestHighlightInline(util.MdCase):
133193
"""Test highlight inline."""
134194

‎tests/test_extensions/test_superfences.py‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,54 @@ def test_title(self):
105105
True
106106
)
107107

108+
def test_title_html(self):
109+
"""Test auto title."""
110+
111+
self.check_markdown(
112+
r'''
113+
```pycon title="My <strong>title</strong>" title_mode="html"
114+
>>> import test
115+
```
116+
''',
117+
r'''
118+
<div class="highlight"><span class="filename">My <strong>title</strong></span><pre><span></span><code><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span><span class="w"> </span><span class="nn">test</span>
119+
</code></pre></div>
120+
''', # noqa: E501
121+
True
122+
)
123+
124+
def test_title_no_html(self):
125+
"""Test auto title no HTML."""
126+
127+
self.check_markdown(
128+
r'''
129+
```pycon title="My <strong>title</strong>"
130+
>>> import test
131+
```
132+
''',
133+
r'''
134+
<div class="highlight"><span class="filename">My &lt;strong&gt;title&lt;/strong&gt;</span><pre><span></span><code><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span><span class="w"> </span><span class="nn">test</span>
135+
</code></pre></div>
136+
''', # noqa: E501
137+
True
138+
)
139+
140+
def test_title_bad_title_mode(self):
141+
"""Test auto title no HTML."""
142+
143+
self.check_markdown(
144+
r'''
145+
```pycon title="My <strong>title</strong>" title_mode="bad"
146+
>>> import test
147+
```
148+
''',
149+
r'''
150+
<div class="highlight"><span class="filename">My &lt;strong&gt;title&lt;/strong&gt;</span><pre><span></span><code><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span><span class="w"> </span><span class="nn">test</span>
151+
</code></pre></div>
152+
''', # noqa: E501
153+
True
154+
)
155+
108156
def test_title_table(self):
109157
"""Test auto title."""
110158

0 commit comments

Comments
 (0)