This repository has been archived by the owner on Sep 24, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 132
/
ensime-startup.el
396 lines (336 loc) · 15.9 KB
/
ensime-startup.el
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
;;; ensime-startup.el --- download and launch ENSIME server
(eval-when-compile
(require 'cl)
(require 'ensime-macros))
(require 'dash)
(defvar ensime-idle-typecheck-timer nil
"Timer called when emacs is idle")
(defvar ensime-last-change-time 0
"Time of last buffer change")
(defvar ensime-server-process-start-hook nil
"Hook called whenever a new process gets started.")
(defvar ensime--classpath-separator
(if (find system-type '(cygwin windows-nt)) ";" ":")
"Separator used in Java classpaths")
(defvar ensime--abort-connection nil)
(defvar ensime--debug-messages nil
"When true, show debugging information in the echo area")
(defvar user-emacs-ensime-directory "ensime"
"The directory to store the calculated classpaths for the ensime server
when running `ensime-update' or starting a server for the first time.")
(defconst ensime--sbt-start-template
"
import sbt._
import IO._
import java.io._
scalaVersion := \"_scala_version_\"
ivyScala := ivyScala.value map { _.copy(overrideScalaVersion = true) }
// allows local builds of scala
resolvers += Resolver.mavenLocal
resolvers += Resolver.sonatypeRepo(\"snapshots\")
resolvers += \"Typesafe repository\" at \"http://repo.typesafe.com/typesafe/releases/\"
resolvers += \"Akka Repo\" at \"http://repo.akka.io/repository\"
libraryDependencies += \"org.ensime\" %% \"ensime\" % \"_server_version_\"
dependencyOverrides ++= Set(
\"org.scala-lang\" % \"scala-compiler\" % scalaVersion.value,
\"org.scala-lang\" % \"scalap\" % scalaVersion.value,
\"org.scala-lang\" % \"scala-reflect\" % scalaVersion.value
)
val saveClasspathTask = TaskKey[Unit](\"saveClasspath\", \"Save the classpath to a file\")
saveClasspathTask := {
val managed = (managedClasspath in Runtime).value.map(_.data.getAbsolutePath)
val unmanaged = (unmanagedClasspath in Runtime).value.map(_.data.getAbsolutePath)
val out = file(\"_classpath_file_\")
write(out, (unmanaged ++ managed).mkString(File.pathSeparator))
}
")
(defun ensime-update ()
"Install the most recent version of ENSIME server."
(interactive)
(let* ((config-file (ensime-config-find))
(config (ensime-config-load config-file))
(scala-version (plist-get config :scala-version)))
(ensime--update-server scala-version `(lambda () (message "ENSIME server updated.")))))
(defun ensime--maybe-update-and-start (&optional host port)
(if (and host port)
;; When both host and port are provided, we assume we're connecting to
;; an existing, listening server.
(let* ((config-file (ensime-config-find))
(config (ensime-config-load config-file))
(cache-dir (file-name-as-directory (ensime--get-cache-dir config))))
(ensime--retry-connect nil host (lambda () port) config cache-dir))
(let* ((config-file (ensime-config-find))
(config (ensime-config-load config-file))
(scala-version (plist-get config :scala-version))
(assembly-file (ensime--assembly-file scala-version))
(classpath-file (ensime--classpath-file scala-version)))
(if (and (not (file-exists-p assembly-file))
(ensime--classfile-needs-refresh-p classpath-file))
(ensime--update-server scala-version `(lambda () (ensime--1 ,config-file)))
(ensime--1 config-file)))))
(defun* ensime--1 (config-file)
(when (and (ensime-source-file-p) (not ensime-mode))
(ensime-mode 1))
(let* ((config (ensime-config-load config-file))
(root-dir (ensime--get-root-dir config) )
(cache-dir (file-name-as-directory (ensime--get-cache-dir config)))
(name (ensime--get-name config))
(scala-version (plist-get config :scala-version))
(server-env (or (plist-get config :server-env) ensime-default-server-env))
(buffer (or (plist-get config :buffer) (concat ensime-default-buffer-prefix name)))
(server-java (file-name-as-directory (plist-get config :java-home)))
(server-flags (or (plist-get config :java-flags) ensime-default-java-flags)))
(make-directory cache-dir 't)
(let* ((server-proc
(ensime--maybe-start-server
(generate-new-buffer-name (concat "*" buffer "*"))
server-java scala-version server-flags
(list* (concat "JDK_HOME=" server-java)
(concat "JAVA_HOME=" server-java)
server-env)
config-file
cache-dir))
(host "127.0.0.1")
(port-fn (lambda () (ensime--read-portfile
(concat cache-dir "/port")))))
;; Surface the server buffer so user can observe the startup progress.
(display-buffer (process-buffer server-proc) nil)
;; Store the config on the server process so we can identify it later.
(process-put server-proc :ensime-config config)
(push server-proc ensime-server-processes)
(ensime--retry-connect server-proc host port-fn config cache-dir))))
;; typecheck continually when idle
(defun ensime-idle-typecheck-set-timer ()
(when (timerp ensime-idle-typecheck-timer)
(cancel-timer ensime-idle-typecheck-timer))
(setq ensime-idle-typecheck-timer
(run-with-timer nil
ensime-typecheck-idle-interval
'ensime-idle-typecheck-function)))
(defun ensime-after-change-function (start stop len)
(set (make-local-variable 'ensime-last-change-time) (float-time)))
(defun ensime-idle-typecheck-function ()
(when (and ensime-typecheck-when-idle
(ensime-connected-p)
(ensime-analyzer-ready))
(let* ((now (float-time))
(last-typecheck (ensime-last-typecheck-run-time (ensime-connection)))
(earliest-allowed-typecheck (+ last-typecheck ensime-typecheck-interval)))
(when (and (>= now (+ ensime-last-change-time ensime-typecheck-idle-interval))
(>= now earliest-allowed-typecheck)
(< last-typecheck ensime-last-change-time))
(ensime-typecheck-current-file t)
(ensime-sem-high-refresh-hook)))))
(defun ensime-reload ()
"Re-initialize the project with the current state of the config file.
Analyzer will be restarted."
(interactive)
(let* ((conn (ensime-connection-or-nil))
(server-process (ensime-owning-server-process-for-source-file (buffer-file-name)))
(buf (when server-process (process-buffer server-process))))
(when conn
(catch (ensime-shutdown)))
(when buf
(kill-buffer buf))
(ensime)))
(defun ensime--maybe-start-server (buffer java-home scala-version flags env config-file cache-dir)
"Return a new or existing server process."
(let ((existing (comint-check-proc buffer)))
(if existing existing
(ensime--start-server buffer java-home scala-version flags env config-file cache-dir))))
(defun ensime--user-directory ()
(file-name-as-directory
(expand-file-name user-emacs-ensime-directory user-emacs-directory)))
(defun ensime--assembly-file (scala-version)
"The expected location of a manually produced assembly file.
If such a file is present, it will override the `ensime--classpath-file' and
`ensime-update' will not be automatically called."
(expand-file-name
(format "ensime_%s-%s-assembly.jar" scala-version ensime-server-version)
(ensime--user-directory)))
(defun ensime--classpath-file (scala-version)
(expand-file-name
(format "classpath_%s_%s" scala-version ensime-server-version)
(ensime--user-directory)))
(defun ensime--classfile-needs-refresh-p (classfile)
(let ((ensime-el (locate-file "ensime" load-path '(".el" ".elc"))))
(if ensime-el
(ensime--dependencies-newer-than-target-p
classfile
(directory-files (file-name-directory ensime-el) t "^ensime.*\\.elc?$"))
nil)))
(defun ensime--update-sentinel (process event scala-version on-success-fn)
(cond
((equal event "finished\n")
(let ((classpath-file (ensime--classpath-file scala-version)))
(if (file-exists-p classpath-file)
(progn
(-when-let
(win (get-buffer-window (process-buffer process)))
(delete-window win))
(funcall on-success-fn))
(message "Could not create classpath file %s" classpath-file))))
(t
(message "Process %s exited: %s" process event))))
(defun ensime--update-server (scala-version on-success-fn)
(with-current-buffer (get-buffer-create "*ensime-update*")
(erase-buffer)
(let* ((default-directory (file-name-as-directory
(make-temp-file "ensime_update_" t)))
(classpath-file (ensime--classpath-file scala-version))
(buildfile (concat default-directory "build.sbt"))
(buildcontents (ensime--create-sbt-start-script scala-version))
(buildpropsfile (concat default-directory "project/build.properties")))
(when (file-exists-p classpath-file) (delete-file classpath-file))
(make-directory (file-name-directory classpath-file) t)
(ensime-write-to-file buildfile buildcontents)
(ensime-write-to-file buildpropsfile "sbt.version=0.13.9\n")
(if (executable-find ensime-sbt-command)
(let ((process (start-process "*ensime-update*" (current-buffer)
ensime-sbt-command "saveClasspath" "clean")))
(display-buffer (current-buffer) nil)
(set-process-sentinel process
`(lambda (process event)
(ensime--update-sentinel process
event
,scala-version
',on-success-fn)))
(message "Updating ENSIME server..."))
(error "sbt command not found")))))
(defun ensime--start-server (buffer java-home scala-version flags user-env config-file cache-dir)
"Start an ensime server in the given buffer and return the created process.
BUFFER is the buffer to receive the server output.
FLAGS is a list of JVM flags.
USER-ENV is a list of environment variables.
CACHE-DIR is the server's persistent output directory."
(message "ENSIME server starting...")
(with-current-buffer (get-buffer-create buffer)
(comint-mode)
(let* ((default-directory cache-dir)
(tools-jar (concat java-home "lib/tools.jar"))
(assembly-file (ensime--assembly-file scala-version))
(classpath-file (ensime--classpath-file scala-version))
(classpath (concat tools-jar
ensime--classpath-separator
(if (file-exists-p assembly-file)
assembly-file
(ensime-read-from-file classpath-file))))
(process-environment (append user-env process-environment))
(java-command (concat java-home "bin/java"))
(args (-flatten (list
"-classpath" classpath
flags
(concat "-Densime.config=" (expand-file-name config-file))
(when ensime-server-logback
(concat "-Dlogback.configurationFile=" ensime-server-logback))
"org.ensime.server.Server"))))
(set (make-local-variable 'comint-process-echoes) nil)
(set (make-local-variable 'comint-use-prompt-regexp) nil)
(when ensime--debug-messages
(make-local-variable 'comint-output-filter-functions)
(push #'(lambda (str) (message "%s" str)) comint-output-filter-functions))
(insert (format "Starting ENSIME server: %s %s\n"
java-command
(mapconcat 'identity args " ")))
(if (executable-find java-command)
(comint-exec (current-buffer) buffer java-command nil args)
(error "java command %s not found" java-command))
;; Make sure we clean up nicely (required on Windows, or port files won't
;; be removed).
(add-hook 'kill-emacs-hook 'ensime-kill-emacs-hook-function)
(add-hook 'kill-buffer-hook 'ensime-interrupt-buffer-process nil t)
(let ((proc (get-buffer-process (current-buffer))))
(ensime-set-query-on-exit-flag proc)
(run-hooks 'ensime-server-process-start-hook)
proc))))
(defun ensime-kill-emacs-hook-function ()
"Swallow and log errors on exit."
(condition-case err
(ensime-interrupt-all-servers)
(message "Error while killing emacs: %s" err)))
(defun ensime--create-sbt-start-script (scala-version)
;; emacs has some weird case-preservation rules in regexp replace
;; see https://github.com/magnars/s.el/issues/62
(s-replace-all (list (cons "_scala_version_" scala-version)
(cons "_server_version_" ensime-server-version)
(cons "_classpath_file_" (ensime--classpath-file scala-version)))
ensime--sbt-start-template))
(defun ensime-shutdown()
"Request that the current ENSIME server kill itself."
(interactive)
(when (ensime-connected-p)
(ensime-quit-connection (ensime-connection))))
(defun ensime-configured-project-root ()
"Return root path of the current project as defined in the
config file and stored in the current connection. Nil is returned
if there is no active connection, or if the project root was not
defined."
(when (ensime-connected-p)
(let ((config (ensime-config (ensime-connection))))
(plist-get config :root-dir))))
(defun ensime--read-portfile (portfile)
"Read the contents of PORTFILE."
(when (file-exists-p portfile)
(save-excursion
(with-temp-buffer
(insert-file-contents portfile)
(goto-char (point-min))
(read (current-buffer))))))
(defun ensime--retry-connect (server-proc host port-fn config cache-dir)
"When application of port-fn yields a valid port, connect to the port at the
given host. Otherwise, schedule ensime--retry-connect for re-execution after 6
seconds."
(cond (ensime--abort-connection
(setq ensime--abort-connection nil)
(message "Aborted"))
((and server-proc (eq (process-status server-proc) 'exit))
(message "Failed to connect: server process exited."))
(t
(let ((port (funcall port-fn)))
(if port
(progn
(ensime--connect host port config)
;; Kill the window displaying the server buffer if it's still
;; visible.
(-when-let
(win (get-buffer-window (process-buffer server-proc)))
(cond
((window-parent)
(delete-window win))
(t
(switch-to-prev-buffer nil t)))))
(run-at-time
"6 sec" nil 'ensime-timer-call 'ensime--retry-connect
server-proc host port-fn config cache-dir))))))
(defun ensime--connect (host port config)
(let ((c (ensime-connect host port)))
(ensime-set-config c config)
(let ((ensime-dispatching-connection c))
(ensime-eval-async
;; hmm, this poses a problem... we can't really do anything
;; until we know the protocol version. This shouldn't be async,
;; but making it sync gives us "error in timer" errors.
'(swank:connection-info)
(ensime-curry #'ensime-handle-connection-info c)))))
(defun ensime-timer-call (fun &rest args)
"Call function FUN with ARGS, reporting all errors.
The default condition handler for timer functions (see
`timer-event-handler') ignores errors."
(condition-case data
(apply fun args)
(error (debug nil (list "Error in timer" fun args data)))))
(defun ensime--abort-connection ()
"Abort connection the current connection attempt."
(interactive)
(setq ensime--abort-connection 't))
(defun ensime-init-project (conn)
"Notify the server that we are ready for project events."
(cond
;; TODO(back_compat)
((version<= (ensime-protocol-version conn) "0.8.9")
(ensime-eval-async `(swank:init-project (:name "NA")) 'identity))
((version<= (ensime-protocol-version conn) "0.8.14")
(ensime-eval-async `(swank:init-project) 'identity))))
(provide 'ensime-startup)
;; Local Variables:
;; End: