regex-replace can use subgroups

--HG--
branch : pmacs2
This commit is contained in:
moculus 2008-04-09 21:35:26 +00:00
parent b5fbae5f23
commit 3ee0d56de6
2 changed files with 35 additions and 7 deletions

View File

@ -3,6 +3,8 @@ import re, sets, string
import color, method, minibuffer, mode, searchutil
from point import Point
subgroup_re = re.compile(r'((?:\\\\)*)\\(0|[1-9][0-9]*)')
class Replace(mode.Fundamental):
modename = 'Replace'
def __init__(self, w):
@ -73,12 +75,33 @@ def _find_next(m, move=False):
newc = searchutil.find_next(r, w, move, start=c.add(0, 0))
if newc:
(m.p1, m.p2) = newc
(m.p1, m.p2, m.match) = newc
return True
else:
(m.p1, m.p2) = (None, None)
(m.p1, m.p2, m.match) = (None, None, None)
return False
def _get_before(m):
if m.match is None:
return m.before
else:
return m.match.group(0)
def _get_after(m):
if m.after is None:
return None
elif m.match is None:
return m.after
def _repl(match):
(pre, num) = (match.group(1), int(match.group(2)))
if num == 0 or m.match.lastindex and num <= m.match.lastindex:
return pre + m.match.group(num)
else:
return match.group(0)
return subgroup_re.sub(_repl, m.after)
def _set_prompt(m):
w = m.old_window
if m.p1 is None:
@ -90,16 +113,21 @@ def _set_prompt(m):
count += w.buffer.lines[y][x:].count(m.before)
y += 1
x = 0
after = _get_after(m)
before = _get_before(m)
if count > 1:
p = 'Replace %r with %r [ynadq] (%d occurances)?' % (m.before, m.after, count)
p = 'Replace %r with %r [ynadq] (%d occurances)?' % (before, after, count)
else:
p = 'Replace %r with %r [ynadq] (1 occurance)?' % (m.before, m.after)
p = 'Replace %r with %r [ynadq] (1 occurance)?' % (before, after)
w.application.mini_prompt = p
def _replace(m):
m.old_window.buffer.delete(m.p1, m.p2)
if m.after:
m.old_window.buffer.insert_string(m.p1, m.after)
after = _get_after(m)
m.old_window.buffer.insert_string(m.p1, after)
def _finish(m, w):
if m.p1 is None:

View File

@ -65,11 +65,11 @@ def find(r, w, move=False, direction='next', start=None, end=None):
for i in indices:
if direction == 'next' and ranges[i][0] > limit:
ranges[i][3] = selected_color
newc = (ranges[i][0], ranges[i][1])
newc = (ranges[i][0], ranges[i][1], ranges[i][4])
break
elif direction == 'previous' and ranges[i][1] < limit:
ranges[i][3] = selected_color
newc = (ranges[i][0], ranges[i][1])
newc = (ranges[i][0], ranges[i][1], ranges[i][4])
break
if ranges and not newc:
return None