Commit c18b0aa

Browse files
avivkelleraduh95
authored andcommitted
repl: add basic syntax highlighting
Signed-off-by: avivkeller <me@aviv.sh> PR-URL: #64591 Backport-PR-URL: #65267 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent 137ff67 commit c18b0aa

11 files changed

Lines changed: 209 additions & 19 deletions

‎lib/internal/readline/interface.js‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,13 +157,15 @@ const kPreviousCursorCols = Symbol('_previousCursorCols');
157157
constkMultilineMove=Symbol('_multilineMove');
158158
constkPreviousPrevRows=Symbol('_previousPrevRows');
159159
constkAddNewLineOnTTY=Symbol('_addNewLineOnTTY');
160+
constkColorize=Symbol('_colorize');
160161

161162
functionInterfaceConstructor(input,output,completer,terminal){
162163
this[kSawReturnAt]=0;
163164
// TODO(BridgeAR): Document this property. The name is not ideal, so we
164165
// might want to expose an alias and document that instead.
165166
this.isCompletionEnabled=true;
166167
this[kSawKeyPress]=false;
168+
this[kColorize]=undefined;
167169
this[kPreviousKey]=null;
168170
this.escapeCodeTimeout=ESCAPE_CODE_TIMEOUT;
169171
this.tabSize=8;
@@ -186,6 +188,7 @@ function InterfaceConstructor(input, output, completer, terminal) {
186188
consthistorySize=input.historySize;
187189
consthistory=input.history;
188190
constremoveHistoryDuplicates=input.removeHistoryDuplicates;
191+
this[kColorize]=input.colorize;
189192

190193
if(input.tabSize!==undefined){
191194
validateUint32(input.tabSize,'tabSize',true);
@@ -523,15 +526,18 @@ class Interface extends InterfaceConstructor {
523526
if(this[kIsMultiline]){
524527
constlines=StringPrototypeSplit(this.line,'\n');
525528
// Write first line with normal prompt
526-
this[kWriteToOutput](this[kPrompt]+lines[0]);
529+
this[kWriteToOutput](this[kPrompt]+
530+
(this[kColorize]?.(lines[0])??lines[0]));
527531

528532
// For continuation lines, add the "|" prefix
529533
for(leti=1;i<lines.length;i++){
530-
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+lines[i]);
534+
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+
535+
(this[kColorize]?.(lines[i])??lines[i]));
531536
}
532537
}else{
533538
// Write the prompt and the current buffer content.
534-
this[kWriteToOutput](line);
539+
this[kWriteToOutput](this[kPrompt]+
540+
(this[kColorize]?.(this.line)??this.line));
535541
}
536542

537543
// Force terminal to allocate a new line
@@ -687,7 +693,11 @@ class Interface extends InterfaceConstructor {
687693
this.line+=c;
688694
}
689695
this.cursor+=c.length;
690-
this[kWriteToOutput](c);
696+
if(this[kColorize]===undefined){
697+
this[kWriteToOutput](c);
698+
}else{
699+
this[kRefreshLine]();
700+
}
691701
return;
692702
}
693703
if(this.cursor<this.line.length){
@@ -706,7 +716,7 @@ class Interface extends InterfaceConstructor {
706716
this.cursor+=c.length;
707717
constnewPos=this.getCursorPos();
708718

709-
if(oldPos.rows<newPos.rows){
719+
if(oldPos.rows<newPos.rows||this[kColorize]!==undefined){
710720
this[kRefreshLine]();
711721
}else{
712722
this[kWriteToOutput](c);

‎lib/internal/repl/highlight.js‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
'use strict';
2+
3+
const{
4+
FunctionPrototypeBind,
5+
StringPrototypeSlice,
6+
}=primordials;
7+
8+
const{ stylizeWithColor }=require('internal/util/inspect');
9+
const{ Parser }=require('internal/deps/acorn/acorn/dist/acorn');
10+
11+
consttokenizer=FunctionPrototypeBind(Parser.tokenizer,Parser);
12+
13+
functiontokenStyle(token){
14+
const{ label, keyword }=token.type;
15+
16+
if(keyword!==undefined){
17+
if(label==='true'||label==='false')return'boolean';
18+
if(label==='null')return'null';
19+
if(label==='import'||label==='export')return'module';
20+
return'special';
21+
}
22+
23+
switch(label){
24+
case'name':
25+
switch(token.value){
26+
case'undefined':
27+
return'undefined';
28+
case'NaN':
29+
case'Infinity':
30+
return'number';
31+
case'Symbol':
32+
return'symbol';
33+
case'Date':
34+
return'date';
35+
default:
36+
returnundefined;
37+
}
38+
case'num':
39+
return'number';
40+
case'bigint':
41+
return'bigint';
42+
case'string':
43+
case'template':
44+
case'`':
45+
return'string';
46+
case'regexp':
47+
return'regexp';
48+
default:
49+
returnundefined;
50+
}
51+
}
52+
53+
functionhighlight(code){
54+
if(code.length===0)returncode;
55+
56+
letresult='';
57+
letoffset=0;
58+
functionwrite(start,end,style){
59+
result+=
60+
StringPrototypeSlice(code,offset,start)+
61+
stylizeWithColor(StringPrototypeSlice(code,start,end),style);
62+
offset=end;
63+
}
64+
65+
try{
66+
constiterator=tokenizer(code,{
67+
__proto__: null,
68+
allowHashBang: true,
69+
ecmaVersion: 'latest',
70+
onComment(_block,_text,start,end){
71+
write(start,end,'undefined');
72+
},
73+
});
74+
75+
for(consttokenofiterator){
76+
conststyle=tokenStyle(token);
77+
if(style!==undefined){
78+
write(token.start,token.end,style);
79+
}
80+
}
81+
}catch{
82+
// Acorn throws for unfinished strings, templates, and comments. Tokens and
83+
// comments reported before that point are still useful while typing.
84+
}
85+
86+
returnresult+StringPrototypeSlice(code,offset);
87+
}
88+
89+
module.exports={ highlight };

‎lib/internal/util/inspect.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3057,6 +3057,7 @@ module.exports = {
30573057
identicalSequenceRange,
30583058
inspect,
30593059
inspectDefaultOptions,
3060+
stylizeWithColor,
30603061
format,
30613062
formatWithOptions,
30623063
getStringWidth,

‎lib/repl.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ const {
109109
}=require('internal/readline/utils');
110110
const{ Console }=require('console');
111111
const{ shouldColorize }=require('internal/util/colors');
112+
const{ highlight }=require('internal/repl/highlight');
112113
constCJSModule=require('internal/modules/cjs/loader').Module;
113114
const{ AsyncLocalStorage }=require('async_hooks');
114115
letdebug=require('internal/util/debuglog').debuglog('repl',(fn)=>{
@@ -326,6 +327,7 @@ class REPLServer extends Interface {
326327
terminal: options.terminal,
327328
historySize: options.historySize,
328329
prompt,
330+
colorize: options.useColors ? highlight : undefined,
329331
});
330332

331333
ObjectDefineProperty(this,'inputStream',{
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Flags: --expose-internals
2+
'use strict';
3+
4+
constcommon=require('../common');
5+
constassert=require('assert');
6+
const{ inspect, stripVTControlCharacters }=require('util');
7+
constArrayStream=require('../common/arraystream');
8+
const{ highlight }=require('internal/repl/highlight');
9+
const{ REPLServer }=require('repl');
10+
11+
common.skipIfInspectorDisabled();
12+
13+
assert.strictEqual(stripVTControlCharacters(highlight(
14+
'const /* comment */ answer = 42; // comment',
15+
)),'const /* comment */ answer = 42; // comment');
16+
17+
assert.strictEqual(
18+
highlight('const value = "text"'),
19+
`\u001b[${inspect.colors.cyan[0]}mconst\u001b[${inspect.colors.cyan[1]}m value = `+
20+
`\u001b[${inspect.colors.green[0]}m"text"\u001b[${inspect.colors.green[1]}m`,
21+
);
22+
23+
for(constsourceof[
24+
'undefined',
25+
'NaN',
26+
'Infinity',
27+
'Symbol.iterator',
28+
'Date.now()',
29+
'true',
30+
'null',
31+
'1n',
32+
'/regexp/u',
33+
'import("node:fs")',
34+
]){
35+
assert.notStrictEqual(highlight(source),source);
36+
}
37+
38+
// Incomplete source is expected while the user is typing.
39+
highlight('const value = "');
40+
41+
{
42+
constinput=newArrayStream();
43+
constoutput=newArrayStream();
44+
letrendered='';
45+
output.write=(chunk)=>{
46+
rendered+=chunk;
47+
};
48+
49+
constrepl=newREPLServer({
50+
input,
51+
output,
52+
prompt: '',
53+
terminal: true,
54+
useColors: false,
55+
});
56+
rendered='';
57+
repl.write('const');
58+
59+
assert.strictEqual(rendered,'const');
60+
repl.close();
61+
}

‎test/parallel/test-repl-multiline.js‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,24 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
const{ startNewREPLServer }=require('../common/repl');
5+
const{ stripVTControlCharacters }=require('util');
56

67
constinput=['const foo = {','};','foo'];
78

89
functionrun({ useColors }){
910
const{ replServer, output }=startNewREPLServer({ useColors });
1011

1112
replServer.on('exit',common.mustCall(()=>{
12-
constactual=output.accumulator.split('\n');
13+
// The output contains various escape codes, including
14+
// screen clears and others, so we trim them all to
15+
// simplify this test.
16+
constactual=stripVTControlCharacters(output.accumulator);
1317

14-
// Validate the output, which contains terminal escape codes.
15-
assert.strictEqual(actual.length,6);
16-
assert.ok(actual[0].endsWith(input[0]));
17-
assert.ok(actual[1].includes('| '));
18-
assert.ok(actual[1].endsWith(input[1]));
19-
assert.ok(actual[2].includes('undefined'));
20-
assert.ok(actual[3].endsWith(input[2]));
21-
assert.strictEqual(actual[4],'{}');
18+
constfirstStatementIdx=actual.indexOf(input.slice(0,1).join('\n| '));
19+
assert(firstStatementIdx>-1);
20+
21+
assert(actual.slice(firstStatementIdx).includes('undefined'));
22+
assert(actual.slice(firstStatementIdx).includes('foo'));
2223
}));
2324

2425
input.forEach((line)=>replServer.write(`${line}\n`));

‎test/parallel/test-repl-preview-newlines.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,14 @@ const { startNewREPLServer } = require('../common/repl');
66

77
common.skipIfInspectorDisabled();
88

9-
const{ input, output }=startNewREPLServer({useColors: true});
9+
// Ignore terminal settings so the preview remains active under TERM=dumb.
10+
process.env.TERM='';
11+
12+
// Keep syntax highlighting out of this test so it only covers preview layout.
13+
// Preview and result colors are enabled after readline is initialized.
14+
const{ input, output, replServer }=startNewREPLServer({useColors: false});
15+
replServer.useColors=true;
16+
replServer.writer.options.colors=true;
1017

1118
output.accumulator='';
1219

‎test/parallel/test-repl-preview-without-inspector.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,13 @@ const repl = new REPLServer({
6969
prompt: PROMPT,
7070
stream: newREPLStream(),
7171
ignoreUndefined: true,
72-
useColors: true,
72+
// Keep syntax highlighting out of these preview transcript assertions.
73+
// Preview and result colors are enabled after readline is initialized.
74+
useColors: false,
7375
terminal: true,
7476
});
77+
repl.useColors=true;
78+
repl.writer.options.colors=true;
7579

7680
repl.inputStream.run([
7781
'function foo(x) { return x; }',

‎test/parallel/test-repl-preview.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,13 @@ async function tests(options) {
6161
prompt: PROMPT,
6262
stream: newREPLStream(),
6363
ignoreUndefined: true,
64-
useColors: true,
64+
// Keep syntax highlighting out of these preview transcript assertions.
65+
// Preview and result colors are enabled after readline is initialized.
66+
useColors: false,
6567
...options
6668
});
69+
repl.useColors=true;
70+
repl.writer.options.colors=true;
6771

6872
repl.inputStream.run([
6973
'function foo(x) { return x; }',

‎test/parallel/test-repl-reverse-search.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,9 @@ function runTest() {
329329
}),
330330
completer: opts.completer,
331331
prompt,
332-
useColors: opts.useColors||false,
332+
// Keep syntax highlighting out of the reverse-search transcript. Result
333+
// colors are enabled below after readline has been initialized.
334+
useColors: false,
333335
terminal: true
334336
},common.mustCall((err,repl)=>{
335337
if(err){
@@ -351,6 +353,11 @@ function runTest() {
351353
setImmediate(runTestWrap,true);
352354
}));
353355

356+
if(opts.useColors){
357+
repl.useColors=true;
358+
repl.writer.options.colors=true;
359+
}
360+
354361
if(opts.columns){
355362
Object.defineProperty(repl,'columns',{
356363
value: opts.columns,

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit c18b0aa

Browse files
avivkelleraduh95
authored andcommitted
repl: add basic syntax highlighting
Signed-off-by: avivkeller <me@aviv.sh> PR-URL: #64591 Backport-PR-URL: #65267 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent 137ff67 commit c18b0aa

11 files changed

Lines changed: 209 additions & 19 deletions

‎lib/internal/readline/interface.js‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,13 +157,15 @@ const kPreviousCursorCols = Symbol('_previousCursorCols');
157157
constkMultilineMove=Symbol('_multilineMove');
158158
constkPreviousPrevRows=Symbol('_previousPrevRows');
159159
constkAddNewLineOnTTY=Symbol('_addNewLineOnTTY');
160+
constkColorize=Symbol('_colorize');
160161

161162
functionInterfaceConstructor(input,output,completer,terminal){
162163
this[kSawReturnAt]=0;
163164
// TODO(BridgeAR): Document this property. The name is not ideal, so we
164165
// might want to expose an alias and document that instead.
165166
this.isCompletionEnabled=true;
166167
this[kSawKeyPress]=false;
168+
this[kColorize]=undefined;
167169
this[kPreviousKey]=null;
168170
this.escapeCodeTimeout=ESCAPE_CODE_TIMEOUT;
169171
this.tabSize=8;
@@ -186,6 +188,7 @@ function InterfaceConstructor(input, output, completer, terminal) {
186188
consthistorySize=input.historySize;
187189
consthistory=input.history;
188190
constremoveHistoryDuplicates=input.removeHistoryDuplicates;
191+
this[kColorize]=input.colorize;
189192

190193
if(input.tabSize!==undefined){
191194
validateUint32(input.tabSize,'tabSize',true);
@@ -523,15 +526,18 @@ class Interface extends InterfaceConstructor {
523526
if(this[kIsMultiline]){
524527
constlines=StringPrototypeSplit(this.line,'\n');
525528
// Write first line with normal prompt
526-
this[kWriteToOutput](this[kPrompt]+lines[0]);
529+
this[kWriteToOutput](this[kPrompt]+
530+
(this[kColorize]?.(lines[0])??lines[0]));
527531

528532
// For continuation lines, add the "|" prefix
529533
for(leti=1;i<lines.length;i++){
530-
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+lines[i]);
534+
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+
535+
(this[kColorize]?.(lines[i])??lines[i]));
531536
}
532537
}else{
533538
// Write the prompt and the current buffer content.
534-
this[kWriteToOutput](line);
539+
this[kWriteToOutput](this[kPrompt]+
540+
(this[kColorize]?.(this.line)??this.line));
535541
}
536542

537543
// Force terminal to allocate a new line
@@ -687,7 +693,11 @@ class Interface extends InterfaceConstructor {
687693
this.line+=c;
688694
}
689695
this.cursor+=c.length;
690-
this[kWriteToOutput](c);
696+
if(this[kColorize]===undefined){
697+
this[kWriteToOutput](c);
698+
}else{
699+
this[kRefreshLine]();
700+
}
691701
return;
692702
}
693703
if(this.cursor<this.line.length){
@@ -706,7 +716,7 @@ class Interface extends InterfaceConstructor {
706716
this.cursor+=c.length;
707717
constnewPos=this.getCursorPos();
708718

709-
if(oldPos.rows<newPos.rows){
719+
if(oldPos.rows<newPos.rows||this[kColorize]!==undefined){
710720
this[kRefreshLine]();
711721
}else{
712722
this[kWriteToOutput](c);

‎lib/internal/repl/highlight.js‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
'use strict';
2+
3+
const{
4+
FunctionPrototypeBind,
5+
StringPrototypeSlice,
6+
}=primordials;
7+
8+
const{ stylizeWithColor }=require('internal/util/inspect');
9+
const{ Parser }=require('internal/deps/acorn/acorn/dist/acorn');
10+
11+
consttokenizer=FunctionPrototypeBind(Parser.tokenizer,Parser);
12+
13+
functiontokenStyle(token){
14+
const{ label, keyword }=token.type;
15+
16+
if(keyword!==undefined){
17+
if(label==='true'||label==='false')return'boolean';
18+
if(label==='null')return'null';
19+
if(label==='import'||label==='export')return'module';
20+
return'special';
21+
}
22+
23+
switch(label){
24+
case'name':
25+
switch(token.value){
26+
case'undefined':
27+
return'undefined';
28+
case'NaN':
29+
case'Infinity':
30+
return'number';
31+
case'Symbol':
32+
return'symbol';
33+
case'Date':
34+
return'date';
35+
default:
36+
returnundefined;
37+
}
38+
case'num':
39+
return'number';
40+
case'bigint':
41+
return'bigint';
42+
case'string':
43+
case'template':
44+
case'`':
45+
return'string';
46+
case'regexp':
47+
return'regexp';
48+
default:
49+
returnundefined;
50+
}
51+
}
52+
53+
functionhighlight(code){
54+
if(code.length===0)returncode;
55+
56+
letresult='';
57+
letoffset=0;
58+
functionwrite(start,end,style){
59+
result+=
60+
StringPrototypeSlice(code,offset,start)+
61+
stylizeWithColor(StringPrototypeSlice(code,start,end),style);
62+
offset=end;
63+
}
64+
65+
try{
66+
constiterator=tokenizer(code,{
67+
__proto__: null,
68+
allowHashBang: true,
69+
ecmaVersion: 'latest',
70+
onComment(_block,_text,start,end){
71+
write(start,end,'undefined');
72+
},
73+
});
74+
75+
for(consttokenofiterator){
76+
conststyle=tokenStyle(token);
77+
if(style!==undefined){
78+
write(token.start,token.end,style);
79+
}
80+
}
81+
}catch{
82+
// Acorn throws for unfinished strings, templates, and comments. Tokens and
83+
// comments reported before that point are still useful while typing.
84+
}
85+
86+
returnresult+StringPrototypeSlice(code,offset);
87+
}
88+
89+
module.exports={ highlight };

‎lib/internal/util/inspect.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3057,6 +3057,7 @@ module.exports = {
30573057
identicalSequenceRange,
30583058
inspect,
30593059
inspectDefaultOptions,
3060+
stylizeWithColor,
30603061
format,
30613062
formatWithOptions,
30623063
getStringWidth,

‎lib/repl.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ const {
109109
}=require('internal/readline/utils');
110110
const{ Console }=require('console');
111111
const{ shouldColorize }=require('internal/util/colors');
112+
const{ highlight }=require('internal/repl/highlight');
112113
constCJSModule=require('internal/modules/cjs/loader').Module;
113114
const{ AsyncLocalStorage }=require('async_hooks');
114115
letdebug=require('internal/util/debuglog').debuglog('repl',(fn)=>{
@@ -326,6 +327,7 @@ class REPLServer extends Interface {
326327
terminal: options.terminal,
327328
historySize: options.historySize,
328329
prompt,
330+
colorize: options.useColors ? highlight : undefined,
329331
});
330332

331333
ObjectDefineProperty(this,'inputStream',{
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Flags: --expose-internals
2+
'use strict';
3+
4+
constcommon=require('../common');
5+
constassert=require('assert');
6+
const{ inspect, stripVTControlCharacters }=require('util');
7+
constArrayStream=require('../common/arraystream');
8+
const{ highlight }=require('internal/repl/highlight');
9+
const{ REPLServer }=require('repl');
10+
11+
common.skipIfInspectorDisabled();
12+
13+
assert.strictEqual(stripVTControlCharacters(highlight(
14+
'const /* comment */ answer = 42; // comment',
15+
)),'const /* comment */ answer = 42; // comment');
16+
17+
assert.strictEqual(
18+
highlight('const value = "text"'),
19+
`\u001b[${inspect.colors.cyan[0]}mconst\u001b[${inspect.colors.cyan[1]}m value = `+
20+
`\u001b[${inspect.colors.green[0]}m"text"\u001b[${inspect.colors.green[1]}m`,
21+
);
22+
23+
for(constsourceof[
24+
'undefined',
25+
'NaN',
26+
'Infinity',
27+
'Symbol.iterator',
28+
'Date.now()',
29+
'true',
30+
'null',
31+
'1n',
32+
'/regexp/u',
33+
'import("node:fs")',
34+
]){
35+
assert.notStrictEqual(highlight(source),source);
36+
}
37+
38+
// Incomplete source is expected while the user is typing.
39+
highlight('const value = "');
40+
41+
{
42+
constinput=newArrayStream();
43+
constoutput=newArrayStream();
44+
letrendered='';
45+
output.write=(chunk)=>{
46+
rendered+=chunk;
47+
};
48+
49+
constrepl=newREPLServer({
50+
input,
51+
output,
52+
prompt: '',
53+
terminal: true,
54+
useColors: false,
55+
});
56+
rendered='';
57+
repl.write('const');
58+
59+
assert.strictEqual(rendered,'const');
60+
repl.close();
61+
}

‎test/parallel/test-repl-multiline.js‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,24 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
const{ startNewREPLServer }=require('../common/repl');
5+
const{ stripVTControlCharacters }=require('util');
56

67
constinput=['const foo = {','};','foo'];
78

89
functionrun({ useColors }){
910
const{ replServer, output }=startNewREPLServer({ useColors });
1011

1112
replServer.on('exit',common.mustCall(()=>{
12-
constactual=output.accumulator.split('\n');
13+
// The output contains various escape codes, including
14+
// screen clears and others, so we trim them all to
15+
// simplify this test.
16+
constactual=stripVTControlCharacters(output.accumulator);
1317

14-
// Validate the output, which contains terminal escape codes.
15-
assert.strictEqual(actual.length,6);
16-
assert.ok(actual[0].endsWith(input[0]));
17-
assert.ok(actual[1].includes('| '));
18-
assert.ok(actual[1].endsWith(input[1]));
19-
assert.ok(actual[2].includes('undefined'));
20-
assert.ok(actual[3].endsWith(input[2]));
21-
assert.strictEqual(actual[4],'{}');
18+
constfirstStatementIdx=actual.indexOf(input.slice(0,1).join('\n| '));
19+
assert(firstStatementIdx>-1);
20+
21+
assert(actual.slice(firstStatementIdx).includes('undefined'));
22+
assert(actual.slice(firstStatementIdx).includes('foo'));
2223
}));
2324

2425
input.forEach((line)=>replServer.write(`${line}\n`));

‎test/parallel/test-repl-preview-newlines.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,14 @@ const { startNewREPLServer } = require('../common/repl');
66

77
common.skipIfInspectorDisabled();
88

9-
const{ input, output }=startNewREPLServer({useColors: true});
9+
// Ignore terminal settings so the preview remains active under TERM=dumb.
10+
process.env.TERM='';
11+
12+
// Keep syntax highlighting out of this test so it only covers preview layout.
13+
// Preview and result colors are enabled after readline is initialized.
14+
const{ input, output, replServer }=startNewREPLServer({useColors: false});
15+
replServer.useColors=true;
16+
replServer.writer.options.colors=true;
1017

1118
output.accumulator='';
1219

‎test/parallel/test-repl-preview-without-inspector.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,13 @@ const repl = new REPLServer({
6969
prompt: PROMPT,
7070
stream: newREPLStream(),
7171
ignoreUndefined: true,
72-
useColors: true,
72+
// Keep syntax highlighting out of these preview transcript assertions.
73+
// Preview and result colors are enabled after readline is initialized.
74+
useColors: false,
7375
terminal: true,
7476
});
77+
repl.useColors=true;
78+
repl.writer.options.colors=true;
7579

7680
repl.inputStream.run([
7781
'function foo(x) { return x; }',

‎test/parallel/test-repl-preview.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,13 @@ async function tests(options) {
6161
prompt: PROMPT,
6262
stream: newREPLStream(),
6363
ignoreUndefined: true,
64-
useColors: true,
64+
// Keep syntax highlighting out of these preview transcript assertions.
65+
// Preview and result colors are enabled after readline is initialized.
66+
useColors: false,
6567
...options
6668
});
69+
repl.useColors=true;
70+
repl.writer.options.colors=true;
6771

6872
repl.inputStream.run([
6973
'function foo(x) { return x; }',

‎test/parallel/test-repl-reverse-search.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,9 @@ function runTest() {
329329
}),
330330
completer: opts.completer,
331331
prompt,
332-
useColors: opts.useColors||false,
332+
// Keep syntax highlighting out of the reverse-search transcript. Result
333+
// colors are enabled below after readline has been initialized.
334+
useColors: false,
333335
terminal: true
334336
},common.mustCall((err,repl)=>{
335337
if(err){
@@ -351,6 +353,11 @@ function runTest() {
351353
setImmediate(runTestWrap,true);
352354
}));
353355

356+
if(opts.useColors){
357+
repl.useColors=true;
358+
repl.writer.options.colors=true;
359+
}
360+
354361
if(opts.columns){
355362
Object.defineProperty(repl,'columns',{
356363
value: opts.columns,

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit c18b0aa

Browse files
avivkelleraduh95
authored andcommitted
repl: add basic syntax highlighting
Signed-off-by: avivkeller <me@aviv.sh> PR-URL: #64591 Backport-PR-URL: #65267 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent 137ff67 commit c18b0aa

11 files changed

Lines changed: 209 additions & 19 deletions

‎lib/internal/readline/interface.js‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,13 +157,15 @@ const kPreviousCursorCols = Symbol('_previousCursorCols');
157157
constkMultilineMove=Symbol('_multilineMove');
158158
constkPreviousPrevRows=Symbol('_previousPrevRows');
159159
constkAddNewLineOnTTY=Symbol('_addNewLineOnTTY');
160+
constkColorize=Symbol('_colorize');
160161

161162
functionInterfaceConstructor(input,output,completer,terminal){
162163
this[kSawReturnAt]=0;
163164
// TODO(BridgeAR): Document this property. The name is not ideal, so we
164165
// might want to expose an alias and document that instead.
165166
this.isCompletionEnabled=true;
166167
this[kSawKeyPress]=false;
168+
this[kColorize]=undefined;
167169
this[kPreviousKey]=null;
168170
this.escapeCodeTimeout=ESCAPE_CODE_TIMEOUT;
169171
this.tabSize=8;
@@ -186,6 +188,7 @@ function InterfaceConstructor(input, output, completer, terminal) {
186188
consthistorySize=input.historySize;
187189
consthistory=input.history;
188190
constremoveHistoryDuplicates=input.removeHistoryDuplicates;
191+
this[kColorize]=input.colorize;
189192

190193
if(input.tabSize!==undefined){
191194
validateUint32(input.tabSize,'tabSize',true);
@@ -523,15 +526,18 @@ class Interface extends InterfaceConstructor {
523526
if(this[kIsMultiline]){
524527
constlines=StringPrototypeSplit(this.line,'\n');
525528
// Write first line with normal prompt
526-
this[kWriteToOutput](this[kPrompt]+lines[0]);
529+
this[kWriteToOutput](this[kPrompt]+
530+
(this[kColorize]?.(lines[0])??lines[0]));
527531

528532
// For continuation lines, add the "|" prefix
529533
for(leti=1;i<lines.length;i++){
530-
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+lines[i]);
534+
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+
535+
(this[kColorize]?.(lines[i])??lines[i]));
531536
}
532537
}else{
533538
// Write the prompt and the current buffer content.
534-
this[kWriteToOutput](line);
539+
this[kWriteToOutput](this[kPrompt]+
540+
(this[kColorize]?.(this.line)??this.line));
535541
}
536542

537543
// Force terminal to allocate a new line
@@ -687,7 +693,11 @@ class Interface extends InterfaceConstructor {
687693
this.line+=c;
688694
}
689695
this.cursor+=c.length;
690-
this[kWriteToOutput](c);
696+
if(this[kColorize]===undefined){
697+
this[kWriteToOutput](c);
698+
}else{
699+
this[kRefreshLine]();
700+
}
691701
return;
692702
}
693703
if(this.cursor<this.line.length){
@@ -706,7 +716,7 @@ class Interface extends InterfaceConstructor {
706716
this.cursor+=c.length;
707717
constnewPos=this.getCursorPos();
708718

709-
if(oldPos.rows<newPos.rows){
719+
if(oldPos.rows<newPos.rows||this[kColorize]!==undefined){
710720
this[kRefreshLine]();
711721
}else{
712722
this[kWriteToOutput](c);

‎lib/internal/repl/highlight.js‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
'use strict';
2+
3+
const{
4+
FunctionPrototypeBind,
5+
StringPrototypeSlice,
6+
}=primordials;
7+
8+
const{ stylizeWithColor }=require('internal/util/inspect');
9+
const{ Parser }=require('internal/deps/acorn/acorn/dist/acorn');
10+
11+
consttokenizer=FunctionPrototypeBind(Parser.tokenizer,Parser);
12+
13+
functiontokenStyle(token){
14+
const{ label, keyword }=token.type;
15+
16+
if(keyword!==undefined){
17+
if(label==='true'||label==='false')return'boolean';
18+
if(label==='null')return'null';
19+
if(label==='import'||label==='export')return'module';
20+
return'special';
21+
}
22+
23+
switch(label){
24+
case'name':
25+
switch(token.value){
26+
case'undefined':
27+
return'undefined';
28+
case'NaN':
29+
case'Infinity':
30+
return'number';
31+
case'Symbol':
32+
return'symbol';
33+
case'Date':
34+
return'date';
35+
default:
36+
returnundefined;
37+
}
38+
case'num':
39+
return'number';
40+
case'bigint':
41+
return'bigint';
42+
case'string':
43+
case'template':
44+
case'`':
45+
return'string';
46+
case'regexp':
47+
return'regexp';
48+
default:
49+
returnundefined;
50+
}
51+
}
52+
53+
functionhighlight(code){
54+
if(code.length===0)returncode;
55+
56+
letresult='';
57+
letoffset=0;
58+
functionwrite(start,end,style){
59+
result+=
60+
StringPrototypeSlice(code,offset,start)+
61+
stylizeWithColor(StringPrototypeSlice(code,start,end),style);
62+
offset=end;
63+
}
64+
65+
try{
66+
constiterator=tokenizer(code,{
67+
__proto__: null,
68+
allowHashBang: true,
69+
ecmaVersion: 'latest',
70+
onComment(_block,_text,start,end){
71+
write(start,end,'undefined');
72+
},
73+
});
74+
75+
for(consttokenofiterator){
76+
conststyle=tokenStyle(token);
77+
if(style!==undefined){
78+
write(token.start,token.end,style);
79+
}
80+
}
81+
}catch{
82+
// Acorn throws for unfinished strings, templates, and comments. Tokens and
83+
// comments reported before that point are still useful while typing.
84+
}
85+
86+
returnresult+StringPrototypeSlice(code,offset);
87+
}
88+
89+
module.exports={ highlight };

‎lib/internal/util/inspect.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3057,6 +3057,7 @@ module.exports = {
30573057
identicalSequenceRange,
30583058
inspect,
30593059
inspectDefaultOptions,
3060+
stylizeWithColor,
30603061
format,
30613062
formatWithOptions,
30623063
getStringWidth,

‎lib/repl.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ const {
109109
}=require('internal/readline/utils');
110110
const{ Console }=require('console');
111111
const{ shouldColorize }=require('internal/util/colors');
112+
const{ highlight }=require('internal/repl/highlight');
112113
constCJSModule=require('internal/modules/cjs/loader').Module;
113114
const{ AsyncLocalStorage }=require('async_hooks');
114115
letdebug=require('internal/util/debuglog').debuglog('repl',(fn)=>{
@@ -326,6 +327,7 @@ class REPLServer extends Interface {
326327
terminal: options.terminal,
327328
historySize: options.historySize,
328329
prompt,
330+
colorize: options.useColors ? highlight : undefined,
329331
});
330332

331333
ObjectDefineProperty(this,'inputStream',{
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Flags: --expose-internals
2+
'use strict';
3+
4+
constcommon=require('../common');
5+
constassert=require('assert');
6+
const{ inspect, stripVTControlCharacters }=require('util');
7+
constArrayStream=require('../common/arraystream');
8+
const{ highlight }=require('internal/repl/highlight');
9+
const{ REPLServer }=require('repl');
10+
11+
common.skipIfInspectorDisabled();
12+
13+
assert.strictEqual(stripVTControlCharacters(highlight(
14+
'const /* comment */ answer = 42; // comment',
15+
)),'const /* comment */ answer = 42; // comment');
16+
17+
assert.strictEqual(
18+
highlight('const value = "text"'),
19+
`\u001b[${inspect.colors.cyan[0]}mconst\u001b[${inspect.colors.cyan[1]}m value = `+
20+
`\u001b[${inspect.colors.green[0]}m"text"\u001b[${inspect.colors.green[1]}m`,
21+
);
22+
23+
for(constsourceof[
24+
'undefined',
25+
'NaN',
26+
'Infinity',
27+
'Symbol.iterator',
28+
'Date.now()',
29+
'true',
30+
'null',
31+
'1n',
32+
'/regexp/u',
33+
'import("node:fs")',
34+
]){
35+
assert.notStrictEqual(highlight(source),source);
36+
}
37+
38+
// Incomplete source is expected while the user is typing.
39+
highlight('const value = "');
40+
41+
{
42+
constinput=newArrayStream();
43+
constoutput=newArrayStream();
44+
letrendered='';
45+
output.write=(chunk)=>{
46+
rendered+=chunk;
47+
};
48+
49+
constrepl=newREPLServer({
50+
input,
51+
output,
52+
prompt: '',
53+
terminal: true,
54+
useColors: false,
55+
});
56+
rendered='';
57+
repl.write('const');
58+
59+
assert.strictEqual(rendered,'const');
60+
repl.close();
61+
}

‎test/parallel/test-repl-multiline.js‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,24 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
const{ startNewREPLServer }=require('../common/repl');
5+
const{ stripVTControlCharacters }=require('util');
56

67
constinput=['const foo = {','};','foo'];
78

89
functionrun({ useColors }){
910
const{ replServer, output }=startNewREPLServer({ useColors });
1011

1112
replServer.on('exit',common.mustCall(()=>{
12-
constactual=output.accumulator.split('\n');
13+
// The output contains various escape codes, including
14+
// screen clears and others, so we trim them all to
15+
// simplify this test.
16+
constactual=stripVTControlCharacters(output.accumulator);
1317

14-
// Validate the output, which contains terminal escape codes.
15-
assert.strictEqual(actual.length,6);
16-
assert.ok(actual[0].endsWith(input[0]));
17-
assert.ok(actual[1].includes('| '));
18-
assert.ok(actual[1].endsWith(input[1]));
19-
assert.ok(actual[2].includes('undefined'));
20-
assert.ok(actual[3].endsWith(input[2]));
21-
assert.strictEqual(actual[4],'{}');
18+
constfirstStatementIdx=actual.indexOf(input.slice(0,1).join('\n| '));
19+
assert(firstStatementIdx>-1);
20+
21+
assert(actual.slice(firstStatementIdx).includes('undefined'));
22+
assert(actual.slice(firstStatementIdx).includes('foo'));
2223
}));
2324

2425
input.forEach((line)=>replServer.write(`${line}\n`));

‎test/parallel/test-repl-preview-newlines.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,14 @@ const { startNewREPLServer } = require('../common/repl');
66

77
common.skipIfInspectorDisabled();
88

9-
const{ input, output }=startNewREPLServer({useColors: true});
9+
// Ignore terminal settings so the preview remains active under TERM=dumb.
10+
process.env.TERM='';
11+
12+
// Keep syntax highlighting out of this test so it only covers preview layout.
13+
// Preview and result colors are enabled after readline is initialized.
14+
const{ input, output, replServer }=startNewREPLServer({useColors: false});
15+
replServer.useColors=true;
16+
replServer.writer.options.colors=true;
1017

1118
output.accumulator='';
1219

‎test/parallel/test-repl-preview-without-inspector.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,13 @@ const repl = new REPLServer({
6969
prompt: PROMPT,
7070
stream: newREPLStream(),
7171
ignoreUndefined: true,
72-
useColors: true,
72+
// Keep syntax highlighting out of these preview transcript assertions.
73+
// Preview and result colors are enabled after readline is initialized.
74+
useColors: false,
7375
terminal: true,
7476
});
77+
repl.useColors=true;
78+
repl.writer.options.colors=true;
7579

7680
repl.inputStream.run([
7781
'function foo(x) { return x; }',

‎test/parallel/test-repl-preview.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,13 @@ async function tests(options) {
6161
prompt: PROMPT,
6262
stream: newREPLStream(),
6363
ignoreUndefined: true,
64-
useColors: true,
64+
// Keep syntax highlighting out of these preview transcript assertions.
65+
// Preview and result colors are enabled after readline is initialized.
66+
useColors: false,
6567
...options
6668
});
69+
repl.useColors=true;
70+
repl.writer.options.colors=true;
6771

6872
repl.inputStream.run([
6973
'function foo(x) { return x; }',

‎test/parallel/test-repl-reverse-search.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,9 @@ function runTest() {
329329
}),
330330
completer: opts.completer,
331331
prompt,
332-
useColors: opts.useColors||false,
332+
// Keep syntax highlighting out of the reverse-search transcript. Result
333+
// colors are enabled below after readline has been initialized.
334+
useColors: false,
333335
terminal: true
334336
},common.mustCall((err,repl)=>{
335337
if(err){
@@ -351,6 +353,11 @@ function runTest() {
351353
setImmediate(runTestWrap,true);
352354
}));
353355

356+
if(opts.useColors){
357+
repl.useColors=true;
358+
repl.writer.options.colors=true;
359+
}
360+
354361
if(opts.columns){
355362
Object.defineProperty(repl,'columns',{
356363
value: opts.columns,

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit c18b0aa

Browse files
avivkelleraduh95
authored andcommitted
repl: add basic syntax highlighting
Signed-off-by: avivkeller <me@aviv.sh> PR-URL: #64591 Backport-PR-URL: #65267 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent 137ff67 commit c18b0aa

11 files changed

Lines changed: 209 additions & 19 deletions

‎lib/internal/readline/interface.js‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,13 +157,15 @@ const kPreviousCursorCols = Symbol('_previousCursorCols');
157157
constkMultilineMove=Symbol('_multilineMove');
158158
constkPreviousPrevRows=Symbol('_previousPrevRows');
159159
constkAddNewLineOnTTY=Symbol('_addNewLineOnTTY');
160+
constkColorize=Symbol('_colorize');
160161

161162
functionInterfaceConstructor(input,output,completer,terminal){
162163
this[kSawReturnAt]=0;
163164
// TODO(BridgeAR): Document this property. The name is not ideal, so we
164165
// might want to expose an alias and document that instead.
165166
this.isCompletionEnabled=true;
166167
this[kSawKeyPress]=false;
168+
this[kColorize]=undefined;
167169
this[kPreviousKey]=null;
168170
this.escapeCodeTimeout=ESCAPE_CODE_TIMEOUT;
169171
this.tabSize=8;
@@ -186,6 +188,7 @@ function InterfaceConstructor(input, output, completer, terminal) {
186188
consthistorySize=input.historySize;
187189
consthistory=input.history;
188190
constremoveHistoryDuplicates=input.removeHistoryDuplicates;
191+
this[kColorize]=input.colorize;
189192

190193
if(input.tabSize!==undefined){
191194
validateUint32(input.tabSize,'tabSize',true);
@@ -523,15 +526,18 @@ class Interface extends InterfaceConstructor {
523526
if(this[kIsMultiline]){
524527
constlines=StringPrototypeSplit(this.line,'\n');
525528
// Write first line with normal prompt
526-
this[kWriteToOutput](this[kPrompt]+lines[0]);
529+
this[kWriteToOutput](this[kPrompt]+
530+
(this[kColorize]?.(lines[0])??lines[0]));
527531

528532
// For continuation lines, add the "|" prefix
529533
for(leti=1;i<lines.length;i++){
530-
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+lines[i]);
534+
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+
535+
(this[kColorize]?.(lines[i])??lines[i]));
531536
}
532537
}else{
533538
// Write the prompt and the current buffer content.
534-
this[kWriteToOutput](line);
539+
this[kWriteToOutput](this[kPrompt]+
540+
(this[kColorize]?.(this.line)??this.line));
535541
}
536542

537543
// Force terminal to allocate a new line
@@ -687,7 +693,11 @@ class Interface extends InterfaceConstructor {
687693
this.line+=c;
688694
}
689695
this.cursor+=c.length;
690-
this[kWriteToOutput](c);
696+
if(this[kColorize]===undefined){
697+
this[kWriteToOutput](c);
698+
}else{
699+
this[kRefreshLine]();
700+
}
691701
return;
692702
}
693703
if(this.cursor<this.line.length){
@@ -706,7 +716,7 @@ class Interface extends InterfaceConstructor {
706716
this.cursor+=c.length;
707717
constnewPos=this.getCursorPos();
708718

709-
if(oldPos.rows<newPos.rows){
719+
if(oldPos.rows<newPos.rows||this[kColorize]!==undefined){
710720
this[kRefreshLine]();
711721
}else{
712722
this[kWriteToOutput](c);

‎lib/internal/repl/highlight.js‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
'use strict';
2+
3+
const{
4+
FunctionPrototypeBind,
5+
StringPrototypeSlice,
6+
}=primordials;
7+
8+
const{ stylizeWithColor }=require('internal/util/inspect');
9+
const{ Parser }=require('internal/deps/acorn/acorn/dist/acorn');
10+
11+
consttokenizer=FunctionPrototypeBind(Parser.tokenizer,Parser);
12+
13+
functiontokenStyle(token){
14+
const{ label, keyword }=token.type;
15+
16+
if(keyword!==undefined){
17+
if(label==='true'||label==='false')return'boolean';
18+
if(label==='null')return'null';
19+
if(label==='import'||label==='export')return'module';
20+
return'special';
21+
}
22+
23+
switch(label){
24+
case'name':
25+
switch(token.value){
26+
case'undefined':
27+
return'undefined';
28+
case'NaN':
29+
case'Infinity':
30+
return'number';
31+
case'Symbol':
32+
return'symbol';
33+
case'Date':
34+
return'date';
35+
default:
36+
returnundefined;
37+
}
38+
case'num':
39+
return'number';
40+
case'bigint':
41+
return'bigint';
42+
case'string':
43+
case'template':
44+
case'`':
45+
return'string';
46+
case'regexp':
47+
return'regexp';
48+
default:
49+
returnundefined;
50+
}
51+
}
52+
53+
functionhighlight(code){
54+
if(code.length===0)returncode;
55+
56+
letresult='';
57+
letoffset=0;
58+
functionwrite(start,end,style){
59+
result+=
60+
StringPrototypeSlice(code,offset,start)+
61+
stylizeWithColor(StringPrototypeSlice(code,start,end),style);
62+
offset=end;
63+
}
64+
65+
try{
66+
constiterator=tokenizer(code,{
67+
__proto__: null,
68+
allowHashBang: true,
69+
ecmaVersion: 'latest',
70+
onComment(_block,_text,start,end){
71+
write(start,end,'undefined');
72+
},
73+
});
74+
75+
for(consttokenofiterator){
76+
conststyle=tokenStyle(token);
77+
if(style!==undefined){
78+
write(token.start,token.end,style);
79+
}
80+
}
81+
}catch{
82+
// Acorn throws for unfinished strings, templates, and comments. Tokens and
83+
// comments reported before that point are still useful while typing.
84+
}
85+
86+
returnresult+StringPrototypeSlice(code,offset);
87+
}
88+
89+
module.exports={ highlight };

‎lib/internal/util/inspect.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3057,6 +3057,7 @@ module.exports = {
30573057
identicalSequenceRange,
30583058
inspect,
30593059
inspectDefaultOptions,
3060+
stylizeWithColor,
30603061
format,
30613062
formatWithOptions,
30623063
getStringWidth,

‎lib/repl.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ const {
109109
}=require('internal/readline/utils');
110110
const{ Console }=require('console');
111111
const{ shouldColorize }=require('internal/util/colors');
112+
const{ highlight }=require('internal/repl/highlight');
112113
constCJSModule=require('internal/modules/cjs/loader').Module;
113114
const{ AsyncLocalStorage }=require('async_hooks');
114115
letdebug=require('internal/util/debuglog').debuglog('repl',(fn)=>{
@@ -326,6 +327,7 @@ class REPLServer extends Interface {
326327
terminal: options.terminal,
327328
historySize: options.historySize,
328329
prompt,
330+
colorize: options.useColors ? highlight : undefined,
329331
});
330332

331333
ObjectDefineProperty(this,'inputStream',{
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Flags: --expose-internals
2+
'use strict';
3+
4+
constcommon=require('../common');
5+
constassert=require('assert');
6+
const{ inspect, stripVTControlCharacters }=require('util');
7+
constArrayStream=require('../common/arraystream');
8+
const{ highlight }=require('internal/repl/highlight');
9+
const{ REPLServer }=require('repl');
10+
11+
common.skipIfInspectorDisabled();
12+
13+
assert.strictEqual(stripVTControlCharacters(highlight(
14+
'const /* comment */ answer = 42; // comment',
15+
)),'const /* comment */ answer = 42; // comment');
16+
17+
assert.strictEqual(
18+
highlight('const value = "text"'),
19+
`\u001b[${inspect.colors.cyan[0]}mconst\u001b[${inspect.colors.cyan[1]}m value = `+
20+
`\u001b[${inspect.colors.green[0]}m"text"\u001b[${inspect.colors.green[1]}m`,
21+
);
22+
23+
for(constsourceof[
24+
'undefined',
25+
'NaN',
26+
'Infinity',
27+
'Symbol.iterator',
28+
'Date.now()',
29+
'true',
30+
'null',
31+
'1n',
32+
'/regexp/u',
33+
'import("node:fs")',
34+
]){
35+
assert.notStrictEqual(highlight(source),source);
36+
}
37+
38+
// Incomplete source is expected while the user is typing.
39+
highlight('const value = "');
40+
41+
{
42+
constinput=newArrayStream();
43+
constoutput=newArrayStream();
44+
letrendered='';
45+
output.write=(chunk)=>{
46+
rendered+=chunk;
47+
};
48+
49+
constrepl=newREPLServer({
50+
input,
51+
output,
52+
prompt: '',
53+
terminal: true,
54+
useColors: false,
55+
});
56+
rendered='';
57+
repl.write('const');
58+
59+
assert.strictEqual(rendered,'const');
60+
repl.close();
61+
}

‎test/parallel/test-repl-multiline.js‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,24 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
const{ startNewREPLServer }=require('../common/repl');
5+
const{ stripVTControlCharacters }=require('util');
56

67
constinput=['const foo = {','};','foo'];
78

89
functionrun({ useColors }){
910
const{ replServer, output }=startNewREPLServer({ useColors });
1011

1112
replServer.on('exit',common.mustCall(()=>{
12-
constactual=output.accumulator.split('\n');
13+
// The output contains various escape codes, including
14+
// screen clears and others, so we trim them all to
15+
// simplify this test.
16+
constactual=stripVTControlCharacters(output.accumulator);
1317

14-
// Validate the output, which contains terminal escape codes.
15-
assert.strictEqual(actual.length,6);
16-
assert.ok(actual[0].endsWith(input[0]));
17-
assert.ok(actual[1].includes('| '));
18-
assert.ok(actual[1].endsWith(input[1]));
19-
assert.ok(actual[2].includes('undefined'));
20-
assert.ok(actual[3].endsWith(input[2]));
21-
assert.strictEqual(actual[4],'{}');
18+
constfirstStatementIdx=actual.indexOf(input.slice(0,1).join('\n| '));
19+
assert(firstStatementIdx>-1);
20+
21+
assert(actual.slice(firstStatementIdx).includes('undefined'));
22+
assert(actual.slice(firstStatementIdx).includes('foo'));
2223
}));
2324

2425
input.forEach((line)=>replServer.write(`${line}\n`));

‎test/parallel/test-repl-preview-newlines.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,14 @@ const { startNewREPLServer } = require('../common/repl');
66

77
common.skipIfInspectorDisabled();
88

9-
const{ input, output }=startNewREPLServer({useColors: true});
9+
// Ignore terminal settings so the preview remains active under TERM=dumb.
10+
process.env.TERM='';
11+
12+
// Keep syntax highlighting out of this test so it only covers preview layout.
13+
// Preview and result colors are enabled after readline is initialized.
14+
const{ input, output, replServer }=startNewREPLServer({useColors: false});
15+
replServer.useColors=true;
16+
replServer.writer.options.colors=true;
1017

1118
output.accumulator='';
1219

‎test/parallel/test-repl-preview-without-inspector.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,13 @@ const repl = new REPLServer({
6969
prompt: PROMPT,
7070
stream: newREPLStream(),
7171
ignoreUndefined: true,
72-
useColors: true,
72+
// Keep syntax highlighting out of these preview transcript assertions.
73+
// Preview and result colors are enabled after readline is initialized.
74+
useColors: false,
7375
terminal: true,
7476
});
77+
repl.useColors=true;
78+
repl.writer.options.colors=true;
7579

7680
repl.inputStream.run([
7781
'function foo(x) { return x; }',

‎test/parallel/test-repl-preview.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,13 @@ async function tests(options) {
6161
prompt: PROMPT,
6262
stream: newREPLStream(),
6363
ignoreUndefined: true,
64-
useColors: true,
64+
// Keep syntax highlighting out of these preview transcript assertions.
65+
// Preview and result colors are enabled after readline is initialized.
66+
useColors: false,
6567
...options
6668
});
69+
repl.useColors=true;
70+
repl.writer.options.colors=true;
6771

6872
repl.inputStream.run([
6973
'function foo(x) { return x; }',

‎test/parallel/test-repl-reverse-search.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,9 @@ function runTest() {
329329
}),
330330
completer: opts.completer,
331331
prompt,
332-
useColors: opts.useColors||false,
332+
// Keep syntax highlighting out of the reverse-search transcript. Result
333+
// colors are enabled below after readline has been initialized.
334+
useColors: false,
333335
terminal: true
334336
},common.mustCall((err,repl)=>{
335337
if(err){
@@ -351,6 +353,11 @@ function runTest() {
351353
setImmediate(runTestWrap,true);
352354
}));
353355

356+
if(opts.useColors){
357+
repl.useColors=true;
358+
repl.writer.options.colors=true;
359+
}
360+
354361
if(opts.columns){
355362
Object.defineProperty(repl,'columns',{
356363
value: opts.columns,

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit c18b0aa

Browse files
avivkelleraduh95
authored andcommitted
repl: add basic syntax highlighting
Signed-off-by: avivkeller <me@aviv.sh> PR-URL: #64591 Backport-PR-URL: #65267 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent 137ff67 commit c18b0aa

11 files changed

Lines changed: 209 additions & 19 deletions

‎lib/internal/readline/interface.js‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,13 +157,15 @@ const kPreviousCursorCols = Symbol('_previousCursorCols');
157157
constkMultilineMove=Symbol('_multilineMove');
158158
constkPreviousPrevRows=Symbol('_previousPrevRows');
159159
constkAddNewLineOnTTY=Symbol('_addNewLineOnTTY');
160+
constkColorize=Symbol('_colorize');
160161

161162
functionInterfaceConstructor(input,output,completer,terminal){
162163
this[kSawReturnAt]=0;
163164
// TODO(BridgeAR): Document this property. The name is not ideal, so we
164165
// might want to expose an alias and document that instead.
165166
this.isCompletionEnabled=true;
166167
this[kSawKeyPress]=false;
168+
this[kColorize]=undefined;
167169
this[kPreviousKey]=null;
168170
this.escapeCodeTimeout=ESCAPE_CODE_TIMEOUT;
169171
this.tabSize=8;
@@ -186,6 +188,7 @@ function InterfaceConstructor(input, output, completer, terminal) {
186188
consthistorySize=input.historySize;
187189
consthistory=input.history;
188190
constremoveHistoryDuplicates=input.removeHistoryDuplicates;
191+
this[kColorize]=input.colorize;
189192

190193
if(input.tabSize!==undefined){
191194
validateUint32(input.tabSize,'tabSize',true);
@@ -523,15 +526,18 @@ class Interface extends InterfaceConstructor {
523526
if(this[kIsMultiline]){
524527
constlines=StringPrototypeSplit(this.line,'\n');
525528
// Write first line with normal prompt
526-
this[kWriteToOutput](this[kPrompt]+lines[0]);
529+
this[kWriteToOutput](this[kPrompt]+
530+
(this[kColorize]?.(lines[0])??lines[0]));
527531

528532
// For continuation lines, add the "|" prefix
529533
for(leti=1;i<lines.length;i++){
530-
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+lines[i]);
534+
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+
535+
(this[kColorize]?.(lines[i])??lines[i]));
531536
}
532537
}else{
533538
// Write the prompt and the current buffer content.
534-
this[kWriteToOutput](line);
539+
this[kWriteToOutput](this[kPrompt]+
540+
(this[kColorize]?.(this.line)??this.line));
535541
}
536542

537543
// Force terminal to allocate a new line
@@ -687,7 +693,11 @@ class Interface extends InterfaceConstructor {
687693
this.line+=c;
688694
}
689695
this.cursor+=c.length;
690-
this[kWriteToOutput](c);
696+
if(this[kColorize]===undefined){
697+
this[kWriteToOutput](c);
698+
}else{
699+
this[kRefreshLine]();
700+
}
691701
return;
692702
}
693703
if(this.cursor<this.line.length){
@@ -706,7 +716,7 @@ class Interface extends InterfaceConstructor {
706716
this.cursor+=c.length;
707717
constnewPos=this.getCursorPos();
708718

709-
if(oldPos.rows<newPos.rows){
719+
if(oldPos.rows<newPos.rows||this[kColorize]!==undefined){
710720
this[kRefreshLine]();
711721
}else{
712722
this[kWriteToOutput](c);

‎lib/internal/repl/highlight.js‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
'use strict';
2+
3+
const{
4+
FunctionPrototypeBind,
5+
StringPrototypeSlice,
6+
}=primordials;
7+
8+
const{ stylizeWithColor }=require('internal/util/inspect');
9+
const{ Parser }=require('internal/deps/acorn/acorn/dist/acorn');
10+
11+
consttokenizer=FunctionPrototypeBind(Parser.tokenizer,Parser);
12+
13+
functiontokenStyle(token){
14+
const{ label, keyword }=token.type;
15+
16+
if(keyword!==undefined){
17+
if(label==='true'||label==='false')return'boolean';
18+
if(label==='null')return'null';
19+
if(label==='import'||label==='export')return'module';
20+
return'special';
21+
}
22+
23+
switch(label){
24+
case'name':
25+
switch(token.value){
26+
case'undefined':
27+
return'undefined';
28+
case'NaN':
29+
case'Infinity':
30+
return'number';
31+
case'Symbol':
32+
return'symbol';
33+
case'Date':
34+
return'date';
35+
default:
36+
returnundefined;
37+
}
38+
case'num':
39+
return'number';
40+
case'bigint':
41+
return'bigint';
42+
case'string':
43+
case'template':
44+
case'`':
45+
return'string';
46+
case'regexp':
47+
return'regexp';
48+
default:
49+
returnundefined;
50+
}
51+
}
52+
53+
functionhighlight(code){
54+
if(code.length===0)returncode;
55+
56+
letresult='';
57+
letoffset=0;
58+
functionwrite(start,end,style){
59+
result+=
60+
StringPrototypeSlice(code,offset,start)+
61+
stylizeWithColor(StringPrototypeSlice(code,start,end),style);
62+
offset=end;
63+
}
64+
65+
try{
66+
constiterator=tokenizer(code,{
67+
__proto__: null,
68+
allowHashBang: true,
69+
ecmaVersion: 'latest',
70+
onComment(_block,_text,start,end){
71+
write(start,end,'undefined');
72+
},
73+
});
74+
75+
for(consttokenofiterator){
76+
conststyle=tokenStyle(token);
77+
if(style!==undefined){
78+
write(token.start,token.end,style);
79+
}
80+
}
81+
}catch{
82+
// Acorn throws for unfinished strings, templates, and comments. Tokens and
83+
// comments reported before that point are still useful while typing.
84+
}
85+
86+
returnresult+StringPrototypeSlice(code,offset);
87+
}
88+
89+
module.exports={ highlight };

‎lib/internal/util/inspect.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3057,6 +3057,7 @@ module.exports = {
30573057
identicalSequenceRange,
30583058
inspect,
30593059
inspectDefaultOptions,
3060+
stylizeWithColor,
30603061
format,
30613062
formatWithOptions,
30623063
getStringWidth,

‎lib/repl.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ const {
109109
}=require('internal/readline/utils');
110110
const{ Console }=require('console');
111111
const{ shouldColorize }=require('internal/util/colors');
112+
const{ highlight }=require('internal/repl/highlight');
112113
constCJSModule=require('internal/modules/cjs/loader').Module;
113114
const{ AsyncLocalStorage }=require('async_hooks');
114115
letdebug=require('internal/util/debuglog').debuglog('repl',(fn)=>{
@@ -326,6 +327,7 @@ class REPLServer extends Interface {
326327
terminal: options.terminal,
327328
historySize: options.historySize,
328329
prompt,
330+
colorize: options.useColors ? highlight : undefined,
329331
});
330332

331333
ObjectDefineProperty(this,'inputStream',{
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Flags: --expose-internals
2+
'use strict';
3+
4+
constcommon=require('../common');
5+
constassert=require('assert');
6+
const{ inspect, stripVTControlCharacters }=require('util');
7+
constArrayStream=require('../common/arraystream');
8+
const{ highlight }=require('internal/repl/highlight');
9+
const{ REPLServer }=require('repl');
10+
11+
common.skipIfInspectorDisabled();
12+
13+
assert.strictEqual(stripVTControlCharacters(highlight(
14+
'const /* comment */ answer = 42; // comment',
15+
)),'const /* comment */ answer = 42; // comment');
16+
17+
assert.strictEqual(
18+
highlight('const value = "text"'),
19+
`\u001b[${inspect.colors.cyan[0]}mconst\u001b[${inspect.colors.cyan[1]}m value = `+
20+
`\u001b[${inspect.colors.green[0]}m"text"\u001b[${inspect.colors.green[1]}m`,
21+
);
22+
23+
for(constsourceof[
24+
'undefined',
25+
'NaN',
26+
'Infinity',
27+
'Symbol.iterator',
28+
'Date.now()',
29+
'true',
30+
'null',
31+
'1n',
32+
'/regexp/u',
33+
'import("node:fs")',
34+
]){
35+
assert.notStrictEqual(highlight(source),source);
36+
}
37+
38+
// Incomplete source is expected while the user is typing.
39+
highlight('const value = "');
40+
41+
{
42+
constinput=newArrayStream();
43+
constoutput=newArrayStream();
44+
letrendered='';
45+
output.write=(chunk)=>{
46+
rendered+=chunk;
47+
};
48+
49+
constrepl=newREPLServer({
50+
input,
51+
output,
52+
prompt: '',
53+
terminal: true,
54+
useColors: false,
55+
});
56+
rendered='';
57+
repl.write('const');
58+
59+
assert.strictEqual(rendered,'const');
60+
repl.close();
61+
}

‎test/parallel/test-repl-multiline.js‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,24 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
const{ startNewREPLServer }=require('../common/repl');
5+
const{ stripVTControlCharacters }=require('util');
56

67
constinput=['const foo = {','};','foo'];
78

89
functionrun({ useColors }){
910
const{ replServer, output }=startNewREPLServer({ useColors });
1011

1112
replServer.on('exit',common.mustCall(()=>{
12-
constactual=output.accumulator.split('\n');
13+
// The output contains various escape codes, including
14+
// screen clears and others, so we trim them all to
15+
// simplify this test.
16+
constactual=stripVTControlCharacters(output.accumulator);
1317

14-
// Validate the output, which contains terminal escape codes.
15-
assert.strictEqual(actual.length,6);
16-
assert.ok(actual[0].endsWith(input[0]));
17-
assert.ok(actual[1].includes('| '));
18-
assert.ok(actual[1].endsWith(input[1]));
19-
assert.ok(actual[2].includes('undefined'));
20-
assert.ok(actual[3].endsWith(input[2]));
21-
assert.strictEqual(actual[4],'{}');
18+
constfirstStatementIdx=actual.indexOf(input.slice(0,1).join('\n| '));
19+
assert(firstStatementIdx>-1);
20+
21+
assert(actual.slice(firstStatementIdx).includes('undefined'));
22+
assert(actual.slice(firstStatementIdx).includes('foo'));
2223
}));
2324

2425
input.forEach((line)=>replServer.write(`${line}\n`));

‎test/parallel/test-repl-preview-newlines.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,14 @@ const { startNewREPLServer } = require('../common/repl');
66

77
common.skipIfInspectorDisabled();
88

9-
const{ input, output }=startNewREPLServer({useColors: true});
9+
// Ignore terminal settings so the preview remains active under TERM=dumb.
10+
process.env.TERM='';
11+
12+
// Keep syntax highlighting out of this test so it only covers preview layout.
13+
// Preview and result colors are enabled after readline is initialized.
14+
const{ input, output, replServer }=startNewREPLServer({useColors: false});
15+
replServer.useColors=true;
16+
replServer.writer.options.colors=true;
1017

1118
output.accumulator='';
1219

‎test/parallel/test-repl-preview-without-inspector.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,13 @@ const repl = new REPLServer({
6969
prompt: PROMPT,
7070
stream: newREPLStream(),
7171
ignoreUndefined: true,
72-
useColors: true,
72+
// Keep syntax highlighting out of these preview transcript assertions.
73+
// Preview and result colors are enabled after readline is initialized.
74+
useColors: false,
7375
terminal: true,
7476
});
77+
repl.useColors=true;
78+
repl.writer.options.colors=true;
7579

7680
repl.inputStream.run([
7781
'function foo(x) { return x; }',

‎test/parallel/test-repl-preview.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,13 @@ async function tests(options) {
6161
prompt: PROMPT,
6262
stream: newREPLStream(),
6363
ignoreUndefined: true,
64-
useColors: true,
64+
// Keep syntax highlighting out of these preview transcript assertions.
65+
// Preview and result colors are enabled after readline is initialized.
66+
useColors: false,
6567
...options
6668
});
69+
repl.useColors=true;
70+
repl.writer.options.colors=true;
6771

6872
repl.inputStream.run([
6973
'function foo(x) { return x; }',

‎test/parallel/test-repl-reverse-search.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,9 @@ function runTest() {
329329
}),
330330
completer: opts.completer,
331331
prompt,
332-
useColors: opts.useColors||false,
332+
// Keep syntax highlighting out of the reverse-search transcript. Result
333+
// colors are enabled below after readline has been initialized.
334+
useColors: false,
333335
terminal: true
334336
},common.mustCall((err,repl)=>{
335337
if(err){
@@ -351,6 +353,11 @@ function runTest() {
351353
setImmediate(runTestWrap,true);
352354
}));
353355

356+
if(opts.useColors){
357+
repl.useColors=true;
358+
repl.writer.options.colors=true;
359+
}
360+
354361
if(opts.columns){
355362
Object.defineProperty(repl,'columns',{
356363
value: opts.columns,

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit c18b0aa

Browse files
avivkelleraduh95
authored andcommitted
repl: add basic syntax highlighting
Signed-off-by: avivkeller <me@aviv.sh> PR-URL: #64591 Backport-PR-URL: #65267 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent 137ff67 commit c18b0aa

11 files changed

Lines changed: 209 additions & 19 deletions

‎lib/internal/readline/interface.js‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,13 +157,15 @@ const kPreviousCursorCols = Symbol('_previousCursorCols');
157157
constkMultilineMove=Symbol('_multilineMove');
158158
constkPreviousPrevRows=Symbol('_previousPrevRows');
159159
constkAddNewLineOnTTY=Symbol('_addNewLineOnTTY');
160+
constkColorize=Symbol('_colorize');
160161

161162
functionInterfaceConstructor(input,output,completer,terminal){
162163
this[kSawReturnAt]=0;
163164
// TODO(BridgeAR): Document this property. The name is not ideal, so we
164165
// might want to expose an alias and document that instead.
165166
this.isCompletionEnabled=true;
166167
this[kSawKeyPress]=false;
168+
this[kColorize]=undefined;
167169
this[kPreviousKey]=null;
168170
this.escapeCodeTimeout=ESCAPE_CODE_TIMEOUT;
169171
this.tabSize=8;
@@ -186,6 +188,7 @@ function InterfaceConstructor(input, output, completer, terminal) {
186188
consthistorySize=input.historySize;
187189
consthistory=input.history;
188190
constremoveHistoryDuplicates=input.removeHistoryDuplicates;
191+
this[kColorize]=input.colorize;
189192

190193
if(input.tabSize!==undefined){
191194
validateUint32(input.tabSize,'tabSize',true);
@@ -523,15 +526,18 @@ class Interface extends InterfaceConstructor {
523526
if(this[kIsMultiline]){
524527
constlines=StringPrototypeSplit(this.line,'\n');
525528
// Write first line with normal prompt
526-
this[kWriteToOutput](this[kPrompt]+lines[0]);
529+
this[kWriteToOutput](this[kPrompt]+
530+
(this[kColorize]?.(lines[0])??lines[0]));
527531

528532
// For continuation lines, add the "|" prefix
529533
for(leti=1;i<lines.length;i++){
530-
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+lines[i]);
534+
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+
535+
(this[kColorize]?.(lines[i])??lines[i]));
531536
}
532537
}else{
533538
// Write the prompt and the current buffer content.
534-
this[kWriteToOutput](line);
539+
this[kWriteToOutput](this[kPrompt]+
540+
(this[kColorize]?.(this.line)??this.line));
535541
}
536542

537543
// Force terminal to allocate a new line
@@ -687,7 +693,11 @@ class Interface extends InterfaceConstructor {
687693
this.line+=c;
688694
}
689695
this.cursor+=c.length;
690-
this[kWriteToOutput](c);
696+
if(this[kColorize]===undefined){
697+
this[kWriteToOutput](c);
698+
}else{
699+
this[kRefreshLine]();
700+
}
691701
return;
692702
}
693703
if(this.cursor<this.line.length){
@@ -706,7 +716,7 @@ class Interface extends InterfaceConstructor {
706716
this.cursor+=c.length;
707717
constnewPos=this.getCursorPos();
708718

709-
if(oldPos.rows<newPos.rows){
719+
if(oldPos.rows<newPos.rows||this[kColorize]!==undefined){
710720
this[kRefreshLine]();
711721
}else{
712722
this[kWriteToOutput](c);

‎lib/internal/repl/highlight.js‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
'use strict';
2+
3+
const{
4+
FunctionPrototypeBind,
5+
StringPrototypeSlice,
6+
}=primordials;
7+
8+
const{ stylizeWithColor }=require('internal/util/inspect');
9+
const{ Parser }=require('internal/deps/acorn/acorn/dist/acorn');
10+
11+
consttokenizer=FunctionPrototypeBind(Parser.tokenizer,Parser);
12+
13+
functiontokenStyle(token){
14+
const{ label, keyword }=token.type;
15+
16+
if(keyword!==undefined){
17+
if(label==='true'||label==='false')return'boolean';
18+
if(label==='null')return'null';
19+
if(label==='import'||label==='export')return'module';
20+
return'special';
21+
}
22+
23+
switch(label){
24+
case'name':
25+
switch(token.value){
26+
case'undefined':
27+
return'undefined';
28+
case'NaN':
29+
case'Infinity':
30+
return'number';
31+
case'Symbol':
32+
return'symbol';
33+
case'Date':
34+
return'date';
35+
default:
36+
returnundefined;
37+
}
38+
case'num':
39+
return'number';
40+
case'bigint':
41+
return'bigint';
42+
case'string':
43+
case'template':
44+
case'`':
45+
return'string';
46+
case'regexp':
47+
return'regexp';
48+
default:
49+
returnundefined;
50+
}
51+
}
52+
53+
functionhighlight(code){
54+
if(code.length===0)returncode;
55+
56+
letresult='';
57+
letoffset=0;
58+
functionwrite(start,end,style){
59+
result+=
60+
StringPrototypeSlice(code,offset,start)+
61+
stylizeWithColor(StringPrototypeSlice(code,start,end),style);
62+
offset=end;
63+
}
64+
65+
try{
66+
constiterator=tokenizer(code,{
67+
__proto__: null,
68+
allowHashBang: true,
69+
ecmaVersion: 'latest',
70+
onComment(_block,_text,start,end){
71+
write(start,end,'undefined');
72+
},
73+
});
74+
75+
for(consttokenofiterator){
76+
conststyle=tokenStyle(token);
77+
if(style!==undefined){
78+
write(token.start,token.end,style);
79+
}
80+
}
81+
}catch{
82+
// Acorn throws for unfinished strings, templates, and comments. Tokens and
83+
// comments reported before that point are still useful while typing.
84+
}
85+
86+
returnresult+StringPrototypeSlice(code,offset);
87+
}
88+
89+
module.exports={ highlight };

‎lib/internal/util/inspect.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3057,6 +3057,7 @@ module.exports = {
30573057
identicalSequenceRange,
30583058
inspect,
30593059
inspectDefaultOptions,
3060+
stylizeWithColor,
30603061
format,
30613062
formatWithOptions,
30623063
getStringWidth,

‎lib/repl.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ const {
109109
}=require('internal/readline/utils');
110110
const{ Console }=require('console');
111111
const{ shouldColorize }=require('internal/util/colors');
112+
const{ highlight }=require('internal/repl/highlight');
112113
constCJSModule=require('internal/modules/cjs/loader').Module;
113114
const{ AsyncLocalStorage }=require('async_hooks');
114115
letdebug=require('internal/util/debuglog').debuglog('repl',(fn)=>{
@@ -326,6 +327,7 @@ class REPLServer extends Interface {
326327
terminal: options.terminal,
327328
historySize: options.historySize,
328329
prompt,
330+
colorize: options.useColors ? highlight : undefined,
329331
});
330332

331333
ObjectDefineProperty(this,'inputStream',{
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Flags: --expose-internals
2+
'use strict';
3+
4+
constcommon=require('../common');
5+
constassert=require('assert');
6+
const{ inspect, stripVTControlCharacters }=require('util');
7+
constArrayStream=require('../common/arraystream');
8+
const{ highlight }=require('internal/repl/highlight');
9+
const{ REPLServer }=require('repl');
10+
11+
common.skipIfInspectorDisabled();
12+
13+
assert.strictEqual(stripVTControlCharacters(highlight(
14+
'const /* comment */ answer = 42; // comment',
15+
)),'const /* comment */ answer = 42; // comment');
16+
17+
assert.strictEqual(
18+
highlight('const value = "text"'),
19+
`\u001b[${inspect.colors.cyan[0]}mconst\u001b[${inspect.colors.cyan[1]}m value = `+
20+
`\u001b[${inspect.colors.green[0]}m"text"\u001b[${inspect.colors.green[1]}m`,
21+
);
22+
23+
for(constsourceof[
24+
'undefined',
25+
'NaN',
26+
'Infinity',
27+
'Symbol.iterator',
28+
'Date.now()',
29+
'true',
30+
'null',
31+
'1n',
32+
'/regexp/u',
33+
'import("node:fs")',
34+
]){
35+
assert.notStrictEqual(highlight(source),source);
36+
}
37+
38+
// Incomplete source is expected while the user is typing.
39+
highlight('const value = "');
40+
41+
{
42+
constinput=newArrayStream();
43+
constoutput=newArrayStream();
44+
letrendered='';
45+
output.write=(chunk)=>{
46+
rendered+=chunk;
47+
};
48+
49+
constrepl=newREPLServer({
50+
input,
51+
output,
52+
prompt: '',
53+
terminal: true,
54+
useColors: false,
55+
});
56+
rendered='';
57+
repl.write('const');
58+
59+
assert.strictEqual(rendered,'const');
60+
repl.close();
61+
}

‎test/parallel/test-repl-multiline.js‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,24 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
const{ startNewREPLServer }=require('../common/repl');
5+
const{ stripVTControlCharacters }=require('util');
56

67
constinput=['const foo = {','};','foo'];
78

89
functionrun({ useColors }){
910
const{ replServer, output }=startNewREPLServer({ useColors });
1011

1112
replServer.on('exit',common.mustCall(()=>{
12-
constactual=output.accumulator.split('\n');
13+
// The output contains various escape codes, including
14+
// screen clears and others, so we trim them all to
15+
// simplify this test.
16+
constactual=stripVTControlCharacters(output.accumulator);
1317

14-
// Validate the output, which contains terminal escape codes.
15-
assert.strictEqual(actual.length,6);
16-
assert.ok(actual[0].endsWith(input[0]));
17-
assert.ok(actual[1].includes('| '));
18-
assert.ok(actual[1].endsWith(input[1]));
19-
assert.ok(actual[2].includes('undefined'));
20-
assert.ok(actual[3].endsWith(input[2]));
21-
assert.strictEqual(actual[4],'{}');
18+
constfirstStatementIdx=actual.indexOf(input.slice(0,1).join('\n| '));
19+
assert(firstStatementIdx>-1);
20+
21+
assert(actual.slice(firstStatementIdx).includes('undefined'));
22+
assert(actual.slice(firstStatementIdx).includes('foo'));
2223
}));
2324

2425
input.forEach((line)=>replServer.write(`${line}\n`));

‎test/parallel/test-repl-preview-newlines.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,14 @@ const { startNewREPLServer } = require('../common/repl');
66

77
common.skipIfInspectorDisabled();
88

9-
const{ input, output }=startNewREPLServer({useColors: true});
9+
// Ignore terminal settings so the preview remains active under TERM=dumb.
10+
process.env.TERM='';
11+
12+
// Keep syntax highlighting out of this test so it only covers preview layout.
13+
// Preview and result colors are enabled after readline is initialized.
14+
const{ input, output, replServer }=startNewREPLServer({useColors: false});
15+
replServer.useColors=true;
16+
replServer.writer.options.colors=true;
1017

1118
output.accumulator='';
1219

‎test/parallel/test-repl-preview-without-inspector.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,13 @@ const repl = new REPLServer({
6969
prompt: PROMPT,
7070
stream: newREPLStream(),
7171
ignoreUndefined: true,
72-
useColors: true,
72+
// Keep syntax highlighting out of these preview transcript assertions.
73+
// Preview and result colors are enabled after readline is initialized.
74+
useColors: false,
7375
terminal: true,
7476
});
77+
repl.useColors=true;
78+
repl.writer.options.colors=true;
7579

7680
repl.inputStream.run([
7781
'function foo(x) { return x; }',

‎test/parallel/test-repl-preview.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,13 @@ async function tests(options) {
6161
prompt: PROMPT,
6262
stream: newREPLStream(),
6363
ignoreUndefined: true,
64-
useColors: true,
64+
// Keep syntax highlighting out of these preview transcript assertions.
65+
// Preview and result colors are enabled after readline is initialized.
66+
useColors: false,
6567
...options
6668
});
69+
repl.useColors=true;
70+
repl.writer.options.colors=true;
6771

6872
repl.inputStream.run([
6973
'function foo(x) { return x; }',

‎test/parallel/test-repl-reverse-search.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,9 @@ function runTest() {
329329
}),
330330
completer: opts.completer,
331331
prompt,
332-
useColors: opts.useColors||false,
332+
// Keep syntax highlighting out of the reverse-search transcript. Result
333+
// colors are enabled below after readline has been initialized.
334+
useColors: false,
333335
terminal: true
334336
},common.mustCall((err,repl)=>{
335337
if(err){
@@ -351,6 +353,11 @@ function runTest() {
351353
setImmediate(runTestWrap,true);
352354
}));
353355

356+
if(opts.useColors){
357+
repl.useColors=true;
358+
repl.writer.options.colors=true;
359+
}
360+
354361
if(opts.columns){
355362
Object.defineProperty(repl,'columns',{
356363
value: opts.columns,

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit c18b0aa

Browse files
avivkelleraduh95
authored andcommitted
repl: add basic syntax highlighting
Signed-off-by: avivkeller <me@aviv.sh> PR-URL: #64591 Backport-PR-URL: #65267 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent 137ff67 commit c18b0aa

11 files changed

Lines changed: 209 additions & 19 deletions

‎lib/internal/readline/interface.js‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,13 +157,15 @@ const kPreviousCursorCols = Symbol('_previousCursorCols');
157157
constkMultilineMove=Symbol('_multilineMove');
158158
constkPreviousPrevRows=Symbol('_previousPrevRows');
159159
constkAddNewLineOnTTY=Symbol('_addNewLineOnTTY');
160+
constkColorize=Symbol('_colorize');
160161

161162
functionInterfaceConstructor(input,output,completer,terminal){
162163
this[kSawReturnAt]=0;
163164
// TODO(BridgeAR): Document this property. The name is not ideal, so we
164165
// might want to expose an alias and document that instead.
165166
this.isCompletionEnabled=true;
166167
this[kSawKeyPress]=false;
168+
this[kColorize]=undefined;
167169
this[kPreviousKey]=null;
168170
this.escapeCodeTimeout=ESCAPE_CODE_TIMEOUT;
169171
this.tabSize=8;
@@ -186,6 +188,7 @@ function InterfaceConstructor(input, output, completer, terminal) {
186188
consthistorySize=input.historySize;
187189
consthistory=input.history;
188190
constremoveHistoryDuplicates=input.removeHistoryDuplicates;
191+
this[kColorize]=input.colorize;
189192

190193
if(input.tabSize!==undefined){
191194
validateUint32(input.tabSize,'tabSize',true);
@@ -523,15 +526,18 @@ class Interface extends InterfaceConstructor {
523526
if(this[kIsMultiline]){
524527
constlines=StringPrototypeSplit(this.line,'\n');
525528
// Write first line with normal prompt
526-
this[kWriteToOutput](this[kPrompt]+lines[0]);
529+
this[kWriteToOutput](this[kPrompt]+
530+
(this[kColorize]?.(lines[0])??lines[0]));
527531

528532
// For continuation lines, add the "|" prefix
529533
for(leti=1;i<lines.length;i++){
530-
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+lines[i]);
534+
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+
535+
(this[kColorize]?.(lines[i])??lines[i]));
531536
}
532537
}else{
533538
// Write the prompt and the current buffer content.
534-
this[kWriteToOutput](line);
539+
this[kWriteToOutput](this[kPrompt]+
540+
(this[kColorize]?.(this.line)??this.line));
535541
}
536542

537543
// Force terminal to allocate a new line
@@ -687,7 +693,11 @@ class Interface extends InterfaceConstructor {
687693
this.line+=c;
688694
}
689695
this.cursor+=c.length;
690-
this[kWriteToOutput](c);
696+
if(this[kColorize]===undefined){
697+
this[kWriteToOutput](c);
698+
}else{
699+
this[kRefreshLine]();
700+
}
691701
return;
692702
}
693703
if(this.cursor<this.line.length){
@@ -706,7 +716,7 @@ class Interface extends InterfaceConstructor {
706716
this.cursor+=c.length;
707717
constnewPos=this.getCursorPos();
708718

709-
if(oldPos.rows<newPos.rows){
719+
if(oldPos.rows<newPos.rows||this[kColorize]!==undefined){
710720
this[kRefreshLine]();
711721
}else{
712722
this[kWriteToOutput](c);

‎lib/internal/repl/highlight.js‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
'use strict';
2+
3+
const{
4+
FunctionPrototypeBind,
5+
StringPrototypeSlice,
6+
}=primordials;
7+
8+
const{ stylizeWithColor }=require('internal/util/inspect');
9+
const{ Parser }=require('internal/deps/acorn/acorn/dist/acorn');
10+
11+
consttokenizer=FunctionPrototypeBind(Parser.tokenizer,Parser);
12+
13+
functiontokenStyle(token){
14+
const{ label, keyword }=token.type;
15+
16+
if(keyword!==undefined){
17+
if(label==='true'||label==='false')return'boolean';
18+
if(label==='null')return'null';
19+
if(label==='import'||label==='export')return'module';
20+
return'special';
21+
}
22+
23+
switch(label){
24+
case'name':
25+
switch(token.value){
26+
case'undefined':
27+
return'undefined';
28+
case'NaN':
29+
case'Infinity':
30+
return'number';
31+
case'Symbol':
32+
return'symbol';
33+
case'Date':
34+
return'date';
35+
default:
36+
returnundefined;
37+
}
38+
case'num':
39+
return'number';
40+
case'bigint':
41+
return'bigint';
42+
case'string':
43+
case'template':
44+
case'`':
45+
return'string';
46+
case'regexp':
47+
return'regexp';
48+
default:
49+
returnundefined;
50+
}
51+
}
52+
53+
functionhighlight(code){
54+
if(code.length===0)returncode;
55+
56+
letresult='';
57+
letoffset=0;
58+
functionwrite(start,end,style){
59+
result+=
60+
StringPrototypeSlice(code,offset,start)+
61+
stylizeWithColor(StringPrototypeSlice(code,start,end),style);
62+
offset=end;
63+
}
64+
65+
try{
66+
constiterator=tokenizer(code,{
67+
__proto__: null,
68+
allowHashBang: true,
69+
ecmaVersion: 'latest',
70+
onComment(_block,_text,start,end){
71+
write(start,end,'undefined');
72+
},
73+
});
74+
75+
for(consttokenofiterator){
76+
conststyle=tokenStyle(token);
77+
if(style!==undefined){
78+
write(token.start,token.end,style);
79+
}
80+
}
81+
}catch{
82+
// Acorn throws for unfinished strings, templates, and comments. Tokens and
83+
// comments reported before that point are still useful while typing.
84+
}
85+
86+
returnresult+StringPrototypeSlice(code,offset);
87+
}
88+
89+
module.exports={ highlight };

‎lib/internal/util/inspect.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3057,6 +3057,7 @@ module.exports = {
30573057
identicalSequenceRange,
30583058
inspect,
30593059
inspectDefaultOptions,
3060+
stylizeWithColor,
30603061
format,
30613062
formatWithOptions,
30623063
getStringWidth,

‎lib/repl.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ const {
109109
}=require('internal/readline/utils');
110110
const{ Console }=require('console');
111111
const{ shouldColorize }=require('internal/util/colors');
112+
const{ highlight }=require('internal/repl/highlight');
112113
constCJSModule=require('internal/modules/cjs/loader').Module;
113114
const{ AsyncLocalStorage }=require('async_hooks');
114115
letdebug=require('internal/util/debuglog').debuglog('repl',(fn)=>{
@@ -326,6 +327,7 @@ class REPLServer extends Interface {
326327
terminal: options.terminal,
327328
historySize: options.historySize,
328329
prompt,
330+
colorize: options.useColors ? highlight : undefined,
329331
});
330332

331333
ObjectDefineProperty(this,'inputStream',{
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Flags: --expose-internals
2+
'use strict';
3+
4+
constcommon=require('../common');
5+
constassert=require('assert');
6+
const{ inspect, stripVTControlCharacters }=require('util');
7+
constArrayStream=require('../common/arraystream');
8+
const{ highlight }=require('internal/repl/highlight');
9+
const{ REPLServer }=require('repl');
10+
11+
common.skipIfInspectorDisabled();
12+
13+
assert.strictEqual(stripVTControlCharacters(highlight(
14+
'const /* comment */ answer = 42; // comment',
15+
)),'const /* comment */ answer = 42; // comment');
16+
17+
assert.strictEqual(
18+
highlight('const value = "text"'),
19+
`\u001b[${inspect.colors.cyan[0]}mconst\u001b[${inspect.colors.cyan[1]}m value = `+
20+
`\u001b[${inspect.colors.green[0]}m"text"\u001b[${inspect.colors.green[1]}m`,
21+
);
22+
23+
for(constsourceof[
24+
'undefined',
25+
'NaN',
26+
'Infinity',
27+
'Symbol.iterator',
28+
'Date.now()',
29+
'true',
30+
'null',
31+
'1n',
32+
'/regexp/u',
33+
'import("node:fs")',
34+
]){
35+
assert.notStrictEqual(highlight(source),source);
36+
}
37+
38+
// Incomplete source is expected while the user is typing.
39+
highlight('const value = "');
40+
41+
{
42+
constinput=newArrayStream();
43+
constoutput=newArrayStream();
44+
letrendered='';
45+
output.write=(chunk)=>{
46+
rendered+=chunk;
47+
};
48+
49+
constrepl=newREPLServer({
50+
input,
51+
output,
52+
prompt: '',
53+
terminal: true,
54+
useColors: false,
55+
});
56+
rendered='';
57+
repl.write('const');
58+
59+
assert.strictEqual(rendered,'const');
60+
repl.close();
61+
}

‎test/parallel/test-repl-multiline.js‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,24 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
const{ startNewREPLServer }=require('../common/repl');
5+
const{ stripVTControlCharacters }=require('util');
56

67
constinput=['const foo = {','};','foo'];
78

89
functionrun({ useColors }){
910
const{ replServer, output }=startNewREPLServer({ useColors });
1011

1112
replServer.on('exit',common.mustCall(()=>{
12-
constactual=output.accumulator.split('\n');
13+
// The output contains various escape codes, including
14+
// screen clears and others, so we trim them all to
15+
// simplify this test.
16+
constactual=stripVTControlCharacters(output.accumulator);
1317

14-
// Validate the output, which contains terminal escape codes.
15-
assert.strictEqual(actual.length,6);
16-
assert.ok(actual[0].endsWith(input[0]));
17-
assert.ok(actual[1].includes('| '));
18-
assert.ok(actual[1].endsWith(input[1]));
19-
assert.ok(actual[2].includes('undefined'));
20-
assert.ok(actual[3].endsWith(input[2]));
21-
assert.strictEqual(actual[4],'{}');
18+
constfirstStatementIdx=actual.indexOf(input.slice(0,1).join('\n| '));
19+
assert(firstStatementIdx>-1);
20+
21+
assert(actual.slice(firstStatementIdx).includes('undefined'));
22+
assert(actual.slice(firstStatementIdx).includes('foo'));
2223
}));
2324

2425
input.forEach((line)=>replServer.write(`${line}\n`));

‎test/parallel/test-repl-preview-newlines.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,14 @@ const { startNewREPLServer } = require('../common/repl');
66

77
common.skipIfInspectorDisabled();
88

9-
const{ input, output }=startNewREPLServer({useColors: true});
9+
// Ignore terminal settings so the preview remains active under TERM=dumb.
10+
process.env.TERM='';
11+
12+
// Keep syntax highlighting out of this test so it only covers preview layout.
13+
// Preview and result colors are enabled after readline is initialized.
14+
const{ input, output, replServer }=startNewREPLServer({useColors: false});
15+
replServer.useColors=true;
16+
replServer.writer.options.colors=true;
1017

1118
output.accumulator='';
1219

‎test/parallel/test-repl-preview-without-inspector.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,13 @@ const repl = new REPLServer({
6969
prompt: PROMPT,
7070
stream: newREPLStream(),
7171
ignoreUndefined: true,
72-
useColors: true,
72+
// Keep syntax highlighting out of these preview transcript assertions.
73+
// Preview and result colors are enabled after readline is initialized.
74+
useColors: false,
7375
terminal: true,
7476
});
77+
repl.useColors=true;
78+
repl.writer.options.colors=true;
7579

7680
repl.inputStream.run([
7781
'function foo(x) { return x; }',

‎test/parallel/test-repl-preview.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,13 @@ async function tests(options) {
6161
prompt: PROMPT,
6262
stream: newREPLStream(),
6363
ignoreUndefined: true,
64-
useColors: true,
64+
// Keep syntax highlighting out of these preview transcript assertions.
65+
// Preview and result colors are enabled after readline is initialized.
66+
useColors: false,
6567
...options
6668
});
69+
repl.useColors=true;
70+
repl.writer.options.colors=true;
6771

6872
repl.inputStream.run([
6973
'function foo(x) { return x; }',

‎test/parallel/test-repl-reverse-search.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,9 @@ function runTest() {
329329
}),
330330
completer: opts.completer,
331331
prompt,
332-
useColors: opts.useColors||false,
332+
// Keep syntax highlighting out of the reverse-search transcript. Result
333+
// colors are enabled below after readline has been initialized.
334+
useColors: false,
333335
terminal: true
334336
},common.mustCall((err,repl)=>{
335337
if(err){
@@ -351,6 +353,11 @@ function runTest() {
351353
setImmediate(runTestWrap,true);
352354
}));
353355

356+
if(opts.useColors){
357+
repl.useColors=true;
358+
repl.writer.options.colors=true;
359+
}
360+
354361
if(opts.columns){
355362
Object.defineProperty(repl,'columns',{
356363
value: opts.columns,

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit c18b0aa

Browse files
avivkelleraduh95
authored andcommitted
repl: add basic syntax highlighting
Signed-off-by: avivkeller <me@aviv.sh> PR-URL: #64591 Backport-PR-URL: #65267 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent 137ff67 commit c18b0aa

11 files changed

Lines changed: 209 additions & 19 deletions

‎lib/internal/readline/interface.js‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -157,13 +157,15 @@ const kPreviousCursorCols = Symbol('_previousCursorCols');
157157
constkMultilineMove=Symbol('_multilineMove');
158158
constkPreviousPrevRows=Symbol('_previousPrevRows');
159159
constkAddNewLineOnTTY=Symbol('_addNewLineOnTTY');
160+
constkColorize=Symbol('_colorize');
160161

161162
functionInterfaceConstructor(input,output,completer,terminal){
162163
this[kSawReturnAt]=0;
163164
// TODO(BridgeAR): Document this property. The name is not ideal, so we
164165
// might want to expose an alias and document that instead.
165166
this.isCompletionEnabled=true;
166167
this[kSawKeyPress]=false;
168+
this[kColorize]=undefined;
167169
this[kPreviousKey]=null;
168170
this.escapeCodeTimeout=ESCAPE_CODE_TIMEOUT;
169171
this.tabSize=8;
@@ -186,6 +188,7 @@ function InterfaceConstructor(input, output, completer, terminal) {
186188
consthistorySize=input.historySize;
187189
consthistory=input.history;
188190
constremoveHistoryDuplicates=input.removeHistoryDuplicates;
191+
this[kColorize]=input.colorize;
189192

190193
if(input.tabSize!==undefined){
191194
validateUint32(input.tabSize,'tabSize',true);
@@ -523,15 +526,18 @@ class Interface extends InterfaceConstructor {
523526
if(this[kIsMultiline]){
524527
constlines=StringPrototypeSplit(this.line,'\n');
525528
// Write first line with normal prompt
526-
this[kWriteToOutput](this[kPrompt]+lines[0]);
529+
this[kWriteToOutput](this[kPrompt]+
530+
(this[kColorize]?.(lines[0])??lines[0]));
527531

528532
// For continuation lines, add the "|" prefix
529533
for(leti=1;i<lines.length;i++){
530-
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+lines[i]);
534+
this[kWriteToOutput](`\n${kMultilinePrompt.description}`+
535+
(this[kColorize]?.(lines[i])??lines[i]));
531536
}
532537
}else{
533538
// Write the prompt and the current buffer content.
534-
this[kWriteToOutput](line);
539+
this[kWriteToOutput](this[kPrompt]+
540+
(this[kColorize]?.(this.line)??this.line));
535541
}
536542

537543
// Force terminal to allocate a new line
@@ -687,7 +693,11 @@ class Interface extends InterfaceConstructor {
687693
this.line+=c;
688694
}
689695
this.cursor+=c.length;
690-
this[kWriteToOutput](c);
696+
if(this[kColorize]===undefined){
697+
this[kWriteToOutput](c);
698+
}else{
699+
this[kRefreshLine]();
700+
}
691701
return;
692702
}
693703
if(this.cursor<this.line.length){
@@ -706,7 +716,7 @@ class Interface extends InterfaceConstructor {
706716
this.cursor+=c.length;
707717
constnewPos=this.getCursorPos();
708718

709-
if(oldPos.rows<newPos.rows){
719+
if(oldPos.rows<newPos.rows||this[kColorize]!==undefined){
710720
this[kRefreshLine]();
711721
}else{
712722
this[kWriteToOutput](c);

‎lib/internal/repl/highlight.js‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
'use strict';
2+
3+
const{
4+
FunctionPrototypeBind,
5+
StringPrototypeSlice,
6+
}=primordials;
7+
8+
const{ stylizeWithColor }=require('internal/util/inspect');
9+
const{ Parser }=require('internal/deps/acorn/acorn/dist/acorn');
10+
11+
consttokenizer=FunctionPrototypeBind(Parser.tokenizer,Parser);
12+
13+
functiontokenStyle(token){
14+
const{ label, keyword }=token.type;
15+
16+
if(keyword!==undefined){
17+
if(label==='true'||label==='false')return'boolean';
18+
if(label==='null')return'null';
19+
if(label==='import'||label==='export')return'module';
20+
return'special';
21+
}
22+
23+
switch(label){
24+
case'name':
25+
switch(token.value){
26+
case'undefined':
27+
return'undefined';
28+
case'NaN':
29+
case'Infinity':
30+
return'number';
31+
case'Symbol':
32+
return'symbol';
33+
case'Date':
34+
return'date';
35+
default:
36+
returnundefined;
37+
}
38+
case'num':
39+
return'number';
40+
case'bigint':
41+
return'bigint';
42+
case'string':
43+
case'template':
44+
case'`':
45+
return'string';
46+
case'regexp':
47+
return'regexp';
48+
default:
49+
returnundefined;
50+
}
51+
}
52+
53+
functionhighlight(code){
54+
if(code.length===0)returncode;
55+
56+
letresult='';
57+
letoffset=0;
58+
functionwrite(start,end,style){
59+
result+=
60+
StringPrototypeSlice(code,offset,start)+
61+
stylizeWithColor(StringPrototypeSlice(code,start,end),style);
62+
offset=end;
63+
}
64+
65+
try{
66+
constiterator=tokenizer(code,{
67+
__proto__: null,
68+
allowHashBang: true,
69+
ecmaVersion: 'latest',
70+
onComment(_block,_text,start,end){
71+
write(start,end,'undefined');
72+
},
73+
});
74+
75+
for(consttokenofiterator){
76+
conststyle=tokenStyle(token);
77+
if(style!==undefined){
78+
write(token.start,token.end,style);
79+
}
80+
}
81+
}catch{
82+
// Acorn throws for unfinished strings, templates, and comments. Tokens and
83+
// comments reported before that point are still useful while typing.
84+
}
85+
86+
returnresult+StringPrototypeSlice(code,offset);
87+
}
88+
89+
module.exports={ highlight };

‎lib/internal/util/inspect.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3057,6 +3057,7 @@ module.exports = {
30573057
identicalSequenceRange,
30583058
inspect,
30593059
inspectDefaultOptions,
3060+
stylizeWithColor,
30603061
format,
30613062
formatWithOptions,
30623063
getStringWidth,

‎lib/repl.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ const {
109109
}=require('internal/readline/utils');
110110
const{ Console }=require('console');
111111
const{ shouldColorize }=require('internal/util/colors');
112+
const{ highlight }=require('internal/repl/highlight');
112113
constCJSModule=require('internal/modules/cjs/loader').Module;
113114
const{ AsyncLocalStorage }=require('async_hooks');
114115
letdebug=require('internal/util/debuglog').debuglog('repl',(fn)=>{
@@ -326,6 +327,7 @@ class REPLServer extends Interface {
326327
terminal: options.terminal,
327328
historySize: options.historySize,
328329
prompt,
330+
colorize: options.useColors ? highlight : undefined,
329331
});
330332

331333
ObjectDefineProperty(this,'inputStream',{
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Flags: --expose-internals
2+
'use strict';
3+
4+
constcommon=require('../common');
5+
constassert=require('assert');
6+
const{ inspect, stripVTControlCharacters }=require('util');
7+
constArrayStream=require('../common/arraystream');
8+
const{ highlight }=require('internal/repl/highlight');
9+
const{ REPLServer }=require('repl');
10+
11+
common.skipIfInspectorDisabled();
12+
13+
assert.strictEqual(stripVTControlCharacters(highlight(
14+
'const /* comment */ answer = 42; // comment',
15+
)),'const /* comment */ answer = 42; // comment');
16+
17+
assert.strictEqual(
18+
highlight('const value = "text"'),
19+
`\u001b[${inspect.colors.cyan[0]}mconst\u001b[${inspect.colors.cyan[1]}m value = `+
20+
`\u001b[${inspect.colors.green[0]}m"text"\u001b[${inspect.colors.green[1]}m`,
21+
);
22+
23+
for(constsourceof[
24+
'undefined',
25+
'NaN',
26+
'Infinity',
27+
'Symbol.iterator',
28+
'Date.now()',
29+
'true',
30+
'null',
31+
'1n',
32+
'/regexp/u',
33+
'import("node:fs")',
34+
]){
35+
assert.notStrictEqual(highlight(source),source);
36+
}
37+
38+
// Incomplete source is expected while the user is typing.
39+
highlight('const value = "');
40+
41+
{
42+
constinput=newArrayStream();
43+
constoutput=newArrayStream();
44+
letrendered='';
45+
output.write=(chunk)=>{
46+
rendered+=chunk;
47+
};
48+
49+
constrepl=newREPLServer({
50+
input,
51+
output,
52+
prompt: '',
53+
terminal: true,
54+
useColors: false,
55+
});
56+
rendered='';
57+
repl.write('const');
58+
59+
assert.strictEqual(rendered,'const');
60+
repl.close();
61+
}

‎test/parallel/test-repl-multiline.js‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,24 @@
22
constcommon=require('../common');
33
constassert=require('assert');
44
const{ startNewREPLServer }=require('../common/repl');
5+
const{ stripVTControlCharacters }=require('util');
56

67
constinput=['const foo = {','};','foo'];
78

89
functionrun({ useColors }){
910
const{ replServer, output }=startNewREPLServer({ useColors });
1011

1112
replServer.on('exit',common.mustCall(()=>{
12-
constactual=output.accumulator.split('\n');
13+
// The output contains various escape codes, including
14+
// screen clears and others, so we trim them all to
15+
// simplify this test.
16+
constactual=stripVTControlCharacters(output.accumulator);
1317

14-
// Validate the output, which contains terminal escape codes.
15-
assert.strictEqual(actual.length,6);
16-
assert.ok(actual[0].endsWith(input[0]));
17-
assert.ok(actual[1].includes('| '));
18-
assert.ok(actual[1].endsWith(input[1]));
19-
assert.ok(actual[2].includes('undefined'));
20-
assert.ok(actual[3].endsWith(input[2]));
21-
assert.strictEqual(actual[4],'{}');
18+
constfirstStatementIdx=actual.indexOf(input.slice(0,1).join('\n| '));
19+
assert(firstStatementIdx>-1);
20+
21+
assert(actual.slice(firstStatementIdx).includes('undefined'));
22+
assert(actual.slice(firstStatementIdx).includes('foo'));
2223
}));
2324

2425
input.forEach((line)=>replServer.write(`${line}\n`));

‎test/parallel/test-repl-preview-newlines.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,14 @@ const { startNewREPLServer } = require('../common/repl');
66

77
common.skipIfInspectorDisabled();
88

9-
const{ input, output }=startNewREPLServer({useColors: true});
9+
// Ignore terminal settings so the preview remains active under TERM=dumb.
10+
process.env.TERM='';
11+
12+
// Keep syntax highlighting out of this test so it only covers preview layout.
13+
// Preview and result colors are enabled after readline is initialized.
14+
const{ input, output, replServer }=startNewREPLServer({useColors: false});
15+
replServer.useColors=true;
16+
replServer.writer.options.colors=true;
1017

1118
output.accumulator='';
1219

‎test/parallel/test-repl-preview-without-inspector.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,13 @@ const repl = new REPLServer({
6969
prompt: PROMPT,
7070
stream: newREPLStream(),
7171
ignoreUndefined: true,
72-
useColors: true,
72+
// Keep syntax highlighting out of these preview transcript assertions.
73+
// Preview and result colors are enabled after readline is initialized.
74+
useColors: false,
7375
terminal: true,
7476
});
77+
repl.useColors=true;
78+
repl.writer.options.colors=true;
7579

7680
repl.inputStream.run([
7781
'function foo(x) { return x; }',

‎test/parallel/test-repl-preview.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,13 @@ async function tests(options) {
6161
prompt: PROMPT,
6262
stream: newREPLStream(),
6363
ignoreUndefined: true,
64-
useColors: true,
64+
// Keep syntax highlighting out of these preview transcript assertions.
65+
// Preview and result colors are enabled after readline is initialized.
66+
useColors: false,
6567
...options
6668
});
69+
repl.useColors=true;
70+
repl.writer.options.colors=true;
6771

6872
repl.inputStream.run([
6973
'function foo(x) { return x; }',

‎test/parallel/test-repl-reverse-search.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,9 @@ function runTest() {
329329
}),
330330
completer: opts.completer,
331331
prompt,
332-
useColors: opts.useColors||false,
332+
// Keep syntax highlighting out of the reverse-search transcript. Result
333+
// colors are enabled below after readline has been initialized.
334+
useColors: false,
333335
terminal: true
334336
},common.mustCall((err,repl)=>{
335337
if(err){
@@ -351,6 +353,11 @@ function runTest() {
351353
setImmediate(runTestWrap,true);
352354
}));
353355

356+
if(opts.useColors){
357+
repl.useColors=true;
358+
repl.writer.options.colors=true;
359+
}
360+
354361
if(opts.columns){
355362
Object.defineProperty(repl,'columns',{
356363
value: opts.columns,

0 commit comments

Comments
 (0)