forked from jorgenschaefer/elpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelpy.el
1600 lines (1394 loc) · 59.3 KB
/
elpy.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
;;; elpy.el --- Emacs Lisp Python Environment -*- lexical-binding: t -*-
;; Copyright (C) 2012, 2013 Jorgen Schaefer
;; Author: Jorgen Schaefer <[email protected]>
;; URL: https://github.com/jorgenschaefer/elpy
;; Version: 1.2.1
;; 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:
;; The Emacs Lisp Python Environment in Emacs
;; Elpy is an Emacs package to bring powerful Python editing to Emacs.
;; It combines a number of existing Emacs packages, and uses one of a
;; selection of Python packages for code introspection.
;; To use, you need to install not only this package, but a few Python
;; packages as well. See the installation instructions on the wiki.
;; Documentation is available there as well.
;; https://github.com/jorgenschaefer/elpy/wiki
;;; Code:
(require 'auto-complete-config)
(require 'elpy-refactor)
(require 'etags)
(require 'find-file-in-project)
(require 'flymake)
(require 'highlight-indentation)
(require 'idomenu)
(require 'json)
(require 'nose)
(require 'python)
(require 'grep)
(require 'thingatpt)
(require 'virtualenv)
(require 'yasnippet)
;;;;;;;;;;;;;;;
;;; Elpy itself
(defgroup elpy nil
"The Emacs Lisp Python Environment."
:prefix "elpy-"
:group 'languages)
(defcustom elpy-rpc-python-command "python"
"The command to be used for the RPC backend."
:type 'string
:group 'elpy)
(defcustom elpy-rpc-project-specific nil
"Whether Elpy should use a separate process for each project."
:type 'boolean
:group 'elpy)
(defcustom elpy-rpc-backend nil
"Your preferred backend.
Either nil, or a string.
nil - Select a backend automatically.
rope - Use the Rope refactoring library. This will create
.ropeproject directories in your project roots.
jedi - Use the Jedi completion library.
native - Do not use any backend, use native Python methods only."
:type '(choice (const "rope")
(const "jedi")
(const "native")
(const nil))
:group 'elpy)
(defcustom elpy-default-minor-modes '(eldoc-mode
flymake-mode
highlight-indentation-mode
yas-minor-mode
auto-complete-mode)
"Minor modes enabled when `elpy-mode' is enabled."
:group 'elpy)
(defcustom elpy-rgrep-ignored-directories '(".tox" "build" "dist")
"Directories ignored by `elpy-rgrep-symbol'.
These are prepended to `grep-find-ignored-directories'."
:group 'elpy)
(defcustom elpy-mode-hook nil
"Hook run when `elpy-mode' is enabled."
:group 'elpy)
(defconst elpy-version "1.2.1"
"The version of the Elpy lisp code.")
(defun elpy-version ()
"Echo the version of Elpy."
(interactive)
(let ((version elpy-version)
(rpc-version (when elpy-rpc--buffer
(or (ignore-errors
(elpy-rpc "version" nil))
"1.1"))))
(if (equal version "devel")
(setq version "development version")
(setq version (format "version %s" version)))
(when rpc-version
(if (equal rpc-version "devel")
(setq rpc-version "development version")
(setq rpc-version (format "version %s" rpc-version))))
(if rpc-version
(message "Elpy %s using the Python backend %s"
version rpc-version)
(message "Elpy %s" version))))
(defvar elpy-mode-map
(let ((map (make-sparse-keymap)))
;; Alphabetical order to make it easier to find free C-c C-X
;; bindings in the future. Heh.
;; (define-key map (kbd "<backspace>") 'python-indent-dedent-line-backspace)
;; (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
;; (define-key map (kbd "<tab>") 'ac-trigger-key)
;; (define-key map (kbd "C-M-x") 'python-shell-send-defun)
;; (define-key map (kbd "C-c <") 'python-indent-shift-left)
;; (define-key map (kbd "C-c >") 'python-indent-shift-right)
(define-key map (kbd "C-c C-c") 'elpy-shell-send-region-or-buffer)
(define-key map (kbd "C-c C-z") 'elpy-shell-switch-to-shell)
(define-key map (kbd "C-c C-d") 'elpy-doc)
(define-key map (kbd "C-c C-f") 'find-file-in-project)
;; (define-key map (kbd "C-c C-i") 'yasnippet-expand)
(define-key map (kbd "C-c C-j") 'idomenu)
(define-key map (kbd "C-c C-n") 'elpy-flymake-forward-error)
(define-key map (kbd "C-c C-o") 'elpy-occur-definitions)
(define-key map (kbd "C-c C-p") 'elpy-flymake-backward-error)
(define-key map (kbd "C-c C-q") 'elpy-show-defun)
(define-key map (kbd "C-c C-r") 'elpy-refactor)
(define-key map (kbd "C-c C-s") 'elpy-rgrep-symbol)
(define-key map (kbd "C-c C-t") 'elpy-test)
(define-key map (kbd "C-c C-v") 'elpy-check)
(define-key map (kbd "C-c C-w") 'elpy-doc-websearch)
;; (define-key map (kbd "C-c C-z") 'python-shell-switch-to-shell)
(define-key map (kbd "<C-down>") 'elpy-nav-forward-definition)
(define-key map (kbd "<C-up>") 'elpy-nav-backward-definition)
;; (define-key map (kbd "M-,") 'iedit-mode
(define-key map (kbd "M-.") 'elpy-goto-definition)
(define-key map (kbd "M-a") 'elpy-nav-backward-statement)
(define-key map (kbd "M-e") 'elpy-nav-forward-statement)
(define-key map (kbd "M-n") 'elpy-nav-forward-definition)
(define-key map (kbd "M-p") 'elpy-nav-backward-definition)
map)
"Key map for the Emacs Lisp Python Environment.")
;;;###autoload
(defun elpy-enable (&optional skip-initialize-variables)
"Enable Elpy in all future Python buffers.
When SKIP-INITIALIZE-VARIABLES is non-nil, this will NOT call
`elpy-initialize-variables' to configure various modes in a way
that the Elpy author considers sensible. If you'd rather
configure those modes yourself, pass t here."
(interactive)
(when (< emacs-major-version 24)
(error "Elpy requires Emacs 24 or newer"))
(let ((filename (find-lisp-object-file-name 'python-mode
'symbol-function)))
(when (and filename
(string-match "/python-mode\\.el\\'"
filename))
(error (concat "You are using python-mode.el. "
"Elpy only works with python.el from "
"Emacs 24 and above"))))
(add-hook 'python-mode-hook 'elpy-mode)
(when (not skip-initialize-variables)
(elpy-initialize-variables)))
;;;###autoload
(defun elpy-disable ()
"Disable Elpy in all future Python buffers."
(interactive)
(remove-hook 'python-mode-hook 'elpy-mode))
;;;###autoload
(define-minor-mode elpy-mode
"Minor mode in Python buffers for the Emacs Lisp Python Environment.
This mode fully supports virtualenvs. Once you switch a
virtualenv using \\[virtualenv-workon], you can use
\\[elpy-rpc-restart] to make the elpy Python process use your
virtualenv.
See https://github.com/jorgenschaefer/elpy/wiki/Keybindings for a
more structured list.
\\{elpy-mode-map}"
:lighter " Elpy"
(when (not (eq major-mode 'python-mode))
(error "Elpy only works with `python-mode'"))
(cond
(elpy-mode
(when buffer-file-name
(set (make-local-variable 'ffip-project-root) (elpy-project-root)))
(set (make-local-variable 'eldoc-documentation-function)
'elpy-eldoc-documentation)
(add-to-list 'ac-sources 'ac-source-elpy)
(add-to-list 'ac-sources 'ac-source-elpy-dot)
;; Enable modes, hence the 1.
(run-hook-with-args 'elpy-default-minor-modes 1))
(t
(kill-local-variable 'ffip-project-root)
(kill-local-variable 'eldoc-documentation-function)
(setq ac-sources
(delq 'ac-source-elpy
(delq 'ac-source-elpy-dot
ac-sources))))))
(defun elpy-installation-instructions (message &optional show-elpy-module)
"Display a window with installation instructions for the Python
side of elpy.
MESSAGE is shown as the first paragraph.
If SHOW-ELPY-MODULE is non-nil, the help buffer will first
explain how to install the elpy module."
(with-help-window "*Elpy Installation*"
(with-current-buffer "*Elpy Installation*"
(let ((inhibit-read-only t))
(erase-buffer)
(insert "Elpy Installation Instructions\n")
(insert "\n")
(insert message)
(when (not (bolp))
(insert "\n"))
(insert "\n")
(when show-elpy-module
(insert "Elpy requires the Python module \"elpy\". The module "
"is available from pypi, so you can install it using "
"the following command:\n")
(insert "\n")
(elpy-installation-command "elpy")
(insert "\n"))
(insert "To find possible completions, Elpy uses one of two "
"Python modules. Either \"rope\" or \"jedi\". To use "
"Elpy to its fullest potential, you should install "
"either one of them. Which one is a matter of taste. "
"You can try both and even switch at runtime using "
"M-x elpy-set-backend.\n")
(insert "\n")
(insert "Elpy also uses the Rope module for refactoring options, "
"so you likely want to install it even if you use jedi "
"for completion.\n")
(insert "\n")
(if (string-match "Python 3" (shell-command-to-string
"python --version"))
(elpy-installation-command "rope_py3k")
(elpy-installation-command "rope"))
(insert "\n")
(elpy-installation-command "jedi")
(insert "\n")
(insert "If you are using virtualenvs, you can use the "
"M-x virtualenv-workon command to switch to a virtualenv "
"of your choice. Afterwards, running the command "
"M-x elpy-rpc-restart will use the packages in "
"that virtualenv.")
(fill-region (point-min) (point-max))))))
(defun elpy-installation-command (python-module)
"Insert an installation command description for PYTHON-MODULE."
(let* ((do-user-install (not (or (getenv "VIRTUAL_ENV")
virtualenv-workon-session)))
(user-option (if do-user-install
"--user "
""))
(command (cond
((executable-find "pip")
(format "pip install %s%s" user-option python-module))
((executable-find "easy_install")
(format "easy_install %s%s" user-option python-module))
(t
nil))))
(if (not command)
(insert "... hm. It appears you have neither pip nor easy_install "
"available. You might want to get the python-pip or "
"or python-setuptools package.\n")
(insert-text-button "[run]"
'action (lambda (button)
(async-shell-command
(button-get button 'command)))
'command command)
(insert " " command "\n"))))
(defun elpy-initialize-variables ()
"This sets some variables in other modes we like to set.
If you want to configure your own keys, do so after this function
is called (usually from `elpy-enable'), or override this function
using (defalias 'elpy-initialize-variables 'identity)"
;; Local variables in `python-mode'. This is not removed when Elpy
;; is disabled, which can cause some confusion.
(add-hook 'python-mode-hook 'elpy-initialize-local-variables)
;; Flymake support using flake8, including warning faces.
(when (or (executable-find "flake8")
(not (executable-find python-check-command)))
(setq python-check-command "flake8"))
;; `flymake-no-changes-timeout': The original value of 0.5 is too
;; short for Python code, as that will result in the current line to
;; be highlighted most of the time, and that's annoying. This value
;; might be on the long side, but at least it does not, in general,
;; interfere with normal interaction.
(setq flymake-no-changes-timeout 60)
;; `flymake-start-syntax-check-on-newline': This should be nil for
;; Python, as;; most lines with a colon at the end will mean the next
;; line is always highlighted as error, which is not helpful and
;; mostly annoying.
(setq flymake-start-syntax-check-on-newline nil)
;; `ac-trigger-key': TAB is a great trigger key. We also need to
;; tell auto-complete about the new trigger key. This is a bad
;; interface to set the trigger key. Don't do this. Just let the
;; user set the key in the keymap. Stop second-guessing the user, or
;; Emacs.
(setq ac-trigger-key "TAB")
(when (fboundp 'ac-set-trigger-key)
(ac-set-trigger-key ac-trigger-key))
;; `ac-auto-show-menu': Short timeout because the menu is great.
(setq ac-auto-show-menu 0.4)
;; `ac-quick-help-delay': I'd like to show the menu right with the
;; completions, but this value should be greater than
;; `ac-auto-show-menu' to show help for the first entry as well.
(setq ac-quick-help-delay 0.5)
;; Fix some key bindings in ac completions. Using RET when a
;; completion is offered is not usually intended to complete (use
;; TAB for that), but done while typing and the inputer is considere
;; complete, with the intent to simply leave it as is and go to the
;; next line. Much like space will not complete, but leave it as is
;; and insert a space.
(define-key ac-completing-map (kbd "RET") nil)
(define-key ac-completing-map (kbd "<return>") nil)
;; `yas-trigger-key': TAB, as is the default, conflicts with the
;; autocompletion. We also need to tell yasnippet about the new
;; binding. This is a bad interface to set the trigger key. Stop
;; doing this.
(let ((old (when (boundp 'yas-trigger-key)
yas-trigger-key)))
(setq yas-trigger-key "C-c C-i")
(when (fboundp 'yas--trigger-key-reload)
(yas--trigger-key-reload old)))
;; We provide some YASnippet snippets. Add them.
(add-to-list
'yas-snippet-dirs
(concat (file-name-directory (locate-library "elpy")) "snippets/")
t)
;; Now load yasnippets.
(yas-reload-all))
(defun elpy-initialize-local-variables ()
"Initialize local variables in python-mode.
This should be run from `python-mode-hook'."
;; Set `forward-sexp-function' to nil in python-mode. See
;; http://debbugs.gnu.org/db/13/13642.html
(setq forward-sexp-function nil)
;; Enable warning faces for flake8 output.
(when (string-match "flake8" python-check-command)
;; COMPAT: Obsolete variable as of 24.4
(if (boundp 'flymake-warning-predicate)
(set (make-local-variable 'flymake-warning-predicate) "^W[0-9]")
(set (make-local-variable 'flymake-warning-re) "^W[0-9]"))))
(defvar elpy-project-root nil
"The root of the project the current buffer is in.")
(make-variable-buffer-local 'elpy-project-root)
(put 'elpy-project-root 'safe-local-variable 'file-directory-p)
(defun elpy-project-root ()
"Return the root of the current buffer's project.
You can set the variable `elpy-project-root' in, for example,
.dir-locals.el to configure this."
(when (not elpy-project-root)
(setq elpy-project-root (elpy-project--find-root))
(when (equal (directory-file-name (expand-file-name default-directory))
(directory-file-name (expand-file-name "~")))
(display-warning 'elpy
(concat "Project root set to your home directory; "
"this can slow down operation considerably")
:warning)))
elpy-project-root)
(defun elpy-project--find-root ()
"Find the first directory in the tree not containing an __init__.py
If there is no __init__.py in the current directory, return the
current directory."
(if (file-exists-p (format "%s/__init__.py" default-directory))
(locate-dominating-file default-directory
(lambda (dir)
(not (file-exists-p
(format "%s/__init__.py" dir)))))
default-directory))
(defun elpy-set-project-root (new-root)
"Set the Elpy project root to NEW-ROOT."
(interactive "DNew project root: ")
(setq elpy-project-root new-root))
(defun elpy-use-ipython (&optional ipython)
"Set defaults to use IPython instead of the standard interpreter.
With prefix arg, prompt for the command to use."
(interactive (list (when current-prefix-arg
(read-file-name "IPython command: "))))
(when (not ipython)
(setq ipython "ipython"))
(if (boundp 'python-python-command)
;; Emacs 24 until 24.3
(setq python-python-command ipython)
;; Emacs 24.3 and onwards.
;; This is from the python.el commentary.
;; Settings for IPython 0.11:
(setq python-shell-interpreter ipython
python-shell-interpreter-args ""
python-shell-prompt-regexp "In \\[[0-9]+\\]: "
python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
python-shell-completion-setup-code
"from IPython.core.completerlib import module_completion"
python-shell-completion-module-string-code
"';'.join(module_completion('''%s'''))\n"
python-shell-completion-string-code
"';'.join(get_ipython().Completer.all_completions('''%s'''))\n")))
(defun elpy-use-cpython (&optional cpython)
"Set defaults to use the standard interpreter instead of IPython.
With prefix arg, prompt for the command to use."
(interactive (list (when current-prefix-arg
(read-file-name "Python command: "))))
(when (not cpython)
(setq cpython "python"))
(if (boundp 'python-python-command)
;; Emacs 24 until 24.3
(setq python-python-command cpython)
;; Emacs 24.3 and onwards.
(setq python-shell-interpreter cpython
python-shell-interpreter-args "-i"
python-shell-prompt-regexp ">>> "
python-shell-prompt-output-regexp ""
python-shell-completion-setup-code
"try:
import readline
except ImportError:
def __COMPLETER_all_completions(text): []
else:
import rlcompleter
readline.set_completer(rlcompleter.Completer().complete)
def __COMPLETER_all_completions(text):
import sys
completions = []
try:
i = 0
while True:
res = readline.get_completer()(text, i)
if not res: break
i += 1
completions.append(res)
except NameError:
pass
return completions"
python-shell-completion-module-string-code ""
python-shell-completion-string-code
"';'.join(__COMPLETER_all_completions('''%s'''))\n")))
(defun elpy-clean-modeline ()
"Clean up the mode line by removing some lighters.
It's not necessary to see (Python Elpy yas AC ElDoc) all the
time. Honestly."
(interactive)
(setq eldoc-minor-mode-string nil)
(dolist (mode '(elpy-mode yas-minor-mode auto-complete-mode
flymake-mode))
(setcdr (assq mode minor-mode-alist)
(list ""))))
(defun elpy-shell-send-region-or-buffer (&optional arg)
"Send the active region or the buffer to the Python shell.
If there is an active region, send that. Otherwise, send the
whole buffer.
Without prefix argument, this will escape the Python idiom of
if __name__ == '__main__' to be false to avoid accidental
execution of code. With prefix argument, this code is executed."
(interactive "P")
;; Ensure process exists
(elpy-shell-get-or-create-process)
(if (region-active-p)
(python-shell-send-string (elpy--region-without-indentation
(region-beginning) (region-end))
nil t)
(python-shell-send-buffer arg))
(elpy-shell-switch-to-shell))
(defun elpy--region-without-indentation (beg end)
"Return the current region as a string, but without indentation."
(let ((region (buffer-substring beg end))
(indent-level nil))
(catch 'return
(with-temp-buffer
(insert region)
(goto-char (point-min))
(while (< (point) (point-max))
(cond
((and (not indent-level)
(not (looking-at "[ \t]*$")))
(setq indent-level (current-indentation)))
((and indent-level
(not (looking-at "[ \t]*$"))
(< (current-indentation)
indent-level))
(error "Can't adjust indentation, consecutive lines indented less than starting line")))
(forward-line))
(indent-rigidly (point-min)
(point-max)
(- indent-level))
(buffer-string)))))
(defun elpy-shell-switch-to-shell ()
"Switch to inferior Python process buffer."
(interactive)
(pop-to-buffer (process-buffer (elpy-shell-get-or-create-process)) t))
(defun elpy-shell-get-or-create-process ()
"Get or create an inferior Python process for current buffer and return it."
(let* ((bufname (format "*%s*" (python-shell-get-process-name nil)))
(proc (get-buffer-process bufname)))
(if proc
proc
(run-python (python-shell-parse-command))
(get-buffer-process bufname))))
(defun elpy-check (&optional whole-project-p)
"Run `python-check-command' on the current buffer's file,
or the project root if WHOLE-PROJECT-P is non-nil (interactively,
with a prefix argument)."
(interactive "P")
(when (not (buffer-file-name))
(error "Can't check a buffer without a file."))
(save-some-buffers (not compilation-ask-about-save) nil)
(let ((process-environment (python-shell-calculate-process-environment))
(exec-path (python-shell-calculate-exec-path))
(file-name-or-directory (expand-file-name
(if whole-project-p
(elpy-project-root)
(buffer-file-name))))
(extra-args (if whole-project-p
" --exclude=.svn,CVS,.bzr,.hg,.git,.tox,build,dist"
"")))
(compilation-start (concat python-check-command
" "
(shell-quote-argument file-name-or-directory)
extra-args)
nil
(lambda (mode-name)
"*Python Check*"))))
(defun elpy-show-defun ()
"Show the current class and method, in case they are not on
screen."
(interactive)
(let ((function (python-info-current-defun)))
(if function
(message "%s()" function)
(message "Not in a function"))))
(defun elpy-goto-definition ()
"Go to the definition of the symbol at point, if found."
(interactive)
(let ((location (elpy-rpc-get-definition)))
(if location
(elpy-goto-location (car location) (cadr location))
(error "No definition found"))))
(defun elpy-goto-location (filename offset)
"Show FILENAME at OFFSET to the user."
(ring-insert find-tag-marker-ring (point-marker))
(let ((buffer (find-file filename)))
(with-current-buffer buffer
(with-selected-window (get-buffer-window buffer)
(goto-char (1+ offset))))))
(defun elpy-nav-forward-statement ()
"Move forward one statement.
This will go to the end of the current statement, or the end of
the next one if already at the end."
(interactive)
(let ((old (point)))
(python-nav-end-of-statement)
(when (= old (point))
(python-nav-forward-statement)
(python-nav-end-of-statement))))
(defun elpy-nav-backward-statement ()
"Move backward one statement.
This will go to the beginning of the current statement, or the
beginning of the previous one if already at the beginning."
(interactive)
(let ((old (point)))
(python-nav-beginning-of-statement)
(when (= old (point))
(python-nav-backward-statement))))
(defun elpy-nav-forward-definition ()
"Move forward to the next definition (class or function)."
(interactive)
(if (save-excursion
(forward-char 1)
(re-search-forward "^ *\\(def\\|class\\) " nil t))
(goto-char (match-beginning 1))
(goto-char (point-max))))
(defun elpy-nav-backward-definition ()
"Move backward to the previous definition (class or function)."
(interactive)
(if (save-excursion
(forward-char -1)
(re-search-backward "^ *\\(def\\|class\\) " nil t))
(goto-char (match-beginning 1))
(goto-char (point-min))))
(defun elpy-occur-definitions ()
"Display an occur buffer of all definitions in the current buffer.
Also, switch to that buffer."
(interactive)
(let ((list-matching-lines-face nil))
(occur "^ *\\(def\\|class\\) "))
(let ((window (get-buffer-window "*Occur*")))
(if window
(select-window window)
(switch-to-buffer "*Occur*"))))
(defun elpy-rgrep-symbol (symbol)
"Search for SYMBOL in the current project.
SYMBOL defaults to the symbol at point, or the current region if
active.
With a prefix argument, prompt for a string to search for."
(interactive
(list
(cond
(current-prefix-arg
(read-from-minibuffer "Search for symbol: "))
((use-region-p)
(buffer-substring-no-properties (region-beginning)
(region-end)))
(t
(or (thing-at-point 'symbol)
(read-from-minibuffer "Search for symbol: "))))))
(grep-compute-defaults)
(let ((grep-find-ignored-directories (append elpy-rgrep-ignored-directories
grep-find-ignored-directories)))
(rgrep (format "\\b%s\\b" symbol)
"*.py"
(elpy-project-root)))
(with-current-buffer next-error-last-buffer
(let ((inhibit-read-only t))
(save-excursion
(goto-char (point-min))
(when (re-search-forward "^find .*" nil t)
(replace-match (format "\\1\nSearching for symbol %s\n"
symbol)))))))
(defun elpy-test (&optional arg)
"Run nosetests on the current project.
With no prefix arg, all tests are run.
With one prefix arg, only the current test is run.
With two prefix args, only the current module is run."
(interactive "p")
(save-some-buffers)
(cond
((>= arg 16) (nosetests-module))
((>= arg 4) (nosetests-one))
(t (nosetests-all))))
;;;;;;;;;;;;;;;;;
;;; Documentation
(defvar elpy-doc-history nil
"History for the `elpy-doc' command.")
(defun elpy-doc-websearch (what)
"Search the Python web documentation for the string WHAT."
(interactive
(list (read-from-minibuffer "Search Python.org for: "
(symbol-name (symbol-at-point)))))
(browse-url
(format "https://www.google.com/search?q=site:docs.python.org%%20%s"
what)))
(defun elpy-doc (&optional use-pydoc-p symbol)
"Show documentation on the thing at point.
If USE-PYDOC is non-nil (interactively, when a prefix argument is
given), use pydoc on the symbol SYMBOL (interactively, the symbol
at point). With a single prefix argument, the user gets a
completion interface for possible symbols. With two prefix
arguments, the interface simply asks for a string."
(interactive
(list current-prefix-arg
(let ((initial (with-syntax-table python-dotty-syntax-table
(let ((symbol (symbol-at-point)))
(if symbol
(symbol-name symbol)
nil)))))
(cond
((and initial (not current-prefix-arg))
initial)
((equal current-prefix-arg '(16))
;; C-u C-u
(read-from-minibuffer "Pydoc: " initial nil nil
'elpy-doc-history))
(t
(elpy-ido-recursive-completing-read "Pydoc: "
'elpy-pydoc--completions
"."
t
initial
'elpy-doc-history))))))
(let ((doc (if use-pydoc-p
(elpy-rpc-get-pydoc-documentation symbol)
(or (elpy-rpc-get-docstring)
;; This will get the right position for
;; multiprocessing.Queue(quxqux_|_)
(ignore-errors
(save-excursion
(elpy-nav-backward-statement)
(with-syntax-table python-dotty-syntax-table
(forward-symbol 1)
(backward-char 1))
(elpy-rpc-get-docstring)))))))
(if doc
(with-help-window "*Python Doc*"
(with-current-buffer "*Python Doc*"
(erase-buffer)
(insert doc)
(goto-char (point-min))
(while (re-search-forward "\\(.\\)\\1" nil t)
(replace-match (propertize (match-string 1)
'face 'bold)
t t))))
(message "No documentation available."))))
(defun elpy-pydoc--completions (rcr-prefix)
"Return a list of modules available in pydoc starting with RCR-PREFIX."
(sort (if (or (not rcr-prefix)
(equal rcr-prefix ""))
(elpy-rpc "get_pydoc_completions" nil)
(elpy-rpc "get_pydoc_completions" (list rcr-prefix)))
(lambda (a b)
(if (and (string-prefix-p "_" b)
(not (string-prefix-p "_" a)))
t
(string< (downcase a)
(downcase b))))))
;;;;;;;;;;;;
;;; elpy-ido
;; This is a wrapper around ido-completing-read, which does not
;; provide for recursive reads by default.
(defvar elpy-ido-rcr-choice-function nil
"Internal variable for `elpy-ido-recursive-completing-read'.
Don't touch. Won't help.")
(defvar elpy-ido-rcr-selection nil
"Internal variable for `elpy-ido-recursive-completing-read'.
Don't touch. Won't help.")
(defvar elpy-ido-rcr-separator nil
"Internal variable for `elpy-ido-recursive-completing-read'.
Don't touch. Won't help.")
(defvar elpy-ido-rcr-choices nil
"Internal variable for `elpy-ido-recursive-completing-read'.
Don't touch. Won't help.")
(defun elpy-ido--rcr-selected ()
"Return the currently selected compound."
(mapconcat #'identity
(reverse elpy-ido-rcr-selection)
elpy-ido-rcr-separator))
(defun elpy-ido--rcr-setup-keymap ()
"Set up the ido keymap for `elpy-ido-recursive-completing-read'."
(define-key ido-completion-map (read-kbd-macro elpy-ido-rcr-separator)
'elpy-ido-rcr-complete)
(define-key ido-completion-map (kbd "DEL") 'elpy-ido-rcr-backspace))
(defun elpy-ido-rcr-complete ()
"Complete the current ido completion and attempt an extension."
(interactive)
(let* ((new (car ido-matches))
(full (concat (elpy-ido--rcr-selected)
elpy-ido-rcr-separator
new))
(choices (funcall elpy-ido-rcr-choice-function full)))
(when choices
(setq elpy-ido-rcr-choices choices
elpy-ido-rcr-selection (cons new elpy-ido-rcr-selection))
(throw 'continue t))))
(defun elpy-ido-rcr-backspace (&optional n)
"Delete the last character in the minibuffer.
If the minibuffer is empty, recurse to the last completion."
(interactive "p")
(if (= (minibuffer-prompt-end) (point))
(progn
(setq elpy-ido-rcr-selection (cdr elpy-ido-rcr-selection)
elpy-ido-rcr-choices (funcall elpy-ido-rcr-choice-function
(elpy-ido--rcr-selected)))
(throw 'continue t))
(delete-char (- n))))
(defun elpy-ido-recursive-completing-read (prompt choice-function
separator
&optional
require-match
initial-input
hist def)
"An alternative to `ido-completing-read' supporting recursive selection.
The CHOICE-FUNCTION is called with a prefix string and should
find all possible selections with this prefix. The user is then
prompted with those options. When the user hits RET, the
currently selected option is returned. When the user hits the
SEPARATOR key, though, the currently selected option is appended,
with the separator, to the selected prefix, and the user is
prompted for further completions returned by CHOICE-FUNCTION.
For REQUIRE-MATCH, INITIAL-INPUT, HIST and DEF, see
`completing-read'."
(let ((ido-setup-hook (cons 'elpy-ido--rcr-setup-keymap
ido-setup-hook))
(elpy-ido-rcr-choice-function choice-function)
(elpy-ido-rcr-separator separator)
elpy-ido-rcr-choices
elpy-ido-rcr-selection)
(when initial-input
(let ((parts (reverse (split-string initial-input
(regexp-quote separator)))))
(setq initial-input (car parts)
elpy-ido-rcr-selection (cdr parts))))
(setq elpy-ido-rcr-choices (funcall choice-function
(elpy-ido--rcr-selected)))
(catch 'return
(while t
(catch 'continue
(throw 'return
(let ((completion (ido-completing-read
(concat prompt
(elpy-ido--rcr-selected)
(if elpy-ido-rcr-selection
elpy-ido-rcr-separator
""))
elpy-ido-rcr-choices
nil require-match
initial-input hist def)))
(concat
(mapconcat (lambda (element)
(concat element elpy-ido-rcr-separator))
(reverse elpy-ido-rcr-selection)
"")
completion))))
;; after the first run, we don't want initial and default
;; anymore.
(setq initial-input nil
def nil)))))
;;;;;;;;;;;;;;;;;;;;;
;;; elpy-rpc backends
;; elpy-rpc is a simple JSON-based RPC protocol. It's mostly JSON-RPC
;; 1.0, except we do not implement the full protocol as we do not need
;; all the features. Emacs starts a Python subprocess which runs a
;; special module. The module reads JSON-RPC requests and responds
;; with JSON-RPC responses.
(defvar elpy-rpc--call-id 0
"Call id of the last elpy-rpc call.
Used to associate responses to callbacks.")
(make-variable-buffer-local 'elpy-rpc--call-id)
(defvar elpy-rpc--buffer-p nil
"True iff the current buffer is an elpy-rpc buffer.")
(make-variable-buffer-local 'elpy-rpc--buffer-p)
(defvar elpy-rpc--buffer nil
"The elpy-rpc buffer associated with this buffer.")
(make-variable-buffer-local 'elpy-rpc--buffer)
(defvar elpy-rpc--backend-project-root nil
"The project root used by this backend.")
(make-variable-buffer-local 'elpy-rpc--backend-project-root)
(defvar elpy-rpc--backend-python-command nil
"The Python interpreter used by this backend.")
(make-variable-buffer-local 'elpy-rpc--backend-python-command)
(defvar elpy-rpc--backend-callbacks nil
"The callbacks registered for calls to the current backend.
This maps call IDs to functions.")
(make-variable-buffer-local 'elpy-rpc--backend-callbacks)
(defvar elpy-rpc--timeout 1
"Number of seconds to wait for a response.
You can dynamically bind this to a higher value if you want to
wait longer.")
(defun elpy-rpc--process-buffer-p (buffer)
"Return non-nil when BUFFER is an elpy-rpc buffer."
(buffer-local-value 'elpy-rpc--buffer-p buffer))
(defun elpy-rpc--live-p (buffer)
"Return non-nil when BUFFER is a live elpy-rpc process."
(and buffer
(get-buffer-process buffer)
(process-live-p (get-buffer-process buffer))))
(defun elpy-rpc--get-rpc-buffer ()
"Return the RPC buffer associated with the current buffer,
creating one if necessary."
(cond
(elpy-rpc--buffer-p
(current-buffer))
((not elpy-mode)
(error "Not an Elpy buffer"))
((elpy-rpc--live-p elpy-rpc--buffer)
elpy-rpc--buffer)
(t
(when elpy-rpc--buffer
(kill-buffer elpy-rpc--buffer))
(setq elpy-rpc--buffer
(or (elpy-rpc--find-buffer (elpy-project-root)
elpy-rpc-python-command)
(elpy-rpc--open (elpy-project-root)
elpy-rpc-python-command)))
elpy-rpc--buffer)))
(defun elpy-rpc--get-rpc-process ()
"Return the RPC process associated with the current buffer,
creating one if necessary."
(get-buffer-process (elpy-rpc--get-rpc-buffer)))
(defun elpy-rpc--find-buffer (project-root python-command)
"Return an existing RPC buffer for this project root and command."