 _ = require 'underscore-plus'
 {
   isEscapedCharRange
+  getEndOfLineForBufferRow
   scanBufferRow
 } = require './utils'
 

  filterEvent: ->
    true

  scanPair: (which, direction, from, fn) ->
    switch direction
      when 'forward'
        scanRange = new Range(from, @editor.buffer.getEndPosition())
        scanFunctionName = 'scanInBufferRange'
      when 'backward'
        scanRange = new Range([0, 0], from)
        scanFunctionName = 'backwardsScanInBufferRange'

    @editor[scanFunctionName] @getPattern(), scanRange, (event) =>
      if not @allowNextLine and (from.row isnt event.range.start.row)
        event.stop()
        return

      return if isEscapedCharRange(@editor, event.range)
      if @filterEvent(event)
        fn(event)

  findPair: (which, direction, from, fn) ->
    stack = []
    range = null


  spliceStack: (stack, eventState) ->
    stack.pop()

  onCloseFound: (stack, {eventState, from}) ->
    openState = @spliceStack(stack, eventState)
    unless openState?
      return true

    if stack.length is 0
      {start} = openState.range
      start.isEqual(from) or (@allowForwarding and start.row is from.row)

  onOpenFound: (stack, {eventState, from}) ->
    @spliceStack(stack, eventState)
    stack.length is 0

  findCloseForward: (from) ->
    @findPair('close', 'forward', from)

  findOpenBackward: (from) ->
    @findPair('open', 'backward', from)

  find: (from) ->
    closeRange = @closeRange = @findCloseForward(from)
    openRange = @findOpenBackward(closeRange.end) if closeRange?

    if closeRange? and openRange?
      {
