Merge branch 'pu'
[jungerl.git] / lib / distel / elisp / erl-service.el
bloba14ff17e983169df1c6a7d56b242134e2c3fe089
1 ;;; erl-service.el --- High-level calls to Erlang services.
3 ;;;; Frontmatter
4 ;;
5 ;; This module implements Emacs commands - i.e. M-x'able key-bind'able
6 ;; sort - for doing stuff with Erlang nodes.
7 ;;
8 ;; The general implementation strategy is to make RPCs to the "distel"
9 ;; erlang module, which does most of the work for us.
11 (require 'erlang)
12 (eval-when-compile (require 'cl))
13 (require 'erl)
15 ;;;; Base framework
17 ;;;;; Target node
19 (defvar erl-nodename-cache nil
20 "The name of the node most recently contacted, for reuse in future
21 commands. Using C-u to bypasses the cache.")
23 (defun erl-target-node ()
24 "Return the name of the default target node for commands."
25 (or erl-nodename-cache
26 (erl-choose-nodename)))
28 (defun erl-choose-nodename ()
29 "Prompt the user for the nodename to connect to in future."
30 (interactive)
31 (let* ((name-string (read-string "Node: "))
32 (name (intern (if (string-match "@" name-string)
33 name-string
34 (concat name-string
35 "@" (erl-determine-hostname))))))
36 (setq erl-nodename-cache name)
37 (setq distel-modeline-node name-string)
38 (force-mode-line-update))
39 erl-nodename-cache)
41 ;;;;; Call MFA lookup
43 (defun erl-read-call-mfa ()
44 "Read module, function, arity at point or from user.
45 Returns the result in a list: module and function as strings, arity as
46 integer."
47 (interactive) ; for testing
48 (let* ((mfa-at-point (erl-mfa-at-point))
49 (mfa (if (or (null mfa-at-point)
50 current-prefix-arg
51 distel-tags-compliant)
52 (erl-parse-mfa (read-string "Function reference: "
53 (erl-format-mfa mfa-at-point)))
54 mfa-at-point)))
55 mfa))
57 (defun erl-format-mfa (mfa)
58 "Format (MOD FUN ARITY) as MOD:FUN/ARITY.
59 If MFA is nil then return nil.
60 If only MOD is nil then return FUN/ARITY."
61 (if mfa
62 (destructuring-bind (m f a) mfa
63 (if m (format "%s:%s/%S" m f a) (format "%s/%S" f a)))))
65 (defun erl-parse-mfa (string &optional default-module)
66 "Parse MFA from a string using `erl-mfa-at-point'."
67 (when (null default-module) (setq default-module (erl-buffer-module-name)))
68 (with-temp-buffer
69 (with-syntax-table erlang-mode-syntax-table
70 (insert string)
71 (goto-char (point-min))
72 (erl-mfa-at-point default-module))))
74 (defun erl-buffer-module-name ()
75 "Return the current buffer's module name, or nil."
76 (erlang-get-module))
78 (defun erl-mfa-at-point (&optional default-module)
79 "Return the module, function, arity of the function reference at point.
80 If not module-qualified then use DEFAULT-MODULE."
81 (when (null default-module) (setq default-module (erl-buffer-module-name)))
82 (save-excursion
83 (erl-goto-end-of-call-name)
84 (let ((arity (erl-arity-at-point))
85 (mf (erlang-get-function-under-point)))
86 (if (null mf)
87 nil
88 (destructuring-bind (module function) mf
89 (list (or module default-module) function arity))))))
91 ;;; FIXME: Merge with erlang.el!
92 (defun erl-arity-at-point ()
93 "Get the number of arguments in a function reference.
94 Should be called with point directly before the opening ( or /."
95 ;; Adapted from erlang-get-function-arity.
96 (save-excursion
97 (cond ((looking-at "/")
98 ;; form is /<n>, like the /2 in foo:bar/2
99 (forward-char)
100 (let ((start (point)))
101 (if (re-search-forward "[0-9]+" nil t)
102 (ignore-errors (car (read-from-string (match-string 0)))))))
103 ((looking-at "[\n\r ]*(")
104 (goto-char (match-end 0))
105 (condition-case nil
106 (let ((res 0)
107 (cont t))
108 (while cont
109 (cond ((eobp)
110 (setq res nil)
111 (setq cont nil))
112 ((looking-at "\\s *)")
113 (setq cont nil))
114 ((looking-at "\\s *\\($\\|%\\)")
115 (forward-line 1))
116 ((looking-at "\\s *,")
117 (incf res)
118 (goto-char (match-end 0)))
120 (when (zerop res)
121 (incf res))
122 (forward-sexp 1))))
123 res)
124 (error nil))))))
126 ;;;; Backend code checking
128 (add-hook 'erl-nodeup-hook 'erl-check-backend)
130 (defun erl-check-backend (node _fsm)
131 "Check if we have the 'distel' module available on `node', and popup
132 a warning if not."
133 (unless distel-inhibit-backend-check
134 (erl-spawn
135 (erl-send `[rex ,node]
136 `[,erl-self [call
137 code ensure_loaded (distel)
138 ,(erl-group-leader)]])
139 (erl-receive (node)
140 ((['rex ['error _]]
141 (with-current-buffer (get-buffer-create "*Distel Warning*")
142 (erase-buffer)
143 (insert (format "\
144 Distel Warning: node `%s' can't seem to load the `distel' module.
146 This means that most Distel commands won't function correctly, because
147 the supporting library is not available. Please check your node's code
148 path, and make sure that Distel's \"ebin\" directory is included.
150 The most likely cause of this problem is either:
152 a) Your ~/.erlang file doesn't add Distel to your load path (the
153 Distel \"make config_install\" target can set this up for you.)
155 b) Your system's boot script doesn't consult your ~/.erlang file to
156 read your code path setting.
158 To disable this warning in future, set `distel-inhibit-backend-check' to t.
161 node))
162 (display-buffer (current-buffer))))
163 (other t))))))
165 ;;;; RPC
167 (defun erl-rpc (k kargs node m f a)
168 "Call {M,F,A} on NODE and deliver the result to the function K.
169 The first argument to K is the result from the RPC, followed by the
170 elements of KARGS."
171 (erl-spawn
172 (erl-send-rpc node m f a)
173 (erl-rpc-receive k kargs)))
175 (defun erl-send-rpc (node mod fun args)
176 "Send an RPC request on NODE to apply(MOD, FUN, ARGS).
177 The reply will be sent back as an asynchronous message of the form:
178 [rex Result]
179 On an error, Result will be [badrpc Reason]."
180 (let ((m 'distel)
181 (f 'rpc_entry)
182 (a (list mod fun args)))
183 (erl-send (tuple 'rex node)
184 ;; {Who, {call, M, F, A, GroupLeader}}
185 (tuple erl-self (tuple 'call m f a (erl-group-leader))))))
187 (defun erl-rpc-receive (k kargs)
188 "Receive the reply to an `erl-rpc'."
189 (erl-receive (k kargs)
190 ((['rex reply] (apply k (cons reply kargs))))))
192 (defun erpc (node m f a)
193 "Make an RPC to an erlang node."
194 (interactive (list (erl-target-node)
195 (intern (read-string "Module: "))
196 (intern (read-string "Function: "))
197 (eval-minibuffer "Args: ")))
198 (erl-rpc (lambda (result) (message "RPC result: %S" result))
200 node
201 m f a))
203 ;;;; Process list
205 (defun erl-process-list (node)
206 "Show a list of all processes running on NODE.
207 The listing is requested asynchronously, and popped up in a buffer
208 when ready."
209 (interactive (list (erl-target-node)))
210 (erl-rpc #'erl-show-process-list (list node)
211 node 'distel 'process_list '()))
213 (defun erl-show-process-list (reply node)
214 (with-current-buffer (get-buffer-create (format "*plist %S*" node))
215 (process-list-mode)
216 (setq buffer-read-only t)
217 (let ((buffer-read-only nil))
218 (erase-buffer)
219 (let ((header (tuple-elt reply 1))
220 (infos (tuple-elt reply 2)))
221 (put-text-property 0 (length header) 'face 'bold header)
222 (insert header)
223 (mapc #'erl-insert-process-info infos))
224 (goto-char (point-min))
225 (next-line 1))
226 (select-window (display-buffer (current-buffer)))))
228 (defun erl-insert-process-info (info)
229 "Insert INFO into the buffer.
230 INFO is [PID SUMMARY-STRING]."
231 (let ((pid (tuple-elt info 1))
232 (text (tuple-elt info 2)))
233 (put-text-property 0 (length text) 'erl-pid pid text)
234 (insert text)))
236 ;; Process list major mode
238 (defvar erl-viewed-pid nil
239 "PID being viewed.")
240 (make-variable-buffer-local 'erl-viewed-pid)
241 (defvar erl-old-window-configuration nil
242 "Window configuration to return to when viewing is finished.")
243 (make-variable-buffer-local 'erl-old-window-configuration)
245 (defun erl-quit-viewer (&optional bury)
246 "Quit the current view and restore the old window config.
247 When BURY is non-nil, buries the buffer instead of killing it."
248 (interactive)
249 (let ((cfg erl-old-window-configuration))
250 (if bury
251 (bury-buffer)
252 (kill-this-buffer))
253 (set-window-configuration cfg)))
255 (defun erl-bury-viewer ()
256 "Bury the current view and restore the old window config."
257 (interactive)
258 (erl-quit-viewer t))
260 (defvar process-list-mode-map nil
261 "Keymap for Process List mode.")
263 (when (null process-list-mode-map)
264 (setq process-list-mode-map (make-sparse-keymap))
265 (define-key process-list-mode-map [?u] 'erl-process-list)
266 (define-key process-list-mode-map [?q] 'erl-quit-viewer)
267 (define-key process-list-mode-map [?k] 'erl-pman-kill-process)
268 (define-key process-list-mode-map [return] 'erl-show-process-info)
269 (define-key process-list-mode-map [(control m)] 'erl-show-process-info)
270 (define-key process-list-mode-map [?i] 'erl-show-process-info-item)
271 (define-key process-list-mode-map [?b] 'erl-show-process-backtrace)
272 (define-key process-list-mode-map [?m] 'erl-show-process-messages))
274 (defun process-list-mode ()
275 "Major mode for viewing Erlang process listings.
277 Available commands:
279 \\[erl-quit-viewer] - Quit the process listing viewer, restoring old window config.
280 \\[erl-process-list] - Update the process list.
281 \\[erl-pman-kill-process] - Send an EXIT signal with reason 'kill' to process at point.
282 \\[erl-show-process-info] - Show process_info for process at point.
283 \\[erl-show-process-info-item] - Show a piece of process_info for process at point.
284 \\[erl-show-process-backtrace] - Show a backtrace for the process at point.
285 \\[erl-show-process-messages] - Show the message queue for the process at point."
286 (interactive)
287 (kill-all-local-variables)
288 (use-local-map process-list-mode-map)
289 (setq mode-name "Process List")
290 (setq major-mode 'process-list-mode)
291 (setq erl-old-window-configuration (current-window-configuration))
292 (run-hooks 'process-list-mode-hook))
294 (defun erl-show-process-info ()
295 "Show information about process at point in a summary buffer."
296 (interactive)
297 (let ((pid (get-text-property (point) 'erl-pid)))
298 (if (null pid)
299 (message "No process at point.")
300 (erl-view-process pid))))
302 (defun erl-show-process-info-item (item)
303 "Show a piece of information about process at point."
304 (interactive (list (intern (read-string "Item: "))))
305 (let ((pid (get-text-property (point) 'erl-pid)))
306 (cond ((null pid)
307 (message "No process at point."))
308 ((string= "" item)
309 (erl-show-process-info))
311 (erl-spawn
312 (erl-send-rpc (erl-pid-node pid)
313 'distel 'process_info_item (list pid item))
314 (erl-receive (item pid)
315 ((['rex ['ok string]]
316 (display-message-or-view string "*pinfo item*"))
317 (other
318 (message "Error from erlang side of process_info:\n %S"
319 other)))))))))
321 (defun display-message-or-view (msg bufname &optional select)
322 "Like `display-buffer-or-message', but with `view-buffer-other-window'.
323 That is, if a buffer pops up it will be in view mode, and pressing q
324 will get rid of it.
326 Only uses the echo area for single-line messages - or more accurately,
327 messages without embedded newlines. They may still need to wrap or
328 truncate to fit on the screen."
329 (if (string-match "\n.*[^\\s-]" msg)
330 ;; Contains a newline with actual text after it, so display as a
331 ;; buffer
332 (with-current-buffer (get-buffer-create bufname)
333 (setq buffer-read-only t)
334 (let ((inhibit-read-only t))
335 (erase-buffer)
336 (insert msg)
337 (goto-char (point-min))
338 (let ((win (display-buffer (current-buffer))))
339 (when select (select-window win)))))
340 ;; Print only the part before the newline (if there is
341 ;; one). Newlines in messages are displayed as "^J" in emacs20,
342 ;; which is ugly
343 (string-match "[^\r\n]*" msg)
344 (message (match-string 0 msg))))
346 (defun erl-show-process-messages ()
347 (interactive)
348 (erl-show-process-info-item 'messages))
349 (defun erl-show-process-backtrace ()
350 (interactive)
351 (erl-show-process-info-item 'backtrace))
353 (defun erl-pman-kill-process ()
354 "Kill process at point in a summary buffer."
355 (interactive)
356 (let ((pid (get-text-property (point) 'erl-pid)))
357 (if (null pid)
358 (message "No process at point.")
359 (message "Sent EXIT (kill) signal ")
360 (erl-exit 'kill pid))))
362 ;;;; Single process viewer
364 (defun erl-view-process (pid)
365 (let ((buf (get-buffer (erl-process-view-buffer-name pid))))
366 (if buf
367 (select-window (display-buffer buf))
368 (erl-spawn
369 (process-view-mode)
370 (setq erl-old-window-configuration (current-window-configuration))
371 (setq erl-viewed-pid pid)
372 (erl-send-rpc (erl-pid-node pid)
373 'distel 'process_summary_and_trace (list erl-self pid))
374 (erl-receive (pid)
375 ((['rex ['error reason]]
376 (message "%s" reason))
377 (['rex ['badrpc reason]]
378 (message "Bad RPC: %s" reason))
379 (['rex summary]
380 (rename-buffer (erl-process-view-buffer-name pid))
381 (erase-buffer)
382 (insert summary)
383 (setq buffer-read-only t)
384 (goto-char (point-min))
385 (select-window (display-buffer (current-buffer)))
386 (&erl-process-trace-loop))
387 (other
388 (message "Unexpected reply: %S" other))))))))
390 (defun erl-process-view-buffer-name (pid)
391 (format "*pinfo %S on %S*"
392 (erl-pid-id pid) (erl-pid-node pid)))
394 (defvar process-view-mode-map nil
395 "Keymap for Process View mode.")
397 (unless process-view-mode-map
398 (setq process-view-mode-map (make-sparse-keymap))
399 (define-key process-view-mode-map [?q] 'erl-quit-viewer))
401 (defun process-view-mode ()
402 "Major mode for viewing an Erlang process."
403 (interactive)
404 (kill-all-local-variables)
405 (use-local-map process-view-mode-map)
406 (setq mode-name "Process View")
407 (setq major-mode 'process-view)
408 (run-hooks 'process-view-mode-hook))
410 (defun &erl-process-trace-loop ()
411 (erl-receive ()
412 ((['trace_msg text]
413 (goto-char (point-max))
414 (let ((buffer-read-only nil))
415 (insert text))))
416 (&erl-process-trace-loop)))
418 ;;;; fprof
420 (defvar fprof-entries nil
421 "Alist of Tag -> Properties.
422 Tag is a symbol like foo:bar/2
423 Properties is an alist of:
424 'text -> String
425 'callers -> list of Tag
426 'callees -> list of Tag
427 'beamfile -> String | undefined")
429 (defvar fprof-header nil
430 "Header listing for fprof text entries.
431 This is received from the Erlang module.")
433 (defun fprof (node expr)
434 "Profile a function and summarise the results."
435 (interactive (list (erl-target-node)
436 (erl-add-terminator (read-string "Expression: "))))
437 (erl-spawn
438 (erl-send-rpc node 'distel 'fprof (list expr))
439 (fprof-receive-analysis)))
441 (defun fprof-analyse (node filename)
442 "View an existing profiler analysis from a file."
443 (interactive (list (erl-target-node)
444 (read-string "Filename: ")))
445 (erl-spawn
446 (erl-send-rpc node 'distel 'fprof_analyse (list filename))
447 (fprof-receive-analysis)))
449 (defun fprof-receive-analysis ()
450 (message "Waiting for fprof reply...")
451 (erl-receive ()
452 ((['rex ['ok preamble header entries]]
453 (message "Got fprof reply, drawing...")
454 (fprof-display preamble header entries))
455 (other (message "Unexpected reply: %S" other)))))
458 (defun fprof-display (preamble header entries)
459 "Display profiler results in the *fprof* buffer."
460 (setq fprof-entries '())
461 (setq fprof-header header)
462 (with-current-buffer (get-buffer-create "*fprof*")
463 (use-local-map (make-sparse-keymap))
464 (define-key (current-local-map) [return] 'fprof-show-detail)
465 (define-key (current-local-map) [(control m)] 'fprof-show-detail)
466 (define-key (current-local-map) [?f] 'fprof-find-source)
467 (define-key (current-local-map) [?q] 'kill-this-buffer)
468 (setq tab-width 10)
469 (erase-buffer)
470 (insert preamble)
471 (insert fprof-header)
472 (mapc #'fprof-add-entry entries)
473 (goto-char (point-min))
474 (select-window (display-buffer (current-buffer)))))
476 (defun fprof-add-entry (entry)
477 "Add a profiled function entry."
478 (mcase entry
479 (['process title info-list]
480 (insert "\n")
481 (insert title "\n")
482 (dolist (info info-list)
483 (insert " " info "\n"))
484 (insert "\n"))
485 (['tracepoint tag mfa text callers callees beamfile]
486 (push `(,tag . ((text . ,text)
487 (mfa . ,mfa)
488 (callers . ,callers)
489 (callees . ,callees)
490 (beamfile . ,beamfile)))
491 fprof-entries)
492 (fprof-insert text tag))))
494 (defun fprof-insert (text tag)
495 (put-text-property 0 (length text) 'fprof-tag tag text)
496 (insert text))
498 (defun fprof-show-detail ()
499 "Show more detail about the profiled function at point.
500 The extra detail is a list of callers and callees, showing how much
501 time the function spent while called from each caller, and how much
502 time it spent in subfunctions."
503 (interactive)
504 (let* ((tag (fprof-tag-at-point))
505 (props (cdr (assq tag fprof-entries)))
506 (text (cdr (assq 'text props)))
507 (callers (cdr (assq 'callers props)))
508 (callees (cdr (assq 'callees props)))
509 (buf (get-buffer-create "*fprof detail*")))
510 (with-current-buffer buf
511 (erase-buffer)
512 (insert fprof-header)
513 (insert text "\n")
514 (insert "Callers:\n")
515 (mapc #'fprof-insert-by-tag callers)
516 (insert "\n")
517 (insert "Callees:\n")
518 (mapc #'fprof-insert-by-tag callees)
519 (goto-char (point-min)))
520 (display-buffer buf)))
522 (defun fprof-insert-by-tag (tag)
523 (let ((text (fprof-lookup tag 'text)))
524 (put-text-property 0 (length text) 'fprof-tag tag text)
525 (insert text)))
527 (defun fprof-find-source ()
528 (interactive)
529 (let ((beamfile (fprof-lookup (fprof-tag-at-point) 'beamfile)))
530 (if (eq beamfile 'undefined)
531 (message "Don't know where that's implemented.")
532 (let* ((src (fprof-sourcefile beamfile))
533 (mfa (fprof-lookup (fprof-tag-at-point) 'mfa))
534 (arity (caddr mfa))
535 (orig-window (selected-window)))
536 (when src
537 (with-current-buffer (find-file-other-window src)
538 (goto-char (point-min))
539 ;; Find the right function/arity
540 (let (found)
541 (while (and (not found)
542 (re-search-forward (concat "^" (symbol-name (cadr mfa)))))
543 (beginning-of-line)
544 (if (eq (erlang-get-function-arity) arity)
545 (setq found t)
546 (forward-line)))
547 (if found
548 (recenter 5))))
549 (select-window orig-window))))))
551 (defun fprof-tag-at-point ()
552 (or (get-text-property (point) 'fprof-tag)
553 (error "No function tag at point.")))
555 (defun fprof-lookup (tag property)
556 (cdr (assq property (cdr (assq tag fprof-entries)))))
558 (defun fprof-sourcefile (beamfile)
559 (let ((string beamfile))
560 (when (string-match "ebin" string)
561 (setq string (replace-match "src" t t string)))
562 (if (null (string-match "beam" string))
564 (setq string (replace-match "erl" t t string))
565 (if (file-exists-p string)
566 string
567 nil))))
571 (defun erl-eval-expression (node string)
572 (interactive (list (erl-target-node)
573 (erl-add-terminator (read-string "Expression: "))))
574 (erl-spawn
575 (erl-send-rpc node
576 'distel
577 'eval_expression
578 (list string))
579 (erl-receive ()
580 ((['rex ['ok string]]
581 (display-message-or-view string "*Expression Result*"))
582 (['rex ['error reason]]
583 (message "Error: %S" reason))
584 (other
585 (message "Unexpected: %S" other))))))
587 (defun erl-add-terminator (s)
588 "Make sure S terminates with a dot (.)"
589 (if (string-match "\\.\\s *$" s)
591 (concat s ".")))
593 (defun erl-reload-modules (node)
594 "reload all out-of-date modules"
595 (interactive (list (erl-target-node)))
596 (erl-rpc (lambda (result) (message "load: %s" result)) nil
597 node 'distel 'reload_modules ()))
600 (defvar erl-reload-dwim nil
601 "Do What I Mean when reloading beam files. If erl-reload-dwim is non-nil,
602 and the module cannot be found in the load path, we attempt to find the correct
603 directory, add it to the load path and retry the load.
604 We also don't prompt for the module name.")
606 (defun erl-reload-module (node module)
607 "Reload a module."
608 (interactive (list (erl-target-node)
609 (if erl-reload-dwim
610 (erlang-get-module)
611 (let* ((module (erlang-get-module))
612 (prompt (if module
613 (format "Module (default %s): " module)
614 "Module: ")))
615 (intern (read-string prompt nil nil module))))))
616 (if (and (eq node edb-monitor-node)
617 (assq module edb-interpreted-modules))
618 (erl-reinterpret-module node module)
619 ;; (erl-eval-expression node (format "c:l('%s')." module))))
620 (erl-do-reload node module)))
622 (defun erl-do-reload (node module)
623 (let ((fname (if erl-reload-dwim (buffer-file-name) nil)))
624 (erl-rpc (lambda (result) (message "load: %s" result)) nil
625 node 'distel 'reload_module (list module fname))))
627 (defun erl-reinterpret-module (node module)
628 ;; int:i(SourcePath).
629 (erl-send-rpc node
630 'int 'i (list (cadr (assq module edb-interpreted-modules)))))
632 ;;;; Definition finding
634 (defvar erl-find-history-ring (make-ring 20)
635 "History ring tracing for following functions to their definitions.")
637 (defun erl-find-source-under-point ()
638 "Goto the source code that defines the function being called at point.
639 For remote calls, contacts an Erlang node to determine which file to
640 look in, with the following algorithm:
642 Find the directory of the module's beam file (loading it if necessary).
643 Look for the source file in:
644 Same directory as the beam file
645 Again with /ebin/ replaced with /src/
646 Again with /ebin/ replaced with /erl/
647 Directory where source file was originally compiled
649 Otherwise, report that the file can't be found.
651 When `distel-tags-compliant' is non-nil, or a numeric prefix argument
652 is given, the user is prompted for the function to lookup (with a
653 default.)"
654 (interactive)
655 (apply #'erl-find-source
656 (or (erl-read-call-mfa) (error "No call at point."))))
658 (defun erl-find-mod (modstr)
659 "goto source code of mfa. mfa can be m, m:f or m:f/a.
660 Similar to erl-find-source-under-point, but prompts user for mfa."
661 (interactive (list (read-string "Module: ")))
662 (let* ((mcolon (split-string modstr ":"))
663 (mslash (case (length mcolon)
664 (1 nil)
665 (2 (split-string (cadr mcolon) "/"))))
666 (mod (car mcolon))
667 (fun (if mslash
668 (car mslash)
669 nil))
670 (ari (if (eq 2 (length mslash))
671 (string-to-number (cadr mslash))
672 nil)))
673 (apply #'erl-find-source (list mod fun ari))))
675 (defun erl-find-source-unwind ()
676 "Unwind back from uses of `erl-find-source-under-point'."
677 (interactive)
678 (unless (ring-empty-p erl-find-history-ring)
679 (let* ((marker (ring-remove erl-find-history-ring))
680 (buffer (marker-buffer marker)))
681 (if (buffer-live-p buffer)
682 (progn (switch-to-buffer buffer)
683 (goto-char (marker-position marker)))
684 ;; If this buffer was deleted, recurse to try the next one
685 (erl-find-source-unwind)))))
687 (defun erl-goto-end-of-call-name ()
688 "Go to the end of the function or module:function at point."
689 ;; We basically just want to do forward-sexp iff we're not already
690 ;; in the right place
691 (unless (or (member (char-before) '(? ?\t ?\n))
692 (and (not (eobp))
693 (member (char-syntax (char-after (point))) '(?w ?_))))
694 (backward-sexp))
695 (forward-sexp)
696 ;; Special case handling: On some emacs installations (Tobbe's
697 ;; machine), the (forward-sexp) won't skip over the : in a remote
698 ;; function call. This is a workaround for that. The issue seems to
699 ;; be that the emacs considers : to be punctuation (syntax class
700 ;; '.'), whereas my emacs calls it a symbol separator (syntax class
701 ;; '_'). FIXME.
702 (when (eq (char-after) ?:)
703 (forward-sexp)))
705 (defun erl-find-source (module &optional function arity)
706 "Find the source code for MODULE in a buffer, loading it if necessary.
707 When FUNCTION is specified, the point is moved to its start."
708 ;; Add us to the history list
709 (ring-insert-at-beginning erl-find-history-ring
710 (copy-marker (point-marker)))
711 (if (equal module (erlang-get-module))
712 (when function
713 (erl-search-function function arity))
714 (let ((node (erl-target-node)))
715 (erl-spawn
716 (erl-send-rpc node 'distel 'find_source (list (intern module)))
717 (erl-receive (function arity)
718 ((['rex ['ok path]]
719 (find-file path)
720 (when function
721 (erl-search-function function arity)))
722 (['rex ['error reason]]
723 ;; Remove the history marker, since we didn't go anywhere
724 (ring-remove erl-find-history-ring)
725 (message "Error: %s" reason))))))))
727 (defun erl-search-function (function arity)
728 "Goto the definition of FUNCTION/ARITY in the current buffer."
729 (let ((origin (point))
730 (str (concat "\n" function "("))
731 (searching t))
732 (goto-char (point-min))
733 (while searching
734 (cond ((search-forward str nil t)
735 (backward-char)
736 (when (or (null arity)
737 (eq (erl-arity-at-point) arity))
738 (beginning-of-line)
739 (setq searching nil)))
741 (setq searching nil)
742 (goto-char origin)
743 (if arity
744 (message "Couldn't find function %S/%S" function arity)
745 (message "Couldn't find function %S" function)))))))
747 (defun erl-read-symbol-or-nil (prompt)
748 "Read a symbol, or NIL on empty input."
749 (let ((s (read-string prompt)))
750 (if (string= s "")
752 (intern s))))
754 ;;;; Completion
756 (defun erl-complete (node)
757 "Complete the module or remote function name at point."
758 (interactive (list (erl-target-node)))
759 (let ((end (point))
760 (beg (ignore-errors
761 (save-excursion (backward-sexp 1)
762 ;; FIXME: see erl-goto-end-of-call-name
763 (when (eql (char-before) ?:)
764 (backward-sexp 1))
765 (point)))))
766 (when beg
767 (let* ((str (buffer-substring-no-properties beg end))
768 (buf (current-buffer))
769 (continuing (equal last-command (cons 'erl-complete str))))
770 (setq this-command (cons 'erl-complete str))
771 (if (string-match "^\\(.*\\):\\(.*\\)$" str)
772 ;; completing function in module:function
773 (let ((mod (intern (match-string 1 str)))
774 (pref (match-string 2 str))
775 (beg (+ beg (match-beginning 2))))
776 (erl-spawn
777 (erl-send-rpc node 'distel 'functions (list mod pref))
778 (&erl-receive-completions "function" beg end pref buf
779 continuing
780 #'erl-complete-sole-function)))
781 ;; completing just a module
782 (erl-spawn
783 (erl-send-rpc node 'distel 'modules (list str))
784 (&erl-receive-completions "module" beg end str buf continuing
785 #'erl-complete-sole-module)))))))
787 (defun &erl-receive-completions (what beg end prefix buf continuing sole)
788 (let ((state (erl-async-state buf)))
789 (erl-receive (what state beg end prefix buf continuing sole)
790 ((['rex ['ok completions]]
791 (when (equal state (erl-async-state buf))
792 (with-current-buffer buf
793 (erl-complete-thing what continuing beg end prefix
794 completions sole))))
795 (['rex ['error reason]]
796 (message "Error: %s" reason))
797 (other
798 (message "Unexpected reply: %S" other))))))
800 (defun erl-async-state (buffer)
801 "Return an opaque state for BUFFER.
802 This is for making asynchronous operations: if the state when we get a
803 reply is not equal to the state when we started, then the user has
804 done something - modified the buffer, or moved the point - so we may
805 want to cancel the operation."
806 (with-current-buffer buffer
807 (cons (buffer-modified-tick)
808 (point))))
810 (defun erl-complete-thing (what scrollable beg end pattern completions sole)
811 "Complete a string in the buffer.
812 WHAT is a string that says what we're completing.
813 SCROLLABLE is a flag saying whether this is a repeated command that
814 may scroll the completion list.
815 BEG and END are the buffer positions around what we're completing.
816 PATTERN is the string to complete from.
817 COMPLETIONS is a list of potential completions (strings.)
818 SOLE is a function which is called when a single completion is selected."
819 ;; This function, and `erl-maybe-scroll-completions', are basically
820 ;; cut and paste programming from `lisp-complete-symbol'. The fancy
821 ;; Emacs completion packages (hippie and pcomplete) looked too
822 ;; scary.
823 (or (and scrollable (erl-maybe-scroll-completions))
824 (let* ((completions (erl-make-completion-alist completions))
825 (completion (try-completion pattern completions)))
826 (cond ((eq completion t)
827 (message "Sole completion")
828 (apply sole '()))
829 ((null completion))
830 ; (message "Can't find completion for %s \"%s\"" what pattern)
831 ; (ding))
832 ((not (string= pattern completion))
833 (delete-region beg end)
834 (insert completion)
835 (if (eq t (try-completion completion completions))
836 (apply sole '())))
838 (message "Making completion list...")
839 (let ((list (all-completions pattern completions)))
840 (setq list (sort list 'string<))
841 (with-output-to-temp-buffer "*Completions*"
842 (display-completion-list list)))
843 (message "Making completion list...%s" "done"))))))
845 (defun erl-complete-sole-module ()
846 (insert ":"))
848 (defun erl-complete-sole-function ()
849 (let ((call (erlang-get-function-under-point)))
850 (insert "(")
851 (erl-print-arglist call (erl-target-node))))
854 (defun erl-make-completion-alist (list)
855 "Make an alist out of list.
856 The same elements go in the CAR, and nil in the CDR. To support the
857 apparently very stupid `try-completions' interface, that wants an
858 alist but ignores CDRs."
859 (mapcar (lambda (x) (cons x nil)) list))
861 (defun erl-maybe-scroll-completions ()
862 "Scroll the completions buffer if it is visible.
863 Returns non-nil iff the window was scrolled."
864 (let ((window (get-buffer-window "*Completions*")))
865 (when (and window (window-live-p window) (window-buffer window)
866 (buffer-name (window-buffer window)))
867 ;; If this command was repeated, and
868 ;; there's a fresh completion window with a live buffer,
869 ;; and this command is repeated, scroll that window.
870 (with-current-buffer (window-buffer window)
871 (if (pos-visible-in-window-p (point-max) window)
872 (set-window-start window (point-min))
873 (save-selected-window
874 (select-window window)
875 (scroll-up))))
876 t)))
878 ;;;; Refactoring
880 (defun erl-refactor-subfunction (node name start end)
881 "Refactor the expression(s) in the region as a function.
883 The expressions are replaced with a call to the new function, and the
884 function itself is placed on the kill ring for manual placement. The
885 new function's argument list includes all variables that become free
886 during refactoring - that is, the local variables needed from the
887 original function.
889 New bindings created by the refactored expressions are *not* exported
890 back to the original function. Thus this is not a \"pure\"
891 refactoring.
893 This command requires Erlang syntax_tools package to be available in
894 the node, version 1.2 (or perhaps later.)"
895 (interactive (list (erl-target-node)
896 (read-string "Function name: ")
897 (region-beginning)
898 (region-end)))
899 ;; Skip forward over whitespace
900 (setq start (save-excursion
901 (goto-char start)
902 (skip-chars-forward " \t\r\n")
903 (point)))
904 ;; Skip backwards over trailing syntax
905 (setq end (save-excursion
906 (goto-char end)
907 (skip-chars-backward ". ,;\r\n\t")
908 (point)))
909 (let ((buffer (current-buffer))
910 (text (erl-refactor-strip-macros
911 (buffer-substring-no-properties start end))))
912 (erl-spawn
913 (erl-send-rpc node 'distel 'free_vars (list text))
914 (erl-receive (name start end buffer text)
915 ((['rex ['badrpc rsn]]
916 (message "Refactor failed: %S" rsn))
917 (['rex ['error rsn]]
918 (message "Refactor failed: %s" rsn))
919 (['rex ['ok free-vars]]
920 (with-current-buffer buffer
921 (let ((arglist
922 (concat "(" (mapconcat 'symbol-name free-vars ", ") ")"))
923 (body
924 (buffer-substring-no-properties start end)))
925 ;; rewrite the original as a call
926 (delete-region start end)
927 (goto-char start)
928 (insert (format "%s%s" name arglist))
929 (indent-according-to-mode)
930 ;; Now generate the function and stick it on the kill ring
931 (kill-new (with-temp-buffer
932 (insert (format "%s%s ->\n%s.\n" name arglist body))
933 (erlang-mode)
934 (indent-region (point-min) (point-max) nil)
935 (buffer-string)))
936 (message "Saved `%s' definition on kill ring." name)))))))))
938 (defun erl-refactor-strip-macros (text)
939 "Removed all use of macros in TEXT.
940 We do this by making a bogus expansion of each macro, such that the
941 expanded code should probably still have the right set of free
942 variables."
943 (with-temp-buffer
944 (save-excursion (insert text))
945 (while (re-search-forward "\\?[A-Za-z_]+" nil t)
946 (replace-match "deadmacro" t))
947 (buffer-string)))
949 ;;;; fdoc interface
951 (defface erl-fdoc-name-face
952 '((t (:bold t)))
953 "Face for function names in `fdoc' results."
954 :group 'distel)
956 (defun erl-fdoc-apropos (node regexp rebuild-db)
957 (interactive (list (erl-target-node)
958 (read-string "Regexp: ")
959 current-prefix-arg))
960 (unless (string= regexp "")
961 (erl-spawn
962 (erl-send-rpc node 'distel 'apropos (list regexp
963 (if rebuild-db 'true 'false)))
964 (message "Sent request; waiting for results..")
965 (erl-receive ()
966 ((['rex ['ok matches]]
967 (erl-show-fdoc-matches matches))
968 (['rex ['badrpc rsn]]
969 (message "fdoc RPC failed: %S" rsn))
970 (other
971 (message "fdoc unexpected result: %S" other)))))))
973 (defun erl-show-fdoc-matches (matches)
974 "Show MATCHES from fdoc. Each match is [MOD FUNC ARITY DOC]."
975 (if (null matches)
976 (message "No matches.")
977 (display-message-or-view
978 (with-temp-buffer
979 (dolist (match matches)
980 (mlet [mod func arity doc] match
981 (let ((entry (format "%s:%s/%s" mod func arity)))
982 (put-text-property 0 (length entry)
983 'face 'erl-fdoc-name-face
984 entry)
985 (insert entry ":\n"))
986 (let ((start (point)))
987 (insert doc)
988 (indent-rigidly start (point) 2)
989 (insert "\n"))))
990 (buffer-string))
991 "*Erlang fdoc results*")))
993 (defvar erl-module-function-arity-regexp
994 ;; Nasty scary not-really-correct stuff.. now I know how perl guys feel
995 (let* ((module-re "[^:]*")
996 (fun-re "[^/]*")
997 (arity-re "[0-9]*")
998 (the-module (format "\\(%s\\)" module-re))
999 (maybe-arity (format "\\(/\\(%s\\)\\)?" arity-re))
1000 (maybe-fun-and-maybe-arity
1001 (format "\\(:\\(%s\\)%s\\)?" fun-re maybe-arity)))
1002 (concat "^" the-module maybe-fun-and-maybe-arity "$"))
1003 "Regexp matching \"module[:function[/arity]]\".
1004 The match positions are erl-mfa-regexp-{module,function,arity}-match.")
1006 (defvar erl-mfa-regexp-module-match 1)
1007 (defvar erl-mfa-regexp-function-match 3)
1008 (defvar erl-mfa-regexp-arity-match 5)
1010 (defun erl-fdoc-describe (node rebuild-db)
1011 (interactive
1012 (list (erl-target-node)
1013 current-prefix-arg))
1014 (let* ((mfa (erl-read-call-mfa))
1015 (defaultstr (if (null mfa)
1017 (concat (if (first mfa) (format "%s:" (first mfa)) "")
1018 (if (second mfa) (format "%s" (second mfa)) "")
1019 (if (third mfa) (format "/%S" (third mfa))))))
1020 (prompt (format "M[:F[/A]]: %s"
1021 (if defaultstr
1022 (format "(default %s) " defaultstr)
1023 "")))
1024 (mfastr (read-string prompt nil nil defaultstr)))
1025 (if (not (string-match erl-module-function-arity-regexp mfastr))
1026 (error "Bad input.")
1027 (let ((mod (match-string erl-mfa-regexp-module-match mfastr))
1028 (fun (ignore-errors (match-string erl-mfa-regexp-function-match mfastr)))
1029 (arity (ignore-errors (match-string erl-mfa-regexp-arity-match mfastr))))
1030 (if (string= mod "")
1031 (error "Bad spec -- which module?")
1032 (erl-spawn
1033 (erl-send-rpc node 'distel 'describe
1034 (list (intern mod)
1035 (if fun (intern fun) '_)
1036 (if arity (string-to-int arity) '_)
1037 (if rebuild-db 'true 'false)))
1038 (message "Sent request; waiting for results..")
1039 (erl-receive ()
1040 ((['rex ['ok matches]]
1041 (erl-show-fdoc-matches matches))
1042 (['rex ['badrpc rsn]]
1043 (message "fdoc RPC failed: %S" rsn))
1044 (['rex ['error rsn]]
1045 (message "fdoc failed: %S" rsn))
1046 (other
1047 (message "fdoc unexpected result: %S" other))))))))))
1049 ;;;; Argument lists
1051 (defun erl-openparent ()
1052 "Insert a '(' character and arglist."
1053 (interactive)
1054 (let ((call (erlang-get-function-under-point)))
1055 (erl-print-arglist call erl-nodename-cache (current-buffer))))
1057 (defun erl-openparen (node)
1058 "Insert a '(' character and show arglist information."
1059 (interactive (list erl-nodename-cache))
1060 (let ((call (erlang-get-function-under-point)))
1061 (insert "(")
1062 (erl-print-arglist call node)))
1064 (defun erl-print-arglist (call node &optional ins-buffer)
1065 (when (and node (member node erl-nodes))
1066 ;; Don't print arglists when we're defining a function (when the
1067 ;; "call" is at the start of the line)
1068 (unless (save-excursion
1069 (skip-chars-backward "a-zA-Z0-9_:'(")
1070 (bolp))
1071 (let* ((call-mod (car call))
1072 (mod (or call-mod (erlang-get-module)))
1073 (fun (cadr call)))
1074 (when fun
1075 (erl-spawn
1076 (erl-send-rpc node 'distel 'get_arglists
1077 (list mod fun))
1078 (erl-receive (call-mod fun ins-buffer)
1079 ((['rex 'error])
1080 (['rex arglists]
1081 (let ((argss (erl-format-arglists arglists)))
1082 (if ins-buffer
1083 (with-current-buffer ins-buffer (insert argss))
1084 (message "%s:%s%s" call-mod fun argss))))))))))))
1086 (defun erl-format-arglists (arglists)
1087 (setq arglists (sort* arglists '< :key 'length))
1088 (format "%s"
1089 (mapconcat 'identity
1090 (mapcar (lambda (arglist)
1091 (format "(%s)"
1092 (mapconcat 'identity arglist ", ")))
1093 arglists)
1094 " | ")))
1096 ;;;; Cross-reference
1098 (defun erl-who-calls (node)
1099 (interactive (list (erl-target-node)))
1100 (apply #'erl-find-callers
1101 (or (erl-read-call-mfa) (error "No call at point."))))
1103 (defun erl-find-callers (mod fun arity)
1104 (erl-spawn
1105 (erl-send-rpc (erl-target-node) 'distel 'who_calls
1106 (list (intern mod) (intern fun) arity))
1107 (message "Request sent..")
1108 (erl-receive ()
1109 ((['rex calls]
1110 (with-current-buffer (get-buffer-create "*Erlang Calls*")
1111 (setq buffer-read-only t)
1112 (let ((inhibit-read-only t))
1113 (erlang-mode)
1114 (erase-buffer)
1115 (dolist (call calls)
1116 (mlet [m f a _line] call
1117 ;; FIXME: Use line number for a hyperlink.
1118 (insert (format "%s:%s/%S\n" m f a)))))
1119 (goto-char (point-min))
1120 (message "")
1121 (pop-to-buffer (current-buffer))))))))
1123 (provide 'erl-service)