Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/markdown-language-features/src/markdownEngine.ts
5240 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import type MarkdownIt = require('markdown-it');
7
import type Token = require('markdown-it/lib/token');
8
import * as vscode from 'vscode';
9
import { ILogger } from './logging';
10
import { MarkdownContributionProvider } from './markdownExtensions';
11
import { MarkdownPreviewConfiguration } from './preview/previewConfig';
12
import { ISlugifier, SlugBuilder } from './slugify';
13
import { ITextDocument } from './types/textDocument';
14
import { WebviewResourceProvider } from './util/resources';
15
import { isOfScheme, Schemes } from './util/schemes';
16
17
/**
18
* Adds begin line index to the output via the 'data-line' data attribute.
19
*/
20
const pluginSourceMap: MarkdownIt.PluginSimple = (md): void => {
21
// Set the attribute on every possible token.
22
md.core.ruler.push('source_map_data_attribute', (state): void => {
23
for (const token of state.tokens) {
24
if (token.map && token.type !== 'inline') {
25
token.attrSet('data-line', String(token.map[0]));
26
token.attrJoin('class', 'code-line');
27
token.attrJoin('dir', 'auto');
28
}
29
}
30
});
31
32
// The 'html_block' renderer doesn't respect `attrs`. We need to insert a marker.
33
const originalHtmlBlockRenderer = md.renderer.rules['html_block'];
34
if (originalHtmlBlockRenderer) {
35
md.renderer.rules['html_block'] = (tokens, idx, options, env, self) => (
36
`<div ${self.renderAttrs(tokens[idx])} ></div>\n` +
37
originalHtmlBlockRenderer(tokens, idx, options, env, self)
38
);
39
}
40
};
41
42
/**
43
* The markdown-it options that we expose in the settings.
44
*/
45
type MarkdownItConfig = Readonly<Required<Pick<MarkdownIt.Options, 'breaks' | 'linkify' | 'typographer'>>>;
46
47
class TokenCache {
48
private _cachedDocument?: {
49
readonly uri: vscode.Uri;
50
readonly version: number;
51
readonly config: MarkdownItConfig;
52
};
53
private _tokens?: Token[];
54
55
public tryGetCached(document: ITextDocument, config: MarkdownItConfig): Token[] | undefined {
56
if (this._cachedDocument
57
&& this._cachedDocument.uri.toString() === document.uri.toString()
58
&& document.version >= 0 && this._cachedDocument.version === document.version
59
&& this._cachedDocument.config.breaks === config.breaks
60
&& this._cachedDocument.config.linkify === config.linkify
61
) {
62
return this._tokens;
63
}
64
return undefined;
65
}
66
67
public update(document: ITextDocument, config: MarkdownItConfig, tokens: Token[]) {
68
this._cachedDocument = {
69
uri: document.uri,
70
version: document.version,
71
config,
72
};
73
this._tokens = tokens;
74
}
75
76
public clean(): void {
77
this._cachedDocument = undefined;
78
this._tokens = undefined;
79
}
80
}
81
82
export interface RenderOutput {
83
html: string;
84
containingImages: Set<string>;
85
}
86
87
interface RenderEnv {
88
readonly containingImages: Set<string>;
89
readonly currentDocument: vscode.Uri | undefined;
90
readonly resourceProvider: WebviewResourceProvider | undefined;
91
readonly slugifier: SlugBuilder;
92
}
93
94
export interface IMdParser {
95
readonly slugifier: ISlugifier;
96
97
tokenize(document: ITextDocument): Promise<Token[]>;
98
}
99
100
export class MarkdownItEngine implements IMdParser {
101
102
private _md?: Promise<MarkdownIt>;
103
104
private readonly _tokenCache = new TokenCache();
105
106
public readonly slugifier: ISlugifier;
107
108
public constructor(
109
private readonly _contributionProvider: MarkdownContributionProvider,
110
slugifier: ISlugifier,
111
private readonly _logger: ILogger,
112
) {
113
this.slugifier = slugifier;
114
115
_contributionProvider.onContributionsChanged(() => {
116
// Markdown plugin contributions may have changed
117
this._md = undefined;
118
this._tokenCache.clean();
119
});
120
}
121
122
123
public async getEngine(resource: vscode.Uri | undefined): Promise<MarkdownIt> {
124
const config = this._getConfig(resource);
125
return this._getEngine(config);
126
}
127
128
private async _getEngine(config: MarkdownItConfig): Promise<MarkdownIt> {
129
if (!this._md) {
130
this._md = (async () => {
131
const markdownIt = await import('markdown-it');
132
let md: MarkdownIt = markdownIt.default(await getMarkdownOptions(() => md));
133
md.linkify.set({ fuzzyLink: false });
134
135
for (const plugin of this._contributionProvider.contributions.markdownItPlugins.values()) {
136
try {
137
md = (await plugin)(md);
138
} catch (e) {
139
console.error('Could not load markdown it plugin', e);
140
}
141
}
142
143
const frontMatterPlugin = await import('markdown-it-front-matter');
144
// Extract rules from front matter plugin and apply at a lower precedence
145
let fontMatterRule: any;
146
// eslint-disable-next-line local/code-no-any-casts
147
frontMatterPlugin.default(<any>{
148
block: {
149
ruler: {
150
before: (_id: any, _id2: any, rule: any) => { fontMatterRule = rule; }
151
}
152
}
153
}, () => { /* noop */ });
154
155
md.block.ruler.before('fence', 'front_matter', fontMatterRule, {
156
alt: ['paragraph', 'reference', 'blockquote', 'list']
157
});
158
159
this._addImageRenderer(md);
160
this._addFencedRenderer(md);
161
this._addLinkNormalizer(md);
162
this._addLinkValidator(md);
163
this._addNamedHeaders(md);
164
this._addLinkRenderer(md);
165
md.use(pluginSourceMap);
166
return md;
167
})();
168
}
169
170
const md = await this._md!;
171
md.set(config);
172
return md;
173
}
174
175
public reloadPlugins() {
176
this._md = undefined;
177
}
178
179
private _tokenizeDocument(
180
document: ITextDocument,
181
config: MarkdownItConfig,
182
engine: MarkdownIt
183
): Token[] {
184
const cached = this._tokenCache.tryGetCached(document, config);
185
if (cached) {
186
return cached;
187
}
188
189
this._logger.trace('MarkdownItEngine', `tokenizeDocument - ${document.uri}`);
190
const tokens = this._tokenizeString(document.getText(), engine);
191
this._tokenCache.update(document, config, tokens);
192
return tokens;
193
}
194
195
private _tokenizeString(text: string, engine: MarkdownIt) {
196
const env: RenderEnv = {
197
currentDocument: undefined,
198
containingImages: new Set<string>(),
199
slugifier: this.slugifier.createBuilder(),
200
resourceProvider: undefined,
201
};
202
return engine.parse(text, env);
203
}
204
205
public async render(input: ITextDocument | string, resourceProvider?: WebviewResourceProvider): Promise<RenderOutput> {
206
const config = this._getConfig(typeof input === 'string' ? undefined : input.uri);
207
const engine = await this._getEngine(config);
208
209
const tokens = typeof input === 'string'
210
? this._tokenizeString(input, engine)
211
: this._tokenizeDocument(input, config, engine);
212
213
const env: RenderEnv = {
214
containingImages: new Set<string>(),
215
currentDocument: typeof input === 'string' ? undefined : input.uri,
216
resourceProvider,
217
slugifier: this.slugifier.createBuilder(),
218
};
219
220
const html = engine.renderer.render(tokens, {
221
...engine.options,
222
...config
223
}, env);
224
225
return {
226
html,
227
containingImages: env.containingImages
228
};
229
}
230
231
public async tokenize(document: ITextDocument): Promise<Token[]> {
232
const config = this._getConfig(document.uri);
233
const engine = await this._getEngine(config);
234
return this._tokenizeDocument(document, config, engine);
235
}
236
237
public cleanCache(): void {
238
this._tokenCache.clean();
239
}
240
241
private _getConfig(resource?: vscode.Uri): MarkdownItConfig {
242
const config = MarkdownPreviewConfiguration.getForResource(resource ?? null);
243
return {
244
breaks: config.previewLineBreaks,
245
linkify: config.previewLinkify,
246
typographer: config.previewTypographer,
247
};
248
}
249
250
private _addImageRenderer(md: MarkdownIt): void {
251
const original = md.renderer.rules.image;
252
md.renderer.rules.image = (tokens: Token[], idx: number, options, env: RenderEnv, self) => {
253
const token = tokens[idx];
254
const src = token.attrGet('src');
255
if (src) {
256
env.containingImages?.add(src);
257
258
if (!token.attrGet('data-src')) {
259
token.attrSet('src', this._toResourceUri(src, env.currentDocument, env.resourceProvider));
260
token.attrSet('data-src', src);
261
}
262
}
263
264
if (original) {
265
return original(tokens, idx, options, env, self);
266
} else {
267
return self.renderToken(tokens, idx, options);
268
}
269
};
270
}
271
272
private _addFencedRenderer(md: MarkdownIt): void {
273
const original = md.renderer.rules['fenced'];
274
md.renderer.rules['fenced'] = (tokens: Token[], idx: number, options, env, self) => {
275
const token = tokens[idx];
276
if (token.map?.length) {
277
token.attrJoin('class', 'hljs');
278
}
279
280
if (original) {
281
return original(tokens, idx, options, env, self);
282
} else {
283
return self.renderToken(tokens, idx, options);
284
}
285
};
286
}
287
288
private _addLinkNormalizer(md: MarkdownIt): void {
289
const normalizeLink = md.normalizeLink;
290
md.normalizeLink = (link: string) => {
291
try {
292
// Normalize VS Code schemes to target the current version
293
if (isOfScheme(Schemes.vscode, link) || isOfScheme(Schemes['vscode-insiders'], link)) {
294
return normalizeLink(vscode.Uri.parse(link).with({ scheme: vscode.env.uriScheme }).toString());
295
}
296
297
} catch (e) {
298
// noop
299
}
300
return normalizeLink(link);
301
};
302
}
303
304
private _addLinkValidator(md: MarkdownIt): void {
305
const validateLink = md.validateLink;
306
md.validateLink = (link: string) => {
307
return validateLink(link)
308
|| isOfScheme(Schemes.vscode, link)
309
|| isOfScheme(Schemes['vscode-insiders'], link)
310
|| /^data:image\/.*?;/.test(link);
311
};
312
}
313
314
private _addNamedHeaders(md: MarkdownIt): void {
315
const original = md.renderer.rules.heading_open;
316
md.renderer.rules.heading_open = (tokens: Token[], idx: number, options, env: unknown, self) => {
317
const title = this._tokenToPlainText(tokens[idx + 1]);
318
const slug = (env as RenderEnv).slugifier ? (env as RenderEnv).slugifier.add(title) : this.slugifier.fromHeading(title);
319
tokens[idx].attrSet('id', slug.value);
320
321
if (original) {
322
return original(tokens, idx, options, env, self);
323
} else {
324
return self.renderToken(tokens, idx, options);
325
}
326
};
327
}
328
329
private _tokenToPlainText(token: Token): string {
330
if (token.children) {
331
return token.children.map(x => this._tokenToPlainText(x)).join('');
332
}
333
334
switch (token.type) {
335
case 'text':
336
case 'emoji':
337
case 'code_inline':
338
return token.content;
339
default:
340
return '';
341
}
342
}
343
344
private _addLinkRenderer(md: MarkdownIt): void {
345
const original = md.renderer.rules.link_open;
346
347
md.renderer.rules.link_open = (tokens: Token[], idx: number, options, env, self) => {
348
const token = tokens[idx];
349
const href = token.attrGet('href');
350
// A string, including empty string, may be `href`.
351
if (typeof href === 'string') {
352
token.attrSet('data-href', href);
353
}
354
if (original) {
355
return original(tokens, idx, options, env, self);
356
} else {
357
return self.renderToken(tokens, idx, options);
358
}
359
};
360
}
361
362
private _toResourceUri(href: string, currentDocument: vscode.Uri | undefined, resourceProvider: WebviewResourceProvider | undefined): string {
363
try {
364
// Support file:// links
365
if (isOfScheme(Schemes.file, href)) {
366
const uri = vscode.Uri.parse(href);
367
if (resourceProvider) {
368
return resourceProvider.asWebviewUri(uri).toString(true);
369
}
370
// Not sure how to resolve this
371
return href;
372
}
373
374
// If original link doesn't look like a url with a scheme, assume it must be a link to a file in workspace
375
if (!/^[a-z\-]+:/i.test(href)) {
376
// Use a fake scheme for parsing
377
let uri = vscode.Uri.parse('markdown-link:' + href);
378
379
// Relative paths should be resolved correctly inside the preview but we need to
380
// handle absolute paths specially to resolve them relative to the workspace root
381
if (uri.path[0] === '/' && currentDocument) {
382
const root = vscode.workspace.getWorkspaceFolder(currentDocument);
383
if (root) {
384
uri = vscode.Uri.joinPath(root.uri, uri.fsPath).with({
385
fragment: uri.fragment,
386
query: uri.query,
387
});
388
389
if (resourceProvider) {
390
return resourceProvider.asWebviewUri(uri).toString(true);
391
} else {
392
uri = uri.with({ scheme: 'markdown-link' });
393
}
394
}
395
}
396
397
return uri.toString(true).replace(/^markdown-link:/, '');
398
}
399
400
return href;
401
} catch {
402
return href;
403
}
404
}
405
}
406
407
async function getMarkdownOptions(md: () => MarkdownIt): Promise<MarkdownIt.Options> {
408
const hljs = (await import('highlight.js')).default;
409
return {
410
html: true,
411
highlight: (str: string, lang?: string) => {
412
lang = normalizeHighlightLang(lang);
413
if (lang && hljs.getLanguage(lang)) {
414
try {
415
return hljs.highlight(str, {
416
language: lang,
417
ignoreIllegals: true,
418
}).value;
419
}
420
catch (error) { }
421
}
422
return md().utils.escapeHtml(str);
423
}
424
};
425
}
426
427
function normalizeHighlightLang(lang: string | undefined) {
428
switch (lang?.toLowerCase()) {
429
case 'shell':
430
return 'sh';
431
432
case 'py3':
433
return 'python';
434
435
case 'tsx':
436
case 'typescriptreact':
437
// Workaround for highlight not supporting tsx: https://github.com/isagalaev/highlight.js/issues/1155
438
return 'jsx';
439
440
case 'json5':
441
case 'jsonc':
442
return 'json';
443
444
case 'c#':
445
case 'csharp':
446
return 'cs';
447
448
default:
449
return lang;
450
}
451
}
452
453