Skip to content

Commit

Permalink
feat(markdown): add title support for code blocks (close #1277) (#1456)
Browse files Browse the repository at this point in the history
Co-authored-by: meteorlxy <meteor.lxy@foxmail.com>
  • Loading branch information
nruffing and meteorlxy committed Dec 31, 2023
1 parent 100ba64 commit 706a427
Show file tree
Hide file tree
Showing 6 changed files with 104 additions and 88 deletions.
8 changes: 6 additions & 2 deletions packages/markdown/src/plugins/codePlugin/codePlugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { PluginWithOptions } from 'markdown-it'
import { resolveAttr } from './resolveAttr.js'
import {
isHighlightLine,
resolveHighlightLines,
Expand Down Expand Up @@ -27,7 +28,7 @@ export interface CodePluginOptions {
*
* - Required for `highlightLines`
* - Required for `lineNumbers`
* - Required for language display of default theme
* - Required for title display of default theme
*/
preWrapper?: boolean

Expand Down Expand Up @@ -130,9 +131,12 @@ export const codePlugin: PluginWithOptions<CodePluginOptions> = (
result = `${result}<div class="line-numbers" aria-hidden="true">${lineNumbersCode}</div>`
}

// resolve title from token info
const title = resolveAttr(info, 'title') ?? language.ext

result = `<div class="${languageClass}${
useLineNumbers ? ' line-numbers-mode' : ''
}" data-ext="${language.ext}">${result}</div>`
}" data-ext="${language.ext}" data-title="${title}">${result}</div>`

return result
}
Expand Down
12 changes: 12 additions & 0 deletions packages/markdown/src/plugins/codePlugin/resolveAttr.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Resolve the specified attribute from token info
*/
export const resolveAttr = (info: string, attr: string): string | null => {
// try to match specified attr mark
const pattern = `\\b${attr}\\s*=\\s*(?<quote>['"])(?<content>.+)\\k<quote>(\\s|$)`
const regex = new RegExp(pattern, 'i')
const match = info.match(regex)

// return content if matched, null if not specified
return match?.groups?.content ?? null
}
Loading

0 comments on commit 706a427

Please sign in to comment.