diff --git a/lib/plugins/tag/include_code.js b/lib/plugins/tag/include_code.js index b96e59e181..f249c14797 100644 --- a/lib/plugins/tag/include_code.js +++ b/lib/plugins/tag/include_code.js @@ -7,6 +7,8 @@ const { highlight } = require('hexo-util'); const rCaptionTitleFile = /(.*)?(?:\s+|^)(\/*\S+)/; const rLang = /\s*lang:(\w+)/i; +const rFrom = /\s*from:(\d+)/i; +const rTo = /\s*to:(\d+)/i; /** * Include code tag @@ -28,6 +30,16 @@ module.exports = ctx => function includeCodeTag(args) { lang = _lang; return ''; }); + let from = 0; + arg = arg.replace(rFrom, (match, _from) => { + from = _from - 1; + return ''; + }); + let to = Number.MAX_VALUE; + arg = arg.replace(rTo, (match, _to) => { + to = _to; + return ''; + }); const match = arg.match(rCaptionTitleFile); @@ -59,7 +71,9 @@ module.exports = ctx => function includeCodeTag(args) { }).then(code => { if (!code) return; - code = stripIndent(code).trim(); + code = stripIndent(code); + const lines = code.split('\n'); + code = lines.slice(from, to).join('\n').trim(); if (!config.enable) { return `
${code}
`; diff --git a/test/scripts/tags/include_code.js b/test/scripts/tags/include_code.js index d12f3b8ebe..610a8ee774 100644 --- a/test/scripts/tags/include_code.js +++ b/test/scripts/tags/include_code.js @@ -58,6 +58,49 @@ describe('include_code', () => { }); }); + it('from', () => { + const fixture = [ + '}' + ].join('\n'); + const expected = highlight(fixture, { + lang: 'js', + caption: 'Hello worldview raw' + }); + + return code('Hello world lang:js from:3 test.js').then(result => { + result.should.eql(expected); + }); + }); + + it('to', () => { + const fixture = [ + 'if (tired && night){', + ' sleep();' + ].join('\n'); + const expected = highlight(fixture, { + lang: 'js', + caption: 'Hello worldview raw' + }); + + return code('Hello world lang:js to:2 test.js').then(result => { + result.should.eql(expected); + }); + }); + + it('from and to', () => { + const fixture = [ + 'sleep();' + ].join('\n'); + const expected = highlight(fixture, { + lang: 'js', + caption: 'Hello worldview raw' + }); + + return code('Hello world lang:js from:2 to:2 test.js').then(result => { + result.should.eql(expected); + }); + }); + it('file not found', () => code('nothing').then(result => { should.not.exist(result); }));