@@ -345,7 +345,7 @@ final class EditorTextView: NSTextView {
345345 }
346346 }
347347
348- if bracket == nil && cursorPos > 0 {
348+ if bracket == nil && cursorPos > 0 && cursorPos - 1 < chars . count {
349349 let char = chars [ cursorPos - 1 ]
350350 if bracketPairs [ char] != nil || reverseBracketPairs [ char] != nil {
351351 bracketPos = cursorPos - 1
@@ -511,26 +511,35 @@ final class EditorTextView: NSTextView {
511511
512512 private func shouldSkipClosingQuote( _ quote: Character ) -> Bool {
513513 let pos = selectedRange ( ) . location
514- guard pos < string. count else { return false }
515- let index = string. index ( string. startIndex, offsetBy: pos)
516- return string [ index] == quote
514+ let utf16View = string. utf16
515+ guard pos < utf16View. count else { return false }
516+ let index = utf16View. index ( utf16View. startIndex, offsetBy: pos)
517+ guard let scalar = UnicodeScalar ( utf16View [ index] ) else { return false }
518+ return Character ( scalar) == quote
517519 }
518520
519521 private func shouldSkipClosingBracket( _ bracket: Character ) -> Bool {
520522 let pos = selectedRange ( ) . location
521- guard pos < string. count else { return false }
522- let index = string. index ( string. startIndex, offsetBy: pos)
523- return string [ index] == bracket
523+ let utf16View = string. utf16
524+ guard pos < utf16View. count else { return false }
525+ let index = utf16View. index ( utf16View. startIndex, offsetBy: pos)
526+ guard let scalar = UnicodeScalar ( utf16View [ index] ) else { return false }
527+ return Character ( scalar) == bracket
524528 }
525529
526530 private func shouldDeletePair( ) -> Bool {
527531 let pos = selectedRange ( ) . location
528- guard pos > 0 , pos < string. count else { return false }
532+ let utf16View = string. utf16
533+ guard pos > 0 , pos < utf16View. count else { return false }
529534
530- let prevIndex = string. index ( string. startIndex, offsetBy: pos - 1 )
531- let nextIndex = string. index ( string. startIndex, offsetBy: pos)
532- let prevChar = string [ prevIndex]
533- let nextChar = string [ nextIndex]
535+ let prevIndex = utf16View. index ( utf16View. startIndex, offsetBy: pos - 1 )
536+ let nextIndex = utf16View. index ( utf16View. startIndex, offsetBy: pos)
537+
538+ guard let prevScalar = UnicodeScalar ( utf16View [ prevIndex] ) ,
539+ let nextScalar = UnicodeScalar ( utf16View [ nextIndex] ) else { return false }
540+
541+ let prevChar = Character ( prevScalar)
542+ let nextChar = Character ( nextScalar)
534543
535544 // Check if we're between a matching pair
536545 if let closing = bracketPairs [ prevChar] , closing == nextChar {
0 commit comments