/
textedit.go
201 lines (187 loc) · 5.89 KB
/
textedit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package main
import (
"bytes"
"context"
"fmt"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/govim/govim/cmd/govim/config"
"github.com/govim/govim/cmd/govim/internal/golang_org_x_tools_gopls/lsp/protocol"
"github.com/govim/govim/cmd/govim/internal/types"
)
type textEdit struct {
buffer int
call string
start int
end int
lines []string
}
func (v *vimstate) applyProtocolTextEdits(b *types.Buffer, edits []protocol.TextEdit) error {
// The protocol doesn't require edits to be sorted, so sort them.
if !sort.IsSorted(editsSort(edits)) {
edits = append([]protocol.TextEdit(nil), edits...)
sortEdits(edits)
}
// prepare the changes to make in Vim
blines := bytes.Split(b.Contents()[:len(b.Contents())-1], []byte("\n"))
var changes []textEdit
for ie := len(edits) - 1; ie >= 0; ie-- {
e := edits[ie]
start, err := types.PointFromPosition(b, e.Range.Start)
if err != nil {
return fmt.Errorf("failed to derive start point from position: %v", err)
}
end, err := types.PointFromPosition(b, e.Range.End)
if err != nil {
return fmt.Errorf("failed to derive end point from position: %v", err)
}
// Skip empty edits
if start == end && e.NewText == "" {
continue
}
// special case deleting of complete lines
if start.Col() == 1 && end.Col() == 1 && e.NewText == "" {
delstart := min(start.Line(), len(blines))
delend := min(end.Line()-1, len(blines))
changes = append(changes, textEdit{
call: "deletebufline",
buffer: b.Num,
start: delstart,
end: delend,
})
blines = append(blines[:delstart-1], blines[delend:]...)
continue
}
newLines := strings.Split(e.NewText, "\n")
appendAdjust := 1
if start.Line()-1 < len(blines) {
appendAdjust = 0
startLine := blines[start.Line()-1]
newLines[0] = string(startLine[:start.Col()-1]) + newLines[0]
if end.Line()-1 < len(blines) {
endLine := blines[end.Line()-1]
newLines[len(newLines)-1] += string(endLine[end.Col()-1:])
}
// we only need to update the start line because we can't have
// overlapping edits
blines[start.Line()-1] = []byte(newLines[0])
changes = append(changes, textEdit{
call: "setbufline",
buffer: b.Num,
start: start.Line(),
lines: []string{string(blines[start.Line()-1])},
})
} else {
blines = append(blines, []byte(newLines[0]))
}
if start.Line() != end.Line() {
// We can't delete beyond the end of the buffer. So the start end end here are
// both min() reduced
delstart := min(start.Line()+1, len(blines))
delend := min(end.Line(), len(blines))
changes = append(changes, textEdit{
call: "deletebufline",
buffer: b.Num,
start: delstart,
end: delend,
})
blines = blines[:delstart-1]
}
if len(newLines) > 1 {
changes = append(changes, textEdit{
call: "appendbufline",
buffer: b.Num,
start: start.Line() - appendAdjust,
lines: newLines[1-appendAdjust : len(newLines)-appendAdjust],
})
}
}
// see :help wundo. The use of wundo! is significant. It first deletes
// the temp file we created, but only recreates it if there is something
// to write. This is inherently racey... because theorectically the file
// might in the meantime have been created by another instance of
// govim.... We reduce that risk using the time above
tf, err := os.CreateTemp("", strconv.FormatInt(time.Now().UnixNano(), 10))
if err != nil {
return fmt.Errorf("failed to create temp undo file: %v", err)
}
v.ChannelExf("wundo! %v", tf.Name())
defer func() {
if _, err := os.Stat(tf.Name()); err != nil {
return
}
v.ChannelExf("silent! rundo %v", tf.Name())
err = os.Remove(tf.Name())
}()
preEventIgnore := v.ParseString(v.ChannelExpr("&eventignore"))
v.ChannelEx("set eventignore=all")
defer v.ChannelExf("set eventignore=%v", preEventIgnore)
v.ChannelCall("listener_remove", b.Listener)
defer func() {
b.Listener = v.ParseInt(v.ChannelCall("listener_add", v.Prefix()+string(config.FunctionEnrichDelta), b.Num))
}()
v.BatchStart()
for _, e := range changes {
switch e.call {
case "setbufline":
v.BatchAssertChannelCall(AssertIsZero(), e.call, b.Num, e.start, e.lines[0])
case "deletebufline":
v.BatchAssertChannelCall(AssertIsZero(), e.call, b.Num, e.start, e.end)
case "appendbufline":
v.BatchAssertChannelCall(AssertIsZero(), e.call, b.Num, e.start, e.lines)
default:
panic(fmt.Errorf("unknown change type: %v", e.call))
}
}
v.BatchAssertChannelCall(AssertIsZero(), "listener_flush", b.Num)
newContentsRes := v.BatchChannelExprf(`join(getbufline(%v, 0, "$"), "\n")."\n"`, b.Num)
v.MustBatchEnd()
var newContents string
v.Parse(newContentsRes(), &newContents)
b.SetContents([]byte(newContents))
v.triggerBufferASTUpdate(b)
b.Version++
params := &protocol.DidChangeTextDocumentParams{
TextDocument: protocol.VersionedTextDocumentIdentifier{
TextDocumentIdentifier: b.ToTextDocumentIdentifier(),
Version: b.Version,
},
ContentChanges: []protocol.TextDocumentContentChangeEvent{
{
Text: newContents,
},
},
}
return v.server.DidChange(context.Background(), params)
}
// sortEdits orders edits by (start, end) offset.
// This ordering puts insertions (end = start) before deletions
// (end > start) at the same point, but uses a stable sort to preserve
// the order of multiple insertions at the same point.
func sortEdits(edits editsSort) {
sort.Stable(edits)
}
type editsSort []protocol.TextEdit
func (a editsSort) Len() int { return len(a) }
func (a editsSort) Less(i, j int) bool {
positionCmp := func(x, y protocol.Position) int {
if cmp := int(x.Line) - int(y.Line); cmp != 0 {
return cmp
}
return int(x.Character) - int(y.Character)
}
if cmp := positionCmp(a[i].Range.Start, a[j].Range.Start); cmp != 0 {
return cmp < 0
}
return positionCmp(a[i].Range.End, a[j].Range.End) < 0
}
func (a editsSort) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func min(i, j int) int {
if i < j {
return i
}
return j
}