如何使用摊牌对换行进行 GitHub 风格的处理?
我尝试了一个类似的扩展:
return text.replace(/[ ]*\n/g, "<br />\n")
它在某些情况下有效,但例如会破坏列表。
好的,所以我想出了可以做到这一点的扩展。
/**
* Showdown extension for GFM newlines.
*
* In very clear cases, let newlines become <br/> tags.
*
* This implementation is adopted from showdown-ghost.
*
*/
(function () {
var newline = function () {
return [{
type: 'lang',
filter: function(text) {
return text.replace(/^( *(\d+\. {1,4}|[\w\<\'\">\-*+])[^\n]*)\n{1}(?!\n| *\d+\. {1,4}| *[-*+] +|#|$)/gm, function(e) {
return e.trim() + " \n";
})
}
}];
};
if (window.showdown) {
window.showdown.extensions.newline = newline;
}
})();
这对我来说非常有用,尽管正则表达式没有经过 100% 的测试,并且在极少数情况下可能会失败,所以请考虑一下自己的警告。
感谢这个伟大的扩展。这对我的一个项目非常有帮助。
看起来这种定义扩展的方式现在已被弃用。由于他们还没有更新文档,所以我使用 prettify 扩展作为模板来更新您编写的扩展,以在摊牌中使用新的编写扩展的方式:
(function (extension) {
'use strict';
if (typeof showdown !== 'undefined') {
extension(showdown);
} else if (typeof define === 'function' && define.amd) {
define(['showdown'], extension);
} else if (typeof exports === 'object') {
module.exports = extension(require('showdown'));
} else {
throw Error('Could not find showdown library');
}
}(function(showdown){
'use strict';
showdown.extension('newline', function() {
return [{
type: 'lang',
filter: function(text) {
return text.replace(/^( *(\d+\. {1,4}|[\w\<\'\">\-*+])[^\n]*)\n{1}(?!\n| *\d+\. {1,4}| *[-*+] +|#|$)/gm, function(e) {
return e.trim() + " \n";
});
}
}];
})
}));
也许对未来的读者有帮助。Showdown 现在可以选择这样做。
converter.setOption('simpleLineBreaks', true);