Skip to content

Commit

Permalink
Fix replace with '$' in a more kosher way
Browse files Browse the repository at this point in the history
On top of JoeKar's fix.
  • Loading branch information
dmaluka authored and JoeKar committed Mar 17, 2024
1 parent 125c229 commit a6b47b4
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
5 changes: 2 additions & 3 deletions internal/action/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -784,7 +784,6 @@ func (h *BufPane) ReplaceCmd(args []string) {

if noRegex {
search = regexp.QuoteMeta(search)
replaceStr = strings.ReplaceAll(replaceStr, "$", "$$")
}

replace := []byte(replaceStr)
Expand All @@ -811,7 +810,7 @@ func (h *BufPane) ReplaceCmd(args []string) {
end = h.Cursor.CurSelection[1]
}
if all {
nreplaced, _ = h.Buf.ReplaceRegex(start, end, regex, replace)
nreplaced, _ = h.Buf.ReplaceRegex(start, end, regex, replace, !noRegex)
} else {
inRange := func(l buffer.Loc) bool {
return l.GreaterEqual(start) && l.LessEqual(end)
Expand Down Expand Up @@ -841,7 +840,7 @@ func (h *BufPane) ReplaceCmd(args []string) {

InfoBar.YNPrompt("Perform replacement (y,n,esc)", func(yes, canceled bool) {
if !canceled && yes {
_, nrunes := h.Buf.ReplaceRegex(locs[0], locs[1], regex, replace)
_, nrunes := h.Buf.ReplaceRegex(locs[0], locs[1], regex, replace, !noRegex)

searchLoc = locs[0]
searchLoc.X += nrunes + locs[0].Diff(locs[1], h.Buf)
Expand Down
12 changes: 8 additions & 4 deletions internal/buffer/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ func (b *Buffer) FindNext(s string, start, end, from Loc, down bool, useRegex bo
// ReplaceRegex replaces all occurrences of 'search' with 'replace' in the given area
// and returns the number of replacements made and the number of runes
// added or removed on the last line of the range
func (b *Buffer) ReplaceRegex(start, end Loc, search *regexp.Regexp, replace []byte) (int, int) {
func (b *Buffer) ReplaceRegex(start, end Loc, search *regexp.Regexp, replace []byte, captureGroups bool) (int, int) {
if start.GreaterThan(end) {
start, end = end, start
}
Expand All @@ -172,9 +172,13 @@ 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)
var result []byte
if captureGroups {
for _, submatches := range search.FindAllSubmatchIndex(in, -1) {
result = search.Expand(result, replace, in, submatches)
}
} else {
result = replace
}
found++
if i == end.Y {
Expand Down

0 comments on commit a6b47b4

Please sign in to comment.