Skip to content

Commit

Permalink
Merge pull request #588 from Tencent/bugfix/emphasis-performance-issue
Browse files Browse the repository at this point in the history
fix(emphasis): fix poor performance when matching across lines
  • Loading branch information
jiawei686 authored Sep 14, 2023
2 parents e574f80 + 6246d87 commit fc01d76
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
20 changes: 8 additions & 12 deletions src/core/hooks/Emphasis.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,7 @@
* limitations under the License.
*/
import SyntaxBase from '@/core/SyntaxBase';
import {
compileRegExp,
DO_NOT_STARTS_AND_END_WITH_SPACES_MULTILINE_ALLOW_EMPTY,
ALLOW_WHITESPACE_MULTILINE,
UNDERSCORE_EMPHASIS_BOUNDARY,
} from '@/utils/regexp';
import { compileRegExp, ALLOW_WHITESPACE_MULTILINE, UNDERSCORE_EMPHASIS_BOUNDARY } from '@/utils/regexp';

export default class Emphasis extends SyntaxBase {
static HOOK_NAME = 'fontEmphasis';
Expand Down Expand Up @@ -94,19 +89,20 @@ export default class Emphasis extends SyntaxBase {
*/
rule({ config } = { config: undefined }) {
const allowWhitespace = config ? !!config.allowWhitespace : false;
const REGEX = allowWhitespace
? ALLOW_WHITESPACE_MULTILINE
: DO_NOT_STARTS_AND_END_WITH_SPACES_MULTILINE_ALLOW_EMPTY;
const emRegexp = (allowWhitespace, symbol) => {
const char = `[^${symbol}\\s]`;
return allowWhitespace ? ALLOW_WHITESPACE_MULTILINE : `(${char}|${char}(.*?(\n${char}.*)*)${char})`;
};
const asterisk = {
begin: '(^|[^\\\\])(\\*+)', // ?<leading>, ?<symbol>
content: `(${REGEX})`, // ?<text>
begin: '(^|[^\\\\])([*]+)', // ?<leading>, ?<symbol>
content: `(${emRegexp(allowWhitespace, '*')})`, // ?<text>
end: '\\2',
};

// UNDERSCORE_EMPHASIS_BORDER:允许除下划线以外的「标点符号」和空格出现,使用[^\w\S \t]或[\W\s]会有性能问题
const underscore = {
begin: `(^|${UNDERSCORE_EMPHASIS_BOUNDARY})(_+)`, // ?<leading>, ?<symbol>
content: `(${REGEX})`, // ?<text>
content: `(${emRegexp(allowWhitespace, '_')})`, // ?<text>
end: `\\2(?=${UNDERSCORE_EMPHASIS_BOUNDARY}|$)`,
};

Expand Down
6 changes: 6 additions & 0 deletions src/utils/regexp.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ export const ALLOW_WHITESPACE_MULTILINE = '(?:.*?)(?:(?:\\n.*?)*?)';
export const DO_NOT_STARTS_AND_END_WITH_SPACES = '(?:\\S|(?:\\S.*?\\S))';
export const DO_NOT_STARTS_AND_END_WITH_SPACES_MULTILINE =
'(?:(?:\\S|(?:\\S[^\\n]*?\\S))(?:\\n(?:\\S|(?:\\S[^\\n]*?\\S)))*?)';

/**
* @deprecated
*
* 存在严重性能问题,应弃用
*/
export const DO_NOT_STARTS_AND_END_WITH_SPACES_MULTILINE_ALLOW_EMPTY = '(?:(?:\\S|(?:\\S.*?\\S))(?:[ \\t]*\\n.*?)*?)';

export const NOT_ALL_WHITE_SPACES_INLINE = '(?:[^\\n]*?\\S[^\\n]*?)';
Expand Down

0 comments on commit fc01d76

Please sign in to comment.