markdown-it + highlight.js简易实现
1、配置highlightjs,针对markdown中各种语言高亮,针对对应的标签 pre code 里面的样式 -- index.js
var hljs = require('highlight.js');
// hljs 只针对pre code 里面的样式 hljs.registerLanguage('actionscript', require('highlight.js/lib/languages/actionscript'));
hljs.registerLanguage('apache', require('highlight.js/lib/languages/apache'));
hljs.registerLanguage('armasm', require('highlight.js/lib/languages/armasm'));
hljs.registerLanguage('xml', require('highlight.js/lib/languages/xml'));
hljs.registerLanguage('asciidoc', require('highlight.js/lib//languages/asciidoc'));
hljs.registerLanguage('avrasm', require('highlight.js/lib/languages/avrasm'));
hljs.registerLanguage('bash', require('highlight.js/lib/languages/bash'));
hljs.registerLanguage('clojure', require('highlight.js/lib/languages/clojure'));
hljs.registerLanguage('cmake', require('highlight.js/lib/languages/cmake'));
hljs.registerLanguage('coffeescript', require('highlight.js/lib/languages/coffeescript'));
hljs.registerLanguage('cpp', require('highlight.js/lib/languages/cpp'));
hljs.registerLanguage('arduino', require('highlight.js/lib/languages/arduino'));
hljs.registerLanguage('css', require('highlight.js/lib/languages/css'));
hljs.registerLanguage('diff', require('highlight.js/lib/languages/diff'));
hljs.registerLanguage('django', require('highlight.js/lib/languages/django'));
hljs.registerLanguage('dockerfile', require('highlight.js/lib/languages/dockerfile'));
hljs.registerLanguage('ruby', require('highlight.js/lib/languages/ruby'));
hljs.registerLanguage('fortran', require('highlight.js/lib/languages/fortran'));
hljs.registerLanguage('glsl', require('highlight.js/lib/languages/glsl'));
hljs.registerLanguage('go', require('highlight.js/lib/languages/go'));
hljs.registerLanguage('groovy', require('highlight.js/lib/languages/groovy'));
hljs.registerLanguage('handlebars', require('highlight.js/lib/languages/handlebars'));
hljs.registerLanguage('haskell', require('highlight.js/lib/languages/haskell'));
hljs.registerLanguage('ini', require('highlight.js/lib/languages/ini'));
hljs.registerLanguage('java', require('highlight.js/lib/languages/java'));
hljs.registerLanguage('javascript', require('highlight.js/lib/languages/javascript'));
hljs.registerLanguage('json', require('highlight.js/lib/languages/json'));
hljs.registerLanguage('less', require('highlight.js/lib/languages/less'));
hljs.registerLanguage('lisp', require('highlight.js/lib/languages/lisp'));
hljs.registerLanguage('livescript', require('highlight.js/lib/languages/livescript'));
hljs.registerLanguage('lua', require('highlight.js/lib/languages/lua'));
hljs.registerLanguage('makefile', require('highlight.js/lib/languages/makefile'));
hljs.registerLanguage('matlab', require('highlight.js/lib/languages/matlab'));
hljs.registerLanguage('mipsasm', require('highlight.js/lib/languages/mipsasm'));
hljs.registerLanguage('perl', require('highlight.js/lib/languages/perl'));
hljs.registerLanguage('nginx', require('highlight.js/lib/languages/nginx'));
hljs.registerLanguage('objectivec', require('highlight.js/lib/languages/objectivec'));
hljs.registerLanguage('php', require('highlight.js/lib/languages/php'));
hljs.registerLanguage('python', require('highlight.js/lib/languages/python'));
hljs.registerLanguage('rust', require('highlight.js/lib/languages/rust'));
hljs.registerLanguage('scala', require('highlight.js/lib/languages/scala'));
hljs.registerLanguage('scheme', require('highlight.js/lib/languages/scheme'));
hljs.registerLanguage('scss', require('highlight.js/lib/languages/scss'));
hljs.registerLanguage('smalltalk', require('highlight.js/lib/languages/smalltalk'));
hljs.registerLanguage('stylus', require('highlight.js/lib/languages/stylus'));
hljs.registerLanguage('swift', require('highlight.js/lib/languages/swift'));
hljs.registerLanguage('tcl', require('highlight.js/lib/languages/tcl'));
hljs.registerLanguage('tex', require('highlight.js/lib/languages/tex'));
hljs.registerLanguage('typescript', require('highlight.js/lib/languages/typescript'));
hljs.registerLanguage('verilog', require('highlight.js/lib/languages/verilog'));
hljs.registerLanguage('vhdl', require('highlight.js/lib/languages/vhdl'));
hljs.registerLanguage('yaml', require('highlight.js/lib/languages/yaml')); var mdHtml; var defaults = {
html: false, // Enable HTML tags in source
xhtmlOut: false, // Use '/' to close single tags (<br />)
breaks: false, // Convert '\n' in paragraphs into <br>
langPrefix: 'language-', // CSS language prefix for fenced blocks
linkify: true, // autoconvert URL-like texts to links
typographer: true, // Enable smartypants and other sweet transforms // options below are for demo only
_highlight: true,
_strict: false,
_view: 'html' // html / src / debug
};
defaults.highlight = function (str, lang) {
var esc = mdHtml.utils.escapeHtml; if (lang && hljs.getLanguage(lang)) {
try {
return '<pre class="hljs"><code>' +
hljs.highlight(lang, str, true).value +
'</code></pre>';
} catch (__) {}
} return '<pre class="hljs"><code>' + esc(str) + '</code></pre>';
}; function mdInit() {
mdHtml = window.markdownit(defaults)
.use(require('markdown-it-abbr'))
.use(require('markdown-it-container'), 'warning')
.use(require('markdown-it-deflist'))
.use(require('markdown-it-emoji'))
.use(require('markdown-it-footnote'))
.use(require('markdown-it-ins'))
.use(require('markdown-it-mark'))
.use(require('markdown-it-sub'))
.use(require('markdown-it-sup'))
.use(require('markdown-it-imsize'))
.use(require('markdown-it-attrs'),{
// optional, these are default options
leftDelimiter: '{',
rightDelimiter: '}',
allowedAttributes: [] // empty array = all attributes are allowed
}) // 可以添加class
.use(require('markdown-it-kbd')) //模拟kbd [[x]]
.use(require('markdown-it-katex'),{"throwOnError" : false, "errorColor" : " #cc0000"}); //数学语法高亮 $\sqrt{3x-1}+(1+x)^2$ // html 标签美化
mdHtml.renderer.rules.table_open = function () {
return '<table class="table table-striped">\n';
};
// 替换 emoji
mdHtml.renderer.rules.emoji = function (token, idx) {
return window.twemoji.parse(token[idx].content);
}; // Inject line numbers for sync scroll. Notes:
//
// - We track only headings and paragraphs on first level. That's enough.
// - Footnotes content causes jumps. Level limit filter it automatically.
function injectLineNumbers(tokens, idx, options, env, slf) {
var line;
if (tokens[idx].map && tokens[idx].level === 0) {
line = tokens[idx].map[0];
tokens[idx].attrJoin('class', 'line');
tokens[idx].attrSet('data-line', String(line));
}
return slf.renderToken(tokens, idx, options, env, slf);
} mdHtml.renderer.rules.paragraph_open = mdHtml.renderer.rules.heading_open = injectLineNumbers;
} $(function () {
mdInit();
var source = $('.source').val();
$('#markinit').html(mdHtml.render(source)); $('.source').on('keyup paste cut mouseup',function(){
var source = $('.source').val();
$('#markinit').html(mdHtml.render(source));
}); })
2、 index.html
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>markdown</title>
<link rel="stylesheet" href="./index.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@9.15.10/styles/ocean.css" integrity="sha256-/k48Q/el/eYQ+d4125d0zSBy6P56LX8iKiUFnP1DU40=" crossorigin="anonymous"> <script src="https://cdn.bootcss.com/markdown-it/10.0.0/markdown-it.min.js"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.15.10/highlight.min.js"></script>
<script src="https://cdn.bootcss.com/twemoji/12.0.4/2/twemoji.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery/1.11.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/katex.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/github-markdown-css/2.2.1/github-markdown.css"/> </head> <body>
<textarea class="source full-height">
---
__Advertisement :)__ - __[pica](https://nodeca.github.io/pica/demo/)__ - high quality and fast image
resize in browser.
- __[babelfish](https://github.com/nodeca/babelfish/)__ - developer friendly
i18n with plurals support and easy syntax. You will like those projects! --- # h1 Heading 8-)
## h2 Heading
### h3 Heading
#### h4 Heading
##### h5 Heading
###### h6 Heading ## Horizontal Rules ___ --- *** ## Typographic replacements Enable typographer option to see result. (c) (C) (r) (R) (tm) (TM) (p) (P) +- test.. test... test..... test?..... test!.... !!!!!! ???? ,, -- --- "Smartypants, double quotes" and 'single quotes' ## Emphasis **This is bold text** __This is bold text__ *This is italic text* _This is italic text_ ~~Strikethrough~~ ## Blockquotes > Blockquotes can also be nested...
>> ...by using additional greater-than signs right next to each other...
> > > ...or with spaces between arrows. ## Lists Unordered + Create a list by starting a line with `+`, `-`, or `*`
+ Sub-lists are made by indenting 2 spaces:
- Marker character change forces new list start:
* Ac tristique libero volutpat at
+ Facilisis in pretium nisl aliquet
- Nulla volutpat aliquam velit
+ Very easy! Ordered 1. Lorem ipsum dolor sit amet
2. Consectetur adipiscing elit
3. Integer molestie lorem at massa 1. You can use sequential numbers...
1. ...or keep all the numbers as `1.` Start numbering with offset: 57. foo
1. bar ## Code Inline `code` Indented code // Some comments
line 1 of code
line 2 of code
line 3 of code Block code "fences" ```
Sample text here...
``` Syntax highlighting ``` js
var foo = function (bar) {
return bar++;
}; console.log(foo(5));
``` ``` java
public String rsaSign(PrivateKey privateKey, String content, String charset){
java.security.Signature signet =
java.security.Signature.getInstance(“SHA1WithRSA”);
signet.initSign(privateKey);
signet.update(content.getBytes(charset));
byte[] signed = signet.sign();
return new String(Base64.encodeBase64(signed),charset);
} ``` ## Tables | Option | Description |
| ------ | ----------- |
| data | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext | extension to be used for dest files. | Right aligned columns | Option | Description |
| ------:| -----------:|
| data | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext | extension to be used for dest files. | ## Links [link text](http://dev.nodeca.com) [link with title](http://nodeca.github.io/pica/demo/ "title text!") Autoconverted link https://github.com/nodeca/pica (enable linkify to see) ## Images ![Minion](https://octodex.github.com/images/minion.png)
![Stormtroopocat](https://octodex.github.com/images/stormtroopocat.jpg "The Stormtroopocat") Like links, Images also have a footnote style syntax ![Alt text][id] With a reference later in the document defining the URL location: [id]: https://octodex.github.com/images/dojocat.jpg "The Dojocat" ## Plugins The killer feature of `markdown-it` is very effective support of
[syntax plugins](https://www.npmjs.org/browse/keyword/markdown-it-plugin). ### [Emojies](https://github.com/markdown-it/markdown-it-emoji) > Classic markup: :wink: :crush: :cry: :tear: :laughing: :yum:
>
> Shortcuts (emoticons): :-) :-( 8-) ;) see [how to change output](https://github.com/markdown-it/markdown-it-emoji#change-output) with twemoji. ### [Subscript](https://github.com/markdown-it/markdown-it-sub) / [Superscript](https://github.com/markdown-it/markdown-it-sup) - 19^th^
- H~2~O ### [\<ins>](https://github.com/markdown-it/markdown-it-ins) ++Inserted text++ ### [\<mark>](https://github.com/markdown-it/markdown-it-mark) ==Marked text== ### [Footnotes](https://github.com/markdown-it/markdown-it-footnote) Footnote 1 link[^first]. Footnote 2 link[^second]. Inline footnote^[Text of inline footnote] definition. Duplicated footnote reference[^second]. [^first]: Footnote **can have markup** and multiple paragraphs. [^second]: Footnote text. ### [Definition lists](https://github.com/markdown-it/markdown-it-deflist) Term 1 : Definition 1
with lazy continuation. Term 2 with *inline markup* : Definition 2 { some code, part of Definition 2 } Third paragraph of definition 2. _Compact style:_ Term 1
~ Definition 1 Term 2
~ Definition 2a
~ Definition 2b ### [Abbreviations](https://github.com/markdown-it/markdown-it-abbr) This is HTML abbreviation example. It converts "HTML", but keep intact partial entries like "xxxHTMLyyy" and so on. *[HTML]: Hyper Text Markup Language ### [Custom containers](https://github.com/markdown-it/markdown-it-container) ::: warning
*here be dragons*
:::
</textarea>
<div id="markinit" class="markdown_views"></div>
<script src="index22.js"></script>
</body> </html>
3.package.json
{
"name": "webpackdemo",
"version": "1.0.0",
"description": "demo",
"main": "index.js",
"scripts": {
"test": "webpack-dev-server --progress --colors --host 127.0.0.1 --port 7890 --in",
"try": "webpack-dev-server --progress --colors --in"
},
"keywords": [
"demo"
],
"author": "Mr liu",
"license": "ISC",
"devDependencies": {
"ansi": "^0.3.0",
"autoprefixer-stylus": "^0.14.0",
"benchmark": "~2.1.0",
"browserify": "^16.3.0",
"chai": "^4.2.0",
"coveralls": "^3.0.4",
"css-loader": "^0.28.10",
"eslint": "^6.0.1",
"express": "^4.14.0",
"highlight.js": "^9.15.10",
"istanbul": "^0.4.5",
"markdown-it-abbr": "^1.0.4",
"markdown-it-container": "^2.0.0",
"markdown-it-deflist": "^2.0.0",
"markdown-it-emoji": "1.4.0",
"markdown-it-footnote": "^3.0.1",
"markdown-it-for-inline": "^0.1.0",
"markdown-it-ins": "^2.0.0",
"markdown-it-mark": "^2.0.0",
"markdown-it-sub": "^1.0.0",
"markdown-it-sup": "^1.0.0",
"markdown-it-testgen": "^0.1.3",
"mocha": "^6.1.4",
"ndoc": "^5.0.0",
"pug-cli": "^1.0.0-alpha6",
"style-loader": "^0.20.3",
"stylus": "^0.54.5",
"supertest": "^4.0.2",
"terser": "^4.1.2",
"webpack": "^4.41.1",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.2"
},
"dependencies": {
"argparse": "^1.0.7",
"entities": "~2.0.0",
"linkify-it": "^2.0.0",
"markdown-it-attrs": "^3.0.1",
"markdown-it-imsize": "^2.0.0",
"markdown-it-katex": "^2.0.3",
"markdown-it-kbd": "^2.0.0",
"mdurl": "^1.0.1",
"uc.micro": "^1.0.5"
}
}
4、readme
webpack npm run try
markdown-it + highlight.js简易实现的更多相关文章
- marked.js简易手册
marked.js简易手册 本文介绍的是marked.js.秉持"来之即用"的原则,对它进行简要的翻译和归纳, 安装 在网上引用或者是引用本地文件即可.要么就用命令行: npm i ...
- 用 highlight.js 为文章中的代码添加语法高亮
来源:http://www.ghostchina.com/adding-syntax-highlighting-to-ghost-using-highlight-js/ --------------- ...
- 使用markdown及highlight
一.markdown 安装markdown2 pip install markdown2 应用markdown2 进入blog APP,创建templatetags文件夹,在文件夹内创建__init_ ...
- Highlight.js语法突出显示
正如我在这个博客开始之前所说的最小可行产品,因此我在几个小时内就开始运行了.这种方法在初始推动之后会减慢你的速度.最新的例子是要提供语法高亮的代码片段. 规格由于使用静态网站生成器,我的狩猎的开始立即 ...
- highlight.js 设置行号
原文地址:highlight.js 设置行号 博客地址:http://www.extlight.com 一.背景 笔者在开发这套博客系统时使用 Editormd 作为 Markdown 编辑器,由于不 ...
- Ghost本地安装highlight.js使代码高亮
对于程序猿写博客来说,这代码高亮是起码的要求.可是Ghost本身没有支持高亮代码. 可是能够通过扩展来实现,它就是highlight.js--附官方站点,看了下首页介绍,真的非常强大,如今说说怎么进行 ...
- 给大家推荐一款高大上的代码高亮插件(sublime,github风格)——highlight.js
经常在一些大神博客里面看到非常好看的高亮代码,有sublime风格,GitHub风格等等.毫无疑问,好的高亮代码插件可以不仅仅让你的博文显得更高大上,更重要的是舒适的阅读体验.经过我在网上的一番搜罗, ...
- highlight.js 页面 代码高亮
官网:https://highlightjs.org/ 功能: 支持 155 种编程语言的语法解析:拥有 73 种样式 自动检测编程语言 可以在 node.js 平台上运行 支持各种标签 与任何 js ...
- js简易日历
js简易日历中设计的知识点:选项卡切换 数组 innerHTML 连接符 与选项卡的区别:div的个数不同 连接符中需要注意的:(优先级) "abc"+12+3+&qu ...
随机推荐
- DAO设计模式总结
1.DAO(Data Access Object,数据访问对象),主要的功能是用于进行数据操作的,在程序的标准开发框架中属于数据层的操作. 数据开发结构流程: 资源层是数据库的操作层,里面可以进行各种 ...
- 粗浅看 Tomcat系统架构分析
原文出处: 吴士龙 http://www.importnew.com/21112.html Tomcat的结构很复杂,但是Tomcat也非常的模块化,找到了Tomcat最核心的模块,就抓住了Tomca ...
- Leetcode173. Binary Search Tree Iterator二叉搜索树迭代器
实现一个二叉搜索树迭代器.你将使用二叉搜索树的根节点初始化迭代器. 调用 next() 将返回二叉搜索树中的下一个最小的数. 注意: next() 和hasNext() 操作的时间复杂度是O(1),并 ...
- 干货来了!2019阿里云合作伙伴峰会SaaS加速器专场回顾合集:嘉宾分享、深度解读
2019年7月26日,在上海举办的阿里云合作伙伴峰会上,阿里云正式发布SaaS生态战略,计划用阿里云的品牌.渠道.资本.方法论.技术加持伙伴,成就亿级营收独角兽. 该生态战略计划招募10家一级SaaS ...
- 微信小程序滚动到某个位置添加class效果。
<scroll-view scroll-y="true" style="height:100vh;" bindscrolltoupper="up ...
- vue 安装 fontawesome
查看最新版的fontawesome 信息: https://github.com/FortAwesome/vue-fontawesome 搜索图标 :https://fontawesome.com/i ...
- dp hdu 5464 Clarke and problem
Problem Description Clarke is a patient with multiple personality disorder. One day, Clarke turned i ...
- Linux监听的网络服务$ netstat -ntlp$ netstat -nulp$ netstat -nxlp
我一般都分开运行这三个命令,不想一下子看到列出一大堆所有的服务.netstat -nalp倒也可以.不过我绝不会用 numeric 选项 (鄙人一点浅薄的看法:IP 地址看起来更方便). 找到所有正在 ...
- Codefroces 213E. Two Permutations
E. Two Permutations time limit per test 3 seconds memory limit per test 256 megabytes input standard ...
- ue4同c#通信时的中文乱码问题
转:https://blog.csdn.net/XIAOZHI0999/article/details/80785570 本文讨论C#同ue4进行通信,出现的中文乱码情况,其他语言类似. 本文分两种情 ...