Skip to content

Commit

Permalink
feature: include ranged code lines (hexojs#3393)
Browse files Browse the repository at this point in the history
fix issue hexojs#3310
  • Loading branch information
kezhenxu94 authored and Thomas Parisot committed Jan 17, 2020
1 parent c5c12db commit 76447d2
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/plugins/tag/include_code.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);

Expand Down Expand Up @@ -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 `<pre><code>${code}</code></pre>`;
Expand Down
43 changes: 43 additions & 0 deletions test/scripts/tags/include_code.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,49 @@ describe('include_code', () => {
});
});

it('from', () => {
const fixture = [
'}'
].join('\n');
const expected = highlight(fixture, {
lang: 'js',
caption: '<span>Hello world</span><a href="/downloads/code/test.js">view raw</a>'
});

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: '<span>Hello world</span><a href="/downloads/code/test.js">view raw</a>'
});

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: '<span>Hello world</span><a href="/downloads/code/test.js">view raw</a>'
});

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);
}));
Expand Down

0 comments on commit 76447d2

Please sign in to comment.