From 30ed25859a0105c6653a5bc0e5f6886d9e1b3723 Mon Sep 17 00:00:00 2001 From: Zachary Yedidia Date: Thu, 13 Feb 2020 16:05:56 -0500 Subject: [PATCH] Support regex capture groups in replace command See https://golang.org/pkg/regexp/syntax/ for the supported syntax. Here are some examples: ``` replace "(foo)" "$1-bar" replace "(foo)" "${1}-bar" replace "(?Pfoo)" "$group-bar" replace "(?Pfoo)" "$group-bar" replace "(?P\w+):\s+(?P\w+)$" "$key=$value" ``` Closes #1115 --- internal/action/command.go | 2 +- internal/buffer/search.go | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/internal/action/command.go b/internal/action/command.go index 667de11b..2d9b2fbb 100644 --- a/internal/action/command.go +++ b/internal/action/command.go @@ -764,7 +764,7 @@ func (h *BufPane) ReplaceCmd(args []string) { InfoBar.YNPrompt("Perform replacement (y,n,esc)", func(yes, canceled bool) { if !canceled && yes { - h.Buf.Replace(locs[0], locs[1], replaceStr) + h.Buf.ReplaceRegex(locs[0], locs[1], regex, replace) searchLoc = locs[0] searchLoc.X += utf8.RuneCount(replace) diff --git a/internal/buffer/search.go b/internal/buffer/search.go index 0930ba2c..64bcc48c 100644 --- a/internal/buffer/search.go +++ b/internal/buffer/search.go @@ -155,8 +155,12 @@ func (b *Buffer) ReplaceRegex(start, end Loc, search *regexp.Regexp, replace []b l = util.SliceStart(l, end.X) } newText := search.ReplaceAllFunc(l, func(in []byte) []byte { + result := []byte{} + for _, submatches := range search.FindAllSubmatchIndex(in, -1) { + result = search.Expand(result, replace, in, submatches) + } found++ - return replace + return result }) from := Loc{charpos, i}