Skip to content

Commit

Permalink
Merge pull request #7 from commenthol/feat-register
Browse files Browse the repository at this point in the history
feat: register languages
  • Loading branch information
valeriangalliat committed Mar 5, 2020
2 parents 7980c36 + 2242296 commit 603503e
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
20 changes: 16 additions & 4 deletions README.md
Expand Up @@ -17,7 +17,19 @@ const md = require('markdown-it')()

The `opts` object can contain:

Name | Description | Default
-------|-------------------------------------------------------------------------|--------
`auto` | Whether to automatically detect language if not specified. | `true`
`code` | Whether to add the `hljs` class to raw code blocks (not fenced blocks). | `true`
Name | Type | Description | Default
-----------|------|----------------------------------------------------------------------------|--------
`auto` | boolean | Whether to automatically detect language if not specified. | `true`
`code` | boolean | Whether to add the `hljs` class to raw code blocks (not fenced blocks). | `true`
`register` | object | Register other languages which are not included in the standard pack. | null

### Register languages

```js
const md = require('markdown-it')()
.use(require('markdown-it-highlightjs'), {
register: {
cypher: require('highlightjs-cypher')
}
})
```
5 changes: 5 additions & 0 deletions index.js
Expand Up @@ -8,6 +8,10 @@ const maybe = f => {
}
}

// allow registration of other languages
const registerLangs = (register) => register &&
Object.entries(register).map(([lang, pack]) => { hljs.registerLanguage(lang, pack) })

// Highlight with given language.
const highlight = (code, lang) =>
maybe(() => hljs.highlight(lang || 'plaintext', code, true).value) || ''
Expand All @@ -28,6 +32,7 @@ const wrap = render =>

const highlightjs = (md, opts) => {
opts = Object.assign({}, highlightjs.defaults, opts)
registerLangs(opts.register)

md.options.highlight = opts.auto ? highlightAuto : highlight
md.renderer.rules.fence = wrap(md.renderer.rules.fence)
Expand Down
7 changes: 7 additions & 0 deletions test.js
Expand Up @@ -37,3 +37,10 @@ equal(
`<pre><code class="hljs">&lt;?php echo 42;
</code></pre>
`)

equal(
md().use(highlightjs, { register: { test: require('highlight.js/lib/languages/sql') } })
.render('```test\nSELECT * FROM TABLE;\n```'),
'<pre><code class="hljs language-test"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">TABLE</span>;\n' +
'</code></pre>\n'
)

0 comments on commit 603503e

Please sign in to comment.