-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcompl.go
490 lines (421 loc) · 10.3 KB
/
compl.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
package main
import (
"image"
"image/draw"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/aarzilli/yacco/buf"
"github.com/aarzilli/yacco/config"
"github.com/aarzilli/yacco/hl"
"github.com/aarzilli/yacco/lsp"
"github.com/aarzilli/yacco/textframe"
"github.com/aarzilli/yacco/util"
)
type Popup struct {
Visible bool
R image.Rectangle
B *image.RGBA
Dir string
start func(*Popup, ExecContext) (bool, string)
ed *Editor
autocompl bool
}
type popupFlags uint8
const (
popupAlignLeft popupFlags = iota
popupAutocompl
)
var tooltipContents string
var Compl, Tooltip Popup
var complPrefixSuffix string
func init() {
Compl.start = complStart
Tooltip.start = tooltipStart
}
func popupFrame(b *image.RGBA, r image.Rectangle) textframe.Frame {
fr := textframe.Frame{
Font: config.ComplFont,
Hackflags: textframe.HF_TRUNCATE,
B: b, R: r,
VisibleTick: false,
Colors: [][]image.Uniform{
config.TheColorScheme.Compl,
config.TheColorScheme.Compl},
TabWidth: 8,
Flush: nil,
Scroll: func(sd, n int) {},
Top: 0,
}
fr.Init(5)
return fr
}
func (p *Popup) prepare(str string) (image.Rectangle, *image.RGBA) {
if p.B == nil {
p.B = image.NewRGBA(image.Rectangle{image.Point{0, 0}, image.Point{config.ComplMaxX, config.ComplMaxY}})
}
fr := popupFrame(p.B, p.B.Bounds())
limit := fr.Insert([]rune(str), nil)
fr.Redraw(false, nil)
limit.X += 10
limit.Y += 10
if limit.X > config.ComplMaxX {
limit.X = config.ComplMaxX
}
if limit.Y > config.ComplMaxY {
limit.Y = config.ComplMaxY
}
p.R.Min = image.ZP
p.R.Max = limit
bd := p.R
bd.Max.X = bd.Min.X + 1
draw.Draw(p.B, bd, &config.TheColorScheme.TopBorder, image.ZP, draw.Src)
bd = p.R
bd.Max.Y = bd.Min.Y + 1
draw.Draw(p.B, bd, &config.TheColorScheme.TopBorder, image.ZP, draw.Src)
bd = p.R
bd.Min.X = bd.Max.X - 1
draw.Draw(p.B, bd, &config.TheColorScheme.TopBorder, image.ZP, draw.Src)
bd = p.R
bd.Min.Y = bd.Max.Y - 1
draw.Draw(p.B, bd, &config.TheColorScheme.TopBorder, image.ZP, draw.Src)
return p.R, p.B
}
func shouldHideTooltip() bool {
for _, col := range Wnd.cols.cols {
for _, editor := range col.editors {
if !editor.sfr.Fr.VisibleTick {
continue
}
p := editor.sfr.Fr.PointToCoord(editor.sfr.Fr.Sel.S)
if p.Y > Tooltip.R.Min.Y || p.Y < Tooltip.R.Min.Y-editor.MinHeight() {
return true
}
}
}
return false
}
func HideCompl(hideTooltip bool) bool {
didhide := false
if Tooltip.Visible && (hideTooltip || shouldHideTooltip()) {
Tooltip.Visible = false
select {
case sideChan <- func() { Wnd.FlushImage(Wnd.img.Bounds().Intersect(Tooltip.R)) }:
default:
}
didhide = true
}
if Compl.Visible {
Compl.Visible = false
select {
case sideChan <- func() { Wnd.FlushImage(Wnd.img.Bounds().Intersect(Compl.R)) }:
default:
}
return true
}
return didhide
}
func tooltipStart(p *Popup, ec ExecContext) (bool, string) {
if ec.buf == nil {
return false, ""
}
return true, tooltipContents
}
func getPrefixSuffix(compls []string, word string) (has bool, prefixSuffix string) {
has = len(compls) > 0
prefix := commonPrefix(compls)
if len(prefix) > len(word) {
prefixSuffix = prefix[len(word):]
}
return
}
const completeUsingLspServer = false // delay too long
func complStart(p *Popup, ec ExecContext) (bool, string) {
if ec.buf == nil {
HideCompl(false)
return false, ""
}
if (ec.ed != nil) && ec.ed.noAutocompl {
HideCompl(false)
return false, ""
}
if (ec.buf.Name == "+Tag") && (ec.ed != nil) && ec.ed.eventChanSpecial {
HideCompl(false)
return false, ""
}
if ec.fr.Sel.S != ec.fr.Sel.E || ec.fr.Sel.S == 0 {
HideCompl(false)
return false, ""
}
fpwd, wdwd, templwd, templind := getComplWords(ec)
compls := []string{}
//fmt.Printf("Completing <%s> <%s>\n", fpwd, wdwd)
var resDir, resName string
if fpwd != "" {
resPath := util.ResolvePath(ec.dir, fpwd)
if fpwd[len(fpwd)-1] == '/' {
resDir = resPath
resName = ""
} else {
resDir = filepath.Dir(resPath)
resName = filepath.Base(resPath)
}
compls = append(compls, getFsComplsMaybe(resDir, resName)...)
//println("after dir:", len(compls))
}
hasFp, fpPrefixSuffix := getPrefixSuffix(compls, resName)
wdCompls := []string{}
var hasWd bool
var wdPrefixSuffix string
if completeUsingLspServer && fpwd != "" && strings.Contains(fpwd, ".") { // intentional, so that '.' is considered a valid character and also because autocompletion requests are too slow
if srv, lspb := lsp.BufferToLsp(Wnd.tagbuf.Dir, ec.buf, ec.fr.Sel, true, Warn, defaultLookForLsp); srv != nil {
wdCompls, wdPrefixSuffix = srv.Complete(lspb)
hasWd = len(wdCompls) > 0
}
}
if len(wdCompls) == 0 {
if (wdwd != "") && ((fpwd == wdwd) || (len(compls) <= 0)) {
wdCompls = append(wdCompls, getWordCompls(wdwd)...)
wdCompls = util.Dedup(wdCompls)
}
hasWd, wdPrefixSuffix = getPrefixSuffix(wdCompls, wdwd)
}
compls = util.Dedup(append(compls, wdCompls...))
templCompl := []string{}
if templwd != "" {
complFilter(templwd, config.Templates, &templCompl)
}
for i := range templCompl {
templCompl[i] = strings.Replace(templCompl[i], "\n", "\n"+templind, -1)
}
hasTempl, templPrefixSuffix := getPrefixSuffix(templCompl, templwd)
compls = append(compls, templCompl...)
if len(compls) <= 0 {
HideCompl(false)
return false, ""
}
initialized := false
if hasFp {
initialized = true
complPrefixSuffix = fpPrefixSuffix
}
if hasWd {
if !initialized {
initialized = true
complPrefixSuffix = wdPrefixSuffix
} else {
complPrefixSuffix = commonPrefix2(complPrefixSuffix, wdPrefixSuffix)
}
}
if hasTempl {
if !initialized {
initialized = true
complPrefixSuffix = templPrefixSuffix
} else {
complPrefixSuffix = commonPrefix2(complPrefixSuffix, templPrefixSuffix)
}
}
cmax := 10
if cmax > len(compls) {
cmax = len(compls)
}
for i := range compls {
if nl := strings.Index(compls[i], "\n"); nl >= 0 {
compls[i] = compls[i][:nl] + "..."
}
}
txt := strings.Join(compls[:cmax], "\n")
if cmax < len(compls) {
txt += "\n...\n"
}
return true, txt
}
func (p *Popup) Start(ec ExecContext, flags popupFlags) {
ok, txt := p.start(p, ec)
if !ok {
return
}
p.autocompl = flags&popupAutocompl != 0
p.ed = ec.ed
p.Dir = ""
if ec.buf != nil {
p.Dir = ec.buf.Dir
}
wasVisible := p.Visible
oldR := p.R
p.prepare(txt)
p0 := ec.fr.PointToCoord(ec.fr.Sel.S)
if flags&popupAlignLeft != 0 {
p0.X = ec.fr.R.Min.X
}
p0 = p0.Add(image.Point{2, 4})
p.R = p.R.Add(p0)
p.Visible = true
var fn func()
if wasVisible {
fn = func() {
Wnd.FlushImage(Wnd.img.Bounds().Intersect(oldR), Wnd.img.Bounds().Intersect(p.R))
}
} else {
fn = func() { Wnd.FlushImage(Wnd.img.Bounds().Intersect(p.R)) }
}
select {
case sideChan <- fn:
default:
}
}
var fsComplRunning = map[string]bool{}
var fsComplRunningLock sync.Mutex
// returns completions for resName files in resDir, but bails out if reading the directory is too slow
func getFsComplsMaybe(resDir, resName string) []string {
fsComplRunningLock.Lock()
if _, ok := fsComplRunning[resDir]; ok {
fsComplRunningLock.Unlock()
return []string{}
}
fsComplRunning[resDir] = true
fsComplRunningLock.Unlock()
done := make(chan []string)
t := time.NewTimer(200 * time.Millisecond)
go func() {
fscompls := getFsCompls(resDir, resName)
fsComplRunningLock.Lock()
delete(fsComplRunning, resDir)
fsComplRunningLock.Unlock()
done <- fscompls
}()
select {
case fscompls := <-done:
return fscompls
case <-t.C:
return []string{}
}
}
func getComplWords(ec ExecContext) (fpwd, wdwd, templwd, templind string) {
fs := ec.buf.Tofp(ec.fr.Sel.S-1, -1)
if ec.fr.Sel.S-fs >= 2 {
fpwd = string(ec.buf.SelectionRunes(util.Sel{fs, ec.fr.Sel.S}))
}
ws := ec.buf.Towd(ec.fr.Sel.S-1, -1, false)
if ec.fr.Sel.S-ws >= 2 {
wdwd = string(ec.buf.SelectionRunes(util.Sel{ws, ec.fr.Sel.S}))
}
ts := ec.buf.Tonl(ec.fr.Sel.S-1, -1)
if ec.fr.Sel.S-ts >= 2 {
templwd = string(ec.buf.SelectionRunes(util.Sel{ts, ec.fr.Sel.S}))
for i, ch := range templwd {
if ch != ' ' && ch != '\t' {
templind = templwd[:i]
templwd = templwd[i:]
break
}
}
}
return
}
type fsComplCacheEntry struct {
expiration time.Time
names []string
}
var fsComplCache map[string]fsComplCacheEntry
var fsComplCacheLock sync.Mutex
func getFsCompls(resDir, resName string) []string {
//println("\tFs:", resDir, resName)
now := time.Now()
fsComplCacheLock.Lock()
if cache, ok := fsComplCache[resDir]; ok && now.Before(cache.expiration) {
fsComplCacheLock.Unlock()
r := []string{}
complFilter(resName, cache.names, &r)
return r
} else {
delete(fsComplCache, resDir)
fsComplCacheLock.Unlock()
}
fh, err := os.Open(resDir)
if err != nil {
return []string{}
}
defer fh.Close()
fes, err := fh.Readdir(-1)
if err != nil {
return []string{}
}
names := make([]string, len(fes))
for i := range fes {
if fes[i].IsDir() {
names[i] = fes[i].Name() + "/"
} else {
names[i] = fes[i].Name()
}
}
newnow := time.Now()
if d := now.Sub(newnow); d > 50*time.Millisecond {
fsComplCacheLock.Lock()
fsComplCache[resDir] = fsComplCacheEntry{
expiration: newnow.Add(d * 4),
names: names,
}
fsComplCacheLock.Unlock()
}
r := []string{}
complFilter(resName, names, &r)
return r
}
func getWordCompls(wd string) []string {
r := []string{}
for i := range Wnd.cols.cols {
for j := range Wnd.cols.cols[i].editors {
complFilter(wd, Wnd.cols.cols[i].editors[j].bodybuf.Words, &r)
}
}
complFilter(wd, Wnd.Words, &r)
r = util.Dedup(r)
return r
}
func complFilter(prefix string, set []string, out *[]string) {
for _, cur := range set {
if strings.HasPrefix(cur, prefix) && (cur != prefix) {
*out = append(*out, cur)
}
}
}
func commonPrefix(in []string) string {
if len(in) <= 0 {
return ""
}
r := in[0]
for _, x := range in {
r = commonPrefix2(r, x)
if r == "" {
break
}
}
return r
}
func commonPrefix2(a, b string) string {
l := len(a)
if l > len(b) {
l = len(b)
}
for i := 0; i < l; i++ {
if a[i] != b[i] {
return a[:i]
}
}
return a[:l]
}
func TooltipClick(e util.MouseDownEvent) LogicalPos {
fr := popupFrame(Tooltip.B, Tooltip.R)
fr.Insert([]rune(tooltipContents), nil)
buf, _ := buf.NewBuffer(Tooltip.Dir, "+Tooltip", false, "\t", hl.NilHighlighter)
buf.ReplaceFull([]rune(tooltipContents))
fr.OnClick(e, nil)
return LogicalPos{
ed: Tooltip.ed,
tagfr: &fr,
tagbuf: buf,
}
}