# query-replace - replace all or some occurrences of a string by another
# Copyright (C) 2001,2002 Philippe Troin <phil@fifi.org>
#
# $Id: query-replace,v 1.4 2002/12/19 02:46:43 phil Exp $
#
# 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 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

# How to use:
#  1. You need the read-within-zle function (available separately)
#  2. Drop read-within-zle and query-replace along your fpath
#  3. Add the following to your .zshrc:
#         autoload -zU query-replace read-within-zle
#         zle -N query-replace
#         bindkey "^[%" query-replace
#	  bindkey "\M-%" query-replace # only if using bindkey -m
#  4. Use M-x query-replace or M-% to start query-replace'ing.


emulate -L zsh

local input=''
read-within-zle 'Query-replace: ' || return 0
local from=$input 
[[ $#from -eq 0 ]] && return 0
read-within-zle 'With: ' || return 0
local to=$input 
local nfound=0 
local replacethis=0
local replaceall=0 
while :
do
  local postmatch=${RBUFFER#*$from} 
  if [[ $#postmatch = $#RBUFFER ]]
  then
    if [[ $nfound -eq 0 ]]
    then
      zle -M "no matches"
    fi
    return
  fi
  ((nfound++))
  local prematch=$RBUFFER[1,-$(($#postmatch+$#from+1))] 
  LBUFFER="$LBUFFER$prematch" 
  RBUFFER="$from$postmatch" 
  if [[ $replaceall -eq 0 ]]
  then
    zle -R "Replace \"$from\" with \"$to\" (y/n/a/!/q)?"
    while :
    do
      local key=''
      read -k key || return
      case $key in
        ([yY])   replacethis=1; break ;;
        ([nN])   replacethis=0; break ;;
        ([aA!])  replacethis=1; replaceall=1; break ;;
        ([qQ]) return ;;
	(*)      zle beep ;;
      esac
    done
  fi
  RBUFFER=$RBUFFER[$#from+1,-1] 
  if [[ $replacethis -eq 1 ]]
  then
    LBUFFER="$LBUFFER$to" 
  else
    LBUFFER="$LBUFFER$from" 
  fi
done
