From 3ee0d56de6052934d05befffa7dc2476f152d723 Mon Sep 17 00:00:00 2001 From: moculus Date: Wed, 9 Apr 2008 21:35:26 +0000 Subject: [PATCH] regex-replace can use subgroups --HG-- branch : pmacs2 --- mode/replace.py | 38 +++++++++++++++++++++++++++++++++----- searchutil.py | 4 ++-- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/mode/replace.py b/mode/replace.py index 0a87521..e2ac827 100644 --- a/mode/replace.py +++ b/mode/replace.py @@ -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: diff --git a/searchutil.py b/searchutil.py index 92a2383..147b7d9 100644 --- a/searchutil.py +++ b/searchutil.py @@ -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