Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify Marp integration by using independent instance #17

Merged
merged 3 commits into from
Mar 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

## [Unreleased]

### Breaking

- Marp renderer can no longer extend by VSCode extensions ([#17](https://github.com/marp-team/marp-vscode/pull/17))

### Changed

- Simplify Marp integration by using independent instance ([#17](https://github.com/marp-team/marp-vscode/pull/17))

## v0.0.6 - 2019-03-19

### Added
Expand Down
2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -118,14 +118,12 @@
"watch": "rollup -w -c ./rollup.config.js"
},
"devDependencies": {
"@neilsustc/markdown-it-katex": "^0.3.0",
"@types/jest": "^24.0.11",
"@types/markdown-it": "^0.0.7",
"codecov": "^3.2.0",
"jest": "^24.5.0",
"jest-junit": "^6.3.0",
"markdown-it": "^8.4.2",
"markdown-it-emoji": "^1.4.0",
"npm-run-all": "^4.1.5",
"prettier": "^1.16.4",
"rimraf": "^2.6.3",
Expand Down
2 changes: 1 addition & 1 deletion rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const sourcemap = !!process.env.ROLLUP_WATCH

export default [
{
external: [...Object.keys(pkg.dependencies)],
external: [...Object.keys(pkg.dependencies), 'vscode'],
input: `src/${path.basename(pkg.main, '.js')}.ts`,
output: { exports: 'named', file: pkg.main, format: 'cjs', sourcemap },
plugins,
Expand Down
112 changes: 24 additions & 88 deletions src/extension.test.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,31 @@
/** @jest-environment node */
import markdownItKatex from '@neilsustc/markdown-it-katex'
import { Marp } from '@marp-team/marp-core'
import markdownIt from 'markdown-it'
import markdownItEmoji from 'markdown-it-emoji'
import { workspace } from 'vscode'
import { activate, extendMarkdownIt } from './extension'

jest.mock('vscode')

const mockWorkspaceConfig = (conf: { [key: string]: any } = {}) =>
jest.spyOn<any, any>(workspace, 'getConfiguration').mockImplementation(
() =>
new Map<string, any>(
Object.entries({
'markdown.marp.enableHtml': false,
...conf,
})
)
)
const mockWorkspaceConfig = (conf: { [key: string]: any } = {}) => {
const config = {
'markdown.marp.enableHtml': false,
...conf,
}

const confSpy = jest.spyOn(workspace, 'getConfiguration') as jest.SpyInstance
confSpy.mockImplementation((section?: string) => {
const entries: any[] = Object.entries(config)
.map(([k, v]) => {
if (!section) return [k, v]

return k.startsWith(`${section}.`)
? [k.slice(section.length + 1), v]
: undefined
})
.filter(tuple => tuple)

return new Map<string, any>(entries)
})
}

beforeEach(() => mockWorkspaceConfig())
afterEach(() => jest.restoreAllMocks())
Expand All @@ -33,7 +41,7 @@ describe('#extendMarkdownIt', () => {
describe('Marp Core', () => {
const markdown = '# Hello :wave:\n\n<!-- header: Hi -->'

it('has not any extends without marp front-matter', () => {
it('uses default engine without marp front-matter', () => {
const html = extendMarkdownIt(new markdownIt()).render(markdown)

expect(html).not.toContain('<div id="marp-vscode">')
Expand All @@ -42,7 +50,7 @@ describe('#extendMarkdownIt', () => {
expect(html).not.toContain('img')
})

it('extends Marp feature with marp front-matter', () => {
it('uses Marp engine with marp front-matter', () => {
const html = extendMarkdownIt(new markdownIt()).render(marpMd(markdown))

expect(html).toContain('<div id="marp-vscode">')
Expand All @@ -52,78 +60,6 @@ describe('#extendMarkdownIt', () => {
})
})

describe('Emoji support', () => {
it('overrides injected markdown-it-emoji renderer by other plugin', () => {
const md = extendMarkdownIt(new markdownIt().use(markdownItEmoji))

expect(md.render(':+1:')).not.toContain('data-marp-twemoji')
expect(md.render(marpMd(':+1:'))).toContain('data-marp-twemoji')
})
})

describe('Math rendering', () => {
// @neilsustc/markdown-it-katex is used by Markdown All in One.
// https://github.com/yzhang-gh/vscode-markdown
const mdMath = extendMarkdownIt(new markdownIt().use(markdownItKatex))
const markdown = '$y=ax^2$\n\n$$ y=ax^2 $$'

it('renders math via Marp with marp front-matter', () => {
const html = mdMath.render(marpMd(markdown))

expect(html).toContain('<span class="katex">')
expect(html).toContain('data-marp-fitting-math')
})

it('renders math via existed plugin without marp front-matter', () => {
const html = mdMath.render(markdown)

expect(html).toContain('<span class="katex">')
expect(html).not.toContain('data-marp-fitting-math')
})
})

describe('Code highlight', () => {
const markdown = '```javascript\nconst test = 1\n```'

let highlight: jest.Mock
let md: markdownIt
let marpHighlighter: jest.SpyInstance

beforeEach(() => {
marpHighlighter = jest.spyOn(Marp.prototype, 'highlighter')
highlight = jest.fn(() => 'baseHighlight')
md = extendMarkdownIt(new markdownIt({ highlight }))
})

it('uses original highlighter when Marp is disabled', () => {
md.render(markdown)

expect(highlight).toBeCalled()
expect(marpHighlighter).not.toBeCalled()
})

it('uses Marp highlighter when Marp is enabled', () => {
md.render(marpMd(markdown))

expect(highlight).not.toBeCalled()
expect(marpHighlighter).toReturnWith(expect.stringContaining('hljs'))
})

it('supports mermaid plugin by other VSCode plugin', () => {
const html = md.render(marpMd('```mermaid\n>>\n```'))

expect(marpHighlighter).toReturnWith('')
expect(html).toContain('<div class="mermaid">&gt;&gt;')
})

it('passes code through when specified unknown language', () => {
const html = md.render(marpMd('```unknownlang\nv => 5\n```'))

expect(marpHighlighter).toReturnWith('')
expect(html).toContain('<code class="language-unknownlang">')
})
})

describe('Workspace config', () => {
const md = extendMarkdownIt(new markdownIt())

Expand All @@ -139,7 +75,7 @@ describe('#extendMarkdownIt', () => {
mockWorkspaceConfig({ 'markdown.marp.enableHtml': false })

const html = md.render(marpMd('line<br>break'))
expect(html).toContain('line<br>break')
expect(html).toContain('line<br />break')
})

it('renders HTML elements when enabled', () => {
Expand Down
132 changes: 31 additions & 101 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,117 +1,47 @@
import { Marp } from '@marp-team/marp-core'
import { workspace } from 'vscode'
import { ExtensionContext, workspace } from 'vscode'

const frontMatterRegex = /^---\s*([^]*)?(?:-{3}|\.{3})\s*/
const marpDirectiveRegex = /^marp\s*:\s*true\s*$/m
const marpVscodeEnabled = Symbol()
const marpConfiguration = () => workspace.getConfiguration('markdown.marp')
const marpVscode = Symbol('marp-vscode')

export function extendMarkdownIt(md: any) {
const marp: any = new Marp({
container: { tag: 'div', id: 'marp-vscode' },
})

md.use(marp.markdownItPlugins)
.use(instance => {
let originalOptions

// Detect `marp: true` front-matter option
instance.core.ruler.before('normalize', 'marp_vscode_toggle', state => {
originalOptions = instance.options

if (state.inlineMode) return

const fmMatch = frontMatterRegex.exec(state.src)
const enabled = !!(
fmMatch && marpDirectiveRegex.exec(fmMatch[1].trim())
)

instance[marpVscodeEnabled] = enabled
state.marpit(enabled)

if (enabled) {
// Avoid collision to the other math plugins (markdown-it-katex)
md.block.ruler.disable('math_block', true)
md.inline.ruler.disable('math_inline', true)

// Override HTML option
instance.set({
html: workspace
.getConfiguration()
.get<boolean>('markdown.marp.enableHtml')
? true
: marp.options.html,
})
} else {
md.block.ruler.enable('math_block', true)
md.inline.ruler.enable('math_inline', true)
}
const { parse, renderer } = md
const { render } = renderer

md[marpVscode] = false
md.parse = (markdown: string, env: any) => {
// Detect `marp: true` front-matter option
const fmMatch = frontMatterRegex.exec(markdown)
const enabled = !!(fmMatch && marpDirectiveRegex.exec(fmMatch[1].trim()))

// Generate tokens by Marp if enabled
md[marpVscode] =
enabled &&
new Marp({
container: { tag: 'div', id: 'marp-vscode' },
html: marpConfiguration().get<boolean>('enableHtml') || undefined,
})

instance.core.ruler.push('marp_vscode_restore_options', state => {
if (state.inlineMode) return
instance.set(originalOptions)
})
})
.use(instance => {
let originalEmojiRule

instance.core.ruler.push('marp_vscode_postprocess', state => {
if (state.inlineMode) return

// Override markdown-it-emoji renderer provided by other plugin
if (
!originalEmojiRule &&
Object.prototype.hasOwnProperty.call(instance.renderer.rules, 'emoji')
) {
originalEmojiRule = instance.renderer.rules.emoji
instance.renderer.rules.emoji = function(...args) {
if (instance[marpVscodeEnabled]) {
return instance.renderer.rules.marp_emoji(...args)
}
return originalEmojiRule(...args)
}
}
})
})

// Render converted CSS together with Markdown
marp.markdown = md
marp.use(instance => {
instance.core.ruler.push(
'marp_vscode_style',
({ Token, tokens, inlineMode }) => {
if (inlineMode) return

const css = marp.renderStyle(marp.lastGlobalDirectives.theme)
const token = new Token('marp_vscode_style', '', 0)
if (md[marpVscode]) return md[marpVscode].markdown.parse(markdown, env)

token.content = css
tokens.unshift(token)
}
)
})
// Fallback to original instance if Marp was not enabled
return parse.call(md, markdown, env)
}

md.renderer.rules.marp_vscode_style = (token, i) =>
`<style id="marp-vscode-style">${token[i].content}</style>`
renderer.render = (tokens: any[], options: any, env: any) => {
const marp = md[marpVscode]

// Override default highlighter to fix wrong background color
const { highlight } = md.options
if (marp) {
const style = marp.renderStyle(marp.lastGlobalDirectives.theme)
const html = marp.markdown.renderer.render(tokens, options, env)

md.set({
highlight: function marpHighlighter(code, lang) {
if (md[marpVscodeEnabled]) {
const marpHighlight = marp.highlighter(code, lang)
if (marpHighlight) return marpHighlight
return `<style id="marp-vscode-style">${style}</style>${html}`
}

// Special support for mermaid plugin
if (lang && lang.toLowerCase() === 'mermaid') {
return `<div class="mermaid">${md.utils.escapeHtml(code)}</div>`
}
return ''
}
return highlight(code, lang)
},
})
return render.call(renderer, tokens, options, env)
}

return md
}
Expand Down
9 changes: 1 addition & 8 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -337,13 +337,6 @@
call-me-maybe "^1.0.1"
glob-to-regexp "^0.3.0"

"@neilsustc/markdown-it-katex@^0.3.0":
version "0.3.0"
resolved "https://registry.yarnpkg.com/@neilsustc/markdown-it-katex/-/markdown-it-katex-0.3.0.tgz#ecf0c518fb092d9b1b4d3a1082dfc4808218c20f"
integrity sha512-LHJ6ybhlRNPiXoXWkKzVM+RBR3eXqRO0OYMw9yaKOLpxGqXoDJ8OtJqBVSdcezbuYn3hsFtebtv5DjSx6pwDbg==
dependencies:
katex "^0.10.0"

"@nodelib/fs.stat@^1.1.2":
version "1.1.3"
resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-1.1.3.tgz#2b5a3ab3f918cca48a8c754c08168e3f03eba61b"
Expand Down Expand Up @@ -3256,7 +3249,7 @@ jsprim@^1.2.2:
json-schema "0.2.3"
verror "1.10.0"

katex@^0.10.0, katex@^0.10.1:
katex@^0.10.1:
version "0.10.1"
resolved "https://registry.yarnpkg.com/katex/-/katex-0.10.1.tgz#5bb0b72bf19cecfc1fa217a9261760e5d301efff"
integrity sha512-iZXZ2L8pEP7HXBLAaeWkdLxnoRQ8Fdks8IuIVt01tYb+D8e0em5JYgfe6J48wXsuEr512IRCN5Kvwb9FjZH6kg==
Expand Down