           scanEnd = Point.INFINITY
 
         if not withinChange
-          if lastValidMarkerIndex >= 0
-            scanStart = @markers[lastValidMarkerIndex].getBufferRange().start
-            spliceIndex = lastValidMarkerIndex
+          if markerIndexBeforeChange >= 0
+            scanStart = @markers[markerIndexBeforeChange].getBufferRange().start
+            spliceIndex = markerIndexBeforeChange
           else
             scanStart = Point.ZERO
             spliceIndex = 0


    changes = @patch.changes()
    change = null
    changesDone = false
    changeEnd = Point.ZERO
    scanEnd = Point.ZERO
    withinChange = false
    markerIndex = 0
    lastValidMarkerIndex = -1

    while (marker = @markers[markerIndex])? or change?
      unless change?
        until changesDone or changeEnd?.isGreaterThan(scanEnd)
          {value: change, done: changesDone} = changes.next()
          changeEnd = change.position.traverse(change.newExtent) if change?

      markerRange = marker?.getBufferRange()

      if withinChange
        if marker?
          if marker.isValid() and markerRange.start.isGreaterThan(changeEnd)

          oldMarkers = @markers.splice(spliceIndex, markerIndex - spliceIndex + 1, newMarkers...)
          oldMarker.destroy() for oldMarker in oldMarkers
          markerIndex += newMarkers.length - oldMarkers.length
          markerIndexBeforeChange = markerIndex
          change = null

      else if change? and markerRange.end.isGreaterThanOrEqual(changeStart)
        withinChange = true
      else if marker.isValid()
        markerIndexBeforeChange = markerIndex

      # A marker that is invalid but is outside of any change can simply be
      # recreated. It must have been temporarily changed but then restored.
      else
        @markers[markerIndex] = @recreateMarker(marker)

      markerIndex++

