# find.py
#
# Moleskine: a source code editor for the GNOME desktop
#
# Copyright (c) 2000 - 2002   Michele Campeotto <micampe@micampe.it>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

import Moleskine
import menu

text = None
new_text = None
flags = 0

def find_next():
    if text is None:
        from Dialogs import FindDialog
        FindDialog()
        return
    
    doc = Moleskine.app.get_current_document()
    
    if doc.get_selection_start() != doc.get_selection_end():
        doc.goto_pos(doc.get_selection_end())
    doc.search_anchor()
    doc.search_next(flags, text)
    doc.goto_pos(doc.get_selection_start())
    doc.search_next(flags, text)
    
    if doc.get_selection_start() != doc.get_selection_end():
        return 1
    else:
        return 0

def find_prev():
    if text is None:
        from Dialogs import FindDialog
        FindDialog()
        return
    
    doc = Moleskine.app.get_current_document()
    
    old_pos = doc.get_selection_start()
    if doc.get_selection_start() != doc.get_selection_end():
        doc.goto_pos(doc.get_selection_start() - 1)
    doc.search_anchor()
    doc.search_prev(flags, text)
    doc.goto_pos(doc.get_selection_start())
    doc.search_prev(flags, text)
    
    if doc.get_selection_start() != doc.get_selection_end():
        return 1
    else:
        doc.goto_pos(old_pos)
        return 0

def replace_next():
    if text is None or new_text is None:
        from Dialogs import ReplaceDialog
        ReplaceDialog()
        return
    
    doc = Moleskine.app.get_current_document()
    
    if doc.get_selection_start() == doc.get_selection_end():
        if not find_next():
            return
    doc.replace_sel(new_text)
