import os, commands, re, tempfile
from subprocess import Popen, PIPE, STDOUT

import buffer, default, dirutil, regex, util, window
from point import Point

from method import Method, Argument

class Search(Method):
    '''Interactive search; finds next occurance of text in buffer'''
    is_literal = True
    direction = 'next'
    prompt = 'I-Search: '
    def execute(self, w, **vargs):
        self.old_cursor = w.logical_cursor()
        self.old_window = w
        w.application.open_mini_buffer(self.prompt, lambda x: None, self, None, 'search')
class ReverseSearch(Search):
    '''Interactive search; finds previous occurance of text in buffer'''
    direction = 'previous'

class RegexSearch(Search):
    '''Interactive search; finds next occurance of regex in buffer'''
    is_literal = False
    prompt = 'I-RegexSearch: '
class RegexReverseSearch(RegexSearch):
    '''Interactive search; finds prevoius occurance of regex in buffer'''
    direction = 'previous'
    
class Replace(Method):
    '''Replace occurances of string X with string Y'''
    is_literal = True
    args = [Argument('before', prompt="Replace String: ",
                     default=default.last_replace_before, load_default=True),
            Argument('after', prompt="Replace With: ",
                     default=default.last_replace_after, load_default=True)]
    def _execute(self, w, **vargs):
        a = w.application
        a.last_replace_before = self.before = vargs['before']
        a.last_replace_after = self.after = vargs['after'].replace('\\n', '\n').replace('\\\\', '\\')
        # ???
        self.old_window = w
        a.open_mini_buffer('I-Replace: ', lambda x: None, self, None, 'replace')
class RegexReplace(Method):
    '''Replace occurances of string X with string Y'''
    is_literal = False
    args = [Argument('before', prompt="Replace Regex: ",
                     default=default.last_replace_before, load_default=True),
            Argument('after', prompt="Replace With: ",
                     default=default.last_replace_after, load_default=True)]
    def _execute(self, w, **vargs):
        w.application.last_replace_before = self.before = vargs['before']
        w.application.last_replace_after  = self.after = vargs['after']
        self.old_window = w
        f = lambda x: None
        w.application.open_mini_buffer('I-RegexReplace: ', f, self, None, 'replace')