1 ;;; erl-service.el --- High-level calls to Erlang services.
5 ;; This module implements Emacs commands - i.e. M-x'able key-bind'able
6 ;; sort - for doing stuff with Erlang nodes.
8 ;; The general implementation strategy is to make RPCs to the "distel"
9 ;; erlang module, which does most of the work for us.
12 (eval-when-compile (require 'cl
))
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."
31 (let* ((name-string (read-string "Node: "))
32 (name (intern (if (string-match "@" name-string
)
35 "@" (erl-determine-hostname))))))
36 (setq erl-nodename-cache name
)
37 (setq distel-modeline-node name-string
)
38 (force-mode-line-update))
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
47 (interactive) ; for testing
48 (let* ((mfa-at-point (erl-mfa-at-point))
49 (mfa (if (or (null mfa-at-point
)
51 distel-tags-compliant
)
52 (erl-parse-mfa (read-string "Function reference: "
53 (erl-format-mfa mfa-at-point
)))
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."
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)))
69 (with-syntax-table erlang-mode-syntax-table
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."
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)))
83 (erl-goto-end-of-call-name)
84 (let ((arity (erl-arity-at-point))
85 (mf (erlang-get-function-under-point)))
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.
97 (cond ((looking-at "/")
98 ;; form is /<n>, like the /2 in foo:bar/2
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))
112 ((looking-at "\\s *)")
114 ((looking-at "\\s *\\($\\|%\\)")
116 ((looking-at "\\s *,")
118 (goto-char (match-end 0)))
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
133 (unless distel-inhibit-backend-check
135 (erl-send `[rex
,node
]
137 code ensure_loaded
(distel)
138 ,(erl-group-leader)]])
141 (with-current-buffer (get-buffer-create "*Distel Warning*")
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.
162 (display-buffer (current-buffer))))
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
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:
179 On an error, Result will be [badrpc Reason]."
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
))
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
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
))
216 (setq buffer-read-only t
)
217 (let ((buffer-read-only nil
))
219 (let ((header (tuple-elt reply
1))
220 (infos (tuple-elt reply
2)))
221 (put-text-property 0 (length header
) 'face
'bold header
)
223 (mapc #'erl-insert-process-info infos
))
224 (goto-char (point-min))
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
)
236 ;; Process list major mode
238 (defvar erl-viewed-pid nil
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."
249 (let ((cfg erl-old-window-configuration
))
253 (set-window-configuration cfg
)))
255 (defun erl-bury-viewer ()
256 "Bury the current view and restore the old window config."
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.
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."
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."
297 (let ((pid (get-text-property (point) 'erl-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)))
307 (message "No process at point."))
309 (erl-show-process-info))
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*"))
318 (message "Error from erlang side of process_info:\n %S"
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
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
332 (with-current-buffer (get-buffer-create bufname)
333 (setq buffer-read-only t)
334 (let ((inhibit-read-only t))
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,
343 (string-match "[^\r\n]*" msg)
344 (message (match-string 0 msg))))
346 (defun erl-show-process-messages ()
348 (erl-show-process-info-item 'messages))
349 (defun erl-show-process-backtrace ()
351 (erl-show-process-info-item 'backtrace))
353 (defun erl-pman-kill-process ()
354 "Kill process at point in a summary buffer."
356 (let ((pid (get-text-property (point) 'erl-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))))
367 (select-window (display-buffer buf))
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))
375 ((['rex ['error reason]]
376 (message "%s" reason))
377 (['rex ['badrpc reason]]
378 (message "Bad RPC: %s" reason))
380 (rename-buffer (erl-process-view-buffer-name pid))
383 (setq buffer-read-only t)
384 (goto-char (point-min))
385 (select-window (display-buffer (current-buffer)))
386 (&erl-process-trace-loop))
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."
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 ()
413 (goto-char (point-max))
414 (let ((buffer-read-only nil))
416 (&erl-process-trace-loop)))
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:
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: "))))
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: ")))
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...")
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
)
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."
479 (['process title info-list
]
482 (dolist (info info-list
)
483 (insert " " info
"\n"))
485 (['tracepoint tag mfa text callers callees beamfile
]
486 (push `(,tag .
((text .
,text
)
490 (beamfile .
,beamfile
)))
492 (fprof-insert text tag
))))
494 (defun fprof-insert (text tag
)
495 (put-text-property 0 (length text
) 'fprof-tag tag 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."
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
512 (insert fprof-header
)
514 (insert "Callers:\n")
515 (mapc #'fprof-insert-by-tag callers
)
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
)
527 (defun fprof-find-source ()
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
))
535 (orig-window (selected-window)))
537 (with-current-buffer (find-file-other-window src
)
538 (goto-char (point-min))
539 ;; Find the right function/arity
541 (while (and (not found
)
542 (re-search-forward (concat "^" (symbol-name (cadr mfa
)))))
544 (if (eq (erlang-get-function-arity) arity
)
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
)
571 (defun erl-eval-expression (node string
)
572 (interactive (list (erl-target-node)
573 (erl-add-terminator (read-string "Expression: "))))
580 ((['rex
['ok string
]]
581 (display-message-or-view string
"*Expression Result*"))
582 (['rex
['error reason
]]
583 (message "Error: %S" reason
))
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
)
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
)
608 (interactive (list (erl-target-node)
611 (let* ((module (erlang-get-module))
613 (format "Module (default %s): " 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).
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
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
)
665 (2 (split-string (cadr mcolon
) "/"))))
670 (ari (if (eq 2 (length mslash
))
671 (string-to-number (cadr mslash
))
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'."
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))
693 (member (char-syntax (char-after (point))) '(?w ?_
))))
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
702 (when (eq (char-after) ?
:)
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))
713 (erl-search-function function arity
))
714 (let ((node (erl-target-node)))
716 (erl-send-rpc node
'distel
'find_source
(list (intern module
)))
717 (erl-receive (function arity
)
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
"("))
732 (goto-char (point-min))
734 (cond ((search-forward str nil t
)
736 (when (or (null arity
)
737 (eq (erl-arity-at-point) arity
))
739 (setq searching nil
)))
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
)))
756 (defun erl-complete (node)
757 "Complete the module or remote function name at point."
758 (interactive (list (erl-target-node)))
761 (save-excursion (backward-sexp 1)
762 ;; FIXME: see erl-goto-end-of-call-name
763 (when (eql (char-before) ?
:)
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))))
777 (erl-send-rpc node
'distel
'functions
(list mod pref
))
778 (&erl-receive-completions
"function" beg end pref buf
780 #'erl-complete-sole-function
)))
781 ;; completing just a module
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
795 (['rex
['error reason
]]
796 (message "Error: %s" reason
))
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)
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
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")
830 ; (message "Can't find completion for %s \"%s\"" what pattern)
832 ((not (string= pattern completion
))
833 (delete-region beg end
)
835 (if (eq t
(try-completion completion completions
))
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 ()
848 (defun erl-complete-sole-function ()
849 (let ((call (erlang-get-function-under-point)))
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
)
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
889 New bindings created by the refactored expressions are *not* exported
890 back to the original function. Thus this is not a \"pure\"
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: ")
899 ;; Skip forward over whitespace
900 (setq start
(save-excursion
902 (skip-chars-forward " \t\r\n")
904 ;; Skip backwards over trailing syntax
905 (setq end
(save-excursion
907 (skip-chars-backward ". ,;\r\n\t")
909 (let ((buffer (current-buffer))
910 (text (erl-refactor-strip-macros
911 (buffer-substring-no-properties start end
))))
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
))
918 (message "Refactor failed: %s" rsn
))
919 (['rex
['ok free-vars
]]
920 (with-current-buffer buffer
922 (concat "(" (mapconcat 'symbol-name free-vars
", ") ")"))
924 (buffer-substring-no-properties start end
)))
925 ;; rewrite the original as a call
926 (delete-region start end
)
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
))
934 (indent-region (point-min) (point-max) nil
)
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
944 (save-excursion (insert text
))
945 (while (re-search-forward "\\?[A-Za-z_]+" nil t
)
946 (replace-match "deadmacro" t
))
951 (defface erl-fdoc-name-face
953 "Face for function names in `fdoc' results."
956 (defun erl-fdoc-apropos (node regexp rebuild-db
)
957 (interactive (list (erl-target-node)
958 (read-string "Regexp: ")
960 (unless (string= regexp
"")
962 (erl-send-rpc node
'distel
'apropos
(list regexp
963 (if rebuild-db
'true
'false
)))
964 (message "Sent request; waiting for results..")
966 ((['rex
['ok matches
]]
967 (erl-show-fdoc-matches matches
))
968 (['rex
['badrpc rsn
]]
969 (message "fdoc RPC failed: %S" rsn
))
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]."
976 (message "No matches.")
977 (display-message-or-view
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
985 (insert entry
":\n"))
986 (let ((start (point)))
988 (indent-rigidly start
(point) 2)
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 "[^:]*")
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
)
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"
1022 (format "(default %s) " defaultstr
)
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?")
1033 (erl-send-rpc node
'distel
'describe
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..")
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
))
1047 (message "fdoc unexpected result: %S" other
))))))))))
1051 (defun erl-openparent ()
1052 "Insert a '(' character and arglist."
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)))
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_:'(")
1071 (let* ((call-mod (car call
))
1072 (mod (or call-mod
(erlang-get-module)))
1076 (erl-send-rpc node
'distel
'get_arglists
1078 (erl-receive (call-mod fun ins-buffer
)
1081 (let ((argss (erl-format-arglists arglists
)))
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
))
1089 (mapconcat 'identity
1090 (mapcar (lambda (arglist)
1092 (mapconcat 'identity arglist
", ")))
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
)
1105 (erl-send-rpc (erl-target-node) 'distel
'who_calls
1106 (list (intern mod
) (intern fun
) arity
))
1107 (message "Request sent..")
1110 (with-current-buffer (get-buffer-create "*Erlang Calls*")
1111 (setq buffer-read-only t
)
1112 (let ((inhibit-read-only t
))
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))
1121 (pop-to-buffer (current-buffer))))))))
1123 (provide 'erl-service
)