Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

readline: refactor readline module #12755

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
49 changes: 36 additions & 13 deletions lib/internal/readline.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,38 @@
const ansi =
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;

const kEscape = '\x1b';

module.exports = {
emitKeys,
stripVTControlCharacters
};
var getStringWidth;
var isFullWidthCodePoint;

function CSI(strings, ...args) {
let ret = `${kEscape}[`;
for (var n = 0; n < strings.length; n++) {
ret += strings[n];
if (n < args.length)
ret += args[n];
}
return ret;
}

CSI.kEscape = kEscape;
CSI.kClearToBeginning = CSI`1K`;
CSI.kClearToEnd = CSI`0K`;
CSI.kClearLine = CSI`2K`;
CSI.kClearScreenDown = CSI`0J`;

if (process.binding('config').hasIntl) {
const icu = process.binding('icu');
module.exports.getStringWidth = function getStringWidth(str, options) {
getStringWidth = function getStringWidth(str, options) {
options = options || {};
if (!Number.isInteger(str))
str = stripVTControlCharacters(String(str));
return icu.getStringWidth(str,
Boolean(options.ambiguousAsFullWidth),
Boolean(options.expandEmojiSequence));
};
module.exports.isFullWidthCodePoint =
isFullWidthCodePoint =
function isFullWidthCodePoint(code, options) {
if (typeof code !== 'number')
return false;
Expand All @@ -33,9 +48,9 @@ if (process.binding('config').hasIntl) {
/**
* Returns the number of columns required to display the given string.
*/
module.exports.getStringWidth = function getStringWidth(str) {
getStringWidth = function getStringWidth(str) {
if (Number.isInteger(str))
return module.exports.isFullWidthCodePoint(str) ? 2 : 1;
return isFullWidthCodePoint(str) ? 2 : 1;

let width = 0;

Expand All @@ -48,7 +63,7 @@ if (process.binding('config').hasIntl) {
i++;
}

if (module.exports.isFullWidthCodePoint(code)) {
if (isFullWidthCodePoint(code)) {
width += 2;
} else {
width++;
Expand All @@ -62,7 +77,7 @@ if (process.binding('config').hasIntl) {
* Returns true if the character represented by a given
* Unicode code point is full-width. Otherwise returns false.
*/
module.exports.isFullWidthCodePoint = function isFullWidthCodePoint(code) {
isFullWidthCodePoint = function isFullWidthCodePoint(code) {
if (!Number.isInteger(code)) {
return false;
}
Expand Down Expand Up @@ -154,11 +169,11 @@ function* emitKeys(stream) {
shift: false
};

if (ch === '\x1b') {
if (ch === kEscape) {
escaped = true;
s += (ch = yield);

if (ch === '\x1b') {
if (ch === kEscape) {
s += (ch = yield);
}
}
Expand Down Expand Up @@ -373,7 +388,7 @@ function* emitKeys(stream) {
// backspace or ctrl+h
key.name = 'backspace';
key.meta = escaped;
} else if (ch === '\x1b') {
} else if (ch === kEscape) {
// escape key
key.name = 'escape';
key.meta = escaped;
Expand Down Expand Up @@ -407,3 +422,11 @@ function* emitKeys(stream) {
/* Unrecognized or broken escape sequence, don't emit anything */
}
}

module.exports = {
emitKeys,
getStringWidth,
isFullWidthCodePoint,
stripVTControlCharacters,
CSI
};
109 changes: 57 additions & 52 deletions lib/readline.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,41 @@

'use strict';

const { debug, inherits } = require('util');
const Buffer = require('buffer').Buffer;
const EventEmitter = require('events');
const {
CSI,
emitKeys,
getStringWidth,
isFullWidthCodePoint,
stripVTControlCharacters
} = require('internal/readline');

const {
kEscape,
kClearToBeginning,
kClearToEnd,
kClearLine,
kClearScreenDown
} = CSI;

const kHistorySize = 30;
const kMincrlfDelay = 100;
const kMaxcrlfDelay = 2000;
// \r\n, \n, or \r followed by something other than \n
const lineEnding = /\r?\n|\r(?!\n)/;

const util = require('util');
const debug = util.debuglog('readline');
const inherits = util.inherits;
const Buffer = require('buffer').Buffer;
const EventEmitter = require('events');
const internalReadline = require('internal/readline');
const emitKeys = internalReadline.emitKeys;
const getStringWidth = internalReadline.getStringWidth;
const isFullWidthCodePoint = internalReadline.isFullWidthCodePoint;
const stripVTControlCharacters = internalReadline.stripVTControlCharacters;
const KEYPRESS_DECODER = Symbol('keypress-decoder');
const ESCAPE_DECODER = Symbol('escape-decoder');

// GNU readline library - keyseq-timeout is 500ms (default)
const ESCAPE_CODE_TIMEOUT = 500;


exports.createInterface = function(input, output, completer, terminal) {
function createInterface(input, output, completer, terminal) {
return new Interface(input, output, completer, terminal);
};
}


function Interface(input, output, completer, terminal) {
Expand Down Expand Up @@ -311,13 +327,13 @@ Interface.prototype._refreshLine = function() {
// first move to the bottom of the current line, based on cursor pos
var prevRows = this.prevRows || 0;
if (prevRows > 0) {
exports.moveCursor(this.output, 0, -prevRows);
moveCursor(this.output, 0, -prevRows);
}

// Cursor to left edge.
exports.cursorTo(this.output, 0);
cursorTo(this.output, 0);
// erase data
exports.clearScreenDown(this.output);
clearScreenDown(this.output);

// Write the prompt and the current buffer content.
this._writeToOutput(line);
Expand All @@ -328,11 +344,11 @@ Interface.prototype._refreshLine = function() {
}

// Move cursor to original position.
exports.cursorTo(this.output, cursorPos.cols);
cursorTo(this.output, cursorPos.cols);

var diff = lineRows - cursorPos.rows;
if (diff > 0) {
exports.moveCursor(this.output, 0, -diff);
moveCursor(this.output, 0, -diff);
}

this.prevRows = cursorPos.rows;
Expand Down Expand Up @@ -373,8 +389,6 @@ Interface.prototype.write = function(d, key) {
this.terminal ? this._ttyWrite(d, key) : this._normalWrite(d);
};

// \r\n, \n, or \r followed by something other than \n
const lineEnding = /\r?\n|\r(?!\n)/;
Interface.prototype._normalWrite = function(b) {
if (b === undefined) {
return;
Expand Down Expand Up @@ -716,7 +730,7 @@ Interface.prototype._moveCursor = function(dx) {
this.line.substring(this.cursor, oldcursor)
);
}
exports.moveCursor(this.output, diffWidth, 0);
moveCursor(this.output, diffWidth, 0);
this.prevRows = newPos.rows;
} else {
this._refreshLine();
Expand Down Expand Up @@ -798,8 +812,8 @@ Interface.prototype._ttyWrite = function(s, key) {
break;

case 'l': // clear the whole screen
exports.cursorTo(this.output, 0, 0);
exports.clearScreenDown(this.output);
cursorTo(this.output, 0, 0);
clearScreenDown(this.output);
this._refreshLine();
break;

Expand Down Expand Up @@ -957,20 +971,10 @@ Interface.prototype._ttyWrite = function(s, key) {
}
};


exports.Interface = Interface;


/**
* accepts a readable Stream instance and makes it emit "keypress" events
*/

const KEYPRESS_DECODER = Symbol('keypress-decoder');
const ESCAPE_DECODER = Symbol('escape-decoder');

// GNU readline library - keyseq-timeout is 500ms (default)
const ESCAPE_CODE_TIMEOUT = 500;

function emitKeypressEvents(stream, iface) {
if (stream[KEYPRESS_DECODER]) return;
var StringDecoder = require('string_decoder').StringDecoder; // lazy load
Expand Down Expand Up @@ -1000,7 +1004,7 @@ function emitKeypressEvents(stream, iface) {
try {
stream[ESCAPE_DECODER].next(r[i]);
// Escape letter at the tail position
if (r[i] === '\x1b' && i + 1 === r.length) {
if (r[i] === kEscape && i + 1 === r.length) {
timeoutId = setTimeout(escapeCodeTimeout, ESCAPE_CODE_TIMEOUT);
}
} catch (err) {
Expand Down Expand Up @@ -1036,8 +1040,6 @@ function emitKeypressEvents(stream, iface) {
stream.on('newListener', onNewListener);
}
}
exports.emitKeypressEvents = emitKeypressEvents;


/**
* moves the cursor to the x and y coordinate on the given stream
Expand All @@ -1054,13 +1056,11 @@ function cursorTo(stream, x, y) {
throw new Error('Can\'t set cursor row without also setting it\'s column');

if (typeof y !== 'number') {
stream.write('\x1b[' + (x + 1) + 'G');
stream.write(CSI`${x + 1}G`);
} else {
stream.write('\x1b[' + (y + 1) + ';' + (x + 1) + 'H');
stream.write(CSI`${y + 1};${x + 1}H`);
}
}
exports.cursorTo = cursorTo;


/**
* moves the cursor relative to its current location
Expand All @@ -1071,19 +1071,17 @@ function moveCursor(stream, dx, dy) {
return;

if (dx < 0) {
stream.write('\x1b[' + (-dx) + 'D');
stream.write(CSI`${-dx}D`);
} else if (dx > 0) {
stream.write('\x1b[' + dx + 'C');
stream.write(CSI`${dx}C`);
}

if (dy < 0) {
stream.write('\x1b[' + (-dy) + 'A');
stream.write(CSI`${-dy}A`);
} else if (dy > 0) {
stream.write('\x1b[' + dy + 'B');
stream.write(CSI`${dy}B`);
}
}
exports.moveCursor = moveCursor;


/**
* clears the current line the cursor is on:
Expand All @@ -1098,17 +1096,15 @@ function clearLine(stream, dir) {

if (dir < 0) {
// to the beginning
stream.write('\x1b[1K');
stream.write(kClearToBeginning);
} else if (dir > 0) {
// to the end
stream.write('\x1b[0K');
stream.write(kClearToEnd);
} else {
// entire line
stream.write('\x1b[2K');
stream.write(kClearLine);
}
}
exports.clearLine = clearLine;


/**
* clears the screen from the current position of the cursor down
Expand All @@ -1118,6 +1114,15 @@ function clearScreenDown(stream) {
if (stream === null || stream === undefined)
return;

stream.write('\x1b[0J');
stream.write(kClearScreenDown);
}
exports.clearScreenDown = clearScreenDown;

module.exports = {
Interface,
clearLine,
clearScreenDown,
createInterface,
cursorTo,
emitKeypressEvents,
moveCursor
};
Loading