Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
repl: add pipe char for browsing multiline history
  • Loading branch information
puskin committed Mar 21, 2025
commit b41273af816d5274ac61c1e5cf099929b369f078
48 changes: 39 additions & 9 deletions lib/internal/readline/interface.js
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,12 @@ class Interface extends InterfaceConstructor {
const normalizedLine = StringPrototypeReplaceAll(this.line, '\n', '\r');
Comment thread
BridgeAR marked this conversation as resolved.
Resolved

if (this.history.length === 0 || this.history[0] !== normalizedLine) {
if (this.lastCommandErrored && this.historyIndex === 0) {
// If the last command errored, remove it from history.
// The user is issuing a new command starting from the errored command,
// Hopefully with the fix
ArrayPrototypeShift(this.history);
}
Comment thread
BridgeAR marked this conversation as resolved.
Resolved
if (this.removeHistoryDuplicates) {
// Remove older history line if identical to new one
const dupIndex = ArrayPrototypeIndexOf(this.history, this.line);
Expand Down Expand Up @@ -504,8 +510,22 @@ class Interface extends InterfaceConstructor {
// erase data
clearScreenDown(this.output);

// Write the prompt and the current buffer content.
this[kWriteToOutput](line);
// Check if this is a multiline entry
const lines = StringPrototypeSplit(this.line, '\n');
Comment thread
BridgeAR marked this conversation as resolved.
Resolved
const isMultiline = lines.length > 1;

if (!isMultiline) {
// Write the prompt and the current buffer content.
this[kWriteToOutput](line);
} else {
// Write first line with normal prompt
this[kWriteToOutput](this[kPrompt] + lines[0]);

// For continuation lines, add the "|" prefix
for (let i = 1; i < lines.length; i++) {
this[kWriteToOutput]('\n| ' + lines[i]);
}
}

// Force terminal to allocate a new line
if (lineCols === 0) {
Expand Down Expand Up @@ -945,8 +965,8 @@ class Interface extends InterfaceConstructor {
if (splitLine.length > 1 && rows < splitLine.length - 1) {
const currentLine = splitLine[rows];
const nextLine = splitLine[rows + 1];
const amountToMove = (cols > nextLine.length) ?
currentLine.length - cols + nextLine.length + 1 :
const amountToMove = (cols > nextLine.length + 1) ?
currentLine.length - cols + nextLine.length + 3 :
currentLine.length + 1;
// Go to the same position on the next line, or the end of the next line
// If the current position does not exist in the next line.
Expand Down Expand Up @@ -997,8 +1017,8 @@ class Interface extends InterfaceConstructor {
// Otherwise treat the "arrow up" as a movement to the previous row.
if (splitLine.length > 1 && rows > 0) {
const previousLine = splitLine[rows - 1];
const amountToMove = (cols > previousLine.length) ?
-cols - 1 :
const amountToMove = (cols > previousLine.length + 1) ?
-cols + 1 :
-previousLine.length - 1;
// Go to the same position on the previous line, or the end of the previous line
// If the current position does not exist in the previous line.
Expand Down Expand Up @@ -1075,9 +1095,19 @@ class Interface extends InterfaceConstructor {
* }}
*/
getCursorPos() {
const strBeforeCursor =
this[kPrompt] + StringPrototypeSlice(this.line, 0, this.cursor);
return this[kGetDisplayPos](strBeforeCursor);
// Handle multiline input by accounting for "| " prefixes on continuation lines
const lineUptoCursor = StringPrototypeSlice(this.line, 0, this.cursor);
const lines = StringPrototypeSplit(lineUptoCursor, '\n');

// First line uses normal prompt, subsequent lines use "| " (2 chars)
let displayText = this[kPrompt] + lines[0];

// Add continuation lines with their prefixes
for (let i = 1; i < lines.length; i++) {
displayText += '\n| ' + lines[i];
}

return this[kGetDisplayPos](displayText);
Comment thread
BridgeAR marked this conversation as resolved.
Resolved
}

// This function moves cursor dx places to the right
Expand Down
22 changes: 22 additions & 0 deletions lib/internal/repl/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,15 @@ function setupPreview(repl, contextSymbol, bufferSymbol, active) {

let escaped = null;

let justExecutedMultilineCommand = false;

function getPreviewPos() {
const displayPos = repl._getDisplayPos(`${repl.getPrompt()}${repl.line}`);
// If the line is a multi line
if (StringPrototypeIndexOf(repl.line, '\n') !== -1) {
// This is to consider the additional "| " that prefixes the line
displayPos.cols += 2;
Comment thread
BridgeAR marked this conversation as resolved.
Resolved
}
const cursorPos = repl.line.length !== repl.cursor ?
repl.getCursorPos() :
displayPos;
Expand All @@ -177,6 +184,11 @@ function setupPreview(repl, contextSymbol, bufferSymbol, active) {
clearLine(repl.output);
moveCursor(repl.output, 0, -rows);
inputPreview = null;
// If pressing enter on some history line,
// The next preview should not be generated
if ((key.name === 'return' || key.name === 'enter') && !key.meta && repl.historyIndex !== -1) {
justExecutedMultilineCommand = true;
}
Comment thread
BridgeAR marked this conversation as resolved.
Resolved
}
if (completionPreview !== null) {
// Prevent cursor moves if not necessary!
Expand Down Expand Up @@ -373,6 +385,11 @@ function setupPreview(repl, contextSymbol, bufferSymbol, active) {
return;
}

if (justExecutedMultilineCommand) {
justExecutedMultilineCommand = false;
return;
}

hasCompletions = false;

// Add the autocompletion preview.
Expand Down Expand Up @@ -444,9 +461,14 @@ function setupPreview(repl, contextSymbol, bufferSymbol, active) {

const { cursorPos, displayPos } = getPreviewPos();
const rows = displayPos.rows - cursorPos.rows;
// Moves one line below all the user lines
moveCursor(repl.output, 0, rows);
// Writes the preview there
repl.output.write(`\n${result}`);

// Go back to the horizontal position of the cursor
cursorTo(repl.output, cursorPos.cols);
// Go back to the vertical position of the cursor
moveCursor(repl.output, 0, -rows - 1);
};

Expand Down
3 changes: 3 additions & 0 deletions lib/repl.js
Original file line number Diff line number Diff line change
Expand Up @@ -974,6 +974,9 @@ function REPLServer(prompt,

if (e) {
self._domain.emit('error', e.err || e);
self.lastCommandErrored = true;
} else {
self.lastCommandErrored = false;
}

// Clear buffer if no SyntaxErrors
Expand Down
64 changes: 46 additions & 18 deletions test/parallel/test-repl-history-navigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -659,11 +659,19 @@ const tests = [
...'which ends here`',
"'I am a multiline strong\\nwhich ends here'\n",
prompt,
`${prompt}a = \`I am a multiline strong\nwhich ends here\``,
`${prompt}a = \`I am a multiline strong\nwhich ends here\``,
`${prompt}a = \`I am a multiline strng\nwhich ends here\``,
`${prompt}a = \`I am a multiline string\nwhich ends here\``,
`${prompt}a = \`I am a multiline string\nwhich ends here\``,
`${prompt}a = \`I am a multiline strong`,
`\n| which ends here\``,
`${prompt}a = \`I am a multiline strong`,
`\n| which ends here\``,

`${prompt}a = \`I am a multiline strng`,
`\n| which ends here\``,

`${prompt}a = \`I am a multiline string`,
`\n| which ends here\``,

`${prompt}a = \`I am a multiline string`,
`\n| which ends here\``,
"'I am a multiline string\\nwhich ends here'\n",
prompt,
],
Expand Down Expand Up @@ -707,14 +715,24 @@ const tests = [
...'am another one`',
'undefined\n',
prompt,
`${prompt}let c = \`I\nam another one\``,
`${prompt}let c = \`I\nam another one\``,

`${prompt}b = \`I am a multiline strong\nwhich ends here\``,
`${prompt}b = \`I am a multiline strong\nwhich ends here\``,
`${prompt}b = \`I am a multiline strng\nwhich ends here\``,
`${prompt}b = \`I am a multiline string\nwhich ends here\``,
`${prompt}b = \`I am a multiline string\nwhich ends here\``,
`${prompt}let c = \`I`,
`\n| am another one\``,

`${prompt}let c = \`I`,
`\n| am another one\``,

`${prompt}b = \`I am a multiline strong`,
`\n| which ends here\``,
`${prompt}b = \`I am a multiline strong`,
`\n| which ends here\``,
`${prompt}b = \`I am a multiline strng`,
`\n| which ends here\``,

`${prompt}b = \`I am a multiline string`,
`\n| which ends here\``,

`${prompt}b = \`I am a multiline string`,
`\n| which ends here\``,
"'I am a multiline string\\nwhich ends here'\n",
prompt,
],
Expand Down Expand Up @@ -758,10 +776,18 @@ const tests = [
` [message]: "Unexpected identifier 'line'"\n` +
'}\n',
prompt,
`${prompt}d = \`I am a\nsuper\nbroken\` line'`,
`${prompt}d = \`I am a\nsuper\nbroken\` line`,
`${prompt}d = \`I am a`,
`\n| super`,
`\n| broken\` line'`,

`${prompt}d = \`I am a`,
`\n| super`,
'\n| broken` line',
'`',
`${prompt}d = \`I am a\nsuper\nbroken line\``,

`${prompt}d = \`I am a`,
`\n| super`,
`\n| broken line\``,
"'I am a\\nsuper\\nbroken line'\n",
prompt,
],
Expand All @@ -784,8 +810,10 @@ const tests = [
...'string`',
'undefined\n',
prompt,
`${prompt}let f = \`multiline\nstring\``,
`${prompt}let f = \`multiline\nstring\``,
`${prompt}let f = \`multiline`,
`\n| string\``,
`${prompt}let f = \`multiline`,
`\n| string\``,
prompt,
],
clean: true
Expand Down
114 changes: 109 additions & 5 deletions test/parallel/test-repl-multiline-navigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ class ActionStream extends stream.Stream {
};
doAction();
}
write(chunk) {
const chunkLines = chunk.toString('utf8').split('\n');
this.lines[this.lines.length - 1] += chunkLines[0];
if (chunkLines.length > 1) {
this.lines.push(...chunkLines.slice(1));
}
this.emit('line', this.lines[this.lines.length - 1]);
return true;
}
resume() {}
pause() {}
}
Expand Down Expand Up @@ -66,12 +75,19 @@ const defaultHistoryPath = tmpdir.resolve('.node_repl_history');
r.input.run([{ name: 'up' }]);
assert.strictEqual(r.cursor, 18);

r.input.run([{ name: 'right' }]);
r.input.run([{ name: 'right' }]);
r.input.run([{ name: 'right' }]);
r.input.run([{ name: 'right' }]);
r.input.run([{ name: 'right' }]);
for (let i = 0; i < 5; i++) {
r.input.run([{ name: 'right' }]);
}
r.input.run([{ name: 'up' }]);
assert.strictEqual(r.cursor, 15);
r.input.run([{ name: 'up' }]);

for (let i = 0; i < 5; i++) {
r.input.run([{ name: 'right' }]);
}
assert.strictEqual(r.cursor, 8);

r.input.run([{ name: 'down' }]);
assert.strictEqual(r.cursor, 15);

r.input.run([{ name: 'down' }]);
Expand All @@ -92,3 +108,91 @@ const defaultHistoryPath = tmpdir.resolve('.node_repl_history');
checkResults
);
}

{
cleanupTmpFile();
// If the last command errored and the user is trying to edit it,
// The errored line should be removed from history
const checkResults = common.mustSucceed((r) => {
r.write('let lineWithMistake = `I have some');
r.input.run([{ name: 'enter' }]);
r.write('problem with` my syntax\'');
r.input.run([{ name: 'enter' }]);
r.input.run([{ name: 'up' }]);
r.input.run([{ name: 'backspace' }]);
r.write('`');
for (let i = 0; i < 11; i++) {
r.input.run([{ name: 'left' }]);
}
r.input.run([{ name: 'backspace' }]);
r.input.run([{ name: 'enter' }]);

assert.strictEqual(r.history.length, 1);
assert.strictEqual(r.history[0], 'let lineWithMistake = `I have some\rproblem with my syntax`');
assert.strictEqual(r.line, '');
});

repl.createInternalRepl(
{ NODE_REPL_HISTORY: defaultHistoryPath },
{
terminal: true,
input: new ActionStream(),
output: new stream.Writable({
write(chunk, _, next) {
next();
}
}),
},
checkResults
);
}

{
cleanupTmpFile();
const outputBuffer = [];

// Test that the REPL preview is properly shown on multiline commands
// And deleted when enter is pressed
const checkResults = common.mustSucceed((r) => {
r.write('Array(100).fill(');
r.input.run([{ name: 'enter' }]);
r.write('123');
r.input.run([{ name: 'enter' }]);
r.write(')');
r.input.run([{ name: 'enter' }]);
r.input.run([{ name: 'up' }]);
r.input.run([{ name: 'up' }]);

assert.deepStrictEqual(r.last, new Array(100).fill(123));
r.input.run([{ name: 'enter' }]);
assert.strictEqual(outputBuffer.includes('[\n' +
' 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123,\n' +
' 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123,\n' +
' 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123,\n' +
' 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123,\n' +
' 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123,\n' +
' 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123,\n' +
' 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123,\n' +
' 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123,\n' +
' 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123,\n' +
' 123\n' +
']\n'), true);
});

repl.createInternalRepl(
{ NODE_REPL_HISTORY: defaultHistoryPath },
{
preview: true,
terminal: true,
input: new ActionStream(),
output: new stream.Writable({
write(chunk, _, next) {
// Store each chunk in the buffer
outputBuffer.push(chunk.toString());
next();
}
}),
},
checkResults
);
}