MCPcopy Index your code
hub / github.com/nodejs/node / highlightRegExp

Function highlightRegExp

lib/internal/util/inspect.js:535–768  ·  view source on GitHub ↗

* Colorize a JavaScript RegExp pattern per ECMAScript grammar. * This is a tolerant single-pass highlighter using heuristics in some cases. * It supports: groups (named/unnamed, lookaround), assertions, alternation, * quantifiers, escapes (incl. Unicode properties), character classes and * backr

(regexpString)

Source from the content-addressed store, hash-verified

533 * @returns {string}
534 */
535function highlightRegExp(regexpString) {
536 let out = '';
537 let i = 0;
538 let depth = 0;
539 let inClass = false;
540
541 // TODO(BridgeAR): Add group type tracking. That allows to increase the depth
542 // in case the same type is next to each other.
543 // let groupType = 0;
544
545 // Verify palette and update cache if user changed colors
546 const paletteNames = highlightRegExp.colors?.length > 0 ?
547 highlightRegExp.colors :
548 highlightRegExpColors;
549
550 const palette = paletteNames.reduce((acc, name) => {
551 const color = inspect.colors[name];
552 if (color) acc.push([`\u001b[${color[0]}m`, `\u001b[${color[1]}m`]);
553 return acc;
554 }, []);
555
556 function writeGroup(start, end, decreaseDepth = 1) {
557 let seq = '';
558 i++;
559 // Only checking for the closing delimiter is a fast heuristic for regular
560 // expressions without the u or v flag. A safer check would verify that the
561 // read characters are all alphanumeric.
562 while (i < regexpString.length && regexpString[i] !== end) {
563 seq += regexpString[i++];
564 }
565 if (i < regexpString.length) {
566 depth -= decreaseDepth;
567 write(start);
568 writeDepth(seq, 1, 1);
569 write(end);
570 depth += decreaseDepth;
571 } else {
572 // The group is not closed which would lead to mistakes in the output.
573 // This is a workaround to prevent output from being corrupted.
574 writeDepth(start, 1, -seq.length);
575 }
576 }
577
578 const write = (str) => {
579 const idx = depth % palette.length;
580 // Safeguard against bugs in the implementation.
581 const color = palette[idx] ?? palette[0];
582 out += color[0] + str + color[1];
583 return idx;
584 };
585
586 function writeDepth(str, incDepth, incI) {
587 depth += incDepth;
588 write(str);
589 depth -= incDepth;
590 i += incI;
591 }
592

Callers

nothing calls this directly

Calls 6

writeGroupFunction · 0.85
writeDepthFunction · 0.85
reduceMethod · 0.80
writeFunction · 0.70
sliceMethod · 0.65
pushMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…