forked from pythonic-emacs/anaconda-mode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
anaconda-mode.el
848 lines (708 loc) · 31.5 KB
/
anaconda-mode.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
;;; anaconda-mode.el --- Code navigation, documentation lookup and completion for Python -*- lexical-binding: t; -*-
;; Copyright (C) 2013-2018 by Artem Malyshev
;; Author: Artem Malyshev <proofit404@gmail.com>
;; URL: https://github.com/proofit404/anaconda-mode
;; Version: 0.1.13
;; Package-Requires: ((emacs "25.1") (pythonic "0.1.0") (dash "2.6.0") (s "1.9") (f "0.16.2"))
;; 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 of the License, 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 this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; See the README for more details.
;;; Code:
(require 'ansi-color)
(require 'pythonic)
(require 'tramp)
(require 'xref)
(require 'json)
(require 'dash)
(require 'url)
(require 's)
(require 'f)
(defgroup anaconda nil
"Code navigation, documentation lookup and completion for Python."
:group 'programming)
(defcustom anaconda-mode-installation-directory
(locate-user-emacs-file "anaconda-mode")
"Installation directory for `anaconda-mode' server."
:type 'directory)
(defcustom anaconda-mode-eldoc-as-single-line nil
"If not nil, trim eldoc string to frame width."
:type 'boolean)
(defcustom anaconda-mode-lighter " Anaconda"
"Text displayed in the mode line when `anaconda-mode’ is active."
:type 'sexp)
(defcustom anaconda-mode-localhost-address "127.0.0.1"
"Address used by `anaconda-mode' to resolve localhost."
:type 'string)
(defcustom anaconda-mode-doc-frame-background (face-attribute 'default :background)
"Doc frame background color, default color is current theme's background."
:type 'string)
(defcustom anaconda-mode-doc-frame-foreground (face-attribute 'default :foreground)
"Doc frame foreground color, default color is current theme's foreground."
:type 'string)
(defcustom anaconda-mode-use-posframe-show-doc nil
"If the value is not nil, use posframe to show eldoc."
:type 'boolean)
(defcustom anaconda-mode-tunnel-setup-sleep 2
"Time in seconds `anaconda-mode' waits after tunnel creation before first RPC call."
:group 'anaconda-mode
:type 'integer)
;;; Compatibility
;; Functions from posframe which is an optional dependency
(declare-function posframe-workable-p "posframe")
(declare-function posframe-hide "posframe")
(declare-function posframe-show "posframe")
;;; Server.
(defvar anaconda-mode-server-version "0.1.13"
"Server version needed to run `anaconda-mode'.")
(defvar anaconda-mode-server-command "
from __future__ import print_function
# CLI arguments.
import sys
assert len(sys.argv) > 3, 'CLI arguments: %s' % sys.argv
server_directory = sys.argv[-3]
server_address = sys.argv[-2]
virtual_environment = sys.argv[-1]
# Ensure directory.
import os
server_directory = os.path.expanduser(server_directory)
virtual_environment = os.path.expanduser(virtual_environment)
if not os.path.exists(server_directory):
os.makedirs(server_directory)
# Installation check.
jedi_dep = ('jedi', '0.13.0')
service_factory_dep = ('service_factory', '0.1.5')
missing_dependencies = []
def instrument_installation():
for package in (jedi_dep, service_factory_dep):
package_is_installed = False
for path in os.listdir(server_directory):
path = os.path.join(server_directory, path)
if path.endswith('.egg') and os.path.isdir(path):
if path not in sys.path:
sys.path.insert(0, path)
if package[0] in path:
package_is_installed = True
if not package_is_installed:
missing_dependencies.append('>='.join(package))
instrument_installation()
# Installation.
def install_deps():
import site
import setuptools.command.easy_install
site.addsitedir(server_directory)
cmd = ['--install-dir', server_directory,
'--site-dirs', server_directory,
'--always-copy','--always-unzip']
cmd.extend(missing_dependencies)
setuptools.command.easy_install.main(cmd)
instrument_installation()
if missing_dependencies:
install_deps()
del missing_dependencies[:]
try:
import jedi
except ImportError:
missing_dependencies.append('>='.join(jedi_dep))
try:
import service_factory
except ImportError:
missing_dependencies.append('>='.join(service_factory_dep))
# Try one more time in case if anaconda installation gets broken somehow
if missing_dependencies:
install_deps()
import jedi
import service_factory
# Setup server.
assert jedi.__version__ >= jedi_dep[1], 'Jedi version should be >= %s, current version: %s' % (jedi_dep[1], jedi.__version__,)
if virtual_environment:
virtual_environment = jedi.create_environment(virtual_environment, safe=False)
else:
virtual_environment = None
# Define JSON-RPC application.
import functools
import threading
def script_method(f):
@functools.wraps(f)
def wrapper(source, line, column, path):
timer = threading.Timer(30.0, sys.exit)
timer.start()
result = f(jedi.Script(source, line, column, path, environment=virtual_environment))
timer.cancel()
return result
return wrapper
def process_definitions(f):
@functools.wraps(f)
def wrapper(script):
definitions = f(script)
if len(definitions) == 1 and not definitions[0].module_path:
return '%s is defined in %s compiled module' % (
definitions[0].name, definitions[0].module_name)
return [[definition.module_path,
definition.line,
definition.column,
definition.get_line_code().strip()]
for definition in definitions
if definition.module_path] or None
return wrapper
@script_method
def complete(script):
return [[definition.name, definition.type]
for definition in script.completions()]
@script_method
def company_complete(script):
return [[definition.name,
definition.type,
definition.docstring(),
definition.module_path,
definition.line]
for definition in script.completions()]
@script_method
def show_doc(script):
return [[definition.module_name, definition.docstring()]
for definition in script.goto_definitions()]
@script_method
@process_definitions
def goto_definitions(script):
return script.goto_definitions()
@script_method
@process_definitions
def goto_assignments(script):
return script.goto_assignments()
@script_method
@process_definitions
def usages(script):
return script.usages()
@script_method
def eldoc(script):
signatures = script.call_signatures()
if len(signatures) == 1:
signature = signatures[0]
return [signature.name,
signature.index,
[param.description[6:] for param in signature.params]]
# Run.
app = [complete, company_complete, show_doc, goto_definitions, goto_assignments, usages, eldoc]
service_factory.service_factory(app, server_address, 0, 'anaconda_mode port {port}')
" "Run `anaconda-mode' server.")
(defvar anaconda-mode-process-name "anaconda-mode"
"Process name for `anaconda-mode' processes.")
(defvar anaconda-mode-process-buffer "*anaconda-mode*"
"Buffer name for `anaconda-mode' process.")
(defvar anaconda-mode-process nil
"Currently running `anaconda-mode' process.")
(defvar anaconda-mode-response-buffer "*anaconda-response*"
"Buffer name for error report when `anaconda-mode' fail to read server response.")
(defvar anaconda-mode-socat-process-name "anaconda-socat"
"Process name for `anaconda-mode' socat companion process.")
(defvar anaconda-mode-socat-process-buffer "*anaconda-socat*"
"Buffer name for `anaconda-mode' socat companion process.")
(defvar anaconda-mode-socat-process nil
"Currently running `anaconda-mode' socat companion process.")
(defvar anaconda-mode-ssh-process-name "anaconda-ssh"
"Process name for `anaconda-mode' ssh port forward companion process.")
(defvar anaconda-mode-ssh-process-buffer "*anaconda-ssh*"
"Buffer name for `anaconda-mode' ssh port forward companion process.")
(defvar anaconda-mode-ssh-process nil
"Currently running `anaconda-mode' ssh port forward companion process.")
(defvar anaconda-mode-doc-frame-name "*Anaconda Posframe*"
"The posframe to show anaconda documentation.")
(defvar anaconda-mode-frame-last-point 0
"The last point of anaconda doc view frame, use for hide frame after move point.")
(defvar anaconda-mode-frame-last-scroll-offset 0
"The last scroll offset when show doc view frame, use for hide frame after window scroll.")
(defun anaconda-mode-server-directory ()
"Anaconda mode installation directory."
(f-short (f-join anaconda-mode-installation-directory
anaconda-mode-server-version)))
(defun anaconda-mode-host ()
"Target host with `anaconda-mode' server."
(cond
((pythonic-remote-docker-p)
anaconda-mode-localhost-address)
((pythonic-remote-p)
(pythonic-remote-host))
(t
anaconda-mode-localhost-address)))
(defun anaconda-mode-port ()
"Port for `anaconda-mode' connection."
(process-get anaconda-mode-process 'port))
(defun anaconda-mode-start (&optional callback)
"Start `anaconda-mode' server.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(when (anaconda-mode-need-restart)
(anaconda-mode-stop))
(if (anaconda-mode-running-p)
(and callback
(anaconda-mode-bound-p)
(funcall callback))
(anaconda-mode-bootstrap callback)))
(defun anaconda-mode-stop ()
"Stop `anaconda-mode' server."
(when (anaconda-mode-running-p)
(set-process-filter anaconda-mode-process nil)
(set-process-sentinel anaconda-mode-process nil)
(kill-process anaconda-mode-process)
(setq anaconda-mode-process nil))
(when (anaconda-mode-socat-running-p)
(kill-process anaconda-mode-socat-process)
(setq anaconda-mode-socat-process nil))
(when (anaconda-mode-ssh-running-p)
(kill-process anaconda-mode-ssh-process)
(setq anaconda-mode-ssh-process nil)))
(defun anaconda-mode-running-p ()
"Is `anaconda-mode' server running."
(and anaconda-mode-process
(process-live-p anaconda-mode-process)))
(defun anaconda-mode-socat-running-p ()
"Is `anaconda-mode' socat companion process running."
(and anaconda-mode-socat-process
(process-live-p anaconda-mode-socat-process)))
(defun anaconda-mode-ssh-running-p ()
"Is `anaconda-mode' ssh port forward companion process running."
(and anaconda-mode-ssh-process
(process-live-p anaconda-mode-ssh-process)))
(defun anaconda-mode-bound-p ()
"Is `anaconda-mode' port bound."
(numberp (anaconda-mode-port)))
(defun anaconda-mode-need-restart ()
"Check if we need to restart `anaconda-mode-server'."
(when (and (anaconda-mode-running-p)
(anaconda-mode-bound-p))
(not (and (equal (process-get anaconda-mode-process 'interpreter)
python-shell-interpreter)
(equal (process-get anaconda-mode-process 'virtualenv)
python-shell-virtualenv-root)
(equal (process-get anaconda-mode-process 'remote-p)
(pythonic-remote-p))
(if (pythonic-local-p)
t
(equal (process-get anaconda-mode-process 'remote-method)
(pythonic-remote-method))
(equal (process-get anaconda-mode-process 'remote-user)
(pythonic-remote-user))
(equal (process-get anaconda-mode-process 'remote-host)
(pythonic-remote-host))
(equal (process-get anaconda-mode-process 'remote-port)
(pythonic-remote-port)))))))
(defun anaconda-mode-bootstrap (&optional callback)
"Run `anaconda-mode' server.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(setq anaconda-mode-process
(pythonic-start-process :process anaconda-mode-process-name
:buffer (get-buffer-create anaconda-mode-process-buffer)
:query-on-exit nil
:filter (lambda (process output)
(anaconda-mode-bootstrap-filter process output callback))
:sentinel (lambda (_process _event))
:args `("-c"
,anaconda-mode-server-command
,(anaconda-mode-server-directory)
,(if (pythonic-remote-p)
"0.0.0.0"
anaconda-mode-localhost-address)
,(or python-shell-virtualenv-root ""))))
(process-put anaconda-mode-process 'interpreter python-shell-interpreter)
(process-put anaconda-mode-process 'virtualenv python-shell-virtualenv-root)
(process-put anaconda-mode-process 'port nil)
(when (pythonic-remote-p)
(process-put anaconda-mode-process 'remote-p t)
(process-put anaconda-mode-process 'remote-method (pythonic-remote-method))
(process-put anaconda-mode-process 'remote-user (pythonic-remote-user))
(process-put anaconda-mode-process 'remote-host (pythonic-remote-host))
(process-put anaconda-mode-process 'remote-port (pythonic-remote-port))))
(defun anaconda-jump-proxy-string ()
"Create -J option string for SSH tunnel."
(let ((dfn
(tramp-dissect-file-name (pythonic-aliased-path default-directory))))
(when (tramp-file-name-hop dfn)
(let ((hop-list (split-string (tramp-file-name-hop dfn) "|"))
(result "-J "))
(delete "" hop-list) ;; remove empty string after final pipe
(dolist (elt hop-list result)
;; tramp-dissect-file-name expects a filename so give it dummy.file
(let ((ts (tramp-dissect-file-name (concat "/" elt ":/dummy.file"))))
(setq result (concat result
(format "%s@%s:%s,"
(tramp-file-name-user ts)
(tramp-file-name-host ts)
(or (tramp-file-name-port-or-default ts) 22))))))
;; Remove final comma
(substring result 0 -1)))))
(defun anaconda-mode-bootstrap-filter (process output &optional callback)
"Set `anaconda-mode-port' from PROCESS OUTPUT.
Connect to the `anaconda-mode' server. CALLBACK function will be
called when `anaconda-mode-port' will be bound."
;; Mimic default filter.
(when (buffer-live-p (process-buffer process))
(with-current-buffer (process-buffer process)
(save-excursion
(goto-char (process-mark process))
(insert (ansi-color-apply output))
(set-marker (process-mark process) (point)))))
(unless (anaconda-mode-bound-p)
(--when-let (s-match "anaconda_mode port \\([0-9]+\\)" output)
(process-put anaconda-mode-process 'port (string-to-number (cadr it)))
(cond ((pythonic-remote-docker-p)
(let* ((container-raw-description (with-output-to-string
(with-current-buffer
standard-output
(call-process "docker" nil t nil "inspect" (pythonic-remote-host)))))
(container-description (let ((json-array-type 'list))
(json-read-from-string container-raw-description)))
(container-ip (cdr (assoc 'IPAddress
(cdadr (assoc 'Networks
(cdr (assoc 'NetworkSettings
(car container-description)))))))))
(setq anaconda-mode-socat-process
(start-process anaconda-mode-socat-process-name
anaconda-mode-socat-process-buffer
"socat"
(format "TCP4-LISTEN:%d" (anaconda-mode-port))
(format "TCP4:%s:%d" container-ip (anaconda-mode-port))))
(set-process-query-on-exit-flag anaconda-mode-socat-process nil)))
((pythonic-remote-ssh-p)
(let ((jump (anaconda-jump-proxy-string)))
(message (format "Anaconda Jump Proxy: %s" jump))
(setq anaconda-mode-ssh-process
(if jump
(start-process anaconda-mode-ssh-process-name
anaconda-mode-ssh-process-buffer
"ssh" jump "-nNT"
"-L" (format "%s:localhost:%s" (anaconda-mode-port) (anaconda-mode-port))
(format "%s@%s" (pythonic-remote-user) (pythonic-remote-host))
"-p" (number-to-string (or (pythonic-remote-port) 22)))
(start-process anaconda-mode-ssh-process-name
anaconda-mode-ssh-process-buffer
"ssh" "-nNT"
"-L" (format "%s:localhost:%s" (anaconda-mode-port) (anaconda-mode-port))
(format "%s@%s" (pythonic-remote-user) (pythonic-remote-host))
"-p" (number-to-string (or (pythonic-remote-port) 22)))))
;; prevent race condition between tunnel setup and first use
(sleep-for anaconda-mode-tunnel-setup-sleep)
(set-process-query-on-exit-flag anaconda-mode-ssh-process nil))))
(when callback
(funcall callback)))))
;;; Interaction.
(defun anaconda-mode-call (command callback)
"Make remote procedure call for COMMAND.
Apply CALLBACK to it result."
(anaconda-mode-start
(lambda () (anaconda-mode-jsonrpc command callback))))
(defun anaconda-mode-jsonrpc (command callback)
"Perform JSONRPC call for COMMAND.
Apply CALLBACK to the call result when retrieve it. Remote
COMMAND must expect four arguments: python buffer content, line
number position, column number position and file path."
(let ((url-request-method "POST")
(url-request-data (anaconda-mode-jsonrpc-request command)))
(url-retrieve
(format "http://%s:%s" anaconda-mode-localhost-address (anaconda-mode-port))
(anaconda-mode-create-response-handler callback)
nil
t)))
(defun anaconda-mode-jsonrpc-request (command)
"Prepare JSON encoded buffer data for COMMAND call."
(encode-coding-string (json-encode (anaconda-mode-jsonrpc-request-data command)) 'utf-8))
(defun anaconda-mode-jsonrpc-request-data (command)
"Prepare buffer data for COMMAND call."
`((jsonrpc . "2.0")
(id . 1)
(method . ,command)
(params . ((source . ,(buffer-substring-no-properties (point-min) (point-max)))
(line . ,(line-number-at-pos (point)))
(column . ,(- (point) (line-beginning-position)))
(path . ,(when (buffer-file-name)
(pythonic-python-readable-file-name (buffer-file-name))))))))
(defun anaconda-mode-create-response-handler (callback)
"Create server response handler based on CALLBACK function."
(let ((anaconda-mode-request-point (point))
(anaconda-mode-request-buffer (current-buffer))
(anaconda-mode-request-window (selected-window))
(anaconda-mode-request-tick (buffer-chars-modified-tick)))
(lambda (status)
(let ((http-buffer (current-buffer)))
(unwind-protect
(if (or (not (equal anaconda-mode-request-window (selected-window)))
(with-current-buffer (window-buffer anaconda-mode-request-window)
(or (not (equal anaconda-mode-request-buffer (current-buffer)))
(not (equal anaconda-mode-request-point (point)))
(not (equal anaconda-mode-request-tick (buffer-chars-modified-tick))))))
nil
(search-forward-regexp "\r?\n\r?\n" nil t)
(let ((response (condition-case nil
(json-read)
((json-readtable-error json-end-of-file end-of-file)
(let ((response (concat (format "# status: %s\n# point: %s\n" status (point))
(buffer-string))))
(with-current-buffer (get-buffer-create anaconda-mode-response-buffer)
(erase-buffer)
(insert response)
(goto-char (point-min)))
nil)))))
(if (null response)
(message "Cannot read anaconda-mode server response")
(if (assoc 'error response)
(let* ((error-structure (cdr (assoc 'error response)))
(error-message (cdr (assoc 'message error-structure)))
(error-data (cdr (assoc 'data error-structure)))
(error-template (if error-data "%s: %s" "%s")))
(apply 'message error-template (delq nil (list error-message error-data))))
(with-current-buffer anaconda-mode-request-buffer
(let ((result (cdr (assoc 'result response))))
;; Terminate `apply' call with empty list so response
;; will be treated as single argument.
(apply callback result nil)))))))
(kill-buffer http-buffer))))))
;;; Code completion.
(defun anaconda-mode-complete ()
"Request completion candidates."
(interactive)
(unless (python-syntax-comment-or-string-p)
(anaconda-mode-call "complete" 'anaconda-mode-complete-callback)))
(defun anaconda-mode-complete-callback (result)
"Start interactive completion on RESULT receiving."
(let* ((bounds (bounds-of-thing-at-point 'symbol))
(start (or (car bounds) (point)))
(stop (or (cdr bounds) (point)))
(collection (anaconda-mode-complete-extract-names result))
(completion-extra-properties '(:annotation-function anaconda-mode-complete-annotation)))
(completion-in-region start stop collection)))
(defun anaconda-mode-complete-extract-names (result)
"Extract completion names from `anaconda-mode' RESULT."
(--map (let ((name (aref it 0))
(type (aref it 1)))
(put-text-property 0 1 'type type name)
name)
result))
(defun anaconda-mode-complete-annotation (candidate)
"Get annotation for CANDIDATE."
(--when-let (get-text-property 0 'type candidate)
(concat " <" it ">")))
;;; View documentation.
(defun anaconda-mode-show-doc ()
"Show documentation for context at point."
(interactive)
(anaconda-mode-call "show_doc" 'anaconda-mode-show-doc-callback))
(defun anaconda-mode-show-doc-callback (result)
"Process view doc RESULT."
(if (> (length result) 0)
(if (and anaconda-mode-use-posframe-show-doc
(require 'posframe nil 'noerror)
(posframe-workable-p))
(anaconda-mode-documentation-posframe-view result)
(pop-to-buffer (anaconda-mode-documentation-view result) t))
(message "No documentation available")))
(defun anaconda-mode-documentation-view (result)
"Show documentation view for rpc RESULT, and return buffer."
(let ((buf (get-buffer-create "*Anaconda*")))
(with-current-buffer buf
(view-mode -1)
(erase-buffer)
(mapc
(lambda (it)
(insert (propertize (aref it 0) 'face 'bold))
(insert "\n")
(insert (s-trim-right (aref it 1)))
(insert "\n\n"))
result)
(view-mode 1)
(goto-char (point-min))
buf)))
(defun anaconda-mode-documentation-posframe-view (result)
"Show documentation view in posframe for rpc RESULT."
(with-current-buffer (get-buffer-create anaconda-mode-doc-frame-name)
(erase-buffer)
(mapc
(lambda (it)
(insert (propertize (aref it 0) 'face 'bold))
(insert "\n")
(insert (s-trim-left (aref it 1)))
(insert "\n\n"))
result))
(posframe-show anaconda-mode-doc-frame-name
:position (point)
:internal-border-width 10
:background-color anaconda-mode-doc-frame-background
:foreground-color anaconda-mode-doc-frame-foreground)
(add-hook 'post-command-hook 'anaconda-mode-hide-frame)
(setq anaconda-mode-frame-last-point (point))
(setq anaconda-mode-frame-last-scroll-offset (window-start)))
(defun anaconda-mode-hide-frame ()
"Hide posframe when window scroll or move point."
(ignore-errors
(when (get-buffer anaconda-mode-doc-frame-name)
(unless (and (equal (point) anaconda-mode-frame-last-point)
(equal (window-start) anaconda-mode-frame-last-scroll-offset))
(posframe-hide anaconda-mode-doc-frame-name)
(remove-hook 'post-command-hook 'anaconda-mode-hide-frame)))))
;;; Find definitions.
(defun anaconda-mode-find-definitions ()
"Find definitions for thing at point."
(interactive)
(anaconda-mode-call
"goto_definitions"
(lambda (result)
(anaconda-mode-show-xrefs result nil "No definitions found"))))
(defun anaconda-mode-find-definitions-other-window ()
"Find definitions for thing at point."
(interactive)
(anaconda-mode-call
"goto_definitions"
(lambda (result)
(anaconda-mode-show-xrefs result 'window "No definitions found"))))
(defun anaconda-mode-find-definitions-other-frame ()
"Find definitions for thing at point."
(interactive)
(anaconda-mode-call
"goto_definitions"
(lambda (result)
(anaconda-mode-show-xrefs result 'frame "No definitions found"))))
;;; Find assignments.
(defun anaconda-mode-find-assignments ()
"Find assignments for thing at point."
(interactive)
(anaconda-mode-call
"goto_assignments"
(lambda (result)
(anaconda-mode-show-xrefs result nil "No assignments found"))))
(defun anaconda-mode-find-assignments-other-window ()
"Find assignments for thing at point."
(interactive)
(anaconda-mode-call
"goto_assignments"
(lambda (result)
(anaconda-mode-show-xrefs result 'window "No assignments found"))))
(defun anaconda-mode-find-assignments-other-frame ()
"Find assignments for thing at point."
(interactive)
(anaconda-mode-call
"goto_assignments"
(lambda (result)
(anaconda-mode-show-xrefs result 'frame "No assignments found"))))
;;; Find references.
(defun anaconda-mode-find-references ()
"Find references for thing at point."
(interactive)
(anaconda-mode-call
"usages"
(lambda (result)
(anaconda-mode-show-xrefs result nil "No references found"))))
(defun anaconda-mode-find-references-other-window ()
"Find references for thing at point."
(interactive)
(anaconda-mode-call
"usages"
(lambda (result)
(anaconda-mode-show-xrefs result 'window "No references found"))))
(defun anaconda-mode-find-references-other-frame ()
"Find references for thing at point."
(interactive)
(anaconda-mode-call
"usages"
(lambda (result)
(anaconda-mode-show-xrefs result 'frame "No references found"))))
;;; Xref.
(defun anaconda-mode-show-xrefs (result display-action error-message)
"Show xref from RESULT using DISPLAY-ACTION.
Show ERROR-MESSAGE if result is empty."
(if result
(if (stringp result)
(message result)
(let ((xrefs (anaconda-mode-make-xrefs result)))
(if (not (cdr xrefs))
(progn
(xref-push-marker-stack)
(funcall (if (fboundp 'xref-pop-to-location)
'xref-pop-to-location
'xref--pop-to-location)
(cl-first xrefs)
display-action))
(xref--show-xrefs (if (functionp 'xref--create-fetcher)
(lambda (&rest _) xrefs)
xrefs)
display-action))))
(message error-message)))
(defun anaconda-mode-make-xrefs (result)
"Return a list of x-reference candidates created from RESULT."
(--map
(xref-make
(aref it 3)
(xref-make-file-location (pythonic-emacs-readable-file-name (aref it 0)) (aref it 1) (aref it 2)))
result))
;;; Eldoc.
(defun anaconda-mode-eldoc-function ()
"Show eldoc for context at point."
(anaconda-mode-call "eldoc" 'anaconda-mode-eldoc-callback)
;; Don't show response buffer name as ElDoc message.
nil)
(defun anaconda-mode-eldoc-callback (result)
"Display eldoc from server RESULT."
(eldoc-message (anaconda-mode-eldoc-format result)))
(defun anaconda-mode-eldoc-format (result)
"Format eldoc string from RESULT."
(when result
(let ((doc (anaconda-mode-eldoc-format-definition
(aref result 0)
(aref result 1)
(aref result 2))))
(if anaconda-mode-eldoc-as-single-line
(substring doc 0 (min (frame-width) (length doc)))
doc))))
(defun anaconda-mode-eldoc-format-definition (name index params)
"Format function definition from NAME, INDEX and PARAMS."
(when index
(aset params index (propertize (aref params index) 'face 'eldoc-highlight-function-argument)))
(concat (propertize name 'face 'font-lock-function-name-face) "(" (mapconcat 'identity params ", ") ")"))
;;; Anaconda minor mode.
(defvar anaconda-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-M-i") 'anaconda-mode-complete)
(define-key map (kbd "M-.") 'anaconda-mode-find-definitions)
(define-key map (kbd "C-x 4 .") 'anaconda-mode-find-definitions-other-window)
(define-key map (kbd "C-x 5 .") 'anaconda-mode-find-definitions-other-frame)
(define-key map (kbd "M-=") 'anaconda-mode-find-assignments)
(define-key map (kbd "C-x 4 =") 'anaconda-mode-find-assignments-other-window)
(define-key map (kbd "C-x 5 =") 'anaconda-mode-find-assignments-other-frame)
(define-key map (kbd "M-r") 'anaconda-mode-find-references)
(define-key map (kbd "C-x 4 r") 'anaconda-mode-find-references-other-window)
(define-key map (kbd "C-x 5 r") 'anaconda-mode-find-references-other-frame)
(define-key map (kbd "M-,") 'xref-pop-marker-stack)
(define-key map (kbd "M-?") 'anaconda-mode-show-doc)
map)
"Keymap for `anaconda-mode'.")
;;;###autoload
(define-minor-mode anaconda-mode
"Code navigation, documentation lookup and completion for Python.
\\{anaconda-mode-map}"
:lighter anaconda-mode-lighter
:keymap anaconda-mode-map
(setq-local url-http-attempt-keepalives nil))
;;;###autoload
(define-minor-mode anaconda-eldoc-mode
"Toggle echo area display of Python objects at point."
:lighter ""
(if anaconda-eldoc-mode
(turn-on-anaconda-eldoc-mode)
(turn-off-anaconda-eldoc-mode)))
(defun turn-on-anaconda-eldoc-mode ()
"Turn on `anaconda-eldoc-mode'."
(make-local-variable 'eldoc-documentation-function)
(setq-local eldoc-documentation-function 'anaconda-mode-eldoc-function)
(eldoc-mode +1))
(defun turn-off-anaconda-eldoc-mode ()
"Turn off `anaconda-eldoc-mode'."
(kill-local-variable 'eldoc-documentation-function)
(eldoc-mode -1))
(provide 'anaconda-mode)
;;; anaconda-mode.el ends here