@@ -20,6 +20,7 @@ const {
2020 MathMaxApply,
2121 NumberIsFinite,
2222 ObjectSetPrototypeOf,
23+ RegExp,
2324 RegExpPrototypeExec,
2425 StringPrototypeCodePointAt,
2526 StringPrototypeEndsWith,
@@ -72,7 +73,7 @@ const kHistorySize = 30;
7273const kMaxUndoRedoStackSize = 2048 ;
7374const kMincrlfDelay = 100 ;
7475// \r\n, \n, or \r followed by something other than \n
75- const lineEnding = / \r ? \n | \r (? ! \n ) / g ;
76+ const lineEndingPattern = ' \r?\n|\r(?!\n)' ;
7677
7778const kLineObjectStream = Symbol ( 'line object stream' ) ;
7879const kQuestionCancel = Symbol ( 'kQuestionCancel' ) ;
@@ -585,6 +586,7 @@ class Interface extends InterfaceConstructor {
585586 }
586587
587588 // Run test() on the new string chunk, not on the entire line buffer.
589+ const lineEnding = new RegExp ( lineEndingPattern , 'g' ) ;
588590 let newPartContainsEnding = RegExpPrototypeExec ( lineEnding , string ) ;
589591 if ( newPartContainsEnding !== null ) {
590592 if ( this [ kLine_buffer ] ) {
@@ -1322,18 +1324,24 @@ class Interface extends InterfaceConstructor {
13221324 // falls through
13231325 default :
13241326 if ( typeof s === 'string' && s ) {
1327+ /**
1328+ * Use Regular Expression scoped to this block, as lastIndex and the state for RegExpPrototypeExec
1329+ * will be overwritten if the same RegEx instance is reused in recursive function calls.
1330+ */
1331+ const lineEnding = new RegExp ( lineEndingPattern , 'g' ) ;
13251332 let nextMatch = RegExpPrototypeExec ( lineEnding , s ) ;
1326- if ( nextMatch !== null ) {
1327- this [ kInsertString ] ( StringPrototypeSlice ( s , 0 , nextMatch . index ) ) ;
1328- let { lastIndex } = lineEnding ;
1329- while ( ( nextMatch = RegExpPrototypeExec ( lineEnding , s ) ) !== null ) {
1330- this [ kLine ] ( ) ;
1333+
1334+ // If no line endings are found, just insert the string as is
1335+ if ( nextMatch === null ) {
1336+ this [ kInsertString ] ( s ) ;
1337+ } else {
1338+ // Keep track of the end of the last match
1339+ let lastIndex = 0 ;
1340+ do {
13311341 this [ kInsertString ] ( StringPrototypeSlice ( s , lastIndex , nextMatch . index ) ) ;
1342+ this [ kLine ] ( ) ;
13321343 ( { lastIndex } = lineEnding ) ;
1333- }
1334- if ( lastIndex === s . length ) this [ kLine ] ( ) ;
1335- } else {
1336- this [ kInsertString ] ( s ) ;
1344+ } while ( ( nextMatch = RegExpPrototypeExec ( lineEnding , s ) ) !== null ) ;
13371345 }
13381346 }
13391347 }
0 commit comments