Skip to content

Commit 1447c8a

Browse files
timaschewQingWei-Li
authored andcommitted
feat: Provide code fragments feature (#748)
1 parent 6ac7bac commit 1447c8a

File tree

4 files changed

+37
-0
lines changed

4 files changed

+37
-0
lines changed

docs/_media/example.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import fetch from 'fetch'
2+
3+
const URL = 'https://example.com'
4+
const PORT = 8080
5+
6+
/// [demo]
7+
const result = fetch(`${URL}:${PORT}`)
8+
.then(function(response) {
9+
return response.json();
10+
})
11+
.then(function(myJson) {
12+
console.log(JSON.stringify(myJson));
13+
});
14+
/// [demo]
15+
16+
result.then(console.log).catch(console.error)

docs/embed-files.md

+15
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,21 @@ You will get it
3939

4040
[filename](_media/example.md ':include :type=code')
4141

42+
## Embedded code fragments
43+
Sometimes you don't want to embed a whole file. Maybe because you need just a few lines but you want to compile and test the file in CI.
44+
45+
```markdown
46+
[filename](_media/example.js ':include :type=code :fragment=demo')
47+
```
48+
49+
In your code file you need to surround the fragment between `/// [demo]` lines (before and after the fragment).
50+
Alternatively you can use `### [demo]`.
51+
52+
Example:
53+
54+
[filename](_media/example.js ':include :type=code :fragment=demo')
55+
56+
4257
## Tag attribute
4358

4459
If you embed the file as `iframe`, `audio` and `video`, then you may need to set the attributes of these tags.

src/core/render/compiler.js

+1
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,7 @@ export class Compiler {
164164
embed = compileMedia[type].call(this, href, title)
165165
embed.type = type
166166
}
167+
embed.fragment = config.fragment
167168

168169
return embed
169170
}

src/core/render/embed.js

+5
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@ function walkFetchEmbed({embedTokens, compile, fetch}, cb) {
2020
if (token.embed.type === 'markdown') {
2121
embedToken = compile.lexer(text)
2222
} else if (token.embed.type === 'code') {
23+
if (token.embed.fragment) {
24+
const fragment = token.embed.fragment
25+
const pattern = new RegExp(`(?:###|\\/\\/\\/)\\s*\\[${fragment}\\]([\\s\\S]*)(?:###|\\/\\/\\/)\\s*\\[${fragment}\\]`)
26+
text = ((text.match(pattern) || [])[1] || '').trim()
27+
}
2328
embedToken = compile.lexer(
2429
'```' +
2530
token.embed.lang +

0 commit comments

Comments
 (0)