Skip to content

from annotation with line range #376

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

Merged
merged 1 commit into from
Jun 11, 2023
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
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