-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathmarkdown.ts
More file actions
600 lines (564 loc) · 19.3 KB
/
Copy pathmarkdown.ts
File metadata and controls
600 lines (564 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
import path from 'node:path'
import {
componentPlugin,
type ComponentPluginOptions
} from '@mdit-vue/plugin-component'
import {
frontmatterPlugin,
type FrontmatterPluginOptions
} from '@mdit-vue/plugin-frontmatter'
import {
headersPlugin,
type HeadersPluginOptions
} from '@mdit-vue/plugin-headers'
import { sfcPlugin, type SfcPluginOptions } from '@mdit-vue/plugin-sfc'
import { titlePlugin } from '@mdit-vue/plugin-title'
import { tocPlugin, type TocPluginOptions } from '@mdit-vue/plugin-toc'
import { slugify as defaultSlugify } from '@mdit-vue/shared'
import { anchor as anchorPlugin, type AnchorOptions } from '@mdit/plugin-anchor'
import {
attrs as attrsPlugin,
type MarkdownItAttrsOptions
} from '@mdit/plugin-attrs'
import { fullEmoji as emojiPlugin } from '@mdit/plugin-emoji'
import { footnote as footnotePlugin } from '@mdit/plugin-footnote'
import {
tasklist as tasklistPlugin,
type MarkdownItTaskListOptions
} from '@mdit/plugin-tasklist'
import { MarkdownItAsync, type MarkdownItAsyncOptions } from 'markdown-it-async'
import mditCjkFriendly from 'markdown-it-cjk-friendly'
import type {
BuiltinLanguage,
BuiltinTheme,
CodeToHastOptions,
Highlighter,
LanguageInput,
ShikiTransformer,
ThemeRegistrationAny
} from 'shiki'
import type { Logger } from 'vite'
import type {
Awaitable,
CodeCopyButtonOptions,
LocaleConfig,
MarkdownLocaleOptions
} from '../shared'
import {
containerPlugin,
gitHubAlertsPlugin,
type ContainerOptions
} from './plugins/containers'
import { eagerFrontmatterInterpolationPlugin } from './plugins/eagerFrontmatterInterpolation'
import { highlight as createHighlighter } from './plugins/highlight'
import { imagePlugin, type Options as ImageOptions } from './plugins/image'
import {
includePlugin,
type Options as IncludePluginOptions
} from './plugins/include'
import { lineNumberPlugin } from './plugins/lineNumbers'
import { linkPlugin } from './plugins/link'
import { preWrapperPlugin } from './plugins/preWrapper'
import { restoreEntities } from './plugins/restoreEntities'
import {
snippetPlugin,
type Options as SnippetPluginOptions
} from './plugins/snippet'
import { tablePlugin } from './plugins/table'
export type { Header } from '../shared'
// not exported from @mdit/plugin-emoji, so derive it from the plugin signature
type EmojiPluginOptions = NonNullable<Parameters<typeof emojiPlugin>[1]>
export type ThemeOptions =
| ThemeRegistrationAny
| BuiltinTheme
| {
light: ThemeRegistrationAny | BuiltinTheme
dark: ThemeRegistrationAny | BuiltinTheme
}
// highlight is marked as any to avoid type conflicts with plugins expecting
// regular markdown-it which has sync highlight function. Such plugins will fail
// if they access highlight directly but currently none of the ones we use do that.
export type MarkdownRenderer = MarkdownItAsync & {
options: { highlight?: any }
}
export interface MarkdownOptions extends MarkdownItAsyncOptions {
/* ==================== General Options ==================== */
/**
* Configure the markdown-it instance before any plugins are applied.
*/
preConfig?: (md: MarkdownRenderer) => Awaitable<void>
/**
* Configure the markdown-it instance after all built-in plugins are applied.
*/
config?: (md: MarkdownRenderer) => Awaitable<void>
/**
* Disable cache (experimental)
*/
cache?: boolean
/**
* HTML attributes applied to external links.
* @default { target: '_blank', rel: 'noreferrer' }
*/
externalLinks?: Record<string, string>
/**
* Per-locale overrides for build-time markdown strings (container titles
* and the code copy button title), keyed by locale index. Populated
* automatically from `locales.<index>.markdown` in the site config - pass
* directly only when using `createMarkdownRenderer` standalone.
*/
locales?: Record<string, MarkdownLocaleOptions>
/* ==================== Syntax Highlighting ==================== */
/**
* Custom theme for syntax highlighting.
*
* You can also pass an object with `light` and `dark` themes to support
* dual themes.
*
* @example { theme: 'github-dark' }
* @example { theme: { light: 'github-light', dark: 'github-dark' } }
*
* You can use an existing theme.
* @see https://shiki.style/themes
* Or add your own theme.
* @see https://shiki.style/guide/load-theme
*/
theme?: ThemeOptions
/**
* Custom languages for syntax highlighting or pre-load built-in languages.
* @see https://shiki.style/languages
*/
languages?: (LanguageInput | BuiltinLanguage)[]
/**
* Custom language aliases for syntax highlighting.
* Maps custom language names to existing languages.
* Alias lookup is case-insensitive and underscores in language names are
* displayed as spaces.
*
* @example
*
* Maps `my_lang` to use Python syntax highlighting.
* ```js
* { 'my_lang': 'python' }
* ```
*
* Usage in markdown:
* ````md
* ```My_Lang
* # This will be highlighted as Python code
* # and will show "My Lang" as the language label
* print("Hello, World!")
* ```
* ````
*
* @see https://shiki.style/guide/load-lang#custom-language-aliases
*/
languageAlias?: Record<string, string>
/**
* Fallback language used when the specified language is not available.
*/
defaultHighlightLang?: string
/**
* Transformers applied to code blocks.
* @see https://shiki.style/guide/transformers
*/
codeTransformers?: ShikiTransformer[]
/**
* Color replacements applied during syntax highlighting.
* Accepts either a flat color map or per-theme replacements.
* @see https://shiki.style/guide/theme-colors#color-replacements
*/
colorReplacements?: CodeToHastOptions['colorReplacements']
/**
* Configure the Shiki instance.
*/
shikiSetup?: (shiki: Highlighter) => void | Promise<void>
/* ==================== Code Blocks ==================== */
/**
* Wrap code blocks in a container carrying the language label and the
* copy button. The default theme's code block styling relies on this
* markup. Disabling it also disables `lineNumbers`.
* @default true
*/
preWrapper?: boolean
/**
* Strings for the copy button in code blocks: `tooltipText` is the
* button's tooltip and `copiedText` is shown next to it after copying.
* @default { tooltipText: 'Copy code', copiedText: 'Copied' }
*/
codeCopyButton?: CodeCopyButtonOptions
/**
* Custom language labels for display.
* Overrides the default language label shown in code blocks.
* Keys are case-insensitive.
*
* @example { 'vue': 'Vue SFC' }
*/
languageLabel?: Record<string, string>
/**
* Show line numbers in code blocks. Requires the `preWrapper` plugin.
* @default false
*/
lineNumbers?: boolean
/**
* Options for importing code snippets from files with `<<<`. Set to
* `false` to disable.
* @see https://vitepress.dev/guide/markdown#import-code-snippets
*/
snippet?: SnippetPluginOptions | boolean
/**
* Options for including markdown files with `<!-- @include: path -->`.
* Set to `false` to disable.
* @see https://vitepress.dev/guide/markdown#markdown-file-inclusion
*/
include?: IncludePluginOptions | boolean
/* ==================== Markdown Extensions ==================== */
/**
* Options for `@mdit/plugin-attrs`. Set to `false` to disable. The `fence`
* rule is off by default so that curly attributes never consume code block
* meta (e.g. line highlighting) - add classes to code blocks using shiki
* transformers instead.
* @see https://mdit-plugins.github.io/attrs.html
*/
attrs?: MarkdownItAttrsOptions | boolean
/**
* Options for `@mdit/plugin-emoji`. Set to `false` to disable.
* @see https://mdit-plugins.github.io/emoji.html
*/
emoji?: EmojiPluginOptions | boolean
/**
* Options for `@mdit/plugin-tasklist` (GitHub-style task lists,
* `- [ ] task`). Set to `false` to disable.
* @see https://mdit-plugins.github.io/tasklist.html
*/
tasklist?: MarkdownItTaskListOptions | boolean
/**
* Whether to enable footnotes (`[^1]` references with definitions, plus
* inline `^[note]` syntax).
* @default true
* @see https://mdit-plugins.github.io/footnote.html
*/
footnote?: boolean
/**
* Improves emphasis (`**bold**`) handling in Japanese, Chinese, and
* Korean text.
* @default true
* @see https://github.com/tats-u/markdown-cjk-friendly
*/
cjkFriendlyEmphasis?: boolean
/**
* Options for `@mdit/plugin-anchor`. Set to `false` to disable adding ids
* and anchor links to headings. Note that the default theme's outline and
* heading hash links rely on these ids.
* @see https://mdit-plugins.github.io/anchor.html
*/
anchor?: AnchorOptions | boolean
/**
* Options for `@mdit-vue/plugin-headers`. Set to `true` or pass options
* to collect page headers into page data.
* @default false
* @see https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-headers
*/
headers?: HeadersPluginOptions | boolean
/**
* Options for `@mdit-vue/plugin-toc`. Set to `false` to disable the
* `[[toc]]` syntax.
* @see https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-toc
*/
toc?: TocPluginOptions | boolean
/**
* Math support.
*
* You need to install `markdown-it-mathjax3` and set `math` to `true` to
* enable it. You can also pass options to `markdown-it-mathjax3` here.
* @default false
* @see https://vitepress.dev/guide/markdown#math-equations
*/
math?: any | boolean
/**
* Custom labels for the built-in containers (`::: tip` etc.) and
* additional user-defined containers. Labels are also used as the
* default titles of GitHub-flavored alerts.
* @see https://vitepress.dev/guide/markdown#custom-containers
*/
container?: ContainerOptions | boolean
/**
* Whether to enable GitHub-flavored alerts (`> [!NOTE]`).
* @default true
* @see https://vitepress.dev/guide/markdown#github-flavored-alerts
*/
gfmAlerts?: boolean
/**
* Add `tabindex="0"` to tables so keyboard users can focus and scroll
* them.
* @default true
*/
tableTabIndex?: boolean
/**
* Options for the image plugin (resolves image sources against the public
* directory, adds dimensions, and supports lazy loading). Set to `false`
* to disable.
* @see https://vitepress.dev/guide/markdown#image-lazy-loading
*/
image?: ImageOptions | boolean
/* ==================== Vue Integration ==================== */
/**
* Options for `@mdit-vue/plugin-component`. Set to `false` to disable.
* @see https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-component
*/
component?: ComponentPluginOptions | boolean
/**
* Options for `@mdit-vue/plugin-frontmatter`.
* @see https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-frontmatter
*/
frontmatter?: FrontmatterPluginOptions
/**
* Resolve `{{ $frontmatter.<path> }}` interpolations to their values while
* rendering markdown, so the value also reaches consumers that never run
* Vue - heading anchors and titles, the local search index, content loader
* output, link destinations - and the compiled Vue template gets static
* text instead of a runtime expression. Only bare property paths resolving
* to simple primitive values in the page's own frontmatter are inlined -
* anything else (complex expressions, missing keys, non-primitive values,
* `v-pre` scopes) keeps its runtime interpolation. Set to `false` to leave
* all interpolation to the Vue runtime - for example when
* `transformPageData` rewrites frontmatter values that pages interpolate,
* which would otherwise render the pre-transform value (a warning is
* logged when that happens).
*
* @experimental
* @default true
*/
eagerFrontmatterInterpolation?: boolean
/**
* Options for `@mdit-vue/plugin-sfc`.
* @see https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-sfc
*/
sfc?: SfcPluginOptions
}
// folds `locales.<index>.markdown` entries from the site config into
// `MarkdownOptions.locales` so per-locale strings reach the renderer -
// site config entries win over directly passed ones
export function mergeMarkdownLocales(
options: MarkdownOptions = {},
locales?: LocaleConfig
): MarkdownOptions {
const entries = Object.entries(locales ?? {}).filter(([, l]) => l?.markdown)
if (!entries.length) return options
const merged = { ...options.locales }
for (const [index, { markdown }] of entries) {
merged[index] = { ...merged[index], ...markdown }
}
return { ...options, locales: merged }
}
let md: MarkdownRenderer | undefined
let _disposeHighlighter: (() => void) | undefined
export function disposeMdItInstance() {
if (md) {
md = undefined
_disposeHighlighter?.()
}
}
/**
* @experimental
*/
export async function createMarkdownRenderer(
srcDir: string,
options: MarkdownOptions = {},
base = '/',
logger: Pick<Logger, 'warn'> = console,
publicDir?: string
): Promise<MarkdownRenderer> {
if (md) return md
publicDir ??= path.resolve(srcDir, 'public')
const theme = options.theme ?? { light: 'github-light', dark: 'github-dark' }
const codeCopyButton = {
tooltipText: options.codeCopyButton?.tooltipText || 'Copy code',
copiedText: options.codeCopyButton?.copiedText || 'Copied'
}
const [highlight, dispose] = options.highlight
? [options.highlight, () => {}]
: await createHighlighter(theme, options, logger)
_disposeHighlighter = dispose
md = new MarkdownItAsync({ html: true, linkify: true, highlight, ...options })
md.linkify.set({ fuzzyLink: false })
restoreEntities(md)
if (options.preConfig) {
await options.preConfig(md)
}
const slugify =
normalizePluginOptions(options.anchor)?.slugify ?? defaultSlugify
// VitePress customizations
if (options.preWrapper !== false) {
preWrapperPlugin(md, {
codeCopyButton,
languageLabel: options.languageLabel,
locales: options.locales
})
// must be applied after preWrapper as it augments its output
lineNumberPlugin(md, options.lineNumbers)
}
if (options.snippet !== false) {
snippetPlugin(md, srcDir, normalizePluginOptions(options.snippet), logger)
}
const containerOptions = normalizePluginOptions(options.container)
if (options.container !== false) {
containerPlugin(md, containerOptions, { locales: options.locales })
}
if (options.gfmAlerts !== false) {
gitHubAlertsPlugin(md, containerOptions, { locales: options.locales })
}
if (options.image !== false) {
imagePlugin(md, publicDir, normalizePluginOptions(options.image))
}
linkPlugin(
md,
{ target: '_blank', rel: 'noreferrer', ...options.externalLinks },
base,
slugify
)
// must come after the image and link plugins so that url rebasing runs
// before their href/src handling
if (options.include !== false) {
includePlugin(md, srcDir, normalizePluginOptions(options.include), logger)
}
if (options.tableTabIndex !== false) {
tablePlugin(md)
}
// community plugins
if (options.attrs !== false) {
attrsPlugin(md, {
// no `fence` - code block meta (e.g. line highlighting) must reach
// the highlighter intact
rule: [
'inline',
'table',
'list',
'heading',
'hr',
'softbreak',
'blockInfo',
'blockEnd',
'tasklist'
],
...normalizePluginOptions(options.attrs)
})
}
if (options.emoji !== false) {
emojiPlugin(md, normalizePluginOptions(options.emoji))
}
if (options.tasklist !== false) {
tasklistPlugin(md, normalizePluginOptions(options.tasklist))
}
if (options.footnote !== false) {
footnotePlugin(md)
}
if (options.cjkFriendlyEmphasis !== false) {
mditCjkFriendly(md)
}
if (options.anchor !== false) {
anchorPlugin(md, {
slugify,
getTokensText: (tokens) => {
return tokens
.filter((t) => !['html_inline', 'emoji'].includes(t.type))
.map((t) => t.content)
.join('')
},
permalink: (slug, _, state, idx) => {
const title =
state.tokens[idx + 1]?.children
?.filter((token) => ['text', 'code_inline'].includes(token.type))
.reduce((acc, t) => acc + t.content, '')
.trim() || ''
const linkTokens = [
Object.assign(new state.Token('text', '', 0), { content: ' ' }),
Object.assign(new state.Token('link_open', 'a', 1), {
attrs: [
['class', 'header-anchor'],
['href', `#${slug}`],
['aria-label', `Permalink to “${title}”`]
]
}),
Object.assign(new state.Token('html_inline', '', 0), {
content: '​',
meta: { isPermalinkSymbol: true }
}),
new state.Token('link_close', 'a', -1)
]
state.tokens[idx + 1].children?.push(...linkTokens)
},
...normalizePluginOptions(options.anchor)
})
}
if (options.math) {
try {
const mathPlugin = await import('markdown-it-mathjax3')
;(mathPlugin.default ?? mathPlugin)(md, {
...normalizePluginOptions(options.math)
})
const origMathInline = md.renderer.rules.math_inline!
md.renderer.rules.math_inline = function (...args) {
return origMathInline
.apply(this, args)
.replace(/^<mjx-container /, '<mjx-container v-pre ')
}
const origMathBlock = md.renderer.rules.math_block!
md.renderer.rules.math_block = function (...args) {
return origMathBlock
.apply(this, args)
.replace(/^<mjx-container /, '<mjx-container v-pre tabindex="0" ')
}
} catch (error) {
throw new Error(
'You need to install `markdown-it-mathjax3@^4` to use math support.'
)
}
}
// mdit-vue plugins
if (options.component !== false) {
componentPlugin(md, normalizePluginOptions(options.component))
}
// pass an empty options object to gray-matter, otherwise it would memoize
// the results in an unbounded cache, where the key is the full file content.
// https://github.com/jonschlinkert/gray-matter/blob/310f9349381775d10a221cef903989eb5acc8843/index.js#L44-L47
;(options.frontmatter ??= {}).grayMatterOptions ??= {}
frontmatterPlugin(md, options.frontmatter)
if (options.headers) {
headersPlugin(md, {
level: [2, 3, 4, 5, 6],
slugify,
...normalizePluginOptions(options.headers)
})
}
sfcPlugin(md, options.sfc)
titlePlugin(md)
const tocOptions = normalizePluginOptions(options.toc)
if (options.toc !== false) {
tocPlugin(md, {
slugify,
...tocOptions,
format: (s) => {
const title = s.replaceAll('&', '&') // encoded twice because of restoreEntities
return tocOptions?.format?.(title) ?? title
}
})
}
// applied after anchor/title so its finalize rule runs once their rules
// have extracted the plain resolved text; its main rule is anchored right
// after `text_join` regardless of when the plugin is applied
if (options.eagerFrontmatterInterpolation !== false) {
eagerFrontmatterInterpolationPlugin(md)
}
// apply user config
if (options.config) {
await options.config(md)
}
return md
}
// `true` and `undefined` enable a plugin with its default options - only an
// object carries user-provided plugin options
function normalizePluginOptions<T>(
value: T | boolean | undefined
): T | undefined {
return typeof value === 'boolean' ? undefined : value
}