Skip to content

Commit 169f789

Browse files
authored
run before and after tokenize hooks (#105)
1 parent 89c194b commit 169f789

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

src/components/Highlight.js

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,10 @@ import type {
1212
TokenInputProps,
1313
TokenOutputProps,
1414
RenderProps,
15+
PrismGrammar,
1516
PrismLib,
1617
PrismTheme,
18+
PrismToken,
1719
} from "../types";
1820

1921
type Props = {
@@ -121,14 +123,35 @@ class Highlight extends Component<Props, *> {
121123
return output;
122124
};
123125

126+
tokenize = (
127+
Prism: PrismLib,
128+
code: string,
129+
grammar: PrismGrammar,
130+
language: Language
131+
): Array<PrismToken> => {
132+
const env = {
133+
code,
134+
grammar,
135+
language,
136+
};
137+
138+
Prism.hooks.run("before-tokenize", env);
139+
env.tokens = Prism.tokenize(env.code, env.grammar, env.language);
140+
Prism.hooks.run("after-tokenize", env);
141+
142+
return env.tokens;
143+
};
144+
124145
render() {
125146
const { Prism, language, code, children } = this.props;
126147

127148
const themeDict = this.getThemeDict(this.props);
128149

129150
const grammar = Prism.languages[language];
130151
const mixedTokens =
131-
grammar !== undefined ? Prism.tokenize(code, grammar, language) : [code];
152+
grammar !== undefined
153+
? this.tokenize(Prism, code, grammar, language)
154+
: [code];
132155
const tokens = normalizeTokens(mixedTokens);
133156

134157
return children({

src/types.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import includedLangs from "./vendor/prism/includeLangs";
55

66
export type Language = $Keys<typeof includedLangs>;
77

8-
type PrismGrammar = {
8+
export type PrismGrammar = {
99
[key: string]: mixed,
1010
};
1111

@@ -37,6 +37,12 @@ export type PrismLib = {
3737
grammar: PrismGrammar,
3838
language: Language
3939
) => string,
40+
hooks: {
41+
run: (
42+
name: string,
43+
env: { code: string, grammar: PrismGrammar, language: Language }
44+
) => void,
45+
},
4046
};
4147

4248
export type StyleObj = {

src/vendor/prism/prism-core.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,7 @@ var Prism = (function () {
339339

340340
hooks: {
341341
add: function () {},
342+
run: function (name, env) {},
342343
},
343344

344345
tokenize: function (text, grammar, language) {

0 commit comments

Comments
 (0)