         
         guard self.selectedRange.length == 0 else { return }
         
-        let string = self.string
         let location = self.selectedRange.location
         
         // delete tab
         if self.isAutomaticTabExpansionEnabled,
-            string.rangeOfIndent(at: location).upperBound >= location
+            self.string.rangeOfIndent(at: location).upperBound >= location
         {
-            let tabWidth = self.tabWidth
-            let column = string.column(of: location, tabWidth: tabWidth)
-            let targetLength = tabWidth - (column % tabWidth)
-            let targetRange = NSRange(location: location - targetLength, length: targetLength)
+            let column = self.string.column(of: location, tabWidth: self.tabWidth)
+            let targetLength = self.tabWidth - (column % self.tabWidth)
+            let targetRange = NSRange((location - targetLength)..<location)
             
             if location >= targetLength,
-                (string as NSString).substring(with: targetRange) == String(repeating: " ", count: targetLength) {
+                (self.string as NSString).substring(with: targetRange) == String(repeating: " ", count: targetLength) {
                 self.selectedRange = targetRange
             }
         }

            return super.insertNewline(sender)
        }
        
        let string = self.string
        let indentRange = string.rangeOfIndent(at: self.selectedRange.location)
        
        // don't auto-indent if indent is selected (2008-12-13)
        guard indentRange.length == 0 || indentRange != self.selectedRange else {

        }
        
        let indent: String = {
            guard let baseIndentRange = indentRange.intersection(NSRange(0..<self.selectedRange.location)) else {
                return ""
            }
            return (self.string as NSString).substring(with: baseIndentRange)
        }()
        
        // calculation for smart indent
