Klimi's new dotfiles with stow.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1345 lines
57 KiB

4 years ago
  1. ;;; nrepl-client.el --- Client for Clojure nREPL -*- lexical-binding: t -*-
  2. ;; Copyright © 2012-2013 Tim King, Phil Hagelberg, Bozhidar Batsov
  3. ;; Copyright © 2013-2019 Bozhidar Batsov, Artur Malabarba and CIDER contributors
  4. ;;
  5. ;; Author: Tim King <kingtim@gmail.com>
  6. ;; Phil Hagelberg <technomancy@gmail.com>
  7. ;; Bozhidar Batsov <bozhidar@batsov.com>
  8. ;; Artur Malabarba <bruce.connor.am@gmail.com>
  9. ;; Hugo Duncan <hugo@hugoduncan.org>
  10. ;; Steve Purcell <steve@sanityinc.com>
  11. ;; Reid McKenzie <me@arrdem.com>
  12. ;;
  13. ;; This program is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;;
  18. ;; This program is distributed in the hope that it will be useful,
  19. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. ;; GNU General Public License for more details.
  22. ;;
  23. ;; You should have received a copy of the GNU General Public License
  24. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  25. ;;
  26. ;; This file is not part of GNU Emacs.
  27. ;;
  28. ;;; Commentary:
  29. ;;
  30. ;; Provides an Emacs Lisp client to connect to Clojure nREPL servers.
  31. ;;
  32. ;; A connection is an abstract idea of the communication between Emacs (client)
  33. ;; and nREPL server. On the Emacs side connections are represented by two
  34. ;; running processes. The two processes are the server process and client
  35. ;; process (the connection to the server). Each of these is represented by its
  36. ;; own process buffer, filter and sentinel.
  37. ;;
  38. ;; The nREPL communication process can be broadly represented as follows:
  39. ;;
  40. ;; 1) The server process is started as an Emacs subprocess (usually by
  41. ;; `cider-jack-in', which in turn fires up leiningen or boot). Note that
  42. ;; if a connection was established using `cider-connect' there won't be
  43. ;; a server process.
  44. ;;
  45. ;; 2) The server's process filter (`nrepl-server-filter') detects the
  46. ;; connection port from the first plain text response from the server and
  47. ;; starts a communication process (socket connection) as another Emacs
  48. ;; subprocess. This is the nREPL client process (`nrepl-client-filter').
  49. ;; All requests and responses handling happens through this client
  50. ;; connection.
  51. ;;
  52. ;; 3) Requests are sent by `nrepl-send-request' and
  53. ;; `nrepl-send-sync-request'. A request is simply a list containing a
  54. ;; requested operation name and the parameters required by the
  55. ;; operation. Each request has an associated callback that is called once
  56. ;; the response for the request has arrived. Besides the above functions
  57. ;; there are specialized request senders for each type of common
  58. ;; operations. Examples are `nrepl-request:eval', `nrepl-request:clone',
  59. ;; `nrepl-sync-request:describe'.
  60. ;;
  61. ;; 4) Responses from the server are decoded in `nrepl-client-filter' and are
  62. ;; physically represented by alists whose structure depends on the type of
  63. ;; the response. After having been decoded, the data from the response is
  64. ;; passed over to the callback that was registered by the original
  65. ;; request.
  66. ;;
  67. ;; Please see the comments in dedicated sections of this file for more detailed
  68. ;; description.
  69. ;;; Code:
  70. (require 'seq)
  71. (require 'subr-x)
  72. (require 'cider-compat)
  73. (require 'cl-lib)
  74. (require 'nrepl-dict)
  75. (require 'queue)
  76. (require 'tramp)
  77. ;;; Custom
  78. (defgroup nrepl nil
  79. "Interaction with the Clojure nREPL Server."
  80. :prefix "nrepl-"
  81. :group 'applications)
  82. ;; (defcustom nrepl-buffer-name-separator " "
  83. ;; "Used in constructing the REPL buffer name.
  84. ;; The `nrepl-buffer-name-separator' separates cider-repl from the project name."
  85. ;; :type '(string)
  86. ;; :group 'nrepl)
  87. (make-obsolete-variable 'nrepl-buffer-name-separator 'cider-session-name-template "0.18")
  88. ;; (defcustom nrepl-buffer-name-show-port nil
  89. ;; "Show the connection port in the nrepl REPL buffer name, if set to t."
  90. ;; :type 'boolean
  91. ;; :group 'nrepl)
  92. (make-obsolete-variable 'nrepl-buffer-name-show-port 'cider-session-name-template "0.18")
  93. (defcustom nrepl-connected-hook nil
  94. "List of functions to call when connecting to the nREPL server."
  95. :type 'hook
  96. :group 'nrepl)
  97. (defcustom nrepl-disconnected-hook nil
  98. "List of functions to call when disconnected from the nREPL server."
  99. :type 'hook
  100. :group 'nrepl)
  101. (defcustom nrepl-file-loaded-hook nil
  102. "List of functions to call when a load file has completed."
  103. :type 'hook
  104. :group 'nrepl)
  105. (defcustom nrepl-force-ssh-for-remote-hosts nil
  106. "If non-nil, do not attempt a direct connection for remote hosts."
  107. :type 'boolean
  108. :group 'nrepl)
  109. (defcustom nrepl-use-ssh-fallback-for-remote-hosts nil
  110. "If non-nil, attempt to connect via ssh to remote hosts when unable to connect directly."
  111. :type 'boolean
  112. :group 'nrepl)
  113. (defcustom nrepl-sync-request-timeout 10
  114. "The number of seconds to wait for a sync response.
  115. Setting this to nil disables the timeout functionality."
  116. :type 'integer
  117. :group 'nrepl)
  118. (defcustom nrepl-hide-special-buffers nil
  119. "Control the display of some special buffers in buffer switching commands.
  120. When true some special buffers like the server buffer will be hidden."
  121. :type 'boolean
  122. :group 'nrepl)
  123. ;;; Buffer Local Declarations
  124. ;; These variables are used to track the state of nREPL connections
  125. (defvar-local nrepl-connection-buffer nil)
  126. (defvar-local nrepl-server-buffer nil)
  127. (defvar-local nrepl-messages-buffer nil)
  128. (defvar-local nrepl-endpoint nil)
  129. (defvar-local nrepl-project-dir nil)
  130. (defvar-local nrepl-is-server nil)
  131. (defvar-local nrepl-server-command nil)
  132. (defvar-local nrepl-tunnel-buffer nil)
  133. (defvar-local nrepl-session nil
  134. "Current nREPL session id.")
  135. (defvar-local nrepl-tooling-session nil
  136. "Current nREPL tooling session id.
  137. To be used for tooling calls (i.e. completion, eldoc, etc)")
  138. (defvar-local nrepl-request-counter 0
  139. "Continuation serial number counter.")
  140. (defvar-local nrepl-pending-requests nil)
  141. (defvar-local nrepl-completed-requests nil)
  142. (defvar-local nrepl-last-sync-response nil
  143. "Result of the last sync request.")
  144. (defvar-local nrepl-last-sync-request-timestamp nil
  145. "The time when the last sync request was initiated.")
  146. (defvar-local nrepl-ops nil
  147. "Available nREPL server ops (from describe).")
  148. (defvar-local nrepl-versions nil
  149. "Version information received from the describe op.")
  150. (defvar-local nrepl-aux nil
  151. "Auxiliary information received from the describe op.")
  152. ;;; nREPL Buffer Names
  153. (defconst nrepl-message-buffer-name-template "*nrepl-messages %s(%r:%S)*")
  154. (defconst nrepl-error-buffer-name "*nrepl-error*")
  155. (defconst nrepl-repl-buffer-name-template "*cider-repl %s(%r:%S)*")
  156. (defconst nrepl-server-buffer-name-template "*nrepl-server %s*")
  157. (defconst nrepl-tunnel-buffer-name-template "*nrepl-tunnel %s*")
  158. (defun nrepl-make-buffer-name (template params &optional dup-ok)
  159. "Generate a buffer name using TEMPLATE and PARAMS.
  160. TEMPLATE and PARAMS are as in `cider-format-connection-params'. If
  161. optional DUP-OK is non-nil, the returned buffer is not \"uniquified\" by a
  162. call to `generate-new-buffer-name'."
  163. (let ((name (cider-format-connection-params template params)))
  164. (if dup-ok
  165. name
  166. (generate-new-buffer-name name))))
  167. (defun nrepl--make-hidden-name (buffer-name)
  168. "Apply a prefix to BUFFER-NAME that will hide the buffer."
  169. (concat (if nrepl-hide-special-buffers " " "") buffer-name))
  170. (defun nrepl-repl-buffer-name (params &optional dup-ok)
  171. "Return the name of the repl buffer.
  172. PARAMS and DUP-OK are as in `nrepl-make-buffer-name'."
  173. (nrepl-make-buffer-name nrepl-repl-buffer-name-template params dup-ok))
  174. (defun nrepl-server-buffer-name (params)
  175. "Return the name of the server buffer.
  176. PARAMS is as in `nrepl-make-buffer-name'."
  177. (nrepl--make-hidden-name
  178. (nrepl-make-buffer-name nrepl-server-buffer-name-template params)))
  179. (defun nrepl-tunnel-buffer-name (params)
  180. "Return the name of the tunnel buffer.
  181. PARAMS is as in `nrepl-make-buffer-name'."
  182. (nrepl--make-hidden-name
  183. (nrepl-make-buffer-name nrepl-tunnel-buffer-name-template params)))
  184. (defun nrepl-messages-buffer-name (params)
  185. "Return the name for the message buffer given connection PARAMS."
  186. (nrepl-make-buffer-name nrepl-message-buffer-name-template params))
  187. ;;; Utilities
  188. (defun nrepl-op-supported-p (op connection)
  189. "Return t iff the given operation OP is supported by the nREPL CONNECTION."
  190. (when (buffer-live-p connection)
  191. (with-current-buffer connection
  192. (and nrepl-ops (nrepl-dict-get nrepl-ops op)))))
  193. (defun nrepl-aux-info (key connection)
  194. "Return KEY's aux info, as returned via the :describe op for CONNECTION."
  195. (with-current-buffer connection
  196. (and nrepl-aux (nrepl-dict-get nrepl-aux key))))
  197. (defun nrepl-local-host-p (host)
  198. "Return t if HOST is local."
  199. (string-match-p tramp-local-host-regexp host))
  200. (defun nrepl-extract-port (dir)
  201. "Read port from .nrepl-port, nrepl-port or target/repl-port files in directory DIR."
  202. (or (nrepl--port-from-file (expand-file-name "repl-port" dir))
  203. (nrepl--port-from-file (expand-file-name ".nrepl-port" dir))
  204. (nrepl--port-from-file (expand-file-name "target/repl-port" dir))
  205. (nrepl--port-from-file (expand-file-name ".shadow-cljs/nrepl.port" dir))))
  206. (defun nrepl--port-from-file (file)
  207. "Attempts to read port from a file named by FILE."
  208. (when (file-exists-p file)
  209. (with-temp-buffer
  210. (insert-file-contents file)
  211. (buffer-string))))
  212. ;;; Bencode
  213. (cl-defstruct (nrepl-response-queue
  214. (:include queue)
  215. (:constructor nil)
  216. (:constructor nrepl-response-queue (&optional stub)))
  217. stub)
  218. (put 'nrepl-response-queue 'function-documentation
  219. "Create queue object used by nREPL to store decoded server responses.
  220. The STUB slot stores a stack of nested, incompletely parsed objects.")
  221. (defun nrepl--bdecode-list (&optional stack)
  222. "Decode a bencode list or dict starting at point.
  223. STACK is as in `nrepl--bdecode-1'."
  224. ;; skip leading l or d
  225. (forward-char 1)
  226. (let* ((istack (nrepl--bdecode-1 stack))
  227. (pos0 (point))
  228. (info (car istack)))
  229. (while (null info)
  230. (setq istack (nrepl--bdecode-1 (cdr istack))
  231. pos0 (point)
  232. info (car istack)))
  233. (cond ((eq info :e)
  234. (cons nil (cdr istack)))
  235. ((eq info :stub)
  236. (goto-char pos0)
  237. istack)
  238. (t istack))))
  239. (defun nrepl--bdecode-1 (&optional stack)
  240. "Decode one elementary bencode object starting at point.
  241. Bencoded object is either list, dict, integer or string. See
  242. http://en.wikipedia.org/wiki/Bencode#Encoding_algorithm for the encoding
  243. rules.
  244. STACK is a list of so far decoded components of the current message. Car
  245. of STACK is the innermost incompletely decoded object. The algorithm pops
  246. this list when inner object was completely decoded or grows it by one when
  247. new list or dict was encountered.
  248. The returned value is of the form (INFO . STACK) where INFO is
  249. :stub, nil, :end or :eob and STACK is either an incomplete parsing state as
  250. above (INFO is :stub, nil or :eob) or a list of one component representing
  251. the completely decoded message (INFO is :end). INFO is nil when an
  252. elementary non-root object was successfully decoded. INFO is :end when this
  253. object is a root list or dict."
  254. (cond
  255. ;; list
  256. ((eq (char-after) ?l)
  257. (nrepl--bdecode-list (cons () stack)))
  258. ;; dict
  259. ((eq (char-after) ?d)
  260. (nrepl--bdecode-list (cons '(dict) stack)))
  261. ;; end of a list or a dict
  262. ((eq (char-after) ?e)
  263. (forward-char 1)
  264. (cons (if (cdr stack) :e :end)
  265. (nrepl--push (nrepl--nreverse (car stack))
  266. (cdr stack))))
  267. ;; string
  268. ((looking-at "\\([0-9]+\\):")
  269. (let ((pos0 (point))
  270. (beg (goto-char (match-end 0)))
  271. (end (byte-to-position (+ (position-bytes (point))
  272. (string-to-number (match-string 1))))))
  273. (if (null end)
  274. (progn (goto-char pos0)
  275. (cons :stub stack))
  276. (goto-char end)
  277. ;; normalise any platform-specific newlines
  278. (let* ((original (buffer-substring-no-properties beg end))
  279. (result (replace-regexp-in-string "\r\n\\|\n\r\\|\r" "\n" original)))
  280. (cons nil (nrepl--push result stack))))))
  281. ;; integer
  282. ((looking-at "i\\(-?[0-9]+\\)e")
  283. (goto-char (match-end 0))
  284. (cons nil (nrepl--push (string-to-number (match-string 1))
  285. stack)))
  286. ;; should happen in tests only as eobp is checked in nrepl-bdecode.
  287. ((eobp)
  288. (cons :eob stack))
  289. ;; truncation in the middle of an integer or in 123: string prefix
  290. ((looking-at-p "[0-9i]")
  291. (cons :stub stack))
  292. ;; else, throw a quiet error
  293. (t
  294. (message "Invalid bencode message detected. See the %s buffer for details."
  295. nrepl-error-buffer-name)
  296. (nrepl-log-error
  297. (format "Decoder error at position %d (`%s'):"
  298. (point) (buffer-substring (point) (min (+ (point) 10) (point-max)))))
  299. (nrepl-log-error (buffer-string))
  300. (ding)
  301. ;; Ensure loop break and clean queues' states in nrepl-bdecode:
  302. (goto-char (point-max))
  303. (cons :end nil))))
  304. (defun nrepl--bdecode-message (&optional stack)
  305. "Decode one full message starting at point.
  306. STACK is as in `nrepl--bdecode-1'. Return a cons (INFO . STACK)."
  307. (let* ((istack (nrepl--bdecode-1 stack))
  308. (info (car istack))
  309. (stack (cdr istack)))
  310. (while (or (null info)
  311. (eq info :e))
  312. (setq istack (nrepl--bdecode-1 stack)
  313. info (car istack)
  314. stack (cdr istack)))
  315. istack))
  316. (defun nrepl-bdecode (string-q &optional response-q)
  317. "Decode STRING-Q and place the results into RESPONSE-Q.
  318. STRING-Q is either a queue of strings or a string. RESPONSE-Q is a queue of
  319. server requests (nREPL dicts). STRING-Q and RESPONSE-Q are modified by side
  320. effects.
  321. Return a cons (STRING-Q . RESPONSE-Q) where STRING-Q is the original queue
  322. containing the remainder of the input strings which could not be
  323. decoded. RESPONSE-Q is the original queue with successfully decoded messages
  324. enqueued and with slot STUB containing a nested stack of an incompletely
  325. decoded message or nil if the strings were completely decoded."
  326. (with-current-buffer (get-buffer-create " *nrepl-decoding*")
  327. (fundamental-mode)
  328. (erase-buffer)
  329. (if (queue-p string-q)
  330. (while (queue-head string-q)
  331. (insert (queue-dequeue string-q)))
  332. (insert string-q)
  333. (setq string-q (queue-create)))
  334. (goto-char 1)
  335. (unless response-q
  336. (setq response-q (nrepl-response-queue)))
  337. (let ((istack (nrepl--bdecode-message
  338. (nrepl-response-queue-stub response-q))))
  339. (while (and (eq (car istack) :end)
  340. (not (eobp)))
  341. (queue-enqueue response-q (cadr istack))
  342. (setq istack (nrepl--bdecode-message)))
  343. (unless (eobp)
  344. (queue-enqueue string-q (buffer-substring (point) (point-max))))
  345. (if (not (eq (car istack) :end))
  346. (setf (nrepl-response-queue-stub response-q) (cdr istack))
  347. (queue-enqueue response-q (cadr istack))
  348. (setf (nrepl-response-queue-stub response-q) nil))
  349. (erase-buffer)
  350. (cons string-q response-q))))
  351. (defun nrepl-bencode (object)
  352. "Encode OBJECT with bencode.
  353. Integers, lists and nrepl-dicts are treated according to bencode
  354. specification. Everything else is encoded as string."
  355. (cond
  356. ((integerp object) (format "i%de" object))
  357. ((nrepl-dict-p object) (format "d%se" (mapconcat #'nrepl-bencode (cdr object) "")))
  358. ((listp object) (format "l%se" (mapconcat #'nrepl-bencode object "")))
  359. (t (format "%s:%s" (string-bytes object) object))))
  360. ;;; Client: Process Filter
  361. (defvar nrepl-response-handler-functions nil
  362. "List of functions to call on each nREPL message.
  363. Each of these functions should be a function with one argument, which will
  364. be called by `nrepl-client-filter' on every response received. The current
  365. buffer will be connection (REPL) buffer of the process. These functions
  366. should take a single argument, a dict representing the message. See
  367. `nrepl--dispatch-response' for an example.
  368. These functions are called before the message's own callbacks, so that they
  369. can affect the behaviour of the callbacks. Errors signaled by these
  370. functions are demoted to messages, so that they don't prevent the
  371. callbacks from running.")
  372. (defun nrepl-client-filter (proc string)
  373. "Decode message(s) from PROC contained in STRING and dispatch them."
  374. (let ((string-q (process-get proc :string-q)))
  375. (queue-enqueue string-q string)
  376. ;; Start decoding only if the last letter is 'e'
  377. (when (eq ?e (aref string (1- (length string))))
  378. (let ((response-q (process-get proc :response-q)))
  379. (nrepl-bdecode string-q response-q)
  380. (while (queue-head response-q)
  381. (with-current-buffer (process-buffer proc)
  382. (let ((response (queue-dequeue response-q)))
  383. (with-demoted-errors "Error in one of the `nrepl-response-handler-functions': %s"
  384. (run-hook-with-args 'nrepl-response-handler-functions response))
  385. (nrepl--dispatch-response response))))))))
  386. (defun nrepl--dispatch-response (response)
  387. "Dispatch the RESPONSE to associated callback.
  388. First we check the callbacks of pending requests. If no callback was found,
  389. we check the completed requests, since responses could be received even for
  390. older requests with \"done\" status."
  391. (nrepl-dbind-response response (id)
  392. (nrepl-log-message response 'response)
  393. (let ((callback (or (gethash id nrepl-pending-requests)
  394. (gethash id nrepl-completed-requests))))
  395. (if callback
  396. (funcall callback response)
  397. (error "[nREPL] No response handler with id %s found" id)))))
  398. (defun nrepl-client-sentinel (process message)
  399. "Handle sentinel events from PROCESS.
  400. Notify MESSAGE and if the process is closed run `nrepl-disconnected-hook'
  401. and kill the process buffer."
  402. (if (string-match "deleted\\b" message)
  403. (message "[nREPL] Connection closed")
  404. (message "[nREPL] Connection closed unexpectedly (%s)"
  405. (substring message 0 -1)))
  406. (when (equal (process-status process) 'closed)
  407. (when-let* ((client-buffer (process-buffer process)))
  408. (sesman-remove-object 'CIDER nil client-buffer
  409. (not (process-get process :keep-server))
  410. 'no-error)
  411. (nrepl--clear-client-sessions client-buffer)
  412. (with-current-buffer client-buffer
  413. (goto-char (point-max))
  414. (insert-before-markers
  415. (propertize
  416. (format "\n*** Closed on %s ***\n" (current-time-string))
  417. 'face 'cider-repl-stderr-face))
  418. (run-hooks 'nrepl-disconnected-hook)
  419. (let ((server-buffer nrepl-server-buffer))
  420. (when (and (buffer-live-p server-buffer)
  421. (not (process-get process :keep-server)))
  422. (setq nrepl-server-buffer nil)
  423. (nrepl--maybe-kill-server-buffer server-buffer)))))))
  424. ;;; Network
  425. (defun nrepl-connect (host port)
  426. "Connect to the nREPL server identified by HOST and PORT.
  427. For local hosts use a direct connection. For remote hosts, if
  428. `nrepl-force-ssh-for-remote-hosts' is nil, attempt a direct connection
  429. first. If `nrepl-force-ssh-for-remote-hosts' is non-nil or the direct
  430. connection failed (and `nrepl-use-ssh-fallback-for-remote-hosts' is
  431. non-nil), try to start a SSH tunneled connection. Return a plist of the
  432. form (:proc PROC :host \"HOST\" :port PORT) that might contain additional
  433. key-values depending on the connection type."
  434. (let ((localp (if host
  435. (nrepl-local-host-p host)
  436. (not (file-remote-p default-directory)))))
  437. (if localp
  438. (nrepl--direct-connect (or host "localhost") port)
  439. ;; we're dealing with a remote host
  440. (if (and host (not nrepl-force-ssh-for-remote-hosts))
  441. (or (nrepl--direct-connect host port 'no-error)
  442. ;; direct connection failed
  443. ;; fallback to ssh tunneling if enabled
  444. (and nrepl-use-ssh-fallback-for-remote-hosts
  445. (message "[nREPL] Falling back to SSH tunneled connection ...")
  446. (nrepl--ssh-tunnel-connect host port))
  447. ;; fallback is either not enabled or it failed as well
  448. (if (and (null nrepl-use-ssh-fallback-for-remote-hosts)
  449. (not localp))
  450. (error "[nREPL] Direct connection to %s:%s failed; try setting `nrepl-use-ssh-fallback-for-remote-hosts' to t"
  451. host port)
  452. (error "[nREPL] Cannot connect to %s:%s" host port)))
  453. ;; `nrepl-force-ssh-for-remote-hosts' is non-nil
  454. (nrepl--ssh-tunnel-connect host port)))))
  455. (defun nrepl--direct-connect (host port &optional no-error)
  456. "If HOST and PORT are given, try to `open-network-stream'.
  457. If NO-ERROR is non-nil, show messages instead of throwing an error."
  458. (if (not (and host port))
  459. (unless no-error
  460. (unless host
  461. (error "[nREPL] Host not provided"))
  462. (unless port
  463. (error "[nREPL] Port not provided")))
  464. (message "[nREPL] Establishing direct connection to %s:%s ..." host port)
  465. (condition-case nil
  466. (prog1 (list :proc (open-network-stream "nrepl-connection" nil host port)
  467. :host host :port port)
  468. (message "[nREPL] Direct connection to %s:%s established" host port))
  469. (error (let ((msg (format "[nREPL] Direct connection to %s:%s failed" host port)))
  470. (if no-error
  471. (message msg)
  472. (error msg))
  473. nil)))))
  474. (defun nrepl--ssh-tunnel-connect (host port)
  475. "Connect to a remote machine identified by HOST and PORT through SSH tunnel."
  476. (message "[nREPL] Establishing SSH tunneled connection to %s:%s ..." host port)
  477. (let* ((remote-dir (if host (format "/ssh:%s:" host) default-directory))
  478. (ssh (or (executable-find "ssh")
  479. (error "[nREPL] Cannot locate 'ssh' executable")))
  480. (cmd (nrepl--ssh-tunnel-command ssh remote-dir port))
  481. (tunnel-buf (nrepl-tunnel-buffer-name
  482. `((:host ,host) (:port ,port))))
  483. (tunnel (start-process-shell-command "nrepl-tunnel" tunnel-buf cmd)))
  484. (process-put tunnel :waiting-for-port t)
  485. (set-process-filter tunnel (nrepl--ssh-tunnel-filter port))
  486. (while (and (process-live-p tunnel)
  487. (process-get tunnel :waiting-for-port))
  488. (accept-process-output nil 0.005))
  489. (if (not (process-live-p tunnel))
  490. (error "[nREPL] SSH port forwarding failed. Check the '%s' buffer" tunnel-buf)
  491. (message "[nREPL] SSH port forwarding established to localhost:%s" port)
  492. (let ((endpoint (nrepl--direct-connect "localhost" port)))
  493. (thread-first endpoint
  494. (plist-put :tunnel tunnel)
  495. (plist-put :remote-host host))))))
  496. (defun nrepl--ssh-tunnel-command (ssh dir port)
  497. "Command string to open SSH tunnel to the host associated with DIR's PORT."
  498. (with-parsed-tramp-file-name dir v
  499. ;; this abuses the -v option for ssh to get output when the port
  500. ;; forwarding is set up, which is used to synchronise on, so that
  501. ;; the port forwarding is up when we try to connect.
  502. (format-spec
  503. "%s -v -N -L %p:localhost:%p %u'%h'"
  504. `((?s . ,ssh)
  505. (?p . ,port)
  506. (?h . ,v-host)
  507. (?u . ,(if v-user (format "-l '%s' " v-user) ""))))))
  508. (autoload 'comint-watch-for-password-prompt "comint" "(autoload).")
  509. (defun nrepl--ssh-tunnel-filter (port)
  510. "Return a process filter that waits for PORT to appear in process output."
  511. (let ((port-string (format "LOCALHOST:%s" port)))
  512. (lambda (proc string)
  513. (when (string-match-p port-string string)
  514. (process-put proc :waiting-for-port nil))
  515. (when (and (process-live-p proc)
  516. (buffer-live-p (process-buffer proc)))
  517. (with-current-buffer (process-buffer proc)
  518. (let ((moving (= (point) (process-mark proc))))
  519. (save-excursion
  520. (goto-char (process-mark proc))
  521. (insert string)
  522. (set-marker (process-mark proc) (point))
  523. (comint-watch-for-password-prompt string))
  524. (if moving (goto-char (process-mark proc)))))))))
  525. ;;; Client: Process Handling
  526. (defun nrepl--kill-process (proc)
  527. "Kill PROC using the appropriate, os specific way.
  528. Implement a workaround to clean up an orphaned JVM process left around
  529. after exiting the REPL on some windows machines."
  530. (if (memq system-type '(cygwin windows-nt))
  531. (interrupt-process proc)
  532. (kill-process proc)))
  533. (defun nrepl-kill-server-buffer (server-buf)
  534. "Kill SERVER-BUF and its process."
  535. (when (buffer-live-p server-buf)
  536. (let ((proc (get-buffer-process server-buf)))
  537. (when (process-live-p proc)
  538. (set-process-query-on-exit-flag proc nil)
  539. (nrepl--kill-process proc))
  540. (kill-buffer server-buf))))
  541. (defun nrepl--maybe-kill-server-buffer (server-buf)
  542. "Kill SERVER-BUF and its process.
  543. Do not kill the server if there is a REPL connected to that server."
  544. (when (buffer-live-p server-buf)
  545. (with-current-buffer server-buf
  546. ;; Don't kill if there is at least one REPL connected to it.
  547. (when (not (seq-find (lambda (b)
  548. (eq (buffer-local-value 'nrepl-server-buffer b)
  549. server-buf))
  550. (buffer-list)))
  551. (nrepl-kill-server-buffer server-buf)))))
  552. (defun nrepl-start-client-process (&optional host port server-proc buffer-builder)
  553. "Create new client process identified by HOST and PORT.
  554. In remote buffers, HOST and PORT are taken from the current tramp
  555. connection. SERVER-PROC must be a running nREPL server process within
  556. Emacs. BUFFER-BUILDER is a function of one argument (endpoint returned by
  557. `nrepl-connect') which returns a client buffer. Return the newly created
  558. client process."
  559. (let* ((endpoint (nrepl-connect host port))
  560. (client-proc (plist-get endpoint :proc))
  561. (builder (or buffer-builder (error "`buffer-builder' must be provided")))
  562. (client-buf (funcall builder endpoint)))
  563. (set-process-buffer client-proc client-buf)
  564. (set-process-filter client-proc 'nrepl-client-filter)
  565. (set-process-sentinel client-proc 'nrepl-client-sentinel)
  566. (set-process-coding-system client-proc 'utf-8-unix 'utf-8-unix)
  567. (process-put client-proc :string-q (queue-create))
  568. (process-put client-proc :response-q (nrepl-response-queue))
  569. (with-current-buffer client-buf
  570. (when-let* ((server-buf (and server-proc (process-buffer server-proc))))
  571. (setq nrepl-project-dir (buffer-local-value 'nrepl-project-dir server-buf)
  572. nrepl-server-buffer server-buf))
  573. (setq nrepl-endpoint endpoint
  574. nrepl-tunnel-buffer (when-let* ((tunnel (plist-get endpoint :tunnel)))
  575. (process-buffer tunnel))
  576. nrepl-pending-requests (make-hash-table :test 'equal)
  577. nrepl-completed-requests (make-hash-table :test 'equal)))
  578. (with-current-buffer client-buf
  579. (nrepl--init-client-sessions client-proc)
  580. (nrepl--init-capabilities client-buf)
  581. (run-hooks 'nrepl-connected-hook))
  582. client-proc))
  583. (defun nrepl--init-client-sessions (client)
  584. "Initialize CLIENT connection nREPL sessions.
  585. We create two client nREPL sessions per connection - a main session and a
  586. tooling session. The main session is general purpose and is used for pretty
  587. much every request that needs a session. The tooling session is used only
  588. for functionality that's implemented in terms of the \"eval\" op, so that
  589. eval requests for functionality like pretty-printing won't clobber the
  590. values of *1, *2, etc."
  591. (let* ((client-conn (process-buffer client))
  592. (response-main (nrepl-sync-request:clone client-conn))
  593. (response-tooling (nrepl-sync-request:clone client-conn t))) ; t for tooling
  594. (nrepl-dbind-response response-main (new-session err)
  595. (if new-session
  596. (with-current-buffer client-conn
  597. (setq nrepl-session new-session))
  598. (error "Could not create new session (%s)" err)))
  599. (nrepl-dbind-response response-tooling (new-session err)
  600. (if new-session
  601. (with-current-buffer client-conn
  602. (setq nrepl-tooling-session new-session))
  603. (error "Could not create new tooling session (%s)" err)))))
  604. (defun nrepl--init-capabilities (conn-buffer)
  605. "Store locally in CONN-BUFFER the capabilities of nREPL server."
  606. (let ((description (nrepl-sync-request:describe conn-buffer)))
  607. (nrepl-dbind-response description (ops versions aux)
  608. (with-current-buffer conn-buffer
  609. (setq nrepl-ops ops)
  610. (setq nrepl-versions versions)
  611. (setq nrepl-aux aux)))))
  612. (defun nrepl--clear-client-sessions (conn-buffer)
  613. "Clear information about nREPL sessions in CONN-BUFFER.
  614. CONN-BUFFER refers to a (presumably) dead connection, which we can eventually reuse."
  615. (with-current-buffer conn-buffer
  616. (setq nrepl-session nil)
  617. (setq nrepl-tooling-session nil)))
  618. ;;; Client: Response Handling
  619. ;; After being decoded, responses (aka, messages from the server) are dispatched
  620. ;; to handlers. Handlers are constructed with `nrepl-make-response-handler'.
  621. (defvar nrepl-err-handler nil
  622. "Evaluation error handler.")
  623. (defun nrepl--mark-id-completed (id)
  624. "Move ID from `nrepl-pending-requests' to `nrepl-completed-requests'.
  625. It is safe to call this function multiple times on the same ID."
  626. ;; FIXME: This should go away eventually when we get rid of
  627. ;; pending-request hash table
  628. (when-let* ((handler (gethash id nrepl-pending-requests)))
  629. (puthash id handler nrepl-completed-requests)
  630. (remhash id nrepl-pending-requests)))
  631. (declare-function cider-repl--emit-interactive-output "cider-repl")
  632. (defun nrepl-notify (msg type)
  633. "Handle \"notification\" server request.
  634. MSG is a string to be displayed. TYPE is the type of the message. All
  635. notifications are currently displayed with `message' function and emitted
  636. to the REPL."
  637. (let* ((face (pcase type
  638. ((or "message" `nil) 'font-lock-builtin-face)
  639. ("warning" 'warning)
  640. ("error" 'error)))
  641. (msg (if face
  642. (propertize msg 'face face)
  643. (format "%s: %s" (upcase type) msg))))
  644. (cider-repl--emit-interactive-output msg (or face 'font-lock-builtin-face))
  645. (message msg)))
  646. (defvar cider-buffer-ns)
  647. (defvar cider-special-mode-truncate-lines)
  648. (declare-function cider-need-input "cider-client")
  649. (declare-function cider-set-buffer-ns "cider-mode")
  650. (defun nrepl-make-response-handler (buffer value-handler stdout-handler
  651. stderr-handler done-handler
  652. &optional eval-error-handler
  653. content-type-handler
  654. truncated-handler)
  655. "Make a response handler for connection BUFFER.
  656. A handler is a function that takes one argument - response received from
  657. the server process. The response is an alist that contains at least 'id'
  658. and 'session' keys. Other standard response keys are 'value', 'out', 'err',
  659. and 'status'.
  660. The presence of a particular key determines the type of the response. For
  661. example, if 'value' key is present, the response is of type 'value', if
  662. 'out' key is present the response is 'stdout' etc.
  663. Depending on the type, the handler dispatches the appropriate value to one
  664. of the supplied handlers: VALUE-HANDLER, STDOUT-HANDLER, STDERR-HANDLER,
  665. DONE-HANDLER, EVAL-ERROR-HANDLER, CONTENT-TYPE-HANDLER, and
  666. TRUNCATED-HANDLER.
  667. Handlers are functions of the buffer and the value they handle, except for
  668. the optional CONTENT-TYPE-HANDLER which should be a function of the buffer,
  669. content, the content-type to be handled as a list `(type attrs)'.
  670. If the optional EVAL-ERROR-HANDLER is nil, the default `nrepl-err-handler'
  671. is used. If any of the other supplied handlers are nil nothing happens for
  672. the corresponding type of response."
  673. (lambda (response)
  674. (nrepl-dbind-response response (content-type content-transfer-encoding body
  675. value ns out err status id)
  676. (when (buffer-live-p buffer)
  677. (with-current-buffer buffer
  678. (when (and ns (not (derived-mode-p 'clojure-mode)))
  679. (cider-set-buffer-ns ns))))
  680. (cond ((and content-type content-type-handler)
  681. (funcall content-type-handler buffer
  682. (if (string= content-transfer-encoding "base64")
  683. (base64-decode-string body)
  684. body)
  685. content-type))
  686. (value
  687. (when value-handler
  688. (funcall value-handler buffer value)))
  689. (out
  690. (when stdout-handler
  691. (funcall stdout-handler buffer out)))
  692. (err
  693. (when stderr-handler
  694. (funcall stderr-handler buffer err)))
  695. (status
  696. (when (and truncated-handler (member "nrepl.middleware.print/truncated" status))
  697. (let ((warning (format "\n... output truncated to %sB ..."
  698. (file-size-human-readable cider-print-quota))))
  699. (funcall truncated-handler buffer warning)))
  700. (when (member "notification" status)
  701. (nrepl-dbind-response response (msg type)
  702. (nrepl-notify msg type)))
  703. (when (member "interrupted" status)
  704. (message "Evaluation interrupted."))
  705. (when (member "eval-error" status)
  706. (funcall (or eval-error-handler nrepl-err-handler)))
  707. (when (member "namespace-not-found" status)
  708. (message "Namespace `%s' not found." ns))
  709. (when (member "need-input" status)
  710. (cider-need-input buffer))
  711. (when (member "done" status)
  712. (nrepl--mark-id-completed id)
  713. (when done-handler
  714. (funcall done-handler buffer))))))))
  715. ;;; Client: Request Core API
  716. ;; Requests are messages from an nREPL client (like CIDER) to an nREPL server.
  717. ;; Requests can be asynchronous (sent with `nrepl-send-request') or
  718. ;; synchronous (send with `nrepl-send-sync-request'). The request is a pair list
  719. ;; of operation name and operation parameters. The core operations are described
  720. ;; at https://github.com/nrepl/nrepl/blob/master/doc/ops.md. CIDER adds
  721. ;; many more operations through nREPL middleware. See
  722. ;; https://github.com/clojure-emacs/cider-nrepl#supplied-nrepl-middleware for
  723. ;; the up-to-date list.
  724. (defun nrepl-next-request-id (connection)
  725. "Return the next request id for CONNECTION."
  726. (with-current-buffer connection
  727. (number-to-string (cl-incf nrepl-request-counter))))
  728. (defun nrepl-send-request (request callback connection &optional tooling)
  729. "Send REQUEST and register response handler CALLBACK using CONNECTION.
  730. REQUEST is a pair list of the form (\"op\" \"operation\" \"par1-name\"
  731. \"par1\" ... ). See the code of `nrepl-request:clone',
  732. `nrepl-request:stdin', etc. This expects that the REQUEST does not have a
  733. session already in it. This code will add it as appropriate to prevent
  734. connection/session drift.
  735. Return the ID of the sent message.
  736. Optional argument TOOLING Set to t if desiring the tooling session rather than the standard session."
  737. (with-current-buffer connection
  738. (when-let* ((session (if tooling nrepl-tooling-session nrepl-session)))
  739. (setq request (append request `("session" ,session))))
  740. (let* ((id (nrepl-next-request-id connection))
  741. (request (cons 'dict (lax-plist-put request "id" id)))
  742. (message (nrepl-bencode request)))
  743. (nrepl-log-message request 'request)
  744. (puthash id callback nrepl-pending-requests)
  745. (process-send-string nil message)
  746. id)))
  747. (defvar nrepl-ongoing-sync-request nil
  748. "Dynamically bound to t while a sync request is ongoing.")
  749. (declare-function cider-repl-emit-interactive-stderr "cider-repl")
  750. (declare-function cider--render-stacktrace-causes "cider-eval")
  751. (defun nrepl-send-sync-request (request connection &optional abort-on-input tooling)
  752. "Send REQUEST to the nREPL server synchronously using CONNECTION.
  753. Hold till final \"done\" message has arrived and join all response messages
  754. of the same \"op\" that came along.
  755. If ABORT-ON-INPUT is non-nil, the function will return nil at the first
  756. sign of user input, so as not to hang the interface.
  757. If TOOLING, use the tooling session rather than the standard session."
  758. (let* ((time0 (current-time))
  759. (response (cons 'dict nil))
  760. (nrepl-ongoing-sync-request t)
  761. status)
  762. (nrepl-send-request request
  763. (lambda (resp) (nrepl--merge response resp))
  764. connection
  765. tooling)
  766. (while (and (not (member "done" status))
  767. (not (and abort-on-input
  768. (input-pending-p))))
  769. (setq status (nrepl-dict-get response "status"))
  770. ;; If we get a need-input message then the repl probably isn't going
  771. ;; anywhere, and we'll just timeout. So we forward it to the user.
  772. (if (member "need-input" status)
  773. (progn (cider-need-input (current-buffer))
  774. ;; If the used took a few seconds to respond, we might
  775. ;; unnecessarily timeout, so let's reset the timer.
  776. (setq time0 (current-time)))
  777. ;; break out in case we don't receive a response for a while
  778. (when (and nrepl-sync-request-timeout
  779. (> (cadr (time-subtract (current-time) time0))
  780. nrepl-sync-request-timeout))
  781. (error "Sync nREPL request timed out %s" request)))
  782. ;; Clean up the response, otherwise we might repeatedly ask for input.
  783. (nrepl-dict-put response "status" (remove "need-input" status))
  784. (accept-process-output nil 0.01))
  785. ;; If we couldn't finish, return nil.
  786. (when (member "done" status)
  787. (nrepl-dbind-response response (ex err eval-error pp-stacktrace id)
  788. (when (and ex err)
  789. (cond (eval-error (funcall nrepl-err-handler))
  790. (pp-stacktrace (cider--render-stacktrace-causes
  791. pp-stacktrace (remove "done" status))))) ;; send the error type
  792. (when id
  793. (with-current-buffer connection
  794. (nrepl--mark-id-completed id)))
  795. response))))
  796. (defun nrepl-request:stdin (input callback connection)
  797. "Send a :stdin request with INPUT using CONNECTION.
  798. Register CALLBACK as the response handler."
  799. (nrepl-send-request `("op" "stdin"
  800. "stdin" ,input)
  801. callback
  802. connection))
  803. (defun nrepl-request:interrupt (pending-request-id callback connection)
  804. "Send an :interrupt request for PENDING-REQUEST-ID.
  805. The request is dispatched using CONNECTION.
  806. Register CALLBACK as the response handler."
  807. (nrepl-send-request `("op" "interrupt"
  808. "interrupt-id" ,pending-request-id)
  809. callback
  810. connection))
  811. (define-minor-mode cider-enlighten-mode nil nil (cider-mode " light")
  812. :global t)
  813. (defun nrepl--eval-request (input &optional ns line column)
  814. "Prepare :eval request message for INPUT.
  815. NS provides context for the request.
  816. If LINE and COLUMN are non-nil and current buffer is a file buffer, \"line\",
  817. \"column\" and \"file\" are added to the message."
  818. (nconc (and ns `("ns" ,ns))
  819. `("op" "eval"
  820. "code" ,(substring-no-properties input))
  821. (when cider-enlighten-mode
  822. '("enlighten" "true"))
  823. (let ((file (or (buffer-file-name) (buffer-name))))
  824. (when (and line column file)
  825. `("file" ,file
  826. "line" ,line
  827. "column" ,column)))))
  828. (defun nrepl-request:eval (input callback connection &optional ns line column additional-params tooling)
  829. "Send the request INPUT and register the CALLBACK as the response handler.
  830. The request is dispatched via CONNECTION. If NS is non-nil,
  831. include it in the request. LINE and COLUMN, if non-nil, define the position
  832. of INPUT in its buffer. A CONNECTION uniquely determines two connections
  833. available: the standard interaction one and the tooling session. If the
  834. tooling is desired, set TOOLING to true.
  835. ADDITIONAL-PARAMS is a plist to be appended to the request message."
  836. (nrepl-send-request (append (nrepl--eval-request input ns line column) additional-params)
  837. callback
  838. connection
  839. tooling))
  840. (defun nrepl-sync-request:clone (connection &optional tooling)
  841. "Sent a :clone request to create a new client session.
  842. The request is dispatched via CONNECTION.
  843. Optional argument TOOLING Tooling is set to t if wanting the tooling session from CONNECTION."
  844. (nrepl-send-sync-request '("op" "clone")
  845. connection
  846. nil tooling))
  847. (defun nrepl-sync-request:close (connection)
  848. "Sent a :close request to close CONNECTION's SESSION."
  849. (nrepl-send-sync-request '("op" "close") connection)
  850. (nrepl-send-sync-request '("op" "close") connection nil t)) ;; close tooling session
  851. (defun nrepl-sync-request:describe (connection)
  852. "Perform :describe request for CONNECTION and SESSION."
  853. (nrepl-send-sync-request '("op" "describe")
  854. connection))
  855. (defun nrepl-sync-request:ls-sessions (connection)
  856. "Perform :ls-sessions request for CONNECTION."
  857. (nrepl-send-sync-request '("op" "ls-sessions") connection))
  858. (defun nrepl-sync-request:eval (input connection &optional ns tooling)
  859. "Send the INPUT to the nREPL server synchronously.
  860. The request is dispatched via CONNECTION.
  861. If NS is non-nil, include it in the request
  862. If TOOLING is non-nil the evaluation is done using the tooling nREPL
  863. session."
  864. (nrepl-send-sync-request
  865. (nrepl--eval-request input ns)
  866. connection
  867. nil
  868. tooling))
  869. (defun nrepl-sessions (connection)
  870. "Get a list of active sessions on the nREPL server using CONNECTION."
  871. (nrepl-dict-get (nrepl-sync-request:ls-sessions connection) "sessions"))
  872. ;;; Server
  873. ;; The server side process is started by `nrepl-start-server-process' and has a
  874. ;; very simple filter that pipes its output directly into its process buffer
  875. ;; (*nrepl-server*). The main purpose of this process is to start the actual
  876. ;; nrepl communication client (`nrepl-client-filter') when the message "nREPL
  877. ;; server started on port ..." is detected.
  878. ;; internal variables used for state transfer between nrepl-start-server-process
  879. ;; and nrepl-server-filter.
  880. (defvar-local nrepl-on-port-callback nil)
  881. (defun nrepl-server-p (buffer-or-process)
  882. "Return t if BUFFER-OR-PROCESS is an nREPL server."
  883. (let ((buffer (if (processp buffer-or-process)
  884. (process-buffer buffer-or-process)
  885. buffer-or-process)))
  886. (buffer-local-value 'nrepl-is-server buffer)))
  887. (defun nrepl-start-server-process (directory cmd on-port-callback)
  888. "Start nREPL server process in DIRECTORY using shell command CMD.
  889. Return a newly created process. Set `nrepl-server-filter' as the process
  890. filter, which starts REPL process with its own buffer once the server has
  891. started. ON-PORT-CALLBACK is a function of one argument (server buffer)
  892. which is called by the process filter once the port of the connection has
  893. been determined."
  894. (let* ((default-directory (or directory default-directory))
  895. (serv-buf (get-buffer-create
  896. (nrepl-server-buffer-name
  897. `(:project-dir ,default-directory)))))
  898. (with-current-buffer serv-buf
  899. (setq nrepl-is-server t
  900. nrepl-project-dir default-directory
  901. nrepl-server-command cmd
  902. nrepl-on-port-callback on-port-callback))
  903. (let ((serv-proc (start-file-process-shell-command
  904. "nrepl-server" serv-buf cmd)))
  905. (set-process-filter serv-proc 'nrepl-server-filter)
  906. (set-process-sentinel serv-proc 'nrepl-server-sentinel)
  907. (set-process-coding-system serv-proc 'utf-8-unix 'utf-8-unix)
  908. (message "[nREPL] Starting server via %s"
  909. (propertize cmd 'face 'font-lock-keyword-face))
  910. serv-proc)))
  911. (defun nrepl-server-filter (process output)
  912. "Process nREPL server output from PROCESS contained in OUTPUT."
  913. ;; In Windows this can be false:
  914. (let ((server-buffer (process-buffer process)))
  915. (when (buffer-live-p server-buffer)
  916. (with-current-buffer server-buffer
  917. ;; auto-scroll on new output
  918. (let ((moving (= (point) (process-mark process))))
  919. (save-excursion
  920. (goto-char (process-mark process))
  921. (insert output)
  922. (ansi-color-apply-on-region (process-mark process) (point))
  923. (set-marker (process-mark process) (point)))
  924. (when moving
  925. (goto-char (process-mark process))
  926. (when-let* ((win (get-buffer-window)))
  927. (set-window-point win (point)))))
  928. ;; detect the port the server is listening on from its output
  929. (when (and (null nrepl-endpoint)
  930. (string-match "nREPL server started on port \\([0-9]+\\)" output))
  931. (let ((port (string-to-number (match-string 1 output))))
  932. (setq nrepl-endpoint (list :host (or (file-remote-p default-directory 'host)
  933. "localhost")
  934. :port port))
  935. (message "[nREPL] server started on %s" port)
  936. (when nrepl-on-port-callback
  937. (funcall nrepl-on-port-callback (process-buffer process)))))))))
  938. (declare-function cider--close-connection "cider-connection")
  939. (defun nrepl-server-sentinel (process event)
  940. "Handle nREPL server PROCESS EVENT."
  941. (let* ((server-buffer (process-buffer process))
  942. (clients (seq-filter (lambda (b)
  943. (eq (buffer-local-value 'nrepl-server-buffer b)
  944. server-buffer))
  945. (buffer-list)))
  946. (problem (if (and server-buffer (buffer-live-p server-buffer))
  947. (with-current-buffer server-buffer
  948. (buffer-substring (point-min) (point-max)))
  949. "")))
  950. (when server-buffer
  951. (kill-buffer server-buffer))
  952. (cond
  953. ((string-match-p "^killed\\|^interrupt" event)
  954. nil)
  955. ((string-match-p "^hangup" event)
  956. (mapc #'cider--close-connection clients))
  957. ;; On Windows, a failed start sends the "finished" event. On Linux it sends
  958. ;; "exited abnormally with code 1".
  959. (t (error "Could not start nREPL server: %s" problem)))))
  960. ;;; Messages
  961. (defcustom nrepl-log-messages nil
  962. "If non-nil, log protocol messages to an nREPL messages buffer.
  963. This is extremely useful for debug purposes, as it allows you to inspect
  964. the communication between Emacs and an nREPL server. Enabling the logging
  965. might have a negative impact on performance, so it's not recommended to
  966. keep it enabled unless you need to debug something."
  967. :type 'boolean
  968. :group 'nrepl
  969. :safe #'booleanp)
  970. (defconst nrepl-message-buffer-max-size 1000000
  971. "Maximum size for the nREPL message buffer.
  972. Defaults to 1000000 characters, which should be an insignificant
  973. memory burden, while providing reasonable history.")
  974. (defconst nrepl-message-buffer-reduce-denominator 4
  975. "Divisor by which to reduce message buffer size.
  976. When the maximum size for the nREPL message buffer is exceeded, the size of
  977. the buffer is reduced by one over this value. Defaults to 4, so that 1/4
  978. of the buffer is removed, which should ensure the buffer's maximum is
  979. reasonably utilized, while limiting the number of buffer shrinking
  980. operations.")
  981. (defvar nrepl-messages-mode-map
  982. (let ((map (make-sparse-keymap)))
  983. (define-key map (kbd "n") #'next-line)
  984. (define-key map (kbd "p") #'previous-line)
  985. (define-key map (kbd "TAB") #'forward-button)
  986. (define-key map (kbd "RET") #'nrepl-log-expand-button)
  987. (define-key map (kbd "e") #'nrepl-log-expand-button)
  988. (define-key map (kbd "E") #'nrepl-log-expand-all-buttons)
  989. (define-key map (kbd "<backtab>") #'backward-button)
  990. map))
  991. (define-derived-mode nrepl-messages-mode special-mode "nREPL Messages"
  992. "Major mode for displaying nREPL messages.
  993. \\{nrepl-messages-mode-map}"
  994. (when cider-special-mode-truncate-lines
  995. (setq-local truncate-lines t))
  996. (setq-local sesman-system 'CIDER)
  997. (setq-local electric-indent-chars nil)
  998. (setq-local comment-start ";")
  999. (setq-local comment-end "")
  1000. (setq-local paragraph-start "(-->\\|(<--")
  1001. (setq-local paragraph-separate "(<--"))
  1002. (defun nrepl-decorate-msg (msg type)
  1003. "Decorate nREPL MSG according to its TYPE."
  1004. (pcase type
  1005. (`request (cons '--> (cdr msg)))
  1006. (`response (cons '<-- (cdr msg)))))
  1007. (defun nrepl-log-message (msg type)
  1008. "Log the nREPL MSG.
  1009. TYPE is either request or response. The message is logged to a buffer
  1010. described by `nrepl-message-buffer-name-template'."
  1011. (when nrepl-log-messages
  1012. ;; append a time-stamp to the message before logging it
  1013. ;; the time-stamps are quite useful for debugging
  1014. (setq msg (cons (car msg)
  1015. (lax-plist-put (cdr msg) "time-stamp"
  1016. (format-time-string "%Y-%m-%0d %H:%M:%S.%N"))))
  1017. (with-current-buffer (nrepl-messages-buffer (current-buffer))
  1018. (setq buffer-read-only nil)
  1019. (when (> (buffer-size) nrepl-message-buffer-max-size)
  1020. (goto-char (/ (buffer-size) nrepl-message-buffer-reduce-denominator))
  1021. (re-search-forward "^(" nil t)
  1022. (delete-region (point-min) (- (point) 1)))
  1023. (goto-char (point-max))
  1024. (nrepl-log-pp-object (nrepl-decorate-msg msg type)
  1025. (nrepl-log--message-color (lax-plist-get (cdr msg) "id"))
  1026. t)
  1027. (when-let* ((win (get-buffer-window)))
  1028. (set-window-point win (point-max)))
  1029. (setq buffer-read-only t))))
  1030. (defun nrepl-toggle-message-logging ()
  1031. "Toggle the value of `nrepl-log-messages' between nil and t.
  1032. This in effect enables or disables the logging of nREPL messages."
  1033. (interactive)
  1034. (setq nrepl-log-messages (not nrepl-log-messages))
  1035. (if nrepl-log-messages
  1036. (message "nREPL message logging enabled")
  1037. (message "nREPL message logging disabled")))
  1038. (defcustom nrepl-message-colors
  1039. '("red" "brown" "coral" "orange" "green" "deep sky blue" "blue" "dark violet")
  1040. "Colors used in the messages buffer."
  1041. :type '(repeat color)
  1042. :group 'nrepl)
  1043. (defun nrepl-log-expand-button (&optional button)
  1044. "Expand the objects hidden in BUTTON's :nrepl-object property.
  1045. BUTTON defaults the button at point."
  1046. (interactive)
  1047. (if-let* ((button (or button (button-at (point)))))
  1048. (let* ((start (overlay-start button))
  1049. (end (overlay-end button))
  1050. (obj (overlay-get button :nrepl-object))
  1051. (inhibit-read-only t))
  1052. (save-excursion
  1053. (goto-char start)
  1054. (delete-overlay button)
  1055. (delete-region start end)
  1056. (nrepl-log-pp-object obj)
  1057. (delete-char -1)))
  1058. (error "No button at point")))
  1059. (defun nrepl-log-expand-all-buttons ()
  1060. "Expand all buttons in nREPL log buffer."
  1061. (interactive)
  1062. (if (not (eq major-mode 'nrepl-messages-mode))
  1063. (user-error "Not in a `nrepl-messages-mode'")
  1064. (save-excursion
  1065. (let* ((pos (point-min))
  1066. (button (next-button pos)))
  1067. (while button
  1068. (setq pos (overlay-start button))
  1069. (nrepl-log-expand-button button)
  1070. (setq button (next-button pos)))))))
  1071. (defun nrepl-log--expand-button-mouse (event)
  1072. "Expand the text hidden under overlay button.
  1073. EVENT gives the button position on window."
  1074. (interactive "e")
  1075. (pcase (elt event 1)
  1076. (`(,window ,_ ,_ ,_ ,_ ,point . ,_)
  1077. (with-selected-window window
  1078. (nrepl-log-expand-button (button-at point))))))
  1079. (defun nrepl-log-insert-button (label object)
  1080. "Insert button with LABEL and :nrepl-object property as OBJECT."
  1081. (insert-button label
  1082. :nrepl-object object
  1083. 'action #'nrepl-log-expand-button
  1084. 'face 'link
  1085. 'help-echo "RET: Expand object."
  1086. ;; Workaround for bug#1568 (don't use local-map here; it
  1087. ;; overwrites major mode map.)
  1088. 'keymap `(keymap (mouse-1 . nrepl-log--expand-button-mouse)))
  1089. (insert "\n"))
  1090. (defun nrepl-log--message-color (id)
  1091. "Return the color to use when pretty-printing the nREPL message with ID.
  1092. If ID is nil, return nil."
  1093. (when id
  1094. (thread-first (string-to-number id)
  1095. (mod (length nrepl-message-colors))
  1096. (nth nrepl-message-colors))))
  1097. (defun nrepl-log--pp-listlike (object &optional foreground button)
  1098. "Pretty print nREPL list like OBJECT.
  1099. FOREGROUND and BUTTON are as in `nrepl-log-pp-object'."
  1100. (cl-flet ((color (str)
  1101. (propertize str 'face
  1102. (append '(:weight ultra-bold)
  1103. (when foreground `(:foreground ,foreground))))))
  1104. (let ((head (format "(%s" (car object))))
  1105. (insert (color head))
  1106. (if (null (cdr object))
  1107. (insert ")\n")
  1108. (let* ((indent (+ 2 (- (current-column) (length head))))
  1109. (sorted-pairs (sort (seq-partition (cl-copy-list (cdr object)) 2)
  1110. (lambda (a b)
  1111. (string< (car a) (car b)))))
  1112. (name-lengths (seq-map (lambda (pair) (length (car pair))) sorted-pairs))
  1113. (longest-name (seq-max name-lengths))
  1114. ;; Special entries are displayed first
  1115. (specialq (lambda (pair) (seq-contains '("id" "op" "session" "time-stamp") (car pair))))
  1116. (special-pairs (seq-filter specialq sorted-pairs))
  1117. (not-special-pairs (seq-remove specialq sorted-pairs))
  1118. (all-pairs (seq-concatenate 'list special-pairs not-special-pairs))
  1119. (sorted-object (apply 'seq-concatenate 'list all-pairs)))
  1120. (insert "\n")
  1121. (cl-loop for l on sorted-object by #'cddr
  1122. do (let ((indent-str (make-string indent ?\s))
  1123. (name-str (propertize (car l) 'face
  1124. ;; Only highlight top-level keys.
  1125. (unless (eq (car object) 'dict)
  1126. 'font-lock-keyword-face)))
  1127. (spaces-str (make-string (- longest-name (length (car l))) ?\s)))
  1128. (insert (format "%s%s%s " indent-str name-str spaces-str))
  1129. (nrepl-log-pp-object (cadr l) nil button)))
  1130. (when (eq (car object) 'dict)
  1131. (delete-char -1))
  1132. (insert (color ")\n")))))))
  1133. (defun nrepl-log-pp-object (object &optional foreground button)
  1134. "Pretty print nREPL OBJECT, delimited using FOREGROUND.
  1135. If BUTTON is non-nil, try making a button from OBJECT instead of inserting
  1136. it into the buffer."
  1137. (let ((min-dict-fold-size 1)
  1138. (min-list-fold-size 10)
  1139. (min-string-fold-size 60))
  1140. (if-let* ((head (car-safe object)))
  1141. ;; list-like objects
  1142. (cond
  1143. ;; top level dicts (always expanded)
  1144. ((memq head '(<-- -->))
  1145. (nrepl-log--pp-listlike object foreground button))
  1146. ;; inner dicts
  1147. ((eq head 'dict)
  1148. (if (and button (> (length object) min-dict-fold-size))
  1149. (nrepl-log-insert-button "(dict ...)" object)
  1150. (nrepl-log--pp-listlike object foreground button)))
  1151. ;; lists
  1152. (t
  1153. (if (and button (> (length object) min-list-fold-size))
  1154. (nrepl-log-insert-button (format "(%s ...)" (prin1-to-string head)) object)
  1155. (pp object (current-buffer)))))
  1156. ;; non-list objects
  1157. (if (stringp object)
  1158. (if (and button (> (length object) min-string-fold-size))
  1159. (nrepl-log-insert-button (format "\"%s...\"" (substring object 0 min-string-fold-size)) object)
  1160. (insert (prin1-to-string object) "\n"))
  1161. (pp object (current-buffer))
  1162. (insert "\n")))))
  1163. (defun nrepl-messages-buffer (conn)
  1164. "Return or create the buffer for CONN.
  1165. The default buffer name is *nrepl-messages connection*."
  1166. (with-current-buffer conn
  1167. (or (and (buffer-live-p nrepl-messages-buffer)
  1168. nrepl-messages-buffer)
  1169. (setq nrepl-messages-buffer
  1170. (let ((buffer (get-buffer-create
  1171. (nrepl-messages-buffer-name
  1172. (cider--gather-connect-params)))))
  1173. (with-current-buffer buffer
  1174. (buffer-disable-undo)
  1175. (nrepl-messages-mode)
  1176. buffer))))))
  1177. (defun nrepl-error-buffer ()
  1178. "Return or create the buffer.
  1179. The default buffer name is *nrepl-error*."
  1180. (or (get-buffer nrepl-error-buffer-name)
  1181. (let ((buffer (get-buffer-create nrepl-error-buffer-name)))
  1182. (with-current-buffer buffer
  1183. (buffer-disable-undo)
  1184. (fundamental-mode)
  1185. buffer))))
  1186. (defun nrepl-log-error (msg)
  1187. "Log the given MSG to the buffer given by `nrepl-error-buffer'."
  1188. (with-current-buffer (nrepl-error-buffer)
  1189. (setq buffer-read-only nil)
  1190. (goto-char (point-max))
  1191. (insert msg)
  1192. (when-let* ((win (get-buffer-window)))
  1193. (set-window-point win (point-max)))
  1194. (setq buffer-read-only t)))
  1195. (make-obsolete 'nrepl-default-client-buffer-builder nil "0.18")
  1196. (provide 'nrepl-client)
  1197. ;;; nrepl-client.el ends here