From 76447d2b3883a2a7b8e399c9654f896ca4179f2c Mon Sep 17 00:00:00 2001 From: kezhenxu94 Date: Tue, 1 Jan 2019 10:09:46 +0800 Subject: [PATCH] feature: include ranged code lines (#3393) fix issue #3310 --- lib/plugins/tag/include_code.js | 16 +++++++++++- test/scripts/tags/include_code.js | 43 +++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) 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); }));