-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathcompletion.go
105 lines (90 loc) · 2.63 KB
/
completion.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
package main
import (
"os/exec"
"os"
"fmt"
"strings"
"bytes"
"strconv"
"encoding/json"
"github.com/wxnacy/wgo/codes"
)
func writeCompleteCode(code string) {
initTempDir()
f, err := os.OpenFile(tempCompleteFile(), os.O_CREATE|os.O_WRONLY, 0600)
handlerErr(err)
f.WriteString(code)
f.Close()
}
type Prompt struct {
Class string `json:"class"` // eg. func
Package string `json:"package"` // eg. fmt
Type string `json:"type"` // eg. func(format string, a ...interface{}) error
Name string `json:"name"` // eg. Errorf
}
func GetPromptBySpace() []Prompt {
var prompts = make([]Prompt, 0)
for _, impt := range Coder().GetImportNames() {
prompts = append(prompts, Prompt{Name: impt, Class: "package"})
}
for _, impt := range Coder().GetVariables() {
prompts = append(prompts, Prompt{Name: impt, Class: "variable"})
}
for _, impt := range codes.GetKeywords() {
prompts = append(prompts, Prompt{Name: impt, Class: "keyword"})
}
return prompts
}
var tmpPrompts []Prompt
func GetPrompts() []Prompt {
return tmpPrompts
}
func clearPrintPrompts() {
tmpPrompts = make([]Prompt, 0)
}
func Complete(s string) []Prompt {
var codes = make([]string, 0)
offset := 0 // 补全 offset
c := Coder()
// imports := c.GetImports()
p := "package main"
codes = append(codes, p)
for k, v := range c.GetImportMap() {
impt := fmt.Sprintf("import %s \"%s\"", v.Aliasname, k)
codes = append(codes, impt)
offset += len(impt) +1
}
mains := c.GetMains()
m := "func main(){"
codes = append(codes, m)
for _, d := range mains {
codes = append(codes, d)
offset += len(d) + 1
}
codes = append(codes, s)
codes = append(codes, "}")
writeCompleteCode("")
writeCompleteCode(strings.Join(codes, "\n"))
offset += len(p) + len(m) + 2 + len(s)
// Logger().Debugf("offset %d", offset)
cmd := exec.Command(
"gocode", "-in=" + tempCompleteFile(), "-f=json", "autocomplete",
tempCompleteFile(), strconv.Itoa(offset),
)
var out bytes.Buffer
cmd.Stdout = &out
cmd.Run()
cmp := out.String()
// Logger().Debugf(cmp)
cmp = cmp[3:len(cmp)-2]
var prompts []Prompt
json.Unmarshal([]byte(cmp), &prompts)
// Logger().Debug(len(tmpPrompts))
if strings.HasSuffix(s, ".") && len(tmpPrompts) == 0 {
Logger().Debug("input prompt")
// tmpPrompts = make([]Prompt, 0)
tmpPrompts = prompts
// Logger().Debug(len(tmpPrompts))
}
return prompts
}