Skip to content

Commit

Permalink
readline: move charLengthLeft() and charLengthAt()
Browse files Browse the repository at this point in the history
This moves the charLengthLeft() and charLengthAt() into the internal
readline file. This allows sharing the functions internally with
other code.

PR-URL: #31112
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
BridgeAR authored and MylesBorins committed Jan 16, 2020
1 parent 7ba21d0 commit f0506c3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 19 deletions.
25 changes: 25 additions & 0 deletions lib/internal/readline/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,29 @@ CSI.kClearToLineEnd = CSI`0K`;
CSI.kClearLine = CSI`2K`;
CSI.kClearScreenDown = CSI`0J`;

// TODO(BridgeAR): Treat combined characters as single character, i.e,
// 'a\u0301' and '\u0301a' (both have the same visual output).
// Check Canonical_Combining_Class in
// http://userguide.icu-project.org/strings/properties
function charLengthLeft(str, i) {
if (i <= 0)
return 0;
if ((i > 1 && str.codePointAt(i - 2) >= kUTF16SurrogateThreshold) ||
str.codePointAt(i - 1) >= kUTF16SurrogateThreshold) {
return 2;
}
return 1;
}

function charLengthAt(str, i) {
if (str.length <= i) {
// Pretend to move to the right. This is necessary to autocomplete while
// moving to the right.
return 1;
}
return str.codePointAt(i) >= kUTF16SurrogateThreshold ? 2 : 1;
}

if (internalBinding('config').hasIntl) {
const icu = internalBinding('icu');
// icu.getStringWidth(string, ambiguousAsFullWidth, expandEmojiSequence)
Expand Down Expand Up @@ -452,6 +475,8 @@ function commonPrefix(strings) {
}

module.exports = {
charLengthAt,
charLengthLeft,
commonPrefix,
emitKeys,
getStringWidth,
Expand Down
21 changes: 2 additions & 19 deletions lib/readline.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ const { validateString } = require('internal/validators');
const { inspect } = require('internal/util/inspect');
const EventEmitter = require('events');
const {
charLengthAt,
charLengthLeft,
commonPrefix,
CSI,
emitKeys,
Expand Down Expand Up @@ -591,25 +593,6 @@ Interface.prototype._wordRight = function() {
}
};

function charLengthLeft(str, i) {
if (i <= 0)
return 0;
if ((i > 1 && str.codePointAt(i - 2) >= kUTF16SurrogateThreshold) ||
str.codePointAt(i - 1) >= kUTF16SurrogateThreshold) {
return 2;
}
return 1;
}

function charLengthAt(str, i) {
if (str.length <= i) {
// Pretend to move to the right. This is necessary to autocomplete while
// moving to the right.
return 1;
}
return str.codePointAt(i) >= kUTF16SurrogateThreshold ? 2 : 1;
}

Interface.prototype._deleteLeft = function() {
if (this.cursor > 0 && this.line.length > 0) {
// The number of UTF-16 units comprising the character to the left
Expand Down

0 comments on commit f0506c3

Please sign in to comment.