Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: include ranged code lines #3393

Merged
merged 1 commit into from
Jan 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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