Skip to content

Commit

Permalink
Merge pull request code-hike#376 from code-hike/from-range
Browse files Browse the repository at this point in the history
`from` annotation with line range
  • Loading branch information
pomber committed Jun 11, 2023
2 parents 984636d + dd65080 commit 716dc3d
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
7 changes: 7 additions & 0 deletions packages/mdx/dev/content/assets/bar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
console.log("one")
console.log("two")
console.log("three")
console.log("four")
console.log("five")
console.log("six")
console.log("seven")
4 changes: 4 additions & 0 deletions packages/mdx/dev/content/external.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
// from ./assets/foo.js
```

```js bar.js
// from ./assets/bar.js 3:5
```

```py foo.py
# from ./assets/foo.py
```
Expand Down
26 changes: 22 additions & 4 deletions packages/mdx/src/remark/code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,9 @@ async function getCodeFromExternalFileIfNeeded(
.map(t => t.content)
.join("")

const codepath = commentData.data
const [codepath, range] = commentData.data
?.trim()
.split(/\s+/)

let fs, path

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

let nodeValue
let content: string
try {
nodeValue = fs.readFileSync(absoluteCodepath, "utf8")
content = fs.readFileSync(absoluteCodepath, "utf8")
} catch (e) {
e.message = `Code Hike couldn't resolve this annotation:
${fileText}
${absoluteCodepath} doesn't exist.`
throw e
}

if (range) {
const [start, end] = range.split(":")
const startLine = parseInt(start)
const endLine = parseInt(end)
if (isNaN(startLine) || isNaN(endLine)) {
throw new Error(
`Code Hike couldn't resolve this annotation:
${fileText}
The range is not valid. Should be something like:
${codepath} 2:5`
)
}
const lines = content.split("\n")
content = lines.slice(startLine - 1, endLine).join("\n")
}

return await highlight({
code: nodeValue,
code: content,
lang: code.lang,
theme: config.theme,
})
Expand Down

0 comments on commit 716dc3d

Please sign in to comment.