Skip to content

Commit

Permalink
feat(v2): support comments for code highlighting (#2456)
Browse files Browse the repository at this point in the history
* feat: support comments for code highlighting

* docs(v2): demonstrate highlighting with comments

* chore: remove debugging console.log

* fix: disable when language is undefined
  • Loading branch information
elviswolcott authored Mar 31, 2020
1 parent 0f73a1f commit 054563b
Show file tree
Hide file tree
Showing 2 changed files with 157 additions and 1 deletion.
113 changes: 112 additions & 1 deletion packages/docusaurus-theme-classic/src/theme/CodeBlock/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,73 @@ import useThemeContext from '@theme/hooks/useThemeContext';
import styles from './styles.module.css';

const highlightLinesRangeRegex = /{([\d,-]+)}/;
const getHighlightDirectiveRegex = (
languages = ['js', 'jsBlock', 'jsx', 'python', 'html'],
) => {
// supported types of comments
const comments = {
js: {
start: '\\/\\/',
end: '',
},
jsBlock: {
start: '\\/\\*',
end: '\\*\\/',
},
jsx: {
start: '\\{\\s*\\/\\*',
end: '\\*\\/\\s*\\}',
},
python: {
start: '#',
end: '',
},
html: {
start: '<!--',
end: '-->',
},
};
// supported directives
const directives = [
'highlight-next-line',
'highlight-start',
'highlight-end',
].join('|');
// to be more reliable, the opening and closing comment must match
const commentPattern = languages
.map(
lang =>
`(?:${comments[lang].start}\\s*(${directives})\\s*${comments[lang].end})`,
)
.join('|');
// white space is allowed, but otherwise it should be on it's own line
return new RegExp(`^\\s*(?:${commentPattern})\\s*$`);
};
// select comment styles based on language
const highlightDirectiveRegex = lang => {
switch (lang) {
case 'js':
case 'javascript':
case 'ts':
case 'typescript':
return getHighlightDirectiveRegex(['js', 'jsBlock']);

case 'jsx':
case 'tsx':
return getHighlightDirectiveRegex(['js', 'jsBlock', 'jsx']);

case 'html':
return getHighlightDirectiveRegex(['js', 'jsBlock', 'html']);

case 'python':
case 'py':
return getHighlightDirectiveRegex(['python']);

default:
// all comment types
return getHighlightDirectiveRegex();
}
};
const codeBlockTitleRegex = /title=".*"/;

export default ({children, className: languageClassName, metastring}) => {
Expand Down Expand Up @@ -86,6 +153,50 @@ export default ({children, className: languageClassName, metastring}) => {
language = prism.defaultLanguage;
}

// only declaration OR directive highlight can be used for a block
let code = children.replace(/\n$/, '');
if (highlightLines.length === 0 && language !== undefined) {
let range = '';
const directiveRegex = highlightDirectiveRegex(language);
// go through line by line
const lines = children.replace(/\n$/, '').split('\n');
let blockStart;
// loop through lines
for (let index = 0; index < lines.length; ) {
const line = lines[index];
// adjust for 0-index
const lineNumber = index + 1;
const match = line.match(directiveRegex);
if (match !== null) {
const directive = match
.slice(1)
.reduce((final, item) => final || item, undefined);
switch (directive) {
case 'highlight-next-line':
range += `${lineNumber},`;
break;

case 'highlight-start':
blockStart = lineNumber;
break;

case 'highlight-end':
range += `${blockStart}-${lineNumber - 1},`;
break;

default:
break;
}
lines.splice(index, 1);
} else {
// lines without directives are unchanged
index += 1;
}
}
highlightLines = rangeParser.parse(range);
code = lines.join('\n');
}

const handleCopyCode = () => {
window.getSelection().empty();
setShowCopied(true);
Expand All @@ -98,7 +209,7 @@ export default ({children, className: languageClassName, metastring}) => {
{...defaultProps}
key={mounted}
theme={prismTheme}
code={children.replace(/\n$/, '')}
code={code}
language={language}>
{({className, style, tokens, getLineProps, getTokenProps}) => (
<>
Expand Down
45 changes: 45 additions & 0 deletions website/docs/markdown-features.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,51 @@ function HighlightSomeText(highlight) {
}
```
You can also use comments with `highlight-next-line`, `highlight-start`, and `highlight-end` to select which lines are highlighted.
```jsx
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';
}
```
```jsx
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';
}
```
JS style (`/* */` and `//`), JSX style (`{ /* */ }`), Python style (`# `), and HTML style (`<!-- -->`) are supported.

To accomplish this, Docusaurus adds the `docusaurus-highlight-code-line` class to the highlighted lines. You will need to define your own styling for this CSS, possibly in your `src/css/custom.css` with a custom background color which is dependent on your selected syntax highlighting theme. The color given below works for the default highlighting theme (Palenight), so if you are using another theme, you will have to tweak the color accordingly.

```css title="/src/css/custom.css"
Expand Down

3 comments on commit 054563b

@lex111
Copy link
Contributor

@lex111 lex111 commented on 054563b Mar 31, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ @yangshun ooops, apparently @elviswolcott forgot to duplicate the changes in the live code block. This is one of the reasons why I created this PR where this problem is solved. #2464 🤕

@yangshun
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it makes sense to have this in the live code block. Did we support line highlighting for live code block?

@lex111
Copy link
Contributor

@lex111 lex111 commented on 054563b Mar 31, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docusaurus-theme-live-codeblock plugin overrides the CodeBlock component, so for it to work (regular code blocks), we always need to duplicate the changes. https://github.com/facebook/docusaurus/blob/master/packages/docusaurus-theme-live-codeblock/src/theme/CodeBlock/index.js

Please sign in to comment.