markdownEngine.ts 4.6 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

import * as vscode from 'vscode';
import * as path from 'path';
10
import { TableOfContentsProvider } from './tableOfContentsProvider';
11 12 13 14 15 16 17 18 19

export interface IToken {
	type: string;
	map: [number, number];
}

interface MarkdownIt {
	render(text: string): string;

20
	parse(text: string, env: any): IToken[];
21 22

	utils: any;
23 24

	set(options: any): MarkdownIt;
25 26
}

27
const FrontMatterRegex = /^---\s*[^]*?(-{3}|\.{3})\s*/;
28

29 30 31
export class MarkdownEngine {
	private md: MarkdownIt;

M
Matt Bierner 已提交
32 33
	private firstLine: number;

34 35
	private currentDocument: vscode.Uri;

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
	private plugins: Array<(md: any) => any> = [];

	public addPlugin(factory: (md: any) => any): void {
		if (this.md) {
			this.usePlugin(factory);
		} else {
			this.plugins.push(factory);
		}
	}

	private usePlugin(factory: (md: any) => any): void {
		try {
			this.md = factory(this.md);
		} catch (e) {
			// noop
		}
	}

54 55 56 57 58 59 60 61 62 63 64 65 66 67
	private get engine(): MarkdownIt {
		if (!this.md) {
			const hljs = require('highlight.js');
			const mdnh = require('markdown-it-named-headers');
			this.md = require('markdown-it')({
				html: true,
				highlight: (str: string, lang: string) => {
					if (lang && hljs.getLanguage(lang)) {
						try {
							return `<pre class="hljs"><code><div>${hljs.highlight(lang, str, true).value}</div></code></pre>`;
						} catch (error) { }
					}
					return `<pre class="hljs"><code><div>${this.engine.utils.escapeHtml(str)}</div></code></pre>`;
				}
68
			}).use(mdnh, {
69
				slugify: (header: string) => TableOfContentsProvider.slugify(header)
70
			});
71

72 73 74 75 76
			for (const plugin of this.plugins) {
				this.usePlugin(plugin);
			}
			this.plugins = [];

77 78 79
			for (const renderName of ['paragraph_open', 'heading_open', 'image', 'code_block', 'blockquote_open', 'list_item_open']) {
				this.addLineNumberRenderer(this.md, renderName);
			}
80 81 82 83

			this.addLinkNormalizer(this.md);
			this.addLinkValidator(this.md);
		}
84
		this.md.set({ breaks: vscode.workspace.getConfiguration('markdown').get('preview.breaks', false) });
85 86 87
		return this.md;
	}

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
	private stripFrontmatter(text: string): { text: string, offset: number } {
		let offset = 0;
		const frontMatterMatch = FrontMatterRegex.exec(text);
		if (frontMatterMatch) {
			const frontMatter = frontMatterMatch[0];
			offset = frontMatter.split(/\r\n|\n|\r/g).length - 1;
			text = text.substr(frontMatter.length);
		}
		return { text, offset };
	}

	public render(document: vscode.Uri, stripFrontmatter: boolean, text: string): string {
		let offset = 0;
		if (stripFrontmatter) {
			const markdownContent = this.stripFrontmatter(text);
			offset = markdownContent.offset;
			text = markdownContent.text;
		}
106
		this.currentDocument = document;
107
		this.firstLine = offset;
108 109 110
		return this.engine.render(text);
	}

111
	public parse(document: vscode.Uri, source: string): IToken[] {
A
Alex Dima 已提交
112
		const { text, offset } = this.stripFrontmatter(source);
113 114
		this.currentDocument = document;
		return this.engine.parse(text, {}).map(token => {
115 116 117 118 119
			if (token.map) {
				token.map[0] += offset;
			}
			return token;
		});
120 121 122 123 124 125
	}

	private addLineNumberRenderer(md: any, ruleName: string): void {
		const original = md.renderer.rules[ruleName];
		md.renderer.rules[ruleName] = (tokens: any, idx: number, options: any, env: any, self: any) => {
			const token = tokens[idx];
126
			if (token.map && token.map.length) {
M
Matt Bierner 已提交
127
				token.attrSet('data-line', this.firstLine + token.map[0]);
128 129
				token.attrJoin('class', 'code-line');
			}
130

131 132 133 134 135 136 137 138 139 140 141 142 143
			if (original) {
				return original(tokens, idx, options, env, self);
			} else {
				return self.renderToken(tokens, idx, options, env, self);
			}
		};
	}

	private addLinkNormalizer(md: any): void {
		const normalizeLink = md.normalizeLink;
		md.normalizeLink = (link: string) => {
			try {
				let uri = vscode.Uri.parse(link);
144
				if (!uri.scheme && uri.path && !uri.fragment) {
145 146
					// Assume it must be a file
					if (uri.path[0] === '/') {
147
						uri = vscode.Uri.file(path.join(vscode.workspace.rootPath || '', uri.path));
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
					} else {
						uri = vscode.Uri.file(path.join(path.dirname(this.currentDocument.path), uri.path));
					}
					return normalizeLink(uri.toString(true));
				}
			} catch (e) {
				// noop
			}
			return normalizeLink(link);
		};
	}

	private addLinkValidator(md: any): void {
		const validateLink = md.validateLink;
		md.validateLink = (link: string) => {
			// support file:// links
M
Matt Bierner 已提交
164
			return validateLink(link) || link.indexOf('file:') === 0;
165 166 167
		};
	}
}