Skip to content

Commit 716dc3d

Browse files
authored
Merge pull request #376 from code-hike/from-range
`from` annotation with line range
2 parents 984636d + dd65080 commit 716dc3d

File tree

3 files changed

+33
-4
lines changed

3 files changed

+33
-4
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
console.log("one")
2+
console.log("two")
3+
console.log("three")
4+
console.log("four")
5+
console.log("five")
6+
console.log("six")
7+
console.log("seven")

packages/mdx/dev/content/external.mdx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22
// from ./assets/foo.js
33
```
44

5+
```js bar.js
6+
// from ./assets/bar.js 3:5
7+
```
8+
59
```py foo.py
610
# from ./assets/foo.py
711
```

packages/mdx/src/remark/code.ts

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,9 @@ async function getCodeFromExternalFileIfNeeded(
212212
.map(t => t.content)
213213
.join("")
214214

215-
const codepath = commentData.data
215+
const [codepath, range] = commentData.data
216+
?.trim()
217+
.split(/\s+/)
216218

217219
let fs, path
218220

@@ -242,18 +244,34 @@ Looks like node "fs" and "path" modules are not available.`
242244
const dir = path.dirname(config.filepath)
243245
const absoluteCodepath = path.resolve(dir, codepath)
244246

245-
let nodeValue
247+
let content: string
246248
try {
247-
nodeValue = fs.readFileSync(absoluteCodepath, "utf8")
249+
content = fs.readFileSync(absoluteCodepath, "utf8")
248250
} catch (e) {
249251
e.message = `Code Hike couldn't resolve this annotation:
250252
${fileText}
251253
${absoluteCodepath} doesn't exist.`
252254
throw e
253255
}
254256

257+
if (range) {
258+
const [start, end] = range.split(":")
259+
const startLine = parseInt(start)
260+
const endLine = parseInt(end)
261+
if (isNaN(startLine) || isNaN(endLine)) {
262+
throw new Error(
263+
`Code Hike couldn't resolve this annotation:
264+
${fileText}
265+
The range is not valid. Should be something like:
266+
${codepath} 2:5`
267+
)
268+
}
269+
const lines = content.split("\n")
270+
content = lines.slice(startLine - 1, endLine).join("\n")
271+
}
272+
255273
return await highlight({
256-
code: nodeValue,
274+
code: content,
257275
lang: code.lang,
258276
theme: config.theme,
259277
})

0 commit comments

Comments
 (0)