-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
robe.el
1552 lines (1417 loc) · 58.5 KB
/
robe.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; robe.el --- Code navigation, documentation lookup and completion for Ruby -*- lexical-binding: t -*-
;; Copyright © 2012 Phil Hagelberg
;; Copyright © 2012-2024 Dmitry Gutov
;; Author: Dmitry Gutov
;; URL: https://github.com/dgutov/robe
;; Version: 0.8.6
;; Keywords: ruby convenience rails
;; Package-Requires: ((inf-ruby "2.5.1") (emacs "25.1"))
;; This file is NOT part of GNU Emacs.
;;; Commentary:
;; You can jump to or read the documentation for the method, module (jump only),
;; `super` or constructor definition at point.
;;
;; ElDoc support and constant and method completion are also provided.
;;; Usage
;; (add-hook 'ruby-mode-hook 'robe-mode)
;;
;; OR
;;
;; (global-robe-mode)
;;
;; - M-. to jump to the definition
;; - M-, to jump back
;; - C-c C-d to see the documentation
;; - C-c C-k to refresh Rails environment
;; - C-M-i to complete the symbol at point
;;; License:
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Code:
(require 'inf-ruby)
(require 'etags)
(require 'json)
(require 'url)
(require 'url-http)
(require 'url-handlers)
(require 'cl-lib)
(require 'cl-generic)
(require 'thingatpt)
(require 'eldoc)
(require 'help-mode)
(require 'ruby-mode)
(defgroup robe nil
"Code navigation, documentation lookup and completion for Ruby"
:group 'languages
:group 'convenience)
(defcustom robe-highlight-capf-candidates t
"When non-nil, `completion-at-point' candidates buffer will
have constants, methods and arguments highlighted in color."
:group 'robe
:type 'boolean)
(defvar robe-ruby-path
(let ((current (or load-file-name (buffer-file-name))))
(expand-file-name "lib" (file-name-directory current)))
"Path to the backend Ruby code.")
(defvar-local robe-host "127.0.0.1")
(defvar-local robe-port nil)
(defvar robe-jump-conservative nil)
(defvar-local robe-running nil)
(defvar-local robe-load-path nil)
(defcustom robe-completing-read-func nil
"Function to call for completing reads, to resolve ambiguous names.
nil means to use the global value of `completing-read-function'."
:type '(choice (const :tag "Ido" ido-completing-read)
(const :tag "Default" nil)
(function :tag "Other function"))
:group 'robe)
(defcustom robe-find-file-hook nil
"Normal hook run after visiting a file."
:type 'hook
:group 'robe)
(defcustom robe-rspec-support t
"Non-nil to recognize RSpec/Minitest spec files."
:type 'boolean)
(defcustom robe-show-doc-source 'auto
"Whether to show the method source in the doc buffer.
When other non-nil, it's shown right away.
When nil, the source can be shown by pressing the button.
When auto, the source will be shown when there is no doc."
:type '(choice (const :tag "Hidden by default" nil)
(const :tag "Shown by default" t)
(const :tag "When there is no doc" auto)))
(defun robe-completing-read (&rest args)
(let ((completing-read-function
; 1) allow read-function override
(or robe-completing-read-func
completing-read-function)))
(apply #'completing-read args))) ; 2) allow completing-read override
(defmacro robe-with-inf-buffer (&rest body)
(declare (debug t))
`(let ((buf (robe-inf-buffer)))
(when buf
(with-current-buffer buf
,@body))))
(defun robe-start (&optional force)
"Start Robe server if it isn't already running.
When called with a prefix argument, kills the current Ruby
process, if any, and starts a new console for the current
project."
(interactive "P")
(defvar inf-ruby-interact-with-fromcomp)
(let* ((ruby-buffer (robe-inf-buffer))
(process (get-buffer-process ruby-buffer)))
(when (or force (not process))
(when (buffer-live-p ruby-buffer)
(with-current-buffer ruby-buffer
(setq robe-running nil)))
(when process
(delete-process process))
(if (or force
(yes-or-no-p "No Ruby console running. Launch automatically?"))
(let ((conf (current-window-configuration)))
(when (buffer-live-p ruby-buffer)
(kill-buffer ruby-buffer))
(inf-ruby-console-auto)
(set-window-configuration conf))
(error "Aborted"))))
(when (not (robe-running-p))
(let* ((inf-ruby-interact-with-fromcomp nil)
(proc (inf-ruby-proc))
started failed
(comint-filter (process-filter proc))
(tmp-filter (lambda (p s)
(cond
((string-match "robe on \\([0-9]+\\)" s)
(setq started t)
(with-current-buffer (process-buffer proc)
(setq robe-port (string-to-number
(match-string 1 s)))))
((let (case-fold-search)
(string-match-p "Error\\>" s))
(setq failed t)))
(funcall comint-filter p s)))
(script (format (mapconcat #'identity
`("unless defined? Robe"
" $:.unshift '%s'"
" require 'robe'"
"end"
,(robe-start-call))
";")
robe-ruby-path)))
(unwind-protect
(progn
(set-process-filter proc tmp-filter)
(comint-send-string proc script)
(while (not started)
(unless (process-live-p proc) (setq failed t))
(when failed
(ruby-switch-to-inf t)
(error "Robe launch failed"))
(accept-process-output proc))
(set-process-sentinel proc #'robe-process-sentinel))
(set-process-filter proc comint-filter)))
(when (robe-request "ping") ;; Meaning "no error".
(robe-with-inf-buffer
(setq robe-running t
robe-load-path (mapcar #'file-name-as-directory
(robe-request "load_path")))
(when (file-exists-p ".robe")
(let ((last-pos (point-max)))
(ruby-load-file ".robe")
(accept-process-output (inf-ruby-proc) 0.01)
(when (string-match-p "Error\\>"
(buffer-substring last-pos (point-max)))
(ruby-switch-to-inf t)
(error "Some problem loading .robe")))))
(message "Robe connection established"))))
(defun robe-start-call ()
(let (args)
(when robe-host (push (format "'%s'" robe-host) args))
(push (or robe-port "0") args)
(format "Robe.start(%s)\n" (mapconcat #'identity args ", "))))
(defun robe-inf-buffer ()
;; Using locate-dominating-file in a large directory
;; (such as .rbenv//gems/), or file-in-directory-p for all LOAD_PATH
;; entries, turns out to be too slow.
(let ((dd (expand-file-name default-directory))
(inf-buffers (cl-remove-if-not
(lambda (buf)
(and (buffer-live-p buf)
(get-buffer-process buf)))
inf-ruby-buffers)))
(cond
((null inf-buffers)
nil)
((= 1 (length inf-buffers))
(car inf-buffers))
(t
;; More than one inf-ruby process, let's use the more complex
;; detection logic.
(or
(robe-find-inf-buffer
(lambda ()
(string-prefix-p (expand-file-name default-directory) dd))
inf-buffers)
(robe-find-inf-buffer
(lambda ()
(cl-find dd robe-load-path
:test (lambda (dd path-element)
(string-prefix-p path-element dd))))
inf-buffers))))))
(defun robe-find-inf-buffer (predicate buffers)
(catch 'buffer
(dolist (buffer buffers)
(with-current-buffer buffer
(when (funcall predicate)
(throw 'buffer buffer))))))
(defun robe-running-p ()
(robe-with-inf-buffer
robe-running))
(defun robe-process-sentinel (proc _event)
(when (memq (process-status proc) '(signal exit))
(setq robe-running nil)))
(defun robe-request (endpoint &rest args)
(let* ((base-url (robe-with-inf-buffer
(format "http://%s:%s" robe-host robe-port)))
(url (format "%s/%s/%s" base-url endpoint
(mapconcat (lambda (arg)
(cond ((eq arg t) "yes")
((cl-plusp (length arg))
(url-hexify-string arg))
(t "-")))
args "/")))
(response-buffer (robe-retrieve url)))
(if response-buffer
(prog1
(with-temp-buffer
(url-insert response-buffer)
(goto-char (point-min))
(robe--parse-buffer))
(kill-buffer response-buffer)))))
(defun robe--parse-buffer ()
(cond ((fboundp 'json-parse-buffer)
(json-parse-buffer
:array-type 'list
:object-type 'alist
:null-object nil))
(t
(let ((json-array-type 'list))
(json-read)))))
(defun robe-retrieve (url)
(defvar url-http-response-status)
(let* ((buffer (condition-case nil (url-retrieve-synchronously url t t)
(file-error nil)))
(status (and buffer
(buffer-local-value 'url-http-response-status buffer))))
(cond
((null status)
(robe-with-inf-buffer
(setq robe-running nil))
(error "Server doesn't respond"))
((/= status 500)
buffer)
(t nil))))
(cl-defstruct (robe-spec (:type list)) module inst-p method params file line)
(defun robe-ask ()
"Prompt for module, method, and jump to its definition."
(interactive)
(robe-jump-to (robe-ask-prompt)))
(defun robe-ask-prompt ()
(let* ((modules (robe-request "modules"))
(module (robe-completing-read "Module: " modules))
(targets (robe-request "targets" module))
(_ (unless targets (error "No methods found")))
(alist (robe-decorate-methods (cdr targets))))
(cdr (assoc (robe-completing-read "Method: " alist nil t)
alist))))
(defun robe-decorate-methods (list)
(mapcar (lambda (spec)
(cons (concat (if (robe-spec-inst-p spec) "#" ".")
(robe-spec-method spec))
spec))
list))
(defun robe-const-p (thing)
(let (case-fold-search) (string-match "\\`\\([A-Z]\\|::\\)" thing)))
;; TODO: Mark as obsolete.
(defun robe-jump (arg)
"Jump to the identifier at point, prompt for module or file if necessary.
Identifier can be a constant, or a variable, or a method call.
If invoked with a prefix or no symbol at point, delegate to `robe-ask'."
(interactive "P")
(let ((thing (robe--jump-thing)))
(cond
((or (not thing) arg)
(robe-start)
(robe-ask))
((robe-const-p thing)
(robe-start)
(robe-jump-to-module thing))
((robe--jump-to-var thing))
(t
(robe-start)
(robe-jump-to (robe-jump-prompt thing))))))
(defun robe--jump-to-var (thing)
(let ((call-context (robe-call-context)))
(unless (or (nth 0 call-context)
(save-excursion
(goto-char (cdr (robe-complete-bounds)))
(looking-at " *(")))
(robe--jump-to-var-1 thing (nth 3 call-context)))))
(defun robe--jump-to-var-1 (thing context)
(let* ((vars (robe-complete--variables (nth 1 context) (nth 2 context)))
(var (cl-member-if (lambda (v) (equal thing (robe--variable-name v)))
vars)))
(when var
(xref-push-marker-stack)
(goto-char (robe--variable-position (car var))))))
(defun robe--jump-thing ()
(let* ((bounds (robe-complete-bounds))
(thing
(when (not (eq (car bounds) (cdr bounds)))
(buffer-substring (car bounds) (cdr bounds)))))
(if (and thing
(save-excursion
(goto-char (car bounds))
(forward-comment (- (point)))
(eq (preceding-char) ?.))
(save-excursion
(goto-char (cdr bounds))
(looking-at " *=[^=]")))
(concat thing "=")
thing)))
(defun robe-jump-prompt (thing)
(let* ((alist (robe-decorate-modules (robe-jump-modules thing
(robe-call-context)))))
(unless alist (error "Method not found"))
(if (= 1 (length alist))
(cdar alist)
(cdr (assoc (robe-completing-read "Module: " alist nil t)
alist)))))
(defun robe-jump-modules (thing context)
(cl-destructuring-bind (target module instance ctx _vars) context
(let (super)
(unless target
(when (string= thing "super")
(setq thing (nth 2 ctx)
super t)))
(robe-request "method_targets"
thing target module instance super
robe-jump-conservative))))
(defun robe-call-context ()
(let* ((ctx (robe-context))
(in-instance-def (nth 1 ctx))
(variables (robe-complete--variables in-instance-def (nth 2 ctx)))
(target (save-excursion
(and (progn (ignore-errors (beginning-of-thing 'symbol))
(eq ?. (char-before)))
(progn (forward-char -1)
(skip-chars-backward " \n\r\t")
(or
(let ((type (robe-call-target-type)))
(if type (cons t type)))
(let ((thing (robe--jump-thing))
var)
(if (setq var (cl-find-if
(lambda (var)
(and
(robe--variable-type var)
(equal (robe--variable-name var)
thing)))
variables))
(cons t (robe--variable-type var))
thing))
"!")))))
(module (car ctx))
(_ (when (equal target "self") (setq target nil)))
(instance (unless target in-instance-def)))
(when (eq (car-safe target) t)
(setq target (cdr target)
instance t))
(when (and module (not target) (not in-instance-def) (robe-context-self-unknown-p))
(setq module nil))
(list target module instance ctx variables)))
(defun robe-context-self-unknown-p ()
;; Heuristic to find out whether we are inside some DSL-style block,
;; where it's popular to change the value of 'self' to something
;; more convenient, but impossible to determine statically.
;; Assume being outside of any method definitions (that check is
;; performed by the caller).
(save-excursion
(let ((start (point))
(re (rx (or (sequence line-start (* (in " \t"))
(group
(or "def" "module" "class"))
symbol-end)
(sequence (or (syntax ?w) (syntax ?_) (syntax ?\))
(syntax ?\") (syntax ?|))
(+ (in " \t"))
(group
(or
(sequence "do" symbol-end)
?\{))))))
res)
(while (and (not res)
(re-search-backward re nil 'move))
(when (robe--not-in-string-or-comment)
(cond
((match-beginning 1)
(setq res 'def))
((save-excursion
(goto-char (match-beginning 2))
(ignore-errors (forward-sexp))
(>= (point) start))
(setq res 'block)))))
(eq res 'block))))
(defun robe-call-target-type ()
(save-excursion
(let (forward-sexp-function)
(cond
((and (eq (char-before) ?\])
(save-excursion
(backward-sexp)
(or (looking-at-p "%[wWiI]")
(robe--beginning-of-expr-p))))
"Array")
;; FIXME: Handle percent literals better, e.g. %w().
((nth 3 (parse-partial-sexp (1- (point)) (point)))
"String")
((and (eq (char-before) ?\})
(save-excursion
(backward-sexp)
(robe--beginning-of-expr-p)))
"Hash")
((and (progn
(when (eq (char-before) ?\))
(backward-sexp))
(equal (thing-at-point 'symbol) "new"))
(progn
(skip-syntax-backward "w_")
(skip-chars-backward " \n\r\t")
(eq ?. (char-before)))
(progn
(forward-char -1)
(skip-chars-backward " \n\r\t")
(let ((bounds (robe-complete-bounds)))
(and bounds
(not (eq (char-before (car bounds)) ?:))
(buffer-substring (car bounds) (cdr bounds)))))))))))
(defun robe--beginning-of-expr-p ()
;; Does not account for the possibility of condinuation method call
;; (. on the previous line), but neither caller allows that.
(skip-chars-backward " \t")
(memq (char-before) '(?, ?\; ?= ?\( ?> ?: ?{ ?| ?\n nil)))
(defun robe-decorate-modules (list)
(cl-loop for spec in list
for name = (cond ((robe-spec-module spec))
((robe-spec-file spec)
(format "<%s>" (file-name-nondirectory
(robe-spec-file spec)))))
when name
collect (cons (concat name
(if (robe-spec-inst-p spec) "#" "."))
(cons name (cdr spec)))))
(defun robe-jump-to-module (name)
"Prompt for module, jump to a file where it has method definitions."
(interactive `(,(robe-completing-read "Module: " (robe-request "modules"))))
(let* ((context-module (car (robe-context)))
(search-result (robe-request "const_locations" name context-module))
(resolved-name (assoc-default 'resolved_name search-result))
(full-scan (assoc-default 'full_scan search-result))
(paths (assoc-default 'files search-result)))
(when full-scan
(setq paths (robe--filter-const-files paths resolved-name)))
(when (null paths) (error "Can't find the location"))
(let ((file (if (= (length paths) 1)
(car paths)
(let ((alist (robe-to-abbr-paths paths)))
(cdr (assoc (robe-completing-read "File: " alist nil t)
alist))))))
(robe-find-file file)
(robe--scan-to-const resolved-name)
(back-to-indentation))))
(defun robe-to-abbr-paths (list)
(let* ((sorted (sort (copy-sequence list) #'string-lessp))
(first (car sorted))
(last (car (last sorted)))
(len (cl-loop for i from 0 to (min (length first)
(length last))
when (/= (aref first i) (aref last i))
return i)))
(unless (zerop len)
(while (/= (aref first (1- len)) ?/) (cl-decf len)))
(mapcar (lambda (path) (cons (substring path len) path)) list)))
(defun robe--scan-to-const (name)
(goto-char (point-min))
(let* ((nesting (split-string name "::"))
(cnt (1- (length nesting)))
(nesting-re (concat "\\_<\\("
(cl-loop for i from 1 to cnt
concat "\\(?:")
(mapconcat #'identity nesting "::\\)?")
"\\_>\\)"))
case-fold-search)
(re-search-forward (concat "^[ \t]*\\(?:class\\|module\\) +.*"
nesting-re
"\\|"
"^[ \t]*" nesting-re " *=[^=>]"))))
(defun robe--filter-const-files (files resolved-name)
(cl-delete-if-not
(lambda (file)
(with-temp-buffer
(insert-file-contents file)
(ruby-mode)
(condition-case nil
(let* ((_ (robe--scan-to-const resolved-name))
(found-name (or (match-string 2) (match-string 1)))
new-module
(full-name (if (match-beginning 1)
;; Working around a bug in
;; ruby-add-log-current-method
;; where it can look at the preceding
;; module when at bol.
(car (robe-context))
(goto-char (match-beginning 2))
(setq new-module (car (robe-context)))
(if new-module
(concat new-module "::" found-name)
found-name))))
(equal full-name resolved-name))
(search-failed nil))))
files))
(defun robe-context ()
(let* ((ruby-symbol-re "[a-zA-Z0-9_?!]")
(current-method (and add-log-current-defun-function
(funcall add-log-current-defun-function))))
(if current-method
;; Side-stepping the module methods bug in the above function.
(let* ((segments (split-string current-method "#\\|\\.\\|::" t))
(method-name (when (string-match "\\.\\|#" current-method)
(car (last segments))))
(instance (string-match "#" current-method))
(module (mapconcat 'identity (if method-name
(butlast segments)
segments) "::")))
(set-text-properties 0 (length module) nil module) ;; for debugging
(set-text-properties 0 (length method-name) nil method-name)
(list module (when instance t) method-name))
(list nil t nil))))
(defun robe-jump-to (spec &optional pop-to-buffer)
(let ((file (robe-spec-file spec)))
(if (null file)
(when (yes-or-no-p "Can't jump to a C method. Show documentation? ")
(robe-show-doc spec))
(robe-find-file file pop-to-buffer)
(goto-char (point-min))
(forward-line (1- (robe-spec-line spec)))
(back-to-indentation))))
(defun robe-find-file (file &optional pop-to-buffer)
(unless (file-exists-p file)
(error "'%s' does not exist" file))
(if pop-to-buffer
(pop-to-buffer (find-file-noselect file))
(xref-push-marker-stack)
(find-file file))
(run-hooks 'robe-find-file-hook))
(defun robe-rails-refresh ()
"Pick up changes in the loaded classes and detect new files.
Only works with Rails, see e.g. `rinari-console'."
(interactive)
(robe-start)
(robe-request "rails_refresh")
(message "Done"))
(defun robe-doc (arg)
"Show docstring for the method at point."
(interactive "P")
(robe-start)
(let ((thing (robe--jump-thing)))
(robe-show-doc (if (or (not thing) arg)
(robe-ask-prompt)
(robe-jump-prompt thing)))))
(defvar robe-code-face 'font-lock-preprocessor-face)
(defvar robe-em-face 'font-lock-variable-name-face)
(defvar robe-doc-rules
'(("<\\(tt\\|code\\)>\\(.+?\\)</\\1>" robe-doc-hl-text 2 robe-code-face)
("\\_<\\+\\([^[:space:]]+\\)\\+\\_>" robe-doc-hl-text 1 robe-code-face)
("<\\(i\\|em\\)>\\(.+?\\)</\\1>" robe-doc-hl-text 2 robe-em-face)
("\\_<_\\([^_][^[:space:]]*\\)_\\_>" robe-doc-hl-text 1 robe-em-face)
("\\(``\\).*?\\(''\\)" robe-doc-replace-text (1 . "\u201c") (2 . "\u201d"))
("\\(`\\).*?\\('\\)" robe-doc-replace-text (1 . "\u2018") (2 . "\u2019"))))
(define-button-type 'robe-method-def
:supertype 'help-xref
'help-function #'robe-jump-to
'help-echo "mouse-2, RET: find method's definition")
(define-button-type 'robe-toggle-source
'action 'robe-toggle-source
'help-echo "mouse-2, RET: toggle source")
(defun robe-show-doc (spec)
(let* ((doc (robe-doc-for spec))
(buffer (get-buffer-create "*robe-doc*"))
(inhibit-read-only t)
(docstring (cdr (assoc 'docstring doc)))
(source (cdr (assoc 'source doc)))
(aliases (cdr (assoc 'aliases doc)))
(visibility (cdr (assoc 'visibility doc)))
(file (robe-spec-file spec)))
(with-help-window buffer
(unless (zerop (length docstring))
(princ "\n\n")
(princ docstring)))
(with-current-buffer buffer
(robe-doc-fontify-regions)
(when source
(insert "\n")
(let ((button (insert-text-button "Source"
'type 'robe-toggle-source)))
(insert "\n\n")
(if file
(let ((beg (point)))
(insert source)
(robe-doc-fontify-ruby beg (point)))
(insert (robe-doc-fontify-c-string source)))
(when (or (not robe-show-doc-source)
(and (eq robe-show-doc-source 'auto)
(> (length docstring) 0)))
(robe-toggle-source button))))
(goto-char (point-min))
(save-excursion
(insert (robe-signature spec))
(when file
(insert " is defined in ")
(insert-text-button (robe-doc-format-file-name file)
'type 'robe-method-def
'help-args (list spec t)))
(when (equal visibility "public")
(setq visibility nil))
(when (or aliases visibility)
(insert "\n"))
(when aliases
(insert "\nAliases: " (mapconcat #'identity aliases ", ")))
(when visibility
(insert "\nVisibility: " visibility)))
(visual-line-mode 1))))
(defun robe-doc-format-file-name (file)
;; TODO: Resolve this dynamically, perhaps (only when no match is
;; found?), or update on a timer.
(let* ((lp (robe-with-inf-buffer robe-load-path))
(dir (cl-find-if
(lambda (lpe) (string-prefix-p lpe file))
lp)))
(if dir
(file-relative-name file dir)
(file-name-nondirectory file))))
(defun robe-doc-fontify-regions ()
(let (last-pos)
(while (not (eobp))
(when last-pos (robe-doc-apply-rules last-pos (point)))
(while (looking-at "\\(\n\\)+\\( +.*\n\\)+\\(\n\\|\\'\\)")
(save-match-data
(robe-doc-fontify-ruby (match-beginning 0) (match-end 0)))
(goto-char (match-end 2)))
(setq last-pos (point))
(re-search-forward "[^[:space:]]\n *$" nil 'move))
(robe-doc-apply-rules last-pos (point))))
(defun robe-doc-apply-rules (from to)
(let ((table (copy-syntax-table (syntax-table))))
(modify-syntax-entry ?- "." table)
(with-syntax-table table
(save-excursion
(goto-char from)
(cl-loop for (re fn . args) in robe-doc-rules do
(save-excursion
(while (re-search-forward re to t)
(apply fn args))))))))
(defun robe-doc-hl-text (group face)
(replace-match (format "\\%d" group))
(put-text-property (match-beginning 0) (match-end 0)
'face (symbol-value face)))
(defun robe-doc-replace-text (&rest rules)
(cl-loop for (group . replacement) in rules do
(replace-match replacement t nil nil group)))
(defun robe-doc-fontify-ruby (from to)
(let ((major-mode 'ruby-mode)
(font-lock-set-defaults nil)
(font-lock-syntax-table nil)
(syntax-propertize-function #'ruby-syntax-propertize-function)
(font-lock-defaults '((ruby-font-lock-keywords) nil nil ((?_ . "w")
(?' . "\"")
(?/ . "\"")
(?# . "<")
(?\n . ">"))))
(font-lock-dont-widen t))
(save-restriction
(narrow-to-region from to)
(font-lock-fontify-region from to))))
(defun robe-doc-fontify-c-string (string)
(with-temp-buffer
(insert string)
(delay-mode-hooks
(c-mode)
(run-hooks 'font-lock-mode-hook)
(font-lock-fontify-buffer)
(buffer-string))))
(defun robe-toggle-source (button)
(let* ((end (button-end button))
(value (get-text-property end 'invisible))
(inhibit-read-only t))
(put-text-property end (point-max) 'invisible (not value))))
(defun robe-signature (spec &optional arg-num)
(concat
(mapconcat (lambda (s) (propertize s 'face font-lock-type-face))
(split-string (or (robe-spec-module spec) "?") "::" t) "::")
(if (robe-spec-inst-p spec) "#" ".")
(propertize (robe-spec-method spec) 'face font-lock-function-name-face)
(robe-signature-params (robe-spec-params spec) arg-num)))
(defun robe-signature-params (params &optional arg-num)
(when params
(when (equal (last params 2) '(("rest" "*") ("block" "&")))
(setq params (nconc (butlast params 2) '(("forward" "...")))))
(let ((cnt 0) args)
(dolist (pair params)
(let ((kind (intern (car pair)))
(name (nth 1 pair)))
(cl-incf cnt)
(unless name
(setq name
(cl-case kind
(rest "args")
(block "block")
(t (format "arg%s" cnt)))))
(push (propertize (format (cl-case kind
(rest "*%s")
(block "&%s")
(opt "[%s]")
(keyreq "%s:")
(key "[%s:]")
(keyrest "**%s")
(t "%s"))
name)
'face (if (and arg-num
(not (memq kind '(keyreq key)))
(or (= arg-num cnt)
(and (memq kind '(rest forward))
(> arg-num cnt))))
(list robe-em-face 'bold)
robe-em-face))
args)))
(concat "(" (mapconcat #'identity (nreverse args) ", ") ")"))))
(defun robe-doc-for (spec)
(apply #'robe-request "doc_for" (cl-subseq spec 0 3)))
(defun robe-call-at-point ()
(let ((state (syntax-ppss)) (start (point))
in-arglist)
(unless (nth 4 state)
(when (nth 3 state) (goto-char (nth 8 state)))
(unless (ignore-errors (save-excursion
(eq ?. (char-before
(beginning-of-thing 'symbol)))))
(when (or (robe-call-goto-paren state)
(robe-call-goto-parenless))
(setq in-arglist t)))
(let ((thing (thing-at-point 'symbol)))
(when (and thing
(or (string= thing "super")
(not (memq (get-text-property 0 'face thing)
(list font-lock-function-name-face
font-lock-keyword-face)))))
(cons thing (when in-arglist
(robe-call-arg-num (point) start))))))))
(defun robe-call-goto-paren (state)
(when (and (cl-plusp (nth 0 state))
(eq (char-after (nth 1 state)) ?\())
(goto-char (nth 1 state))
(skip-chars-backward " ")))
(defun robe-call-goto-parenless ()
(let ((table (copy-syntax-table (syntax-table)))
(punct (string-to-syntax "."))
(start (point))
point)
(modify-syntax-entry ?! "_" table)
(modify-syntax-entry ?@ "_" table)
(with-syntax-table table
(save-excursion
(catch 'stop
(unless (eobp) (forward-char 1))
(while (re-search-backward "\\S-\\([ ]+\\)\\S-" nil t)
(let ((state (parse-partial-sexp (match-beginning 1) start)))
(goto-char (match-beginning 1))
(when (and (zerop (nth 0 state)) (not (nth 8 state)))
(cond
((save-match-data (string-match-p ";\\|=[^>]" (match-string 0)))
(throw 'stop t))
((eq (char-after (match-beginning 0)) ?\n)
(unless (eq (char-before (match-beginning 0)) ?,)
(throw 'stop t)))
((eq (char-after (match-beginning 0)) ?:) nil)
((not (or (eq (syntax-after (match-beginning 0)) punct)
(eq (syntax-after (match-end 1)) punct)))
(setq point (match-beginning 1))
(throw 'stop t))))))))
(when point (goto-char point)))))
(defun robe-call-arg-num (from point)
(save-excursion
(let ((depth (car (save-excursion (parse-partial-sexp from point))))
(n 1))
(while (re-search-forward "," point t)
(let ((state (parse-partial-sexp from (point))))
(when (and (= depth (car state)) (not (nth 8 state)))
(cl-incf n))))
n)))
(defun robe-eldoc ()
(when (robe-running-p)
(let* ((context nil)
(inhibit-redisplay t)
(call (save-excursion
(prog1
(robe-call-at-point)
(setq context (robe-call-context)))))
(thing (car call))
(arg-num (cdr call))
(url-show-status nil))
(when (and thing (not (robe-const-p thing)))
(let* ((robe-jump-conservative t)
(list (cl-loop for spec in (robe-jump-modules thing context)
when (robe-spec-module spec) collect spec)))
(when (consp list)
(let* ((spec (car list))
(doc (robe-doc-for spec))
(summary
(if doc
(with-temp-buffer
(insert (cdr (assoc 'docstring doc)))
(unless (= (point) (point-min))
(goto-char (point-min))
(save-excursion
(forward-sentence)
(delete-region (point) (point-max)))
(robe-doc-apply-rules (point) (point-max))
(while (search-forward "\n" nil t)
(replace-match " ")))
(buffer-string))
""))
(sig (robe-signature spec arg-num))
(msg (format "%s %s" sig summary)))
(substring msg 0 (min (frame-width) (length msg))))))))))
(defun robe-complete-symbol-p (beginning)
(not (or (eq (char-before beginning) ?:)
;; TODO: Implement symbol completion using Symbol.all_symbols.
(memq (get-text-property beginning 'face)
(list font-lock-function-name-face
font-lock-comment-face
font-lock-string-face)))))
(defun robe-complete-bounds ()
(cons
(save-excursion
(while (or (not (zerop (skip-syntax-backward "w_")))
(not (zerop (skip-chars-backward ":")))))
(when (looking-at-p ":[^:]")
(forward-char 1))
(skip-chars-backward "@")
(point))
(save-excursion
(skip-syntax-forward "w_")
(point))))
(defun robe-complete-at-point ()
(when (robe-running-p)
(let ((bounds (robe-complete-bounds))
(fn (completion-table-with-cache #'robe-complete-thing)))
(when (robe-complete-symbol-p (car bounds))
(list (car bounds) (cdr bounds) fn
:annotation-function #'robe-complete-annotation
:exit-function #'robe-complete-exit
:company-doc-buffer #'robe-complete-doc-buffer
:company-location #'robe-complete-location
:company-dogsig #'robe-complete-docsig
:company-kind #'robe-complete-kind)))))
(defvar robe-specs-cache nil)
(defun robe-cached-specs (method)
(when robe-specs-cache
(gethash method robe-specs-cache)))
(defun robe-complete-annotation (thing)
(unless (get-text-property 0 'robe-type thing)
(let ((params (robe-signature-params (robe-spec-params
(car (robe-cached-specs thing))))))
(if robe-highlight-capf-candidates
params
(and params
(substring-no-properties params))))))
(defun robe-complete-exit (&rest _)
(setq robe-specs-cache nil))
(defun robe-complete--choose-spec (thing)
(let ((specs (robe-cached-specs thing)))
(when specs
(if (cdr specs)
(let ((alist (cl-loop for spec in specs
for module = (robe-spec-module spec)
when module
collect (cons module spec))))
(cdr (assoc (robe-completing-read "Module: " alist nil t) alist)))
(car specs)))))
(defun robe-complete-doc-buffer (thing)
(let ((spec (robe-complete--choose-spec thing))
(inhibit-redisplay t)
;; XXX: Maybe revisit company-mode/company-mode#548.
(timer-list nil))
(when spec
(save-window-excursion
(robe-show-doc spec)