about summary refs log tree commit diff
path: root/Functions/Zle/replace-string
blob: 577e9174daf593e3d2257dfe04f95ae55d767a70 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
emulate -L zsh
setopt extendedglob

autoload read-from-minibuffer

local p1="Replace: " p2="   with: "
local REPLY MATCH MBEGIN MEND curwidget=$WIDGET previous
local -a match mbegin mend

if (( ${+NUMERIC} )); then
  (( $NUMERIC > 0 )) && previous=1
else
  zstyle -t ":zle:$WIDGET" edit-previous && previous=1
fi

read-from-minibuffer $p1 ${previous:+$_replace_string_src} || return 1
_replace_string_src=$REPLY

read-from-minibuffer "$p1$_replace_string_src$p2" \
  ${previous:+$_replace_string_rep} || return 1
_replace_string_rep=$REPLY

if [[ $curwidget = *pattern* ]]; then
    local rep2
    # The following horror is so that an & preceded by an even
    # number of backslashes is active, without stripping backslashes,
    # while preceded by an odd number of backslashes is inactive,
    # with one backslash being stripped.  A similar logic applies
    # to \digit.
    local rep=$_replace_string_rep
    while [[ $rep = (#b)([^\\]#)(\\\\)#(\\|)(\&|\\<->|\\\{<->\})(*) ]]; do
	if [[ -n $match[3] ]]; then
	    # Expression is quoted, strip quotes
	    rep2="${match[1]}${match[2]}${match[4]}"
	else
	    rep2+="${match[1]}${match[2]}"
	    if [[ $match[4] = \& ]]; then
		rep2+='${MATCH}'
	    elif [[ $match[4] = \\\{* ]]; then
		rep2+='${match['${match[4][3,-2]}']}'
	    else
		rep2+='${match['${match[4][2,-1]}']}'
	    fi
	fi
	rep=${match[5]}
    done
    rep2+=$rep
    LBUFFER=${LBUFFER//(#bm)$~_replace_string_src/${(e)rep2}}
    RBUFFER=${RBUFFER//(#bm)$~_replace_string_src/${(e)rep2}}
else
    LBUFFER=${LBUFFER//$_replace_string_src/$_replace_string_rep}
    RBUFFER=${RBUFFER//$_replace_string_src/$_replace_string_rep}
fi