       escaped = true
   escaped
 
+# Return 'open' or 'close'
+getPairState = (editor, event) ->
+  {matchText, range, match} = event
+  switch match.length
+    when 2
+      pairStateInBufferRange(editor, event)
+    when 3
+      switch
+        when match[1] then 'open'
+        when match[2] then 'close'
+
+pairStateInBufferRange = (editor, {matchText, range}) ->
+  text = getLineTextToBufferPosition(editor, range.end)
+  escapedChar = _.escapeRegExp(matchText)
+  bs = backSlashPattern
+  patterns = [
+    "#{bs}#{bs}#{escapedChar}"
+    "[^#{bs}]?#{escapedChar}"
+  ]
+  pattern = new RegExp(patterns.join('|'))
+  ['close', 'open'][(countChar(text, pattern) % 2)]
+
 # -------------------------
 class Pair extends TextObject
   @extend(false)

  pair: null
  wise: 'characterwise'
  supportCount: true

  # Return 'open' or 'close'
  getPairState: ({matchText, range, match}) ->
    switch match.length
      when 2
        @pairStateInBufferRange(range, matchText)
      when 3
        switch
          when match[1] then 'open'
          when match[2] then 'close'

  pairStateInBufferRange: (range, char) ->
    text = getLineTextToBufferPosition(@editor, range.end)
    escapedChar = _.escapeRegExp(char)
    bs = backSlashPattern
    patterns = [
      "#{bs}#{bs}#{escapedChar}"
      "[^#{bs}]?#{escapedChar}"
    ]
    pattern = new RegExp(patterns.join('|'))
    ['close', 'open'][(countChar(text, pattern) % 2)]

  getFilters: (from) ->
    filters = []

    when 'backward'
      scanRange = new Range([0, 0], from)
      editor.backwardsScanInBufferRange(pattern, scanRange, fn)

findPairRange = ({editor, from, pair, which, direction, filters}, fn) ->
  stack = []
  range = null

  scanPair editor, from, pair, direction, (event) ->
    if filters? and filters.some((filter) -> filter(event))
      return

    if getPairState(editor, event) isnt which
      stack.push(event)
    else
      topEvent = stack.pop()
      if fn(stack, topEvent)
        range = event.range
        event.stop()
  range

# Take start point of matched range.
backSlashPattern = _.escapeRegExp('\\')
