         @update()
 
     get_text_state: () ->
+        start = @$pad[0].selectionStart
+        end = @$pad[0].selectionEnd
+        if start > end
+            [start, end] = [end, start]
         text_state = [
             @$pad.val(),
-            [@$pad[0].selectionEnd, @$pad[0].selectionStart],
+            [start, end],
             @$holder.scrollTop(),
         ]
         print "get scrollTop", @$holder.scrollTop()


    constructor: ->
        @$box = $("#search-box")
        @$input = $("#search-input")
        @$input.keyup (e) =>
            if keybord_key(e) == "enter"
                @enter()

    envoke: =>
        esc()
        @$box.show()
        @$input.focus()
        @$input[0].selectionStart = 0
        @$input[0].selectionEnd = @$input.val().length

    enter: ->
        query = @$input.val()

        at = editor.$pad[0].selectionStart
        end = editor.$pad[0].selectionEnd

        bottom = editor.text[at+1...]
        pos = bottom.indexOf(query)
        if pos != -1
            at = at + pos
        else
            pos = editor.text.indexOf(query)
            if pos != -1
                at = pos
            else
                return

        editor.$pad[0].selectionStart = at + 1
        editor.$pad[0].selectionEnd = at + query.length + 1
        editor.update()
        editor.scroll_pos(at)
        @$input.focus()


class MiniMap

        return [start, end]

    tab: =>
        if $("#search-input").is(":focus")
            print "focus replace"
            $("#replace-input").focus()
            return
        if $("#replace-input").is(":focus")
            print "focus search"
            $("#search-input").focus()
            return
        if not @$pad.is(":focus")
            return
        if @autocomplete()
            return
        @indent()
        return

    autocomplete: =>
        [text, [start, end], s] = @get_text_state()
