Skip to content

Commit 1ea20dc

Browse files
Escape braces that are in string or comments when finding matching brace
1 parent dc77592 commit 1ea20dc

File tree

1 file changed

+39
-4
lines changed

1 file changed

+39
-4
lines changed

internal/buffer/buffer.go

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import (
1616
"sync"
1717
"sync/atomic"
1818
"time"
19+
"sort"
1920

2021
luar "layeh.com/gopher-luar"
2122

@@ -1140,7 +1141,41 @@ var BracePairs = [][2]rune{
11401141
{'[', ']'},
11411142
}
11421143

1144+
func (b *Buffer) getSortedSyntaxIndices(lineN int) []int {
1145+
keys := make([]int, 0, len(b.Match(lineN)))
1146+
for k := range b.Match(lineN) {
1147+
keys = append(keys, k)
1148+
}
1149+
sort.Ints(keys)
1150+
return keys
1151+
}
1152+
1153+
// Returns the Group (syntax highlight group ID) at the specified location and a boolean
1154+
// that indicates if a group is found or not
1155+
func (b *Buffer) GetGroupAtLoc(loc Loc) (highlight.Group, bool) {
1156+
sortedIndices := b.getSortedSyntaxIndices(loc.Y)
1157+
i := sort.SearchInts(sortedIndices, loc.X)
1158+
if i == 0 || i == len(sortedIndices) {
1159+
return 0, false
1160+
}
1161+
if sortedIndices[i] == loc.X && b.Match(loc.Y)[sortedIndices[i]] != 0 {
1162+
return b.Match(loc.Y)[sortedIndices[i]], true
1163+
}
1164+
return b.Match(loc.Y)[sortedIndices[i - 1]], true
1165+
}
1166+
1167+
func (b *Buffer) isLocInStringOrComment(loc Loc) bool {
1168+
g, gFound := b.GetGroupAtLoc(loc)
1169+
if gFound && (g.String() == "constant.string" || strings.Contains(g.String(), "comment")) {
1170+
return true
1171+
}
1172+
return false
1173+
}
1174+
11431175
func (b *Buffer) findMatchingBrace(braceType [2]rune, start Loc, char rune) (Loc, bool) {
1176+
if b.isLocInStringOrComment(start) {
1177+
return start, false
1178+
}
11441179
var i int
11451180
if char == braceType[0] {
11461181
for y := start.Y; y < b.LinesNum(); y++ {
@@ -1151,9 +1186,9 @@ func (b *Buffer) findMatchingBrace(braceType [2]rune, start Loc, char rune) (Loc
11511186
}
11521187
for x := xInit; x < len(l); x++ {
11531188
r := l[x]
1154-
if r == braceType[0] {
1189+
if r == braceType[0] && !b.isLocInStringOrComment(Loc{x, y}) {
11551190
i++
1156-
} else if r == braceType[1] {
1191+
} else if r == braceType[1] && !b.isLocInStringOrComment(Loc{x, y}) {
11571192
i--
11581193
if i == 0 {
11591194
return Loc{x, y}, true
@@ -1170,9 +1205,9 @@ func (b *Buffer) findMatchingBrace(braceType [2]rune, start Loc, char rune) (Loc
11701205
}
11711206
for x := xInit; x >= 0; x-- {
11721207
r := l[x]
1173-
if r == braceType[1] {
1208+
if r == braceType[1] && !b.isLocInStringOrComment(Loc{x, y}){
11741209
i++
1175-
} else if r == braceType[0] {
1210+
} else if r == braceType[0] && !b.isLocInStringOrComment(Loc{x, y}){
11761211
i--
11771212
if i == 0 {
11781213
return Loc{x, y}, true

0 commit comments

Comments
 (0)