facebook / facebook/docusaurus

Use magic comments to define HTML anchors in a code block: // anchor-next-line my-anchor

Open
#11,617 1 comment 0 reactions 0 assignees View on GitHub
feature
Dominant language
TypeScript
Stars
66.2k
Forks
10k
Avg merge
1d 3h
Merged PRs (30d)
52

Description

### Have you read the Contributing Guidelines on issues?

- [x] I have read the [Contributing Guidelines on issues](https://github.com/facebook/docusaurus/blob/main/CONTRIBUTING.md#issues).

### Description

Today you can use [magic comments](https://docusaurus.io/docs/markdown-features/code-blocks#custom-magic-comments) like `// highlight-next-line` to highlight a line in a code block:

````markdown
```js
function HighlightSomeText(highlight) {
if (highlight) {
// highlight-next-line
return 'This text is highlighted!';
}

return 'Nothing highlighted';
}

function HighlightMoreText(highlight) {
// highlight-start
if (highlight) {
return 'This range is highlighted!';
}
// highlight-end

return 'Nothing highlighted';
}
```
````

In the same way, it would be really convenient to be able to make HTML anchor tags, like this:
````markdown
```js
// anchor-next-line api-highlight-some-text
function HighlightSomeText(highlight) {
. . .
}

// anchor-next-line api-highlight-more-text
function HighlightMoreText(highlight) {
. . .
}
```
````
This would produce an HTML ``.

### Has this been requested on Canny?

no

### Motivation

With this feature, your URL can specify `/my-page#api-highlight-more-text`; when visiting this URL, the browser will jump to show that specific line on the web page.

Some websites have fairly large code listings in ` ``` ` blocks, so it would be really handy to be able to hyperlink specific lines of code.

I also considered the idea of enabling the user to hyperlink any arbitrary line (like GitHub does), however with possibly multiple code blocks on the same page, that could be too complicated. Also, in the described scenario, line numbers might get shuffled around when code is updated. The magic comment approach is much more robust.

### API design

The implementation mainly involves adding an `anchor` field to this structure:

https://github.com/facebook/docusaurus/blob/d4a66aa2ed578d0e4d486954a2bbde59cb43bc50/packages/docusaurus-theme-common/src/utils/codeBlockUtils.tsx#L47-L51

### Have you tried building it?

I'm willing to implement this feature, if the Docusaurus maintainers agree with the idea and are interested to accept it.

### Self-service

- [x] I'd be willing to contribute this feature to Docusaurus myself.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.