-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclient.go
354 lines (316 loc) · 8.11 KB
/
client.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
// Utilities for communicating with an Emacs server.
package emacsclient
import (
"bufio"
"errors"
"flag"
"fmt"
"io"
"net"
"os"
"path"
"strings"
"github.com/tudurom/ttyname"
)
// Client dialing options.
type Options struct {
SocketName string
ServerFile string
}
// OptionsFromFlags returns client options controlled by standard command-line flags.
func OptionsFromFlags() *Options {
options := &Options{}
flag.StringVar(&options.SocketName, "socket-name", defaultSocketName(), "Emacs server unix socket")
flag.StringVar(&options.ServerFile, "server-file", defaultServerFile(), "Emacs server TCP file")
return options
}
// checkPath returns `true` if the folder exists
func checkPath(path string) bool {
if "" == path {
return false
}
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
// defaultSocketName returns the default Emacs server socket for the current user.
func defaultSocketName() string {
fromEnv := os.Getenv("EMACS_SOCKET_NAME")
if checkPath(fromEnv) {
return fromEnv
}
runDir := os.Getenv("XDG_RUNTIME_DIR")
if runDir != "" {
inRunDir := path.Join(runDir, "emacs", "server")
if checkPath(inRunDir) {
return inRunDir
}
} else {
uid := fmt.Sprintf("%d", os.Getuid())
inRunDir := path.Join("run", "user", uid, "emacs", "server")
if checkPath(inRunDir) {
return inRunDir
}
inVarRunDir := path.Join(
"var", "run", "user", uid, "emacs", "server")
if checkPath(inVarRunDir) {
return inVarRunDir
}
}
// old-style socket path
return path.Join(
os.TempDir(), fmt.Sprintf("emacs%d", os.Getuid()), "server")
}
// defaultEmacsDir returns the default Emacs configuration directory (aka `.emacs.d`) for the current user.
func defaultEmacsDir() string {
var emacsDir string
xdgPathA := path.Join(os.Getenv("XDG_CONFIG_HOME"), "emacs")
xdgPathB := path.Join(os.Getenv("HOME"), ".config", "emacs") // user following convention without XDG_CONFIG_HOME set
legacyPath := path.Join(os.Getenv("HOME"), ".emacs.d") // windows (if HOME is set) and emacs pre-v27
userConfigDir, _ := os.UserConfigDir()
osDefaultPath := path.Join(userConfigDir, ".emacs.d")
switch {
case checkPath(xdgPathA):
emacsDir = xdgPathA
case checkPath(xdgPathB):
emacsDir = xdgPathB
case checkPath(legacyPath):
emacsDir = legacyPath
default:
emacsDir = osDefaultPath
}
return emacsDir
}
// defaultServerFile returns the default Emacs server file for the current user.
func defaultServerFile() (serverFile string) {
fromEnv := os.Getenv("EMACS_SERVER_FILE")
fromEmacsDir := path.Join(defaultEmacsDir(), "server", "server")
if checkPath(fromEnv) {
return fromEnv
}
if checkPath(fromEmacsDir) {
return fromEmacsDir
}
// No file exists, return a reasonable value.
if fromEnv != "" {
return fromEnv
}
return fromEmacsDir
}
// parseServerFile return the emacs server TCP address and auth key from an emacs server file
func parseServerFile(serverFile string) (serverAddr string, authString string, err error) {
fp, err := os.Open(serverFile)
if err != nil {
return "", "", err
}
defer fp.Close()
scanner := bufio.NewScanner(fp)
if scanner.Scan() {
// 1st line
serverAddr = strings.Split(scanner.Text(), " ")[0]
}
if scanner.Scan() {
// 2nd line
authString = scanner.Text()
}
return
}
// Dial connects to the remote Emacs server.
func Dial(options *Options) (net.Conn, error) {
switch {
case checkPath(options.SocketName):
return dialUnix(options)
case checkPath(options.ServerFile):
return dialTcp(options)
default:
err := errors.New("no valid unix socket or server file was found")
return nil, err
}
}
// dialUnix connects to an Emacs server instance via Unix Socket.
func dialUnix(options *Options) (net.Conn, error) {
conn, err := net.Dial("unix", options.SocketName)
if err != nil {
return nil, err
}
if err = initConnection(conn); err != nil {
conn.Close()
return nil, err
}
return conn, nil
}
// dialTcp connects to an Emacs server instance via TCP.
func dialTcp(options *Options) (net.Conn, error) {
addr, authKey, err := parseServerFile(options.ServerFile)
if err != nil {
return nil, err
}
conn, err := net.Dial("tcp", addr)
if err != nil {
return nil, err
}
if err = sendAuth(conn, authKey); err != nil {
conn.Close()
return nil, err
}
if err = initConnection(conn); err != nil {
conn.Close()
return nil, err
}
return conn, nil
}
// initConnection initializes the connection with Emacs.
func initConnection(c net.Conn) error {
return sendPWD(c)
}
// sendAuth sends the specified authKey to Emacs.
func sendAuth(c net.Conn, authKey string) error {
_, err := io.WriteString(c, "-auth "+authKey+"\n")
return err
}
// sendPWD sends the current directory to Emacs.
func sendPWD(c net.Conn) error {
pwd := os.Getenv("PWD")
if pwd == "" {
cwd, err := os.Getwd()
if err != nil {
return err
}
pwd = cwd
}
_, err := io.WriteString(c, "-dir "+quoteArgument(pwd)+"/ ")
return err
}
// SendTTY sends the current terminal information to Emacs.
func SendTTY(c net.Conn) error {
ttyType := os.Getenv("TERM")
ttyName, err := ttyname.TTY()
if err != nil {
return err
}
if ttyName == "" {
return errors.New("no TTY")
}
_, err = io.WriteString(c, "-tty "+quoteArgument(ttyName)+" "+quoteArgument(ttyType)+" ")
return err
}
// SendCreateFrame tells Emacs to create a new frame.
func SendCreateFrame(c net.Conn) error {
_, err := io.WriteString(c, "-window-system ")
return err
}
// SendEval sends a elisp expression to Emacs to evaluate.
//
// It returns the result as a string.
func SendEval(c net.Conn, elisp string) error {
_, err := io.WriteString(c, "-eval "+quoteArgument(elisp)+" ")
return err
}
// SendEvalFromTemplate calls SendEval on the result of ExecuteTemplate.
func SendEvalFromTemplate(c net.Conn, args interface{}, template string) error {
expr, err := ExecuteTemplate(args, template)
if err != nil {
return err
}
return SendEval(c, expr)
}
type closeWriter interface {
CloseWrite() error
}
// sendDone tells Emacs we're done sending commands.
func sendDone(c net.Conn) error {
if _, err := io.WriteString(c, "\n"); err != nil {
return err
}
return nil
}
// Response received from the Emacs server
type Response struct {
Type ResponseType
Text string
}
type ResponseType int32
const (
SuccessResponse ResponseType = 0
ContinueResponse ResponseType = 1
ErrorResponse ResponseType = 2
)
// Receive closes the write channel and reads responses from Emacs,
// puts them into responses and closes the channel.
func Receive(c net.Conn, responses chan Response) error {
if err := sendDone(c); err != nil {
return err
}
input := bufio.NewScanner(c)
for input.Scan() {
line := input.Text()
switch {
case strings.HasPrefix(line, "-print "):
responses <- Response{
Type: SuccessResponse,
Text: unquoteArgument(line[len("-print "):]),
}
case strings.HasPrefix(line, "-print-nonl "):
responses <- Response{
Type: ContinueResponse,
Text: unquoteArgument(line[len("-print-nonl "):]),
}
case strings.HasPrefix(line, "-error "):
responses <- Response{
Type: ErrorResponse,
Text: unquoteArgument(line[len("-error "):]),
}
}
}
close(responses)
return input.Err()
}
// quoteArgument quotes the given string to send to the Emacs server.
func quoteArgument(unquoted string) string {
var quoted strings.Builder
runes := []rune(unquoted)
for len(runes) > 0 && runes[0] == '-' {
quoted.WriteString("&-")
runes = runes[1:]
}
for _, c := range runes {
switch c {
case ' ':
quoted.WriteString("&_")
case '\n':
quoted.WriteString("&n")
case '&':
quoted.WriteString("&&")
default:
quoted.WriteRune(c)
}
}
return quoted.String()
}
// appendUnquoted unquotes a string received from the Emacs server.
// It writes the result to the given string builder.
func unquoteArgument(quoted string) string {
var unquoted strings.Builder
amp := false
for _, r := range quoted {
if amp {
switch r {
case '_':
unquoted.WriteRune(' ')
case 'n':
unquoted.WriteRune('\n')
default:
unquoted.WriteRune(r)
}
amp = false
} else if r == '&' {
amp = true
} else {
unquoted.WriteRune(r)
}
}
return unquoted.String()
}