]> git.lizzy.rs Git - micro.git/commitdiff
Support regex capture groups in replace command
authorZachary Yedidia <zyedidia@gmail.com>
Thu, 13 Feb 2020 21:05:56 +0000 (16:05 -0500)
committerZachary Yedidia <zyedidia@gmail.com>
Thu, 13 Feb 2020 21:05:56 +0000 (16:05 -0500)
See https://golang.org/pkg/regexp/syntax/ for the
supported syntax. Here are some examples:

```
replace "(foo)" "$1-bar"
replace "(foo)" "${1}-bar"
replace "(?P<group>foo)" "$group-bar"
replace "(?P<group>foo)" "$group-bar"
replace "(?P<key>\w+):\s+(?P<value>\w+)$" "$key=$value"
```

Closes #1115

internal/action/command.go
internal/buffer/search.go

index 667de11b921b2f04400b7b1902bfada08f70b17e..2d9b2fbbbb361671f7fe8b4f85d3db9b18334909 100644 (file)
@@ -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)
index 0930ba2cac4c4c508fbe7cd99b53b2a7e7ea2f55..64bcc48c8b429b11befc6233984a8d8355d6d499 100644 (file)
@@ -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}