Skip to content

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

@octogonz

Description

@octogonz

Have you read the Contributing Guidelines on issues?

Description

Today you can use magic comments like // highlight-next-line to highlight a line in a code block:

```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:

```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 <span class="token-line" id="api-highlight-more-text">.

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:

export type MagicCommentConfig = {
className: string;
line?: string;
block?: {start: string; end: string};
};

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

  • I'd be willing to contribute this feature to Docusaurus myself.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureThis is not a bug or issue with Docusausus, per se. It is a feature request for the future.status: needs triageThis issue has not been triaged by maintainers

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions