Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4084 lines
156 KiB

  1. ;;; elpy.el --- Emacs Python Development Environment -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2012-2019 Jorgen Schaefer
  3. ;; Author: Jorgen Schaefer <contact@jorgenschaefer.de>, Gaby Launay <gaby.launay@protonmail.com>
  4. ;; URL: https://github.com/jorgenschaefer/elpy
  5. ;; Version: 1.35.0
  6. ;; Keywords: Python, IDE, Languages, Tools
  7. ;; Package-Requires: ((company "0.9.10") (emacs "24.4") (highlight-indentation "0.7.0") (pyvenv "1.20") (yasnippet "0.13.0") (s "1.12.0"))
  8. ;; This program is free software; you can redistribute it and/or
  9. ;; modify it under the terms of the GNU General Public License
  10. ;; as published by the Free Software Foundation; either version 3
  11. ;; of the License, or (at your option) any later version.
  12. ;; This program is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; The Emacs Lisp Python Environment in Emacs
  20. ;; Elpy is an Emacs package to bring powerful Python editing to Emacs.
  21. ;; It combines a number of existing Emacs packages, both written in
  22. ;; Emacs Lisp as well as Python.
  23. ;; For more information, read the Elpy manual:
  24. ;; https://elpy.readthedocs.io/en/latest/index.html
  25. ;;; Code:
  26. (require 'cus-edit)
  27. (require 'etags)
  28. (require 'files-x)
  29. (require 'grep)
  30. (require 'ido)
  31. (require 'json)
  32. (require 'python)
  33. (require 'subr-x)
  34. (require 'xref nil t)
  35. (require 'cl-lib) ; for `cl-every', `cl-copy-list', `cl-delete-if-not'
  36. (require 'elpy-refactor)
  37. (require 'elpy-django)
  38. (require 'elpy-profile)
  39. (require 'elpy-shell)
  40. (require 'elpy-rpc)
  41. (require 'pyvenv)
  42. (defconst elpy-version "1.35.0"
  43. "The version of the Elpy Lisp code.")
  44. ;;;;;;;;;;;;;;;;;;;;;;
  45. ;;; User customization
  46. (defgroup elpy nil
  47. "The Emacs Lisp Python Environment."
  48. :prefix "elpy-"
  49. :group 'languages)
  50. (defcustom elpy-mode-hook nil
  51. "Hook run when `elpy-mode' is enabled.
  52. This can be used to enable minor modes for Python development."
  53. :type 'hook
  54. :options '(subword-mode hl-line-mode)
  55. :group 'elpy)
  56. (defcustom elpy-modules '(elpy-module-sane-defaults
  57. elpy-module-company
  58. elpy-module-eldoc
  59. elpy-module-flymake
  60. elpy-module-highlight-indentation
  61. elpy-module-pyvenv
  62. elpy-module-yasnippet
  63. elpy-module-django)
  64. "Which Elpy modules to use.
  65. Elpy can use a number of modules for additional features, which
  66. can be inidividually enabled or disabled."
  67. :type '(set (const :tag "Inline code completion (company-mode)"
  68. elpy-module-company)
  69. (const :tag "Show function signatures (ElDoc)"
  70. elpy-module-eldoc)
  71. (const :tag "Highlight syntax errors (Flymake)"
  72. elpy-module-flymake)
  73. (const :tag "Code folding"
  74. elpy-module-folding)
  75. (const :tag "Show the virtualenv in the mode line (pyvenv)"
  76. elpy-module-pyvenv)
  77. (const :tag "Display indentation markers (highlight-indentation)"
  78. elpy-module-highlight-indentation)
  79. (const :tag "Expand code snippets (YASnippet)"
  80. elpy-module-yasnippet)
  81. (const :tag "Django configurations (Elpy-Django)"
  82. elpy-module-django)
  83. (const :tag "Automatically update documentation (Autodoc)."
  84. elpy-module-autodoc)
  85. (const :tag "Configure some sane defaults for Emacs"
  86. elpy-module-sane-defaults))
  87. :group 'elpy)
  88. (defcustom elpy-project-ignored-directories
  89. '(".tox" "build" "dist" ".cask" ".ipynb_checkpoints")
  90. "Directories ignored by functions working on the whole project.
  91. This is in addition to `vc-directory-exclusion-list'
  92. and `grep-find-ignored-directories', as appropriate."
  93. :type '(repeat string)
  94. :safe (lambda (val)
  95. (cl-every #'stringp val))
  96. :group 'elpy)
  97. (defun elpy-project-ignored-directories ()
  98. "Compute the list of ignored directories for project.
  99. Combines
  100. `elpy-project-ignored-directories'
  101. `vc-directory-exclusion-list'
  102. `grep-find-ignored-directories'"
  103. (delete-dups
  104. (append elpy-project-ignored-directories
  105. vc-directory-exclusion-list
  106. (if (fboundp 'rgrep-find-ignored-directories)
  107. (rgrep-find-ignored-directories (elpy-project-root))
  108. (cl-delete-if-not #'stringp (cl-copy-list
  109. grep-find-ignored-directories))))))
  110. (defcustom elpy-project-root nil
  111. "The root of the project the current buffer is in.
  112. There is normally no use in setting this variable directly, as
  113. Elpy tries to detect the project root automatically. See
  114. `elpy-project-root-finder-functions' for a way of influencing
  115. this.
  116. Setting this variable globally will override Elpy's automatic
  117. project detection facilities entirely.
  118. Alternatively, you can set this in file- or directory-local
  119. variables using \\[add-file-local-variable] or
  120. \\[add-dir-local-variable].
  121. Do not use this variable in Emacs Lisp programs. Instead, call
  122. the `elpy-project-root' function. It will do the right thing."
  123. :type 'directory
  124. :safe 'file-directory-p
  125. :group 'elpy)
  126. (make-variable-buffer-local 'elpy-project-root)
  127. (defcustom elpy-project-root-finder-functions
  128. '(elpy-project-find-projectile-root
  129. elpy-project-find-python-root
  130. elpy-project-find-git-root
  131. elpy-project-find-hg-root
  132. elpy-project-find-svn-root)
  133. "List of functions to ask for the current project root.
  134. These will be checked in turn. The first directory found is used."
  135. :type '(set (const :tag "Projectile project root"
  136. elpy-project-find-projectile-root)
  137. (const :tag "Python project (setup.py, setup.cfg)"
  138. elpy-project-find-python-root)
  139. (const :tag "Git repository root (.git)"
  140. elpy-project-find-git-root)
  141. (const :tag "Mercurial project root (.hg)"
  142. elpy-project-find-hg-root)
  143. (const :tag "Subversion project root (.svn)"
  144. elpy-project-find-svn-root)
  145. (const :tag "Django project root (manage.py, django-admin.py)"
  146. elpy-project-find-django-root))
  147. :group 'elpy)
  148. (make-obsolete-variable 'elpy-company-hide-modeline
  149. 'elpy-remove-modeline-lighter
  150. "1.10.0")
  151. (defcustom elpy-remove-modeline-lighter t
  152. "Non-nil if Elpy should remove most mode line display.
  153. Modeline shows many minor modes currently active. For Elpy, this is mostly
  154. uninteresting information, but if you rely on your modeline in other modes,
  155. you might want to keep it."
  156. :type 'boolean
  157. :group 'elpy)
  158. (defcustom elpy-company-post-completion-function 'ignore
  159. "Your preferred Company post completion function.
  160. Elpy can automatically insert parentheses after completing
  161. callable objects.
  162. The heuristic on when to insert these parentheses can easily be
  163. wrong, though, so this is disabled by default. Set this variable
  164. to the function `elpy-company-post-complete-parens' to enable
  165. this feature."
  166. :type '(choice (const :tag "Ignore post complete" ignore)
  167. (const :tag "Complete callables with parens"
  168. elpy-company-post-complete-parens)
  169. (function :tag "Other function"))
  170. :group 'elpy)
  171. (defcustom elpy-get-info-from-shell nil
  172. "If t, use the shell to gather docstrings and completions.
  173. Normally elpy provides completion and documentation using static code analysis (from jedi). With this option set to t, elpy will add the completion candidates and the docstrings from the associated python shell; This activates fallback completion candidates for cases when static code analysis fails."
  174. :type 'boolean
  175. :group 'elpy)
  176. (defcustom elpy-get-info-from-shell-timeout 1
  177. "Timeout (in seconds) for gathering information from the shell."
  178. :type 'number
  179. :group 'elpy)
  180. (defcustom elpy-eldoc-show-current-function t
  181. "If true, show the current function if no calltip is available.
  182. When Elpy can not find the calltip of the function call at point,
  183. it can show the name of the function or class and method being
  184. edited instead. Setting this variable to nil disables this feature."
  185. :type 'boolean
  186. :group 'elpy)
  187. (defcustom elpy-test-runner 'elpy-test-discover-runner
  188. "The test runner to use to run tests."
  189. :type '(choice (const :tag "Unittest Discover" elpy-test-discover-runner)
  190. (const :tag "Green" elpy-test-green-runner)
  191. (const :tag "Django Discover" elpy-test-django-runner)
  192. (const :tag "Nose" elpy-test-nose-runner)
  193. (const :tag "py.test" elpy-test-pytest-runner)
  194. (const :tag "Twisted Trial" elpy-test-trial-runner))
  195. :safe 'elpy-test-runner-p
  196. :group 'elpy)
  197. (defcustom elpy-test-discover-runner-command '("python-shell-interpreter" "-m" "unittest")
  198. "The command to use for `elpy-test-discover-runner'.
  199. If the string \"python-shell-interpreter\" is present, it will be replaced with
  200. the value of `python-shell-interpreter'."
  201. :type '(repeat string)
  202. :group 'elpy)
  203. (defcustom elpy-test-green-runner-command '("green")
  204. "The command to use for `elpy-test-green-runner'."
  205. :type '(repeat string)
  206. :group 'elpy)
  207. (defcustom elpy-test-nose-runner-command '("nosetests")
  208. "The command to use for `elpy-test-nose-runner'."
  209. :type '(repeat string)
  210. :group 'elpy)
  211. (defcustom elpy-test-trial-runner-command '("trial")
  212. "The command to use for `elpy-test-trial-runner'."
  213. :type '(repeat string)
  214. :group 'elpy)
  215. (defcustom elpy-test-pytest-runner-command '("py.test")
  216. "The command to use for `elpy-test-pytest-runner'."
  217. :type '(repeat string)
  218. :group 'elpy)
  219. (defcustom elpy-test-compilation-function 'compile
  220. "Function used by `elpy-test-run' to run a test command.
  221. The function should behave similarly to `compile'. Another good
  222. option is `pdb'."
  223. :type 'string
  224. :group 'elpy)
  225. (defcustom elpy-rgrep-file-pattern "*.py"
  226. "FILES to use for `elpy-rgrep-symbol'."
  227. :type 'string
  228. :group 'elpy)
  229. (defcustom elpy-disable-backend-error-display t
  230. "Non-nil if Elpy should disable backend error display."
  231. :type 'boolean
  232. :group 'elpy)
  233. (defcustom elpy-formatter nil
  234. "Auto formatter used by `elpy-format-code'.
  235. if nil, use the first formatter found amongst
  236. `yapf' , `autopep8' and `black'."
  237. :type '(choice (const :tag "First one found" nil)
  238. (const :tag "Yapf" yapf)
  239. (const :tag "autopep8" autopep8)
  240. (const :tag "Black" black))
  241. :group 'elpy)
  242. (defcustom elpy-syntax-check-command "flake8"
  243. "The command to use for `elpy-check'."
  244. :type 'string
  245. :group 'elpy)
  246. ;;;;;;;;;;;;;
  247. ;;; Elpy Mode
  248. (defvar elpy-refactor-map
  249. (let ((map (make-sparse-keymap "Refactor")))
  250. (define-key map (kbd "i") (cons (format "%smport fixup"
  251. (propertize "i" 'face 'bold))
  252. 'elpy-importmagic-fixup))
  253. (define-key map (kbd "f") (cons (format "%sormat code"
  254. (propertize "f" 'face 'bold))
  255. 'elpy-format-code))
  256. (define-key map (kbd "r") (cons (format "%sefactor"
  257. (propertize "r" 'face 'bold))
  258. 'elpy-refactor))
  259. map)
  260. "Key map for the refactor command.")
  261. (defvar elpy-mode-map
  262. (let ((map (make-sparse-keymap)))
  263. ;; Alphabetical order to make it easier to find free C-c C-X
  264. ;; bindings in the future. Heh.
  265. ;; (define-key map (kbd "<backspace>") 'python-indent-dedent-line-backspace)
  266. ;; (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
  267. ;; (define-key map (kbd "C-M-x") 'python-shell-send-defun)
  268. ;; (define-key map (kbd "C-c <") 'python-indent-shift-left)
  269. ;; (define-key map (kbd "C-c >") 'python-indent-shift-right)
  270. (define-key map (kbd "C-c RET") 'elpy-importmagic-add-import)
  271. (define-key map (kbd "C-c C-b") 'elpy-nav-expand-to-indentation)
  272. (define-key map (kbd "C-c C-c") 'elpy-shell-send-region-or-buffer)
  273. (define-key map (kbd "C-c C-d") 'elpy-doc)
  274. (define-key map (kbd "C-c C-e") 'elpy-multiedit-python-symbol-at-point)
  275. (define-key map (kbd "C-c C-f") 'elpy-find-file)
  276. (define-key map (kbd "C-c C-n") 'elpy-flymake-next-error)
  277. (define-key map (kbd "C-c C-o") 'elpy-occur-definitions)
  278. (define-key map (kbd "C-c C-p") 'elpy-flymake-previous-error)
  279. (define-key map (kbd "C-c @ C-c") 'elpy-folding-toggle-at-point)
  280. (define-key map (kbd "C-c @ C-b") 'elpy-folding-toggle-docstrings)
  281. (define-key map (kbd "C-c @ C-m") 'elpy-folding-toggle-comments)
  282. (define-key map (kbd "C-c @ C-f") 'elpy-folding-hide-leafs)
  283. (define-key map (kbd "C-c C-s") 'elpy-rgrep-symbol)
  284. (define-key map (kbd "C-c C-t") 'elpy-test)
  285. (define-key map (kbd "C-c C-v") 'elpy-check)
  286. (define-key map (kbd "C-c C-z") 'elpy-shell-switch-to-shell)
  287. (define-key map (kbd "C-c C-k") 'elpy-shell-kill)
  288. (define-key map (kbd "C-c C-K") 'elpy-shell-kill-all)
  289. (define-key map (kbd "C-c C-r") elpy-refactor-map)
  290. (define-key map (kbd "C-c C-x") elpy-django-mode-map)
  291. (define-key map (kbd "<S-return>") 'elpy-open-and-indent-line-below)
  292. (define-key map (kbd "<C-S-return>") 'elpy-open-and-indent-line-above)
  293. (define-key map (kbd "<C-return>") 'elpy-shell-send-statement-and-step)
  294. (define-key map (kbd "<C-down>") 'elpy-nav-forward-block)
  295. (define-key map (kbd "<C-up>") 'elpy-nav-backward-block)
  296. (define-key map (kbd "<C-left>") 'elpy-nav-backward-indent)
  297. (define-key map (kbd "<C-right>") 'elpy-nav-forward-indent)
  298. (define-key map (kbd "<M-down>") 'elpy-nav-move-line-or-region-down)
  299. (define-key map (kbd "<M-up>") 'elpy-nav-move-line-or-region-up)
  300. (define-key map (kbd "<M-left>") 'elpy-nav-indent-shift-left)
  301. (define-key map (kbd "<M-right>") 'elpy-nav-indent-shift-right)
  302. (unless (fboundp 'xref-find-definitions)
  303. (define-key map (kbd "M-.") 'elpy-goto-definition))
  304. (if (not (fboundp 'xref-find-definitions-other-window))
  305. (define-key map (kbd "C-x 4 M-.") 'elpy-goto-definition-other-window)
  306. (define-key map (kbd "C-x 4 M-.") 'xref-find-definitions-other-window))
  307. (when (fboundp 'xref-pop-marker-stack)
  308. (define-key map (kbd "M-*") 'xref-pop-marker-stack))
  309. (define-key map (kbd "M-TAB") 'elpy-company-backend)
  310. map)
  311. "Key map for the Emacs Lisp Python Environment.")
  312. (defvar elpy-shell-map
  313. (let ((map (make-sparse-keymap)))
  314. (define-key map (kbd "e") 'elpy-shell-send-statement)
  315. (define-key map (kbd "E") 'elpy-shell-send-statement-and-go)
  316. (define-key map (kbd "s") 'elpy-shell-send-top-statement)
  317. (define-key map (kbd "S") 'elpy-shell-send-top-statement-and-go)
  318. (define-key map (kbd "f") 'elpy-shell-send-defun)
  319. (define-key map (kbd "F") 'elpy-shell-send-defun-and-go)
  320. (define-key map (kbd "c") 'elpy-shell-send-defclass)
  321. (define-key map (kbd "C") 'elpy-shell-send-defclass-and-go)
  322. (define-key map (kbd "o") 'elpy-shell-send-group)
  323. (define-key map (kbd "O") 'elpy-shell-send-group-and-go)
  324. (define-key map (kbd "w") 'elpy-shell-send-codecell)
  325. (define-key map (kbd "W") 'elpy-shell-send-codecell-and-go)
  326. (define-key map (kbd "r") 'elpy-shell-send-region-or-buffer)
  327. (define-key map (kbd "R") 'elpy-shell-send-region-or-buffer-and-go)
  328. (define-key map (kbd "b") 'elpy-shell-send-buffer)
  329. (define-key map (kbd "B") 'elpy-shell-send-buffer-and-go)
  330. (define-key map (kbd "C-e") 'elpy-shell-send-statement-and-step)
  331. (define-key map (kbd "C-S-E") 'elpy-shell-send-statement-and-step-and-go)
  332. (define-key map (kbd "C-s") 'elpy-shell-send-top-statement-and-step)
  333. (define-key map (kbd "C-S-S") 'elpy-shell-send-top-statement-and-step-and-go)
  334. (define-key map (kbd "C-f") 'elpy-shell-send-defun-and-step)
  335. (define-key map (kbd "C-S-F") 'elpy-shell-send-defun-and-step-and-go)
  336. (define-key map (kbd "C-c") 'elpy-shell-send-defclass-and-step)
  337. (define-key map (kbd "C-S-C") 'elpy-shell-send-defclass-and-step-and-go)
  338. (define-key map (kbd "C-o") 'elpy-shell-send-group-and-step)
  339. (define-key map (kbd "C-S-O") 'elpy-shell-send-group-and-step-and-go)
  340. (define-key map (kbd "C-w") 'elpy-shell-send-codecell-and-step)
  341. (define-key map (kbd "C-S-W") 'elpy-shell-send-codecell-and-step-and-go)
  342. (define-key map (kbd "C-r") 'elpy-shell-send-region-or-buffer-and-step)
  343. (define-key map (kbd "C-S-R") 'elpy-shell-send-region-or-buffer-and-step-and-go)
  344. (define-key map (kbd "C-b") 'elpy-shell-send-buffer-and-step)
  345. (define-key map (kbd "C-S-B") 'elpy-shell-send-buffer-and-step-and-go)
  346. map)
  347. "Key map for the shell related commands.")
  348. (fset 'elpy-shell-map elpy-shell-map)
  349. (defcustom elpy-shell-command-prefix-key "C-c C-y"
  350. "Prefix key used to call elpy shell related commands.
  351. This option need to bet set through `customize' or `customize-set-variable' to be taken into account."
  352. :type 'string
  353. :group 'elpy
  354. :set
  355. (lambda (var key)
  356. (when (and (boundp var) (symbol-value var))
  357. (define-key elpy-mode-map (kbd (symbol-value var)) nil))
  358. (when key
  359. (define-key elpy-mode-map (kbd key) 'elpy-shell-map)
  360. (set var key))))
  361. (defvar elpy-pdb-map
  362. (let ((map (make-sparse-keymap)))
  363. (define-key map (kbd "d") 'elpy-pdb-debug-buffer)
  364. (define-key map (kbd "p") 'elpy-pdb-break-at-point)
  365. (define-key map (kbd "e") 'elpy-pdb-debug-last-exception)
  366. (define-key map (kbd "b") 'elpy-pdb-toggle-breakpoint-at-point)
  367. map)
  368. "Key map for the shell related commands.")
  369. (fset 'elpy-pdb-map elpy-pdb-map)
  370. (define-key elpy-mode-map (kbd "C-c C-u") 'elpy-pdb-map)
  371. (easy-menu-define elpy-menu elpy-mode-map
  372. "Elpy Mode Menu"
  373. '("Elpy"
  374. ["Documentation" elpy-doc
  375. :help "Get documentation for symbol at point"]
  376. ["Run Tests" elpy-test
  377. :help "Run test at point, or all tests in the project"]
  378. ["Go to Definition" elpy-goto-definition
  379. :help "Go to the definition of the symbol at point"]
  380. ["Go to previous definition" pop-tag-mark
  381. :active (not (ring-empty-p find-tag-marker-ring))
  382. :help "Return to the position"]
  383. ["Complete" elpy-company-backend
  384. :keys "M-TAB"
  385. :help "Complete at point"]
  386. ["Refactor" elpy-refactor
  387. :help "Refactor options"]
  388. "---"
  389. ("Interactive Python"
  390. ["Switch to Python Shell" elpy-shell-switch-to-shell
  391. :help "Start and switch to the interactive Python"]
  392. ["Send Region or Buffer" elpy-shell-send-region-or-buffer
  393. :label (if (use-region-p)
  394. "Send Region to Python"
  395. "Send Buffer to Python")
  396. :help "Send the current region or the whole buffer to Python"]
  397. ["Send Definition" elpy-shell-send-defun
  398. :help "Send current definition to Python"]
  399. ["Kill Python shell" elpy-shell-kill
  400. :help "Kill the current Python shell"]
  401. ["Kill all Python shells" elpy-shell-kill-all
  402. :help "Kill all Python shells"])
  403. ("Debugging"
  404. ["Debug buffer" elpy-pdb-debug-buffer
  405. :help "Debug the current buffer using pdb"]
  406. ["Debug at point" elpy-pdb-break-at-point
  407. :help "Debug the current buffer and stop at the current position"]
  408. ["Debug last exception" elpy-pdb-debug-last-exception
  409. :help "Run post-mortem pdb on the last exception"]
  410. ["Add/remove breakpoint" elpy-pdb-toggle-breakpoint-at-point
  411. :help "Add or remove a breakpoint at the current position"])
  412. ("Project"
  413. ["Find File" elpy-find-file
  414. :help "Interactively find a file in the current project"]
  415. ["Find Symbol" elpy-rgrep-symbol
  416. :help "Find occurrences of a symbol in the current project"]
  417. ["Set Project Root" elpy-set-project-root
  418. :help "Change the current project root"]
  419. ["Set Project Variable" elpy-set-project-variable
  420. :help "Configure a project-specific option"])
  421. ("Syntax Check"
  422. ["Check Syntax" elpy-check
  423. :help "Check the syntax of the current file"]
  424. ["Next Error" elpy-flymake-next-error
  425. :help "Go to the next inline error, if any"]
  426. ["Previous Error" elpy-flymake-previous-error
  427. :help "Go to the previous inline error, if any"])
  428. ("Code folding"
  429. ["Hide/show at point" elpy-folding-toggle-at-point
  430. :help "Hide or show the block or docstring at point"]
  431. ["Hide/show all docstrings" elpy-folding-toggle-docstrings
  432. :help "Hide or show all the docstrings"]
  433. ["Hide/show all comments" elpy-folding-toggle-comments
  434. :help "Hide or show all the comments"]
  435. ["Hide leafs" elpy-folding-hide-leafs
  436. :help "Hide all leaf blocks (blocks not containing other blocks)"])
  437. ("Indentation Blocks"
  438. ["Dedent" python-indent-shift-left
  439. :help "Dedent current block or region"
  440. :suffix (if (use-region-p) "Region" "Block")]
  441. ["Indent" python-indent-shift-right
  442. :help "Indent current block or region"
  443. :suffix (if (use-region-p) "Region" "Block")]
  444. ["Up" elpy-nav-move-line-or-region-up
  445. :help "Move current block or region up"
  446. :suffix (if (use-region-p) "Region" "Block")]
  447. ["Down" elpy-nav-move-line-or-region-down
  448. :help "Move current block or region down"
  449. :suffix (if (use-region-p) "Region" "Block")])
  450. "---"
  451. ["Configure" elpy-config t]))
  452. (defvar elpy-enabled-p nil
  453. "Is Elpy enabled or not.")
  454. ;;;###autoload
  455. (defun elpy-enable (&optional _ignored)
  456. "Enable Elpy in all future Python buffers."
  457. (interactive)
  458. (unless elpy-enabled-p
  459. (when (< emacs-major-version 24)
  460. (error "Elpy requires Emacs 24 or newer"))
  461. (when _ignored
  462. (warn "The argument to `elpy-enable' is deprecated, customize `elpy-modules' instead"))
  463. (let ((filename (find-lisp-object-file-name 'python-mode
  464. 'symbol-function)))
  465. (when (and filename
  466. (string-match "/python-mode\\.el\\'"
  467. filename))
  468. (error (concat "You are using python-mode.el. "
  469. "Elpy only works with python.el from "
  470. "Emacs 24 and above"))))
  471. (elpy-modules-global-init)
  472. (define-key inferior-python-mode-map (kbd "C-c C-z") 'elpy-shell-switch-to-buffer)
  473. (add-hook 'python-mode-hook 'elpy-mode)
  474. (add-hook 'pyvenv-post-activate-hooks 'elpy-rpc--disconnect)
  475. (add-hook 'pyvenv-post-deactivate-hooks 'elpy-rpc--disconnect)
  476. (add-hook 'inferior-python-mode-hook 'elpy-shell--enable-output-filter)
  477. (add-hook 'python-shell-first-prompt-hook 'elpy-shell--send-setup-code t)
  478. ;; Add codecell boundaries highligting
  479. (font-lock-add-keywords
  480. 'python-mode
  481. `((,(replace-regexp-in-string "\\\\" "\\\\"
  482. elpy-shell-cell-boundary-regexp)
  483. 0 'elpy-codecell-boundary prepend)))
  484. ;; Enable Elpy-mode in the opened python buffer
  485. (setq elpy-enabled-p t)
  486. (dolist (buffer (buffer-list))
  487. (and (not (string-match "^ ?\\*" (buffer-name buffer)))
  488. (with-current-buffer buffer
  489. (when (string= major-mode 'python-mode)
  490. (python-mode) ;; update codecell fontification
  491. (elpy-mode t)))))
  492. ))
  493. (defun elpy-disable ()
  494. "Disable Elpy in all future Python buffers."
  495. (interactive)
  496. (elpy-modules-global-stop)
  497. (define-key inferior-python-mode-map (kbd "C-c C-z") nil)
  498. (remove-hook 'python-mode-hook 'elpy-mode)
  499. (remove-hook 'pyvenv-post-activate-hooks 'elpy-rpc--disconnect)
  500. (remove-hook 'pyvenv-post-deactivate-hooks 'elpy-rpc--disconnect)
  501. (remove-hook 'inferior-python-mode-hook 'elpy-shell--enable-output-filter)
  502. (remove-hook 'python-shell-first-prompt-hook 'elpy-shell--send-setup-code)
  503. ;; Remove codecell boundaries highligting
  504. (font-lock-remove-keywords
  505. 'python-mode
  506. `((,(replace-regexp-in-string "\\\\" "\\\\"
  507. elpy-shell-cell-boundary-regexp)
  508. 0 'elpy-codecell-boundary prepend)))
  509. (setq elpy-enabled-p nil))
  510. ;;;###autoload
  511. (define-minor-mode elpy-mode
  512. "Minor mode in Python buffers for the Emacs Lisp Python Environment.
  513. This mode fully supports virtualenvs. Once you switch a
  514. virtualenv using \\[pyvenv-workon], you can use
  515. \\[elpy-rpc-restart] to make the elpy Python process use your
  516. virtualenv.
  517. \\{elpy-mode-map}"
  518. :lighter " Elpy"
  519. (unless (derived-mode-p 'python-mode)
  520. (error "Elpy only works with `python-mode'"))
  521. (unless elpy-enabled-p
  522. (error "Please enable Elpy with `(elpy-enable)` before using it"))
  523. (when (boundp 'xref-backend-functions)
  524. (add-hook 'xref-backend-functions #'elpy--xref-backend nil t))
  525. ;; Set this for `elpy-check' command
  526. (setq-local python-check-command elpy-syntax-check-command)
  527. (cond
  528. (elpy-mode
  529. (elpy-modules-buffer-init))
  530. ((not elpy-mode)
  531. (elpy-modules-buffer-stop))))
  532. ;;;;;;;;;;;;;;;
  533. ;;; Elpy Config
  534. (defvar elpy-config--related-custom-groups
  535. '(("Elpy" elpy "elpy-")
  536. ("Python" python "python-")
  537. ("Virtual Environments (Pyvenv)" pyvenv "pyvenv-")
  538. ("Completion (Company)" company "company-")
  539. ("Call Signatures (ElDoc)" eldoc "eldoc-")
  540. ("Inline Errors (Flymake)" flymake "flymake-")
  541. ("Code folding (hideshow)" hideshow "hs-")
  542. ("Snippets (YASnippet)" yasnippet "yas-")
  543. ("Directory Grep (rgrep)" grep "grep-")
  544. ("Search as You Type (ido)" ido "ido-")
  545. ("Django extension" elpy-django "elpy-django-")
  546. ("Autodoc extension" elpy-autodoc "elpy-autodoc-")
  547. ;; ffip does not use defcustom
  548. ;; highlight-indent does not use defcustom, either. Its sole face
  549. ;; is defined in basic-faces.
  550. ))
  551. (defvar elpy-config--get-config "import json
  552. import sys
  553. from distutils.version import LooseVersion
  554. import warnings
  555. warnings.filterwarnings('ignore', category=FutureWarning)
  556. try:
  557. import urllib2 as urllib
  558. except ImportError:
  559. import urllib.request as urllib
  560. # Check if we can connect to pypi quickly enough
  561. try:
  562. response = urllib.urlopen('https://pypi.org/pypi', timeout=1)
  563. CAN_CONNECT_TO_PYPI = True
  564. except:
  565. CAN_CONNECT_TO_PYPI = False
  566. def latest(package, version=None):
  567. if not CAN_CONNECT_TO_PYPI:
  568. return None
  569. try:
  570. response = urllib.urlopen('https://pypi.org/pypi/{package}/json'.format(package=package),
  571. timeout=2).read()
  572. latest = json.loads(response)['info']['version']
  573. if version is None or LooseVersion(version) < LooseVersion(latest):
  574. return latest
  575. else:
  576. return None
  577. except:
  578. return None
  579. config = {}
  580. config['can_connect_to_pypi'] = CAN_CONNECT_TO_PYPI
  581. config['rpc_python_version'] = ('{major}.{minor}.{micro}'
  582. .format(major=sys.version_info[0],
  583. minor=sys.version_info[1],
  584. micro=sys.version_info[2]))
  585. try:
  586. import elpy
  587. config['elpy_version'] = elpy.__version__
  588. except:
  589. config['elpy_version'] = None
  590. try:
  591. import jedi
  592. if isinstance(jedi.__version__, tuple):
  593. config['jedi_version'] = '.'.join(str(x) for x in jedi.__version__)
  594. else:
  595. config['jedi_version'] = jedi.__version__
  596. config['jedi_latest'] = latest('jedi', config['jedi_version'])
  597. except:
  598. config['jedi_version'] = None
  599. config['jedi_latest'] = latest('jedi')
  600. try:
  601. import rope
  602. config['rope_version'] = rope.VERSION
  603. if sys.version_info[0] <= 2:
  604. config['rope_latest'] = latest('rope', config['rope_version'])
  605. else:
  606. config['rope_latest'] = latest('rope_py3k', config['rope_version'])
  607. except:
  608. config['rope_version'] = None
  609. config['rope_latest'] = latest('rope')
  610. try:
  611. import autopep8
  612. config['autopep8_version'] = autopep8.__version__
  613. config['autopep8_latest'] = latest('autopep8', config['autopep8_version'])
  614. except:
  615. config['autopep8_version'] = None
  616. config['autopep8_latest'] = latest('autopep8')
  617. try:
  618. import yapf
  619. config['yapf_version'] = yapf.__version__
  620. config['yapf_latest'] = latest('yapf', config['yapf_version'])
  621. except:
  622. config['yapf_version'] = None
  623. config['yapf_latest'] = latest('yapf')
  624. try:
  625. import black
  626. config['black_version'] = black.__version__
  627. config['black_latest'] = latest('black', config['black_version'])
  628. except:
  629. config['black_version'] = None
  630. config['black_latest'] = latest('black')
  631. json.dump(config, sys.stdout)
  632. ")
  633. (defun elpy-config-error (&optional fmt &rest args)
  634. "Note a configuration problem.
  635. FMT is the formating string.
  636. This will show a message in the minibuffer that tells the user to
  637. use \\[elpy-config]."
  638. (let ((msg (if fmt
  639. (apply #'format fmt args)
  640. "Elpy is not properly configured")))
  641. (error "%s; use M-x elpy-config to configure it" msg)))
  642. ;;;###autoload
  643. (defun elpy-config ()
  644. "Configure Elpy.
  645. This function will pop up a configuration buffer, which is mostly
  646. a customize buffer, but has some more options."
  647. (interactive)
  648. (let ((buf (custom-get-fresh-buffer "*Elpy Config*"))
  649. (config (elpy-config--get-config))
  650. (custom-search-field nil))
  651. (with-current-buffer buf
  652. (elpy-insert--header "Elpy Configuration")
  653. (elpy-config--insert-configuration-table config)
  654. (insert "\n")
  655. (elpy-insert--header "Warnings")
  656. (elpy-config--insert-configuration-problems config)
  657. (elpy-insert--header "Options")
  658. (let ((custom-buffer-style 'tree))
  659. (Custom-mode)
  660. (elpy-config--insert-help)
  661. (dolist (cust elpy-config--related-custom-groups)
  662. (widget-create 'custom-group
  663. :custom-last t
  664. :custom-state 'hidden
  665. :tag (car cust)
  666. :value (cadr cust)))
  667. (widget-setup)
  668. (goto-char (point-min))))
  669. (pop-to-buffer-same-window buf)))
  670. ;;;###autoload
  671. (defun elpy-version ()
  672. "Display the version of Elpy."
  673. (interactive)
  674. (message "Elpy %s (use M-x elpy-config for details)" elpy-version))
  675. (defun elpy-config--insert-help ()
  676. "Insert the customization help."
  677. (let ((start (point)))
  678. ;; Help display from `customize-browse'
  679. (widget-insert (format "\
  680. %s buttons; type RET or click mouse-1
  681. on a button to invoke its action.
  682. Invoke [+] to expand a group, and [-] to collapse an expanded group.\n"
  683. (if custom-raised-buttons
  684. "`Raised' text indicates"
  685. "Square brackets indicate")))
  686. (if custom-browse-only-groups
  687. (widget-insert "\
  688. Invoke the [Group] button below to edit that item in another window.\n\n")
  689. (widget-insert "Invoke the ")
  690. (widget-create 'item
  691. :format "%t"
  692. :tag "[Group]"
  693. :tag-glyph "folder")
  694. (widget-insert ", ")
  695. (widget-create 'item
  696. :format "%t"
  697. :tag "[Face]"
  698. :tag-glyph "face")
  699. (widget-insert ", and ")
  700. (widget-create 'item
  701. :format "%t"
  702. :tag "[Option]"
  703. :tag-glyph "option")
  704. (widget-insert " buttons below to edit that
  705. item in another window.\n\n")
  706. (fill-region start (point)))))
  707. (defun elpy-config--insert-configuration-problems (&optional config)
  708. "Insert help text and widgets for configuration problems."
  709. (unless config
  710. (setq config (elpy-config--get-config)))
  711. (let* ((rpc-python-version (gethash "rpc_python_version" config))
  712. (rope-pypi-package (if (and rpc-python-version
  713. (string-match "^3\\." rpc-python-version))
  714. "rope_py3k"
  715. "rope")))
  716. ;; Python not found
  717. (unless (gethash "rpc_python_executable" config)
  718. (elpy-insert--para
  719. "Elpy can not find the configured Python interpreter. Please make "
  720. "sure that the variable `elpy-rpc-python-command' points to a "
  721. "command in your PATH. You can change the variable below.\n\n"))
  722. ;; No virtual env
  723. (when (and (gethash "rpc_python_executable" config)
  724. (not (gethash "virtual_env" config)))
  725. (elpy-insert--para
  726. "You have not activated a virtual env. It is not mandatory but"
  727. " often a good idea to work inside a virtual env. You can use "
  728. "`M-x pyvenv-activate` or `M-x pyvenv-workon` to activate one.\n\n"))
  729. ;; No virtual env, but ~/.local/bin not in PATH
  730. (when (and (not (memq system-type '(ms-dos windows-nt)))
  731. (gethash "rpc_python_executable" config)
  732. (not pyvenv-virtual-env)
  733. (not (or (member (expand-file-name "~/.local/bin")
  734. exec-path)
  735. (member (expand-file-name "~/.local/bin/")
  736. exec-path))))
  737. (elpy-insert--para
  738. "The directory ~/.local/bin/ is not in your PATH. As there is "
  739. "no active virtualenv, installing Python packages locally will "
  740. "place executables in that directory, so Emacs won't find them. "
  741. "If you are missing some commands, do add this directory to your "
  742. "PATH -- and then do `elpy-rpc-restart'.\n\n"))
  743. ;; Python found, but can't find the elpy module
  744. (when (and (gethash "rpc_python_executable" config)
  745. (not (gethash "elpy_version" config)))
  746. (elpy-insert--para
  747. "The Python interpreter could not find the elpy module. "
  748. "Please report to: "
  749. "https://github.com/jorgenschaefer/elpy/issues/new."
  750. "\n")
  751. (insert "\n"))
  752. ;; Bad backend version
  753. (when (and (gethash "elpy_version" config)
  754. (not (equal (gethash "elpy_version" config)
  755. elpy-version)))
  756. (let ((elpy-python-version (gethash "elpy_version" config)))
  757. (elpy-insert--para
  758. "The Elpy backend is version " elpy-python-version " while "
  759. "the Emacs package is " elpy-version ". This is incompatible. "
  760. "Please report to: https://github.com/jorgenschaefer/elpy/issues/new."
  761. "\n")))
  762. ;; Otherwise unparseable output.
  763. (when (gethash "error_output" config)
  764. (elpy-insert--para
  765. "There was an unexpected problem starting the RPC process. Please "
  766. "check the following output to see if this makes sense to you. "
  767. "To me, it doesn't.\n")
  768. (insert "\n"
  769. (gethash "error_output" config) "\n"
  770. "\n"))
  771. ;; Interactive python interpreter not in the current virtual env
  772. (when (and pyvenv-virtual-env
  773. (not (string-prefix-p (expand-file-name pyvenv-virtual-env)
  774. (executable-find
  775. python-shell-interpreter))))
  776. (elpy-insert--para
  777. "The python interactive interpreter (" python-shell-interpreter
  778. ") is not installed on the current virtualenv ("
  779. pyvenv-virtual-env "). The system binary ("
  780. (executable-find python-shell-interpreter)
  781. ") will be used instead."
  782. "\n")
  783. (insert "\n")
  784. (widget-create 'elpy-insert--pip-button
  785. :package python-shell-interpreter :norpc t)
  786. (insert "\n\n"))
  787. ;; Couldn't connect to pypi to check package versions
  788. (when (not (gethash "can_connect_to_pypi" config))
  789. (elpy-insert--para
  790. "Elpy could not connect to Pypi (or at least not quickly enough) "
  791. "and check if the python packages were up-to-date. "
  792. "You can still try to update all of them:"
  793. "\n")
  794. (insert "\n")
  795. (widget-create 'elpy-insert--generic-button
  796. :button-name "[Update python packages]"
  797. :function (lambda () (with-elpy-rpc-virtualenv-activated
  798. (elpy-rpc--install-dependencies))))
  799. (insert "\n\n"))
  800. ;; Pip not available in the rpc virtualenv
  801. (when (and
  802. (equal elpy-rpc-virtualenv-path 'default)
  803. (elpy-rpc--pip-missing))
  804. (elpy-insert--para
  805. "Pip doesn't seem to be installed in the dedicated virtualenv "
  806. "created by Elpy (" (elpy-rpc-get-virtualenv-path) "). "
  807. "This may prevent some features from working properly"
  808. " (completion, documentation, reformatting, ...). "
  809. "You can try reinstalling the virtualenv. "
  810. "If the problem persists, please report on Elpy's github page."
  811. "\n\n")
  812. (widget-create 'elpy-insert--generic-button
  813. :button-name "[Reinstall RPC virtualenv]"
  814. :function (lambda () (elpy-rpc-reinstall-virtualenv)))
  815. (insert "\n\n"))
  816. ;; Requested backend unavailable
  817. (when (and (gethash "rpc_python_executable" config)
  818. (not (gethash "jedi_version" config)))
  819. (elpy-insert--para
  820. "The Jedi package is not currently installed. "
  821. "This package is needed for code completion, code navigation "
  822. "and access to documentation.\n")
  823. (insert "\n")
  824. (widget-create 'elpy-insert--pip-button
  825. :package "jedi")
  826. (insert "\n\n"))
  827. ;; Newer version of Rope available
  828. (when (and (gethash "rope_version" config)
  829. (gethash "rope_latest" config))
  830. (elpy-insert--para
  831. "There is a newer version of Rope available.\n")
  832. (insert "\n")
  833. (widget-create 'elpy-insert--pip-button
  834. :package rope-pypi-package :upgrade t)
  835. (insert "\n\n"))
  836. ;; Newer version of Jedi available
  837. (when (and (gethash "jedi_version" config)
  838. (gethash "jedi_latest" config))
  839. (elpy-insert--para
  840. "There is a newer version of Jedi available.\n")
  841. (insert "\n")
  842. (widget-create 'elpy-insert--pip-button
  843. :package "jedi" :upgrade t)
  844. (insert "\n\n"))
  845. ;; No auto formatting tool available
  846. (unless (or
  847. (gethash "autopep8_version" config)
  848. (gethash "yapf_version" config)
  849. (gethash "black_version" config))
  850. (elpy-insert--para
  851. "No autoformatting package is currently installed. "
  852. "At least one is needed (Autopep8, Yapf or Black) "
  853. "to perform autoformatting (`C-c C-r f` in a python buffer).\n")
  854. (insert "\n")
  855. (widget-create 'elpy-insert--pip-button
  856. :package "autopep8")
  857. (insert "\n")
  858. (widget-create 'elpy-insert--pip-button
  859. :package "yapf")
  860. (insert "\n")
  861. (widget-create 'elpy-insert--pip-button
  862. :package "black")
  863. (insert "\n\n"))
  864. ;; Newer version of autopep8 available
  865. (when (and (gethash "autopep8_version" config)
  866. (gethash "autopep8_latest" config))
  867. (elpy-insert--para
  868. "There is a newer version of the autopep8 package available.\n")
  869. (insert "\n")
  870. (widget-create 'elpy-insert--pip-button
  871. :package "autopep8" :upgrade t)
  872. (insert "\n\n"))
  873. ;; Newer version of yapf available
  874. (when (and (gethash "yapf_version" config)
  875. (gethash "yapf_latest" config))
  876. (elpy-insert--para
  877. "There is a newer version of the yapf package available.\n")
  878. (insert "\n")
  879. (widget-create 'elpy-insert--pip-button
  880. :package "yapf" :upgrade t)
  881. (insert "\n\n"))
  882. ;; Newer version of black available
  883. (when (and (gethash "black_version" config)
  884. (gethash "black_latest" config))
  885. (elpy-insert--para
  886. "There is a newer version of the black package available.\n")
  887. (insert "\n")
  888. (widget-create 'elpy-insert--pip-button
  889. :package "black" :upgrade t)
  890. (insert "\n\n"))
  891. ;; Syntax checker not available
  892. (unless (executable-find (car (split-string elpy-syntax-check-command)))
  893. (elpy-insert--para
  894. (format
  895. "The configured syntax checker (%s) could not be found. Elpy uses this "
  896. (car (split-string elpy-syntax-check-command)))
  897. "program to provide syntax checks of your code. You can either "
  898. "install it, or select another one using `elpy-syntax-check-command`.\n")
  899. (insert "\n")
  900. (widget-create 'elpy-insert--pip-button :package "flake8" :norpc t)
  901. (insert "\n\n"))
  902. ))
  903. (defun elpy-config--package-available-p (package)
  904. "Check if PACKAGE is installed in the rpc."
  905. (with-elpy-rpc-virtualenv-activated
  906. (equal 0 (call-process elpy-rpc-python-command nil nil nil "-c"
  907. (format "import %s" package)))))
  908. (defun elpy-config--get-config ()
  909. "Return the configuration from `elpy-rpc-python-command'.
  910. This returns a hash table with the following keys (all strings):
  911. emacs_version
  912. elpy_version
  913. python_interactive
  914. python_interactive_version
  915. python_interactive_executable
  916. rpc_virtualenv
  917. rpc_virtualenv_short
  918. rpc_python
  919. rpc_python_version
  920. rpc_python_executable
  921. jedi_version
  922. rope_version
  923. virtual_env
  924. virtual_env_short"
  925. (with-temp-buffer
  926. (let ((config (make-hash-table :test #'equal)))
  927. (puthash "emacs_version" emacs-version config)
  928. (let ((rpc-venv (elpy-rpc-get-or-create-virtualenv)))
  929. (puthash "rpc_virtualenv" rpc-venv config)
  930. (if rpc-venv
  931. (puthash "rpc_virtualenv_short"
  932. (file-name-nondirectory (directory-file-name rpc-venv))
  933. config)
  934. (puthash "rpc_virtualenv_short" nil config)))
  935. (with-elpy-rpc-virtualenv-activated
  936. (puthash "rpc_python" elpy-rpc-python-command config)
  937. (puthash "rpc_python_executable"
  938. (executable-find elpy-rpc-python-command)
  939. config))
  940. (let ((interactive-python (if (boundp 'python-python-command)
  941. python-python-command
  942. python-shell-interpreter)))
  943. (puthash "python_interactive"
  944. interactive-python
  945. config)
  946. (puthash "python_interactive_version"
  947. (let ((pversion (shell-command-to-string
  948. (format "%s --version"
  949. python-shell-interpreter))))
  950. (when (string-match "[0-9.]+" pversion)
  951. (match-string 0 pversion)))
  952. config)
  953. (puthash "python_interactive_executable"
  954. (executable-find interactive-python)
  955. config))
  956. (let ((venv (getenv "VIRTUAL_ENV")))
  957. (puthash "virtual_env" venv config)
  958. (if venv
  959. (puthash "virtual_env_short" (file-name-nondirectory
  960. (directory-file-name venv))
  961. config)
  962. (puthash "virtual_env_short" nil config)))
  963. (with-elpy-rpc-virtualenv-activated
  964. (let ((return-value (ignore-errors
  965. (let ((process-environment
  966. (elpy-rpc--environment))
  967. (default-directory "/"))
  968. (call-process elpy-rpc-python-command
  969. nil
  970. (current-buffer)
  971. nil
  972. "-c"
  973. elpy-config--get-config)))))
  974. (when return-value
  975. (let ((data (ignore-errors
  976. (let ((json-array-type 'list)
  977. (json-false nil)
  978. (json-encoding-pretty-print nil)) ;; Link to bug https://github.com/jorgenschaefer/elpy/issues/1521
  979. (goto-char (point-min))
  980. (json-read)))))
  981. (if (not data)
  982. (puthash "error_output" (buffer-string) config)
  983. (dolist (pair data)
  984. (puthash (symbol-name (car pair)) (cdr pair) config)))))))
  985. config)))
  986. (defun elpy-config--insert-configuration-table (&optional config)
  987. "Insert a table describing the current Elpy config."
  988. (unless config
  989. (setq config (elpy-config--get-config)))
  990. (let ((emacs-version (gethash "emacs_version" config))
  991. (elpy-python-version (gethash "elpy_version" config))
  992. (virtual-env (gethash "virtual_env" config))
  993. (virtual-env-short (gethash "virtual_env_short" config))
  994. (python-interactive (gethash "python_interactive" config))
  995. (python-interactive-version (gethash "python_interactive_version" config))
  996. (python-interactive-executable (gethash "python_interactive_executable"
  997. config))
  998. (rpc-python (gethash "rpc_python" config))
  999. (rpc-python-executable (gethash "rpc_python_executable" config))
  1000. (rpc-python-version (gethash "rpc_python_version" config))
  1001. (rpc-virtualenv (gethash "rpc_virtualenv" config))
  1002. (rpc-virtualenv-short (gethash "rpc_virtualenv_short" config))
  1003. (jedi-version (gethash "jedi_version" config))
  1004. (jedi-latest (gethash "jedi_latest" config))
  1005. (rope-version (gethash "rope_version" config))
  1006. (rope-latest (gethash "rope_latest" config))
  1007. (autopep8-version (gethash "autopep8_version" config))
  1008. (autopep8-latest (gethash "autopep8_latest" config))
  1009. (yapf-version (gethash "yapf_version" config))
  1010. (yapf-latest (gethash "yapf_latest" config))
  1011. (black-version (gethash "black_version" config))
  1012. (black-latest (gethash "black_latest" config))
  1013. table maxwidth)
  1014. (setq table
  1015. `(("Emacs" . ,emacs-version)
  1016. ("Elpy" . ,(cond
  1017. ((and elpy-python-version elpy-version
  1018. (equal elpy-python-version elpy-version))
  1019. elpy-version)
  1020. (elpy-python-version
  1021. (format "%s (Python), %s (Emacs Lisp)"
  1022. elpy-python-version
  1023. elpy-version))
  1024. (t
  1025. (format "Not found (Python), %s (Emacs Lisp)"
  1026. elpy-version))))
  1027. (("Virtualenv" (lambda ()
  1028. (call-interactively 'pyvenv-workon)
  1029. (elpy-config)))
  1030. . ,(if (gethash "virtual_env" config)
  1031. (format "%s (%s)"
  1032. virtual-env-short
  1033. virtual-env)
  1034. "None"))
  1035. (("Interactive Python" (lambda ()
  1036. (customize-variable
  1037. 'python-shell-interpreter)))
  1038. . ,(cond
  1039. (python-interactive-executable
  1040. (format "%s %s (%s)"
  1041. python-interactive
  1042. python-interactive-version
  1043. python-interactive-executable))
  1044. (python-interactive
  1045. (format "%s (not found)"
  1046. python-interactive))
  1047. (t
  1048. "Not configured")))
  1049. ("RPC virtualenv"
  1050. . ,(format "%s (%s)"
  1051. (if (or (eq elpy-rpc-virtualenv-path 'system)
  1052. (eq elpy-rpc-virtualenv-path 'global)) ;; for backward compatibility
  1053. "system"
  1054. rpc-virtualenv-short)
  1055. rpc-virtualenv))
  1056. ((" Python" (lambda ()
  1057. (customize-variable
  1058. 'elpy-rpc-python-command)))
  1059. . ,(cond
  1060. (rpc-python-executable
  1061. (format "%s %s (%s)"
  1062. rpc-python
  1063. rpc-python-version
  1064. rpc-python-executable))
  1065. (rpc-python-executable
  1066. rpc-python-executable)
  1067. (rpc-python
  1068. (format "%s (not found)" rpc-python))
  1069. (t
  1070. (format "Not configured"))))
  1071. (" Jedi" . ,(elpy-config--package-link "jedi"
  1072. jedi-version
  1073. jedi-latest))
  1074. (" Rope" . ,(elpy-config--package-link "rope"
  1075. rope-version
  1076. rope-latest))
  1077. (" Autopep8" . ,(elpy-config--package-link "autopep8"
  1078. autopep8-version
  1079. autopep8-latest))
  1080. (" Yapf" . ,(elpy-config--package-link "yapf"
  1081. yapf-version
  1082. yapf-latest))
  1083. (" Black" . ,(elpy-config--package-link "black"
  1084. black-version
  1085. black-latest))
  1086. (("Syntax checker" (lambda ()
  1087. (customize-variable 'elpy-syntax-check-command)))
  1088. . ,(let ((syntax-checker
  1089. (executable-find
  1090. (car (split-string
  1091. elpy-syntax-check-command)))))
  1092. (if syntax-checker
  1093. (format "%s (%s)"
  1094. (file-name-nondirectory
  1095. syntax-checker)
  1096. syntax-checker)
  1097. (format "Not found (%s)"
  1098. elpy-syntax-check-command))))))
  1099. (setq maxwidth 0)
  1100. (dolist (row table)
  1101. (let (length)
  1102. (if (stringp (car row))
  1103. (setq length (length (car row)))
  1104. (setq length (length (car (car row)))))
  1105. (when (> length maxwidth)
  1106. (setq maxwidth length ))))
  1107. (dolist (row table)
  1108. (if (stringp (car row))
  1109. (insert (car row)
  1110. (make-string (- maxwidth (length (car row)))
  1111. ?.))
  1112. (widget-create 'elpy-insert--generic-button
  1113. :button-name (car (car row))
  1114. :function (car (cdr (car row))))
  1115. (insert (make-string (- maxwidth (length (car (car row))))
  1116. ?.)))
  1117. (insert ": "
  1118. (cdr row)
  1119. "\n"))))
  1120. (defun elpy-config--package-link (_name version latest)
  1121. "Return a string detailing a Python package.
  1122. NAME is the PyPI name of the package. VERSION is the currently
  1123. installed version. LATEST is the latest-available version on
  1124. PyPI, or nil if that's VERSION."
  1125. (cond
  1126. ((and (not version) (not latest))
  1127. "Not found")
  1128. ((not latest)
  1129. version)
  1130. ((not version)
  1131. (format "Not found (%s available)" latest))
  1132. (t
  1133. (format "%s (%s available)" version latest))))
  1134. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1135. ;;; Elpy Formatted Insertion
  1136. (defun elpy-insert--para (&rest messages)
  1137. "Insert MESSAGES, a list of strings, and then fill it."
  1138. (let ((start (point)))
  1139. (mapc (lambda (obj)
  1140. (if (stringp obj)
  1141. (insert obj)
  1142. (insert (format "%s" obj))))
  1143. messages)
  1144. (fill-region start (point))))
  1145. (defun elpy-insert--header (&rest text)
  1146. "Insert TEXT has a header for a buffer."
  1147. (insert (propertize (mapconcat #'(lambda (x) x)
  1148. text
  1149. "")
  1150. 'face 'header-line)
  1151. "\n"
  1152. "\n"))
  1153. (define-widget 'elpy-insert--generic-button 'item
  1154. "A button that run a rgiven function."
  1155. :button-prefix ""
  1156. :button-suffix ""
  1157. :format "%[%v%]"
  1158. :value-create 'elpy-insert--generic-button-value-create
  1159. :action 'elpy-insert--generic-button-action)
  1160. (defun elpy-insert--generic-button-value-create (widget)
  1161. "The :value-create option for the customize button widget."
  1162. (insert (widget-get widget :button-name)))
  1163. (defun elpy-insert--generic-button-action (widget &optional _event)
  1164. "The :action option for the customize button widget."
  1165. (funcall (widget-get widget :function)))
  1166. (define-widget 'elpy-insert--pip-button 'item
  1167. "A button that runs pip (or an alternative)."
  1168. :button-prefix "["
  1169. :button-suffix "]"
  1170. :format "%[%v%]"
  1171. :value-create 'elpy-insert--pip-button-value-create
  1172. :action 'elpy-insert--pip-button-action)
  1173. (defun elpy-insert--pip-button-value-create (widget)
  1174. "The :value-create option for the pip button widget."
  1175. (let* ((python-package (widget-get widget :package))
  1176. (do-upgrade (widget-get widget :upgrade))
  1177. (upgrade-option (if do-upgrade
  1178. "--upgrade "
  1179. ""))
  1180. (command (cond
  1181. ((= (call-process elpy-rpc-python-command
  1182. nil nil nil
  1183. "-m" "pip" "--help")
  1184. 0)
  1185. (format "%s -m pip install %s%s"
  1186. elpy-rpc-python-command
  1187. upgrade-option
  1188. python-package))
  1189. ((executable-find "easy_install")
  1190. (format "easy_install %s" python-package))
  1191. (t
  1192. (error "Neither easy_install nor pip found")))))
  1193. (widget-put widget :command command)
  1194. (if do-upgrade
  1195. (insert (format "Update %s" python-package))
  1196. (insert (format "Install %s" python-package)))))
  1197. (defun elpy-insert--pip-button-action (widget &optional _event)
  1198. "The :action option for the pip button widget."
  1199. (let ((command (widget-get widget :command))
  1200. (norpc (widget-get widget :norpc)))
  1201. (if norpc
  1202. (async-shell-command command)
  1203. (with-elpy-rpc-virtualenv-activated
  1204. (async-shell-command command)))))
  1205. ;;;;;;;;;;;;
  1206. ;;; Projects
  1207. (defvar elpy-project--variable-name-history nil
  1208. "The history for `elpy-project--read-project-variable'.")
  1209. (defun elpy-project-root ()
  1210. "Return the root of the current buffer's project.
  1211. This can very well be nil if the current file is not part of a
  1212. project.
  1213. See `elpy-project-root-finder-functions' for a way to configure
  1214. how the project root is found. You can also set the variable
  1215. `elpy-project-root' in, for example, .dir-locals.el to override
  1216. this."
  1217. (unless elpy-project-root
  1218. (setq elpy-project-root
  1219. (run-hook-with-args-until-success
  1220. 'elpy-project-root-finder-functions)))
  1221. elpy-project-root)
  1222. (defun elpy-set-project-root (new-root)
  1223. "Set the Elpy project root to NEW-ROOT."
  1224. (interactive "DNew project root: ")
  1225. (setq elpy-project-root new-root))
  1226. (defun elpy-project-find-python-root ()
  1227. "Return the current Python project root, if any.
  1228. This is marked with 'setup.py', 'setup.cfg' or 'pyproject.toml'."
  1229. (or (locate-dominating-file default-directory "setup.py")
  1230. (locate-dominating-file default-directory "setup.cfg")
  1231. (locate-dominating-file default-directory "pyproject.toml")))
  1232. (defun elpy-project-find-git-root ()
  1233. "Return the current git repository root, if any."
  1234. (locate-dominating-file default-directory ".git"))
  1235. (defun elpy-project-find-hg-root ()
  1236. "Return the current git repository root, if any."
  1237. (locate-dominating-file default-directory ".hg"))
  1238. (defun elpy-project-find-svn-root ()
  1239. "Return the current git repository root, if any."
  1240. (locate-dominating-file default-directory
  1241. (lambda (dir)
  1242. (and (file-directory-p (format "%s/.svn" dir))
  1243. (not (file-directory-p (format "%s/../.svn"
  1244. dir)))))))
  1245. (defun elpy-project-find-projectile-root ()
  1246. "Return the current project root according to projectile."
  1247. ;; `ignore-errors' both to avoid an unbound function error as well
  1248. ;; as ignore projectile saying there is no project root here.
  1249. (ignore-errors
  1250. (projectile-project-root)))
  1251. (defun elpy-library-root ()
  1252. "Return the root of the Python package chain of the current buffer.
  1253. That is, if you have /foo/package/module.py, it will return /foo,
  1254. so that import package.module will pick up module.py."
  1255. (locate-dominating-file default-directory
  1256. (lambda (dir)
  1257. (not (file-exists-p
  1258. (format "%s/__init__.py"
  1259. dir))))))
  1260. (defun elpy-project--read-project-variable (prompt)
  1261. "Prompt the user for a variable name to set project-wide using PROMPT."
  1262. (let* ((prefixes (mapcar (lambda (cust)
  1263. (nth 2 cust))
  1264. elpy-config--related-custom-groups))
  1265. (var-regex (format "^%s" (regexp-opt prefixes))))
  1266. (intern
  1267. (completing-read
  1268. prompt
  1269. obarray
  1270. (lambda (sym)
  1271. (and (get sym 'safe-local-variable)
  1272. (string-match var-regex (symbol-name sym))
  1273. (get sym 'custom-type)))
  1274. :require-match
  1275. nil
  1276. 'elpy-project--variable-name-history))))
  1277. (defun elpy-project--read-variable-value (prompt variable)
  1278. "Read the value for VARIABLE from the user using PROMPT."
  1279. (let ((custom-type (get variable 'custom-type)))
  1280. (if custom-type
  1281. (widget-prompt-value (if (listp custom-type)
  1282. custom-type
  1283. (list custom-type))
  1284. prompt
  1285. (if (boundp variable)
  1286. (funcall
  1287. (or (get variable 'custom-get)
  1288. 'symbol-value)
  1289. variable))
  1290. (not (boundp variable)))
  1291. (eval-minibuffer prompt))))
  1292. (defun elpy-set-project-variable (variable value)
  1293. "Set or remove a variable in the project-wide .dir-locals.el.
  1294. With prefix argument, remove the variable."
  1295. (interactive
  1296. (let* ((variable (elpy-project--read-project-variable
  1297. (if current-prefix-arg
  1298. "Remove project variable: "
  1299. "Set project variable: ")))
  1300. (value (if current-prefix-arg
  1301. nil
  1302. (elpy-project--read-variable-value (format "Value for %s: "
  1303. variable)
  1304. variable))))
  1305. (list variable value)))
  1306. (with-current-buffer (find-file-noselect (format "%s/%s"
  1307. (elpy-project-root)
  1308. dir-locals-file))
  1309. (modify-dir-local-variable nil
  1310. variable
  1311. value
  1312. (if current-prefix-arg
  1313. 'delete
  1314. 'add-or-replace))))
  1315. ;;;;;;;;;;;;;;;;;;;;;;;;
  1316. ;;; Search Project Files
  1317. (defun elpy-rgrep-symbol (regexp)
  1318. "Search for REGEXP in the current project.
  1319. REGEXP defaults to the symbol at point, or the current region if
  1320. active.
  1321. With a prefix argument, always prompt for a string to search for."
  1322. (interactive
  1323. (list
  1324. (let ((symbol
  1325. (if (use-region-p)
  1326. (buffer-substring-no-properties (region-beginning)
  1327. (region-end))
  1328. (thing-at-point 'symbol))))
  1329. (if (and symbol (not current-prefix-arg))
  1330. (concat "\\<" symbol "\\>")
  1331. (read-from-minibuffer "Search in project for regexp: " symbol)))))
  1332. (grep-compute-defaults)
  1333. (let ((grep-find-ignored-directories (elpy-project-ignored-directories)))
  1334. (rgrep regexp
  1335. elpy-rgrep-file-pattern
  1336. (or (elpy-project-root)
  1337. default-directory)))
  1338. (with-current-buffer next-error-last-buffer
  1339. (let ((inhibit-read-only t))
  1340. (save-excursion
  1341. (goto-char (point-min))
  1342. (when (re-search-forward "^find .*" nil t)
  1343. (replace-match (format "Searching for '%s'\n"
  1344. (regexp-quote regexp))))))))
  1345. ;;;;;;;;;;;;;;;;;;;;;;
  1346. ;;; Find Project Files
  1347. (defcustom elpy-ffip-prune-patterns '()
  1348. "Elpy-specific extension of `ffip-prune-patterns'.
  1349. This is in addition to `elpy-project-ignored-directories'
  1350. and `completion-ignored-extensions'.
  1351. The final value of `ffip-prune-patterns' used is computed
  1352. by the eponymous function `elpy-ffip-prune-patterns'."
  1353. :type '(repeat string)
  1354. :safe (lambda (val)
  1355. (cl-every #'stringp val))
  1356. :group 'elpy)
  1357. (defun elpy-ffip-prune-patterns ()
  1358. "Compute `ffip-prune-patterns' from other variables.
  1359. This combines
  1360. `elpy-ffip-prune-patterns'
  1361. `elpy-project-ignored-directories'
  1362. `completion-ignored-extensions'
  1363. `ffip-prune-patterns'."
  1364. (delete-dups
  1365. (nconc
  1366. (mapcar (lambda (dir) (concat "*/" dir "/*"))
  1367. elpy-project-ignored-directories)
  1368. (mapcar (lambda (ext) (if (s-ends-with? "/" ext)
  1369. (concat "*" ext "*")
  1370. (concat "*" ext)))
  1371. completion-ignored-extensions)
  1372. (cl-copy-list elpy-ffip-prune-patterns)
  1373. (cl-copy-list ffip-prune-patterns))))
  1374. (defun elpy-find-file (&optional dwim)
  1375. "Efficiently find a file in the current project.
  1376. It necessitates `projectile' or `find-file-in-project' to be installed.
  1377. With prefix argument (or DWIM non-nil), tries to guess what kind of
  1378. file the user wants to open:
  1379. - On an import line, it opens the file of that module.
  1380. - Otherwise, it opens a test file associated with the current file,
  1381. if one exists. A test file is named test_<name>.py if the current
  1382. file is <name>.py, and is either in the same directory or a
  1383. \"test\" or \"tests\" subdirectory."
  1384. (interactive "P")
  1385. (cond
  1386. ((and dwim
  1387. (buffer-file-name)
  1388. (save-excursion
  1389. (goto-char (line-beginning-position))
  1390. (or (looking-at "^ *import +\\([[:alnum:]._]+\\)")
  1391. (looking-at "^ *from +\\([[:alnum:]._]+\\) +import +\\([[:alnum:]._]+\\)"))))
  1392. (let* ((module (if (match-string 2)
  1393. (format "%s.%s" (match-string 1) (match-string 2))
  1394. (match-string 1)))
  1395. (path (elpy-find--resolve-module module)))
  1396. (if path
  1397. (find-file path)
  1398. (elpy-find-file nil))))
  1399. ((and dwim
  1400. (buffer-file-name))
  1401. (let ((test-file (elpy-find--test-file)))
  1402. (if test-file
  1403. (find-file test-file)
  1404. (elpy-find-file nil))))
  1405. ((fboundp 'projectile-find-file)
  1406. (let ((projectile-globally-ignored-file-suffixes
  1407. (delete-dups
  1408. (nconc
  1409. (cl-copy-list projectile-globally-ignored-file-suffixes)
  1410. (cl-copy-list completion-ignored-extensions))))
  1411. (projectile-globally-ignored-directories
  1412. (delete-dups
  1413. (nconc
  1414. (cl-copy-list projectile-globally-ignored-directories)
  1415. (cl-copy-list elpy-ffip-prune-patterns)
  1416. (elpy-project-ignored-directories))))
  1417. (projectile-project-root (or (elpy-project-root)
  1418. default-directory)))
  1419. (projectile-find-file)))
  1420. ((fboundp 'find-file-in-project)
  1421. (let ((ffip-prune-patterns (elpy-ffip-prune-patterns))
  1422. (ffip-project-root (or (elpy-project-root)
  1423. default-directory))
  1424. ;; Set up ido to use vertical file lists.
  1425. (ffip-prefer-ido-mode t)
  1426. (ido-decorations '("\n" "" "\n" "\n..."
  1427. "[" "]" " [No match]" " [Matched]"
  1428. " [Not readable]" " [Too big]"
  1429. " [Confirm]"))
  1430. (ido-setup-hook (cons (lambda ()
  1431. (define-key ido-completion-map (kbd "<down>")
  1432. 'ido-next-match)
  1433. (define-key ido-completion-map (kbd "<up>")
  1434. 'ido-prev-match))
  1435. ido-setup-hook)))
  1436. (find-file-in-project)))
  1437. (t
  1438. (error "`elpy-find-file' necessitates `projectile' or `find-file-in-project' to be installed"))))
  1439. (defun elpy-find--test-file ()
  1440. "Return the test file for the current file, if any.
  1441. If this is a test file, return the non-test file.
  1442. A test file is named test_<name>.py if the current file is
  1443. <name>.py, and is either in the same directors or a \"test\" or
  1444. \"tests\" subdirectory."
  1445. (let* ((project-root (or (elpy-project-root) default-directory))
  1446. (filename (file-name-base (buffer-file-name)))
  1447. (impl-file (when (string-match "test_\\(.*\\)" filename)
  1448. (match-string 1 filename)))
  1449. (files
  1450. (cond
  1451. ((fboundp 'projectile-find-file)
  1452. (let ((projectile-project-root project-root))
  1453. (projectile-current-project-files)))
  1454. ((fboundp 'find-file-in-project)
  1455. (cl-map 'list 'cdr (ffip-project-search nil nil project-root)))
  1456. (t '())))
  1457. (file (if impl-file
  1458. (cl-remove-if (lambda (file)
  1459. (not (string=
  1460. impl-file
  1461. (file-name-base file))))
  1462. files)
  1463. (cl-remove-if (lambda (file)
  1464. (not (string=
  1465. (format "test_%s" filename)
  1466. (file-name-base file))))
  1467. files))))
  1468. (when file
  1469. (if (> (length file) 1)
  1470. (setq file (completing-read "Which file: " file))
  1471. (setq file (car file)))
  1472. (if (file-name-absolute-p file)
  1473. file
  1474. (concat (file-name-as-directory project-root) file)))))
  1475. (defun elpy-find--module-path (module)
  1476. "Return a directory path for MODULE.
  1477. The resulting path is not guaranteed to exist. This simply
  1478. resolves leading periods relative to the current directory and
  1479. replaces periods in the middle of the string with slashes.
  1480. Only works with absolute imports. Stop using implicit relative
  1481. imports. They're a bad idea."
  1482. (let* ((relative-depth (when(string-match "^\\.+" module)
  1483. (length (match-string 0 module))))
  1484. (base-directory (if relative-depth
  1485. (format "%s/%s"
  1486. (buffer-file-name)
  1487. (mapconcat (lambda (_)
  1488. "../")
  1489. (make-vector relative-depth
  1490. nil)
  1491. ""))
  1492. (elpy-library-root)))
  1493. (file-name (replace-regexp-in-string
  1494. "\\."
  1495. "/"
  1496. (if relative-depth
  1497. (substring module relative-depth)
  1498. module))))
  1499. (expand-file-name (format "%s/%s" base-directory file-name))))
  1500. (defun elpy-find--resolve-module (module)
  1501. "Resolve MODULE relative to the current file and project.
  1502. Returns a full path name for that module."
  1503. (catch 'return
  1504. (let ((path (elpy-find--module-path module)))
  1505. (while (string-prefix-p (expand-file-name (elpy-library-root))
  1506. path)
  1507. (dolist (name (list (format "%s.py" path)
  1508. (format "%s/__init__.py" path)))
  1509. (when (file-exists-p name)
  1510. (throw 'return name)))
  1511. (if (string-match "/$" path)
  1512. (setq path (substring path 0 -1))
  1513. (setq path (file-name-directory path)))))
  1514. nil))
  1515. ;;;;;;;;;;;;;;;;;
  1516. ;;; Syntax Checks
  1517. (defun elpy-check (&optional whole-project-p)
  1518. "Run `python-check-command' on the current buffer's file,
  1519. or the project root if WHOLE-PROJECT-P is non-nil (interactively,
  1520. with a prefix argument)."
  1521. (interactive "P")
  1522. (unless (buffer-file-name)
  1523. (error "Can't check a buffer without a file"))
  1524. (save-some-buffers (not compilation-ask-about-save) nil)
  1525. (let ((process-environment (python-shell-calculate-process-environment))
  1526. (exec-path (python-shell-calculate-exec-path))
  1527. (file-name-or-directory (expand-file-name
  1528. (if whole-project-p
  1529. (or (elpy-project-root)
  1530. (buffer-file-name))
  1531. (buffer-file-name))))
  1532. (extra-args (if whole-project-p
  1533. (concat
  1534. (if (string-match "pylint$" python-check-command)
  1535. " --ignore="
  1536. " --exclude=")
  1537. (mapconcat #'identity
  1538. (elpy-project-ignored-directories)
  1539. ","))
  1540. "")))
  1541. (compilation-start (concat python-check-command
  1542. " "
  1543. (shell-quote-argument file-name-or-directory)
  1544. extra-args)
  1545. nil
  1546. (lambda (_mode-name)
  1547. "*Python Check*"))))
  1548. ;;;;;;;;;;;;;;
  1549. ;;; Navigation
  1550. (defvar elpy-nav-expand--initial-position nil
  1551. "Initial position before expanding to indentation.")
  1552. (make-variable-buffer-local 'elpy-nav-expand--initial-position)
  1553. (defun elpy-rpc-warn-if-jedi-not-available ()
  1554. "Display a warning if jedi is not available in the current RPC."
  1555. (unless elpy-rpc--jedi-available
  1556. (error "This feature requires the `jedi` package to be installed. Please check `elpy-config` for more information.")))
  1557. (defun elpy-goto-definition ()
  1558. "Go to the definition of the symbol at point, if found."
  1559. (interactive)
  1560. (elpy-rpc-warn-if-jedi-not-available)
  1561. (let ((location (elpy-rpc-get-definition)))
  1562. (if location
  1563. (elpy-goto-location (car location) (cadr location))
  1564. (error "No definition found"))))
  1565. (defun elpy-goto-assignment ()
  1566. "Go to the assignment of the symbol at point, if found."
  1567. (interactive)
  1568. (elpy-rpc-warn-if-jedi-not-available)
  1569. (let ((location (elpy-rpc-get-assignment)))
  1570. (if location
  1571. (elpy-goto-location (car location) (cadr location))
  1572. (error "No assignment found"))))
  1573. (defun elpy-goto-definition-other-window ()
  1574. "Go to the definition of the symbol at point in other window, if found."
  1575. (interactive)
  1576. (elpy-rpc-warn-if-jedi-not-available)
  1577. (let ((location (elpy-rpc-get-definition)))
  1578. (if location
  1579. (elpy-goto-location (car location) (cadr location) 'other-window)
  1580. (error "No definition found"))))
  1581. (defun elpy-goto-assignment-other-window ()
  1582. "Go to the assignment of the symbol at point in other window, if found."
  1583. (interactive)
  1584. (elpy-rpc-warn-if-jedi-not-available)
  1585. (let ((location (elpy-rpc-get-assignment)))
  1586. (if location
  1587. (elpy-goto-location (car location) (cadr location) 'other-window)
  1588. (error "No assignment found"))))
  1589. (defun elpy-goto-location (filename offset &optional other-window-p)
  1590. "Show FILENAME at OFFSET to the user.
  1591. If OTHER-WINDOW-P is non-nil, show the same in other window."
  1592. (ring-insert find-tag-marker-ring (point-marker))
  1593. (let ((buffer (find-file-noselect filename)))
  1594. (if other-window-p
  1595. (pop-to-buffer buffer t)
  1596. (switch-to-buffer buffer))
  1597. (goto-char (1+ offset))
  1598. ))
  1599. (defun elpy-nav-forward-block ()
  1600. "Move to the next line indented like point.
  1601. This will skip over lines and statements with different
  1602. indentation levels."
  1603. (interactive "^")
  1604. (let ((indent (current-column))
  1605. (start (point))
  1606. (cur nil))
  1607. (when (/= (% indent python-indent-offset)
  1608. 0)
  1609. (setq indent (* (1+ (/ indent python-indent-offset))
  1610. python-indent-offset)))
  1611. (python-nav-forward-statement)
  1612. (while (and (< indent (current-indentation))
  1613. (not (eobp)))
  1614. (when (equal (point) cur)
  1615. (error "Statement does not finish"))
  1616. (setq cur (point))
  1617. (python-nav-forward-statement))
  1618. (when (< (current-indentation)
  1619. indent)
  1620. (goto-char start))))
  1621. (defun elpy-nav-backward-block ()
  1622. "Move to the previous line indented like point.
  1623. This will skip over lines and statements with different
  1624. indentation levels."
  1625. (interactive "^")
  1626. (let ((indent (current-column))
  1627. (start (point))
  1628. (cur nil))
  1629. (when (/= (% indent python-indent-offset)
  1630. 0)
  1631. (setq indent (* (1+ (/ indent python-indent-offset))
  1632. python-indent-offset)))
  1633. (python-nav-backward-statement)
  1634. (while (and (< indent (current-indentation))
  1635. (not (bobp)))
  1636. (when (equal (point) cur)
  1637. (error "Statement does not start"))
  1638. (setq cur (point))
  1639. (python-nav-backward-statement))
  1640. (when (< (current-indentation)
  1641. indent)
  1642. (goto-char start))))
  1643. (defun elpy-nav-forward-indent ()
  1644. "Move forward to the next indent level, or over the next word."
  1645. (interactive "^")
  1646. (if (< (current-column) (current-indentation))
  1647. (let* ((current (current-column))
  1648. (next (* (1+ (/ current python-indent-offset))
  1649. python-indent-offset)))
  1650. (goto-char (+ (point-at-bol)
  1651. next)))
  1652. (let ((eol (point-at-eol)))
  1653. (forward-word)
  1654. (when (> (point) eol)
  1655. (goto-char (point-at-bol))))))
  1656. (defun elpy-nav-backward-indent ()
  1657. "Move backward to the previous indent level, or over the previous word."
  1658. (interactive "^")
  1659. (if (and (<= (current-column) (current-indentation))
  1660. (/= (current-column) 0))
  1661. (let* ((current (current-column))
  1662. (next (* (1- (/ current python-indent-offset))
  1663. python-indent-offset)))
  1664. (goto-char (+ (point-at-bol)
  1665. next)))
  1666. (backward-word)))
  1667. (defun elpy-nav-move-line-or-region-down (&optional beg end)
  1668. "Move the current line or active region down."
  1669. (interactive
  1670. (if (use-region-p)
  1671. (list (region-beginning) (region-end))
  1672. (list nil nil)))
  1673. (if beg
  1674. (elpy--nav-move-region-vertically beg end 1)
  1675. (elpy--nav-move-line-vertically 1)))
  1676. (defun elpy-nav-move-line-or-region-up (&optional beg end)
  1677. "Move the current line or active region down."
  1678. (interactive
  1679. (if (use-region-p)
  1680. (list (region-beginning) (region-end))
  1681. (list nil nil)))
  1682. (if beg
  1683. (elpy--nav-move-region-vertically beg end -1)
  1684. (elpy--nav-move-line-vertically -1)))
  1685. (defun elpy--nav-move-line-vertically (dir)
  1686. "Move the current line vertically in direction DIR."
  1687. (let* ((beg (point-at-bol))
  1688. (end (point-at-bol 2))
  1689. (col (current-column))
  1690. (region (delete-and-extract-region beg end)))
  1691. (forward-line dir)
  1692. (save-excursion
  1693. (insert region))
  1694. (goto-char (+ (point) col))))
  1695. (defun elpy--nav-move-region-vertically (beg end dir)
  1696. "Move the current region vertically in direction DIR."
  1697. (let* ((point-before-mark (< (point) (mark)))
  1698. (beg (save-excursion
  1699. (goto-char beg)
  1700. (point-at-bol)))
  1701. (end (save-excursion
  1702. (goto-char end)
  1703. (if (bolp)
  1704. (point)
  1705. (point-at-bol 2))))
  1706. (region (delete-and-extract-region beg end)))
  1707. (goto-char beg)
  1708. (forward-line dir)
  1709. (save-excursion
  1710. (insert region))
  1711. (if point-before-mark
  1712. (set-mark (+ (point)
  1713. (length region)))
  1714. (set-mark (point))
  1715. (goto-char (+ (point)
  1716. (length region))))
  1717. (setq deactivate-mark nil)))
  1718. (defun elpy-open-and-indent-line-below ()
  1719. "Open a line below the current one, move there, and indent."
  1720. (interactive)
  1721. (move-end-of-line 1)
  1722. (newline-and-indent))
  1723. (defun elpy-open-and-indent-line-above ()
  1724. "Open a line above the current one, move there, and indent."
  1725. (interactive)
  1726. (move-beginning-of-line 1)
  1727. (save-excursion
  1728. (insert "\n"))
  1729. (indent-according-to-mode))
  1730. (defun elpy-nav-expand-to-indentation ()
  1731. "Select surrounding lines with current indentation."
  1732. (interactive)
  1733. (setq elpy-nav-expand--initial-position (point))
  1734. (let ((indentation (current-indentation)))
  1735. (if (= indentation 0)
  1736. (progn
  1737. (push-mark (point))
  1738. (push-mark (point-max) nil t)
  1739. (goto-char (point-min)))
  1740. (while (<= indentation (current-indentation))
  1741. (forward-line -1))
  1742. (forward-line 1)
  1743. (push-mark (point) nil t)
  1744. (while (<= indentation (current-indentation))
  1745. (forward-line 1))
  1746. (backward-char))))
  1747. (defadvice keyboard-quit (before collapse-region activate)
  1748. "Abort elpy selection by indentation on quit."
  1749. (when (eq last-command 'elpy-nav-expand-to-indentation)
  1750. (goto-char elpy-nav-expand--initial-position)))
  1751. (defun elpy-nav-normalize-region ()
  1752. "If the first or last line are not fully selected, select them completely."
  1753. (let ((beg (region-beginning))
  1754. (end (region-end)))
  1755. (goto-char beg)
  1756. (beginning-of-line)
  1757. (push-mark (point) nil t)
  1758. (goto-char end)
  1759. (unless (= (point) (line-beginning-position))
  1760. (end-of-line))))
  1761. (defun elpy-nav-indent-shift-right (&optional _count)
  1762. "Shift current line by COUNT columns to the right.
  1763. COUNT defaults to `python-indent-offset'.
  1764. If region is active, normalize the region and shift."
  1765. (interactive)
  1766. (if (use-region-p)
  1767. (progn
  1768. (elpy-nav-normalize-region)
  1769. (python-indent-shift-right (region-beginning) (region-end) current-prefix-arg))
  1770. (python-indent-shift-right (line-beginning-position) (line-end-position) current-prefix-arg)))
  1771. (defun elpy-nav-indent-shift-left (&optional _count)
  1772. "Shift current line by COUNT columns to the left.
  1773. COUNT defaults to `python-indent-offset'.
  1774. If region is active, normalize the region and shift."
  1775. (interactive)
  1776. (if (use-region-p)
  1777. (progn
  1778. (elpy-nav-normalize-region)
  1779. (python-indent-shift-left (region-beginning) (region-end) current-prefix-arg))
  1780. (python-indent-shift-left (line-beginning-position) (line-end-position) current-prefix-arg)))
  1781. ;;;;;;;;;;;;;;;;
  1782. ;;; Test running
  1783. (defvar elpy-set-test-runner-history nil
  1784. "History variable for `elpy-set-test-runner'.")
  1785. (defun elpy-test (&optional test-whole-project)
  1786. "Run tests on the current test, or the whole project.
  1787. If there is a test at point, run that test. If not, or if a
  1788. prefix is given, run all tests in the current project."
  1789. (interactive "P")
  1790. (let ((current-test (elpy-test-at-point)))
  1791. (if test-whole-project
  1792. ;; With prefix arg, test the whole project.
  1793. (funcall elpy-test-runner
  1794. (car current-test)
  1795. nil nil nil)
  1796. ;; Else, run only this test
  1797. (apply elpy-test-runner current-test))))
  1798. (defun elpy-set-test-runner (test-runner)
  1799. "Tell Elpy to use TEST-RUNNER to run tests.
  1800. See `elpy-test' for how to invoke it."
  1801. (interactive
  1802. (list
  1803. (let* ((runners (mapcar (lambda (value)
  1804. (cons (nth 2 value)
  1805. (nth 3 value)))
  1806. (cdr (get 'elpy-test-runner 'custom-type))))
  1807. (current (cdr (assq elpy-test-runner
  1808. (mapcar (lambda (cell)
  1809. (cons (cdr cell) (car cell)))
  1810. runners))))
  1811. (choice (completing-read (if current
  1812. (format "Test runner (currently %s): "
  1813. current)
  1814. "Test runner: ")
  1815. runners
  1816. nil t nil 'elpy-set-test-runner-history)))
  1817. (if (equal choice "")
  1818. elpy-test-runner
  1819. (cdr (assoc choice runners))))))
  1820. (setq elpy-test-runner test-runner))
  1821. (defun elpy-test-at-point ()
  1822. "Return a list specifying the test at point, if any.
  1823. This is used as the interactive
  1824. This list has four elements.
  1825. - Top level directory:
  1826. All test files should be importable from here.
  1827. - Test file:
  1828. The current file name.
  1829. - Test module:
  1830. The module name, relative to the top level directory.
  1831. - Test name:
  1832. The full name of the current test within the module, for
  1833. example TestClass.test_method
  1834. If there is no test at point, test name is nil.
  1835. If the current buffer is not visiting a file, only the top level
  1836. directory is not nil."
  1837. (if (not buffer-file-name)
  1838. (progn
  1839. (save-some-buffers)
  1840. (list (elpy-library-root) nil nil nil))
  1841. (let* ((top (elpy-library-root))
  1842. (file buffer-file-name)
  1843. (module (elpy-test--module-name-for-file top file))
  1844. (test (elpy-test--current-test-name)))
  1845. (if (and file (string-match "test" (or module test "")))
  1846. (progn
  1847. (save-buffer)
  1848. (list top file module test))
  1849. (save-some-buffers)
  1850. (list top nil nil nil)))))
  1851. (defun elpy-test--current-test-name ()
  1852. "Return the name of the test at point."
  1853. (let ((name (python-info-current-defun)))
  1854. (if (and name
  1855. (string-match "\\`\\([^.]+\\.[^.]+\\)\\." name))
  1856. (match-string 1 name)
  1857. name)))
  1858. (defun elpy-test--module-name-for-file (top-level module-file)
  1859. "Return the module name relative to TOP-LEVEL for MODULE-FILE.
  1860. For example, for a top level of /project/root/ and a module file
  1861. of /project/root/package/module.py, this would return
  1862. \"package.module\"."
  1863. (let* ((relative-name (file-relative-name module-file top-level))
  1864. (no-extension (replace-regexp-in-string "\\.py\\'" "" relative-name))
  1865. (no-init (replace-regexp-in-string "/__init__\\'" "" no-extension))
  1866. (dotted (replace-regexp-in-string "/" "." no-init)))
  1867. (if (string-match "^\\." dotted)
  1868. (concat "." (replace-regexp-in-string (regexp-quote "...") "." dotted))
  1869. dotted)))
  1870. (defun elpy-test-runner-p (obj)
  1871. "Return t iff OBJ is a test runner.
  1872. This uses the `elpy-test-runner-p' symbol property."
  1873. (get obj 'elpy-test-runner-p))
  1874. (defun elpy-test-run (working-directory command &rest args)
  1875. "Run COMMAND with ARGS in WORKING-DIRECTORY as a test command."
  1876. (let ((default-directory working-directory))
  1877. (funcall elpy-test-compilation-function
  1878. (mapconcat #'shell-quote-argument
  1879. (cons command args)
  1880. " "))))
  1881. (defun elpy-test-get-discover-runner ()
  1882. "Return the test discover runner from `elpy-test-discover-runner-command'."
  1883. (cl-loop
  1884. for string in elpy-test-discover-runner-command
  1885. if (string= string "python-shell-interpreter")
  1886. collect python-shell-interpreter
  1887. else
  1888. collect string))
  1889. (defun elpy-test-discover-runner (top _file module test)
  1890. "Test the project using the python unittest discover runner.
  1891. This requires Python 2.7 or later."
  1892. (interactive (elpy-test-at-point))
  1893. (let ((test (cond
  1894. (test (format "%s.%s" module test))
  1895. (module module)
  1896. (t "discover"))))
  1897. (apply #'elpy-test-run
  1898. top
  1899. (append (elpy-test-get-discover-runner)
  1900. (list test)))))
  1901. (put 'elpy-test-discover-runner 'elpy-test-runner-p t)
  1902. (defun elpy-test-green-runner (top _file module test)
  1903. "Test the project using the green runner."
  1904. (interactive (elpy-test-at-point))
  1905. (let* ((test (cond
  1906. (test (format "%s.%s" module test))
  1907. (module module)))
  1908. (command (if test
  1909. (append elpy-test-green-runner-command (list test))
  1910. elpy-test-green-runner-command)))
  1911. (apply #'elpy-test-run top command)))
  1912. (put 'elpy-test-green-runner 'elpy-test-runner-p t)
  1913. (defun elpy-test-nose-runner (top _file module test)
  1914. "Test the project using the nose test runner.
  1915. This requires the nose package to be installed."
  1916. (interactive (elpy-test-at-point))
  1917. (if module
  1918. (apply #'elpy-test-run
  1919. top
  1920. (append elpy-test-nose-runner-command
  1921. (list (if test
  1922. (format "%s:%s" module test)
  1923. module))))
  1924. (apply #'elpy-test-run
  1925. top
  1926. elpy-test-nose-runner-command)))
  1927. (put 'elpy-test-nose-runner 'elpy-test-runner-p t)
  1928. (defun elpy-test-trial-runner (top _file module test)
  1929. "Test the project using Twisted's Trial test runner.
  1930. This requires the twisted-core package to be installed."
  1931. (interactive (elpy-test-at-point))
  1932. (if module
  1933. (apply #'elpy-test-run
  1934. top
  1935. (append elpy-test-trial-runner-command
  1936. (list (if test
  1937. (format "%s.%s" module test)
  1938. module))))
  1939. (apply #'elpy-test-run top elpy-test-trial-runner-command)))
  1940. (put 'elpy-test-trial-runner 'elpy-test-runner-p t)
  1941. (defun elpy-test-pytest-runner (top file module test)
  1942. "Test the project using the py.test test runner.
  1943. This requires the pytest package to be installed."
  1944. (interactive (elpy-test-at-point))
  1945. (cond
  1946. (test
  1947. (let ((test-list (split-string test "\\.")))
  1948. (apply #'elpy-test-run
  1949. top
  1950. (append elpy-test-pytest-runner-command
  1951. (list (mapconcat #'identity
  1952. (cons file test-list)
  1953. "::"))))))
  1954. (module
  1955. (apply #'elpy-test-run top (append elpy-test-pytest-runner-command
  1956. (list file))))
  1957. (t
  1958. (apply #'elpy-test-run top elpy-test-pytest-runner-command))))
  1959. (put 'elpy-test-pytest-runner 'elpy-test-runner-p t)
  1960. ;;;;;;;;;;;;;;;;;
  1961. ;;; Documentation
  1962. (defvar elpy-doc-history nil
  1963. "History for the `elpy-doc' command.")
  1964. (defun elpy-doc ()
  1965. "Show documentation for the symbol at point.
  1966. If there is no documentation for the symbol at point, or if a
  1967. prefix argument is given, prompt for a symbol from the user."
  1968. (interactive)
  1969. (let ((doc nil))
  1970. (unless current-prefix-arg
  1971. (setq doc (elpy-rpc-get-docstring))
  1972. (unless doc
  1973. (save-excursion
  1974. (python-nav-backward-up-list)
  1975. (setq doc (elpy-rpc-get-docstring))))
  1976. (unless doc
  1977. (setq doc (elpy-rpc-get-pydoc-documentation
  1978. (elpy-doc--symbol-at-point))))
  1979. (unless doc
  1980. (save-excursion
  1981. (python-nav-backward-up-list)
  1982. (setq doc (elpy-rpc-get-pydoc-documentation
  1983. (elpy-doc--symbol-at-point))))))
  1984. (unless doc
  1985. (setq doc (elpy-rpc-get-pydoc-documentation
  1986. (elpy-doc--read-identifier-from-minibuffer
  1987. (elpy-doc--symbol-at-point)))))
  1988. (if doc
  1989. (elpy-doc--show doc)
  1990. (error "No documentation found"))))
  1991. (defun elpy-doc--read-identifier-from-minibuffer (initial)
  1992. "Read a pydoc-able identifier from the minibuffer."
  1993. (completing-read "Pydoc for: "
  1994. (completion-table-dynamic #'elpy-rpc-get-pydoc-completions)
  1995. nil nil initial 'elpy-doc-history))
  1996. (defun elpy-doc--show (documentation)
  1997. "Show DOCUMENTATION to the user, replacing ^H with bold."
  1998. (with-help-window "*Python Doc*"
  1999. (with-current-buffer "*Python Doc*"
  2000. (erase-buffer)
  2001. (insert documentation)
  2002. (goto-char (point-min))
  2003. (while (re-search-forward "\\(.\\)\\1" nil t)
  2004. (replace-match (propertize (match-string 1)
  2005. 'face 'bold)
  2006. t t)))))
  2007. (defun elpy-doc--symbol-at-point ()
  2008. "Return the Python symbol at point, including dotted paths."
  2009. (with-syntax-table python-dotty-syntax-table
  2010. (let ((symbol (symbol-at-point)))
  2011. (if symbol
  2012. (symbol-name symbol)
  2013. nil))))
  2014. ;;;;;;;;;;;;;;
  2015. ;;; Buffer manipulation
  2016. (defun elpy-buffer--replace-block (spec)
  2017. "Replace a block. SPEC is (startline endline newblock)."
  2018. (let ((start-line (nth 0 spec))
  2019. (end-line (nth 1 spec))
  2020. (new-block (nth 2 spec)))
  2021. (save-excursion
  2022. (save-restriction
  2023. (widen)
  2024. (goto-char (point-min))
  2025. (forward-line start-line)
  2026. (let ((beg (point))
  2027. (end (progn (forward-line (- end-line start-line)) (point))))
  2028. ;; Avoid deleting and re-inserting when the blocks are equal.
  2029. (unless (string-equal (buffer-substring beg end) new-block)
  2030. (delete-region beg end)
  2031. (insert new-block)))))))
  2032. (defun elpy-buffer--replace-region (beg end rep)
  2033. "Replace text in BUFFER in region (BEG END) with REP."
  2034. (unless (string-equal (buffer-substring beg end) rep)
  2035. (save-excursion
  2036. (goto-char end)
  2037. (insert rep)
  2038. (delete-region beg end))))
  2039. ;;;;;;;;;;;;;;;;;;;;;
  2040. ;;; Importmagic - make obsolete
  2041. (defun elpy-importmagic-add-import ()
  2042. (interactive))
  2043. (defun elpy-importmagic-fixup ()
  2044. (interactive))
  2045. (make-obsolete 'elpy-importmagic-add-import "support for importmagic has been dropped." "1.17.0")
  2046. (make-obsolete 'elpy-importmagic-fixup "support for importmagic has been dropped." "1.17.0")
  2047. ;;;;;;;;;;;;;;;;;;;;;
  2048. ;;; Code reformatting
  2049. (defun elpy-format-code ()
  2050. "Format code using the available formatter."
  2051. (interactive)
  2052. (let ((elpy-formatter (or elpy-formatter
  2053. (catch 'available
  2054. (dolist (formatter '(yapf autopep8 black))
  2055. (when (elpy-config--package-available-p
  2056. formatter)
  2057. (throw 'available formatter)))))))
  2058. (unless elpy-formatter
  2059. (error "No formatter installed, please install one using `elpy-config'"))
  2060. (unless (elpy-config--package-available-p elpy-formatter)
  2061. (error "The '%s' formatter is not installed, please install it using `elpy-config' or choose another one using `elpy-formatter'"
  2062. elpy-formatter))
  2063. (when (interactive-p) (message "Autoformatting code with %s."
  2064. elpy-formatter))
  2065. (funcall (intern (format "elpy-%s-fix-code" elpy-formatter)))))
  2066. (defun elpy-yapf-fix-code ()
  2067. "Automatically formats Python code with yapf.
  2068. Yapf can be configured with a style file placed in the project
  2069. root directory."
  2070. (interactive)
  2071. (elpy--fix-code-with-formatter "fix_code_with_yapf"))
  2072. (defun elpy-autopep8-fix-code ()
  2073. "Automatically formats Python code to conform to the PEP 8 style guide.
  2074. Autopep8 can be configured with a style file placed in the project
  2075. root directory."
  2076. (interactive)
  2077. (elpy--fix-code-with-formatter "fix_code"))
  2078. (defun elpy-black-fix-code ()
  2079. "Automatically formats Python code with black."
  2080. (interactive)
  2081. (elpy--fix-code-with-formatter "fix_code_with_black"))
  2082. (defun elpy--fix-code-with-formatter (method)
  2083. "Common routine for formatting python code."
  2084. (let ((line (line-number-at-pos))
  2085. (col (current-column))
  2086. (directory (if (elpy-project-root)
  2087. (expand-file-name (elpy-project-root))
  2088. default-directory)))
  2089. (if (use-region-p)
  2090. (let ((new-block (elpy-rpc method
  2091. (list (elpy-rpc--region-contents)
  2092. directory)))
  2093. (beg (region-beginning))
  2094. (end (region-end)))
  2095. (elpy-buffer--replace-region
  2096. beg end (string-trim-right new-block))
  2097. (goto-char end)
  2098. (deactivate-mark))
  2099. (let ((new-block (elpy-rpc method
  2100. (list (elpy-rpc--buffer-contents)
  2101. directory)))
  2102. (beg (point-min))
  2103. (end (point-max)))
  2104. (elpy-buffer--replace-region beg end new-block)
  2105. (when (bobp)
  2106. (forward-line (1- line))
  2107. (forward-char col))))))
  2108. ;;;;;;;;;;;;;;
  2109. ;;; Multi-Edit
  2110. (defvar elpy-multiedit-overlays nil
  2111. "List of overlays currently being edited.")
  2112. (defun elpy-multiedit-add-overlay (beg end)
  2113. "Add an editable overlay between BEG and END.
  2114. A modification in any of these overlays will modify all other
  2115. overlays, too."
  2116. (interactive "r")
  2117. (when (elpy-multiedit--overlays-in-p beg end)
  2118. (error "Overlapping multiedit overlays are not allowed"))
  2119. (let ((ov (make-overlay beg end nil nil :rear-advance)))
  2120. (overlay-put ov 'elpy-multiedit t)
  2121. (overlay-put ov 'face 'highlight)
  2122. (overlay-put ov 'modification-hooks '(elpy-multiedit--overlay-changed))
  2123. (overlay-put ov 'insert-in-front-hooks '(elpy-multiedit--overlay-changed))
  2124. (overlay-put ov 'insert-behind-hooks '(elpy-multiedit--overlay-changed))
  2125. (push ov elpy-multiedit-overlays)))
  2126. (defun elpy-multiedit--overlays-in-p (beg end)
  2127. "Return t iff there are multiedit overlays between beg and end."
  2128. (catch 'return
  2129. (dolist (ov (overlays-in beg end))
  2130. (when (overlay-get ov 'elpy-multiedit)
  2131. (throw 'return t)))
  2132. nil))
  2133. (defun elpy-multiedit-stop ()
  2134. "Stop editing multiple places at once."
  2135. (interactive)
  2136. (dolist (ov elpy-multiedit-overlays)
  2137. (delete-overlay ov))
  2138. (setq elpy-multiedit-overlays nil))
  2139. (defun elpy-multiedit--overlay-changed (ov after-change _beg _end
  2140. &optional _pre-change-length)
  2141. "Called for each overlay that changes.
  2142. This updates all other overlays."
  2143. (when (and after-change
  2144. (not undo-in-progress)
  2145. (overlay-buffer ov))
  2146. (let ((text (buffer-substring (overlay-start ov)
  2147. (overlay-end ov)))
  2148. (inhibit-modification-hooks t))
  2149. (dolist (other-ov elpy-multiedit-overlays)
  2150. (when (and (not (equal other-ov ov))
  2151. (buffer-live-p (overlay-buffer other-ov)))
  2152. (with-current-buffer (overlay-buffer other-ov)
  2153. (save-excursion
  2154. (goto-char (overlay-start other-ov))
  2155. (insert text)
  2156. (delete-region (point) (overlay-end other-ov)))))))))
  2157. (defun elpy-multiedit ()
  2158. "Edit all occurences of the symbol at point, or the active region.
  2159. If multiedit is active, stop it."
  2160. (interactive)
  2161. (if elpy-multiedit-overlays
  2162. (elpy-multiedit-stop)
  2163. (let ((regex (if (use-region-p)
  2164. (regexp-quote (buffer-substring (region-beginning)
  2165. (region-end)))
  2166. (format "\\_<%s\\_>" (regexp-quote
  2167. (symbol-name
  2168. (symbol-at-point))))))
  2169. (case-fold-search nil))
  2170. (save-excursion
  2171. (goto-char (point-min))
  2172. (while (re-search-forward regex nil t)
  2173. (elpy-multiedit-add-overlay (match-beginning 0)
  2174. (match-end 0)))))))
  2175. (defun elpy-multiedit-python-symbol-at-point (&optional use-symbol-p)
  2176. "Edit all usages of the the Python symbol at point.
  2177. With prefix arg, edit all syntactic usages of the symbol at
  2178. point. This might include unrelated symbols that just share the
  2179. name."
  2180. (interactive "P")
  2181. (if (or elpy-multiedit-overlays
  2182. use-symbol-p
  2183. (use-region-p))
  2184. ;; If we are already doing a multiedit, or are explicitly told
  2185. ;; to use the symbol at point, or if we are on an active region,
  2186. ;; call the multiedit function that does just that already.
  2187. (call-interactively 'elpy-multiedit)
  2188. ;; Otherwise, fetch usages from backend.
  2189. (save-some-buffers)
  2190. (let ((usages (condition-case err
  2191. (elpy-rpc-get-usages)
  2192. ;; This is quite the stunt, but elisp parses JSON
  2193. ;; null as nil, which is indistinguishable from
  2194. ;; the empty list, we stick to the error.
  2195. (error
  2196. (if (and (eq (car err) 'error)
  2197. (stringp (cadr err))
  2198. (string-match "not implemented" (cadr err)))
  2199. 'not-supported
  2200. (error (cadr err)))))))
  2201. (cond
  2202. ((eq usages 'not-supported)
  2203. (call-interactively 'elpy-multiedit)
  2204. (message (concat "Using syntactic editing "
  2205. "as current backend does not support get_usages.")))
  2206. ((null usages)
  2207. (call-interactively 'elpy-multiedit)
  2208. (if elpy-multiedit-overlays
  2209. (message (concat "Using syntactic editing as no usages of the "
  2210. "symbol at point were found by the backend."))
  2211. (message "No occurrences of the symbol at point found")))
  2212. (t
  2213. (save-restriction
  2214. (widen)
  2215. (elpy-multiedit--usages usages)))))))
  2216. (defun elpy-multiedit--usages (usages)
  2217. "Mark the usages in USAGES for editing."
  2218. (let ((name nil)
  2219. (locations (make-hash-table :test #'equal)))
  2220. (dolist (usage usages)
  2221. (let* ((filename (cdr (assq 'filename usage)))
  2222. (this-name (cdr (assq 'name usage)))
  2223. (offset (cdr (assq 'offset usage))))
  2224. (setq name this-name)
  2225. (with-current-buffer (if filename
  2226. (find-file-noselect filename)
  2227. (current-buffer))
  2228. (elpy-multiedit-add-overlay (+ offset 1)
  2229. (+ offset 1 (length this-name)))
  2230. (save-excursion
  2231. (goto-char (+ offset 1))
  2232. (puthash filename
  2233. (cons (list offset
  2234. (buffer-substring (line-beginning-position)
  2235. (line-end-position))
  2236. (- (point)
  2237. (line-beginning-position))
  2238. (- (+ (point) (length this-name))
  2239. (line-beginning-position)))
  2240. (gethash filename locations))
  2241. locations)))))
  2242. (if (<= (hash-table-count locations)
  2243. 1)
  2244. (message "Editing %s usages of '%s' in this buffer"
  2245. (length usages) name)
  2246. (with-current-buffer (get-buffer-create "*Elpy Edit Usages*")
  2247. (let ((inhibit-read-only t)
  2248. (filenames nil))
  2249. (erase-buffer)
  2250. (elpy-insert--para
  2251. "The symbol '" name "' was found in multiple files. Editing "
  2252. "all locations:\n\n")
  2253. (maphash (lambda (key _value)
  2254. (unless (member key filenames)
  2255. (setq filenames (cons key filenames))))
  2256. locations)
  2257. (dolist (filename (sort filenames #'string<))
  2258. (elpy-insert--header filename)
  2259. (dolist (location (sort (gethash filename locations)
  2260. (lambda (loc1 loc2)
  2261. (< (car loc1)
  2262. (car loc2)))))
  2263. (let ((line (nth 1 location))
  2264. (start (+ (line-beginning-position)
  2265. (nth 2 location)))
  2266. (end (+ (line-end-position)
  2267. (nth 3 location))))
  2268. ;; Insert the \n first, else we extend the overlay.
  2269. (insert line "\n")
  2270. (elpy-multiedit-add-overlay start end)))
  2271. (insert "\n"))
  2272. (goto-char (point-min))
  2273. (display-buffer (current-buffer)
  2274. nil
  2275. 'visible))))))
  2276. ;;;;;;;;;;;;;;;;;;;;;
  2277. ;;; Occur Definitions
  2278. (defun elpy-occur-definitions ()
  2279. "Display an occur buffer of all definitions in the current buffer.
  2280. Also, switch to that buffer."
  2281. (interactive)
  2282. (let ((list-matching-lines-face nil))
  2283. (occur "^\s*\\(\\(async\s\\|\\)def\\|class\\)\s"))
  2284. (let ((window (get-buffer-window "*Occur*")))
  2285. (if window
  2286. (select-window window)
  2287. (switch-to-buffer "*Occur*"))))
  2288. ;;;;;;;;;;;;;;;;
  2289. ;;; Xref backend
  2290. (defun elpy--xref-backend ()
  2291. "Return the name of the elpy xref backend."
  2292. ;; If no rpc available, start one and assume jedi is available
  2293. (if (or (and (not (elpy-rpc--process-buffer-p elpy-rpc--buffer))
  2294. (elpy-rpc--get-rpc-buffer))
  2295. elpy-rpc--jedi-available)
  2296. 'elpy
  2297. nil))
  2298. (defvar elpy-xref--format-references
  2299. (let ((str "%s:\t%s"))
  2300. (put-text-property 0 4 'face 'compilation-line-number str)
  2301. str)
  2302. "String used to format references in xref buffers.")
  2303. ;; Elpy location structure
  2304. (when (featurep 'xref)
  2305. (cl-defstruct (xref-elpy-location
  2306. (:constructor xref-make-elpy-location (file pos)))
  2307. "Location of a python symbol definition."
  2308. file pos)
  2309. (defun xref-make-elpy-location (file pos)
  2310. "Return an elpy location structure.
  2311. Points to file FILE, at position POS."
  2312. (make-instance 'xref-etags-location
  2313. :file (expand-file-name file)
  2314. :pos pos))
  2315. (cl-defmethod xref-location-marker ((l xref-elpy-location))
  2316. (with-current-buffer (find-file-noselect (xref-elpy-location-file l))
  2317. (save-excursion
  2318. (goto-char (xref-elpy-location-pos l))
  2319. (point-marker))))
  2320. (cl-defmethod xref-location-group ((l xref-elpy-location))
  2321. (xref-elpy-location-file l))
  2322. ;; Identifiers
  2323. (cl-defmethod xref-backend-identifier-at-point ((_backend (eql elpy)))
  2324. (elpy-xref--identifier-at-point))
  2325. (defun elpy-xref--identifier-at-point ()
  2326. "Return identifier at point.
  2327. Is a string, formatted as \"LINE_NUMBER: VARIABLE_NAME\".
  2328. "
  2329. (let* ((symb (symbol-at-point))
  2330. (symb-str (substring-no-properties (symbol-name symb))))
  2331. (when symb
  2332. (format "%s: %s" (line-number-at-pos) symb-str))))
  2333. (defun elpy-xref--identifier-name (id)
  2334. "Return the identifier ID variable name."
  2335. (string-match ".*: \\([^:]*\\)" id)
  2336. (match-string 1 id))
  2337. (defun elpy-xref--identifier-line (id)
  2338. "Return the identifier ID line number."
  2339. (string-match "\\([^:]*\\):.*" id)
  2340. (string-to-number (match-string 1 id)))
  2341. (defun elpy-xref--goto-identifier (id)
  2342. "Goto the identifier ID in the current buffer.
  2343. This is needed to get information on the identifier with jedi
  2344. \(that work only on the symbol at point\)"
  2345. (let ((case-fold-search nil))
  2346. (goto-char (point-min))
  2347. (forward-line (1- (elpy-xref--identifier-line id)))
  2348. (search-forward (elpy-xref--identifier-name id) (line-end-position))
  2349. (goto-char (match-beginning 0))))
  2350. ;; Find definition
  2351. (cl-defmethod xref-backend-definitions ((_backend (eql elpy)) id)
  2352. (elpy-xref--definitions id))
  2353. (defun elpy-xref--definitions (id)
  2354. "Return SYMBOL definition position as a xref object."
  2355. (save-excursion
  2356. (elpy-xref--goto-identifier id)
  2357. (let* ((location (elpy-rpc-get-definition)))
  2358. (if (not location)
  2359. (error "No definition found")
  2360. (let* ((file (expand-file-name (car location)))
  2361. (pos (+ 1 (cadr location)))
  2362. (line (with-current-buffer (find-file-noselect file)
  2363. (goto-char (+ pos 1))
  2364. (buffer-substring (line-beginning-position) (line-end-position))))
  2365. (linenumber (with-current-buffer (find-file-noselect file)
  2366. (line-number-at-pos pos)))
  2367. (summary (format elpy-xref--format-references linenumber line))
  2368. (loc (xref-make-elpy-location file pos)))
  2369. (list (xref-make summary loc)))))))
  2370. ;; Find references
  2371. (cl-defmethod xref-backend-references ((_backend (eql elpy)) id)
  2372. (elpy-xref--references id))
  2373. (defun elpy-xref--references (id)
  2374. "Return SYMBOL references as a list of xref objects."
  2375. (save-excursion
  2376. (elpy-xref--goto-identifier id)
  2377. (let* ((references (elpy-rpc-get-usages)))
  2378. (cl-loop
  2379. for ref in references
  2380. for file = (alist-get 'filename ref)
  2381. for pos = (+ (alist-get 'offset ref) 1)
  2382. for line = (when file
  2383. (with-current-buffer (find-file-noselect file)
  2384. (save-excursion
  2385. (goto-char (+ pos 1))
  2386. (buffer-substring (line-beginning-position) (line-end-position)))))
  2387. for linenumber = (when file
  2388. (with-current-buffer (find-file-noselect file)
  2389. (line-number-at-pos pos)))
  2390. for summary = (format elpy-xref--format-references linenumber line)
  2391. for loc = (xref-make-elpy-location file pos)
  2392. if file
  2393. collect (xref-make summary loc)))))
  2394. ;; Completion table (used when calling `xref-find-references`)
  2395. (cl-defmethod xref-backend-identifier-completion-table ((_backend (eql elpy)))
  2396. (elpy-xref--get-completion-table))
  2397. (defun elpy-xref--get-completion-table ()
  2398. "Return the completion table for identifiers."
  2399. (cl-loop
  2400. for ref in (nreverse (elpy-rpc-get-names))
  2401. for offset = (+ (alist-get 'offset ref) 1)
  2402. for line = (line-number-at-pos offset)
  2403. for id = (format "%s: %s" line (alist-get 'name ref))
  2404. collect id))
  2405. ;; Apropos
  2406. (cl-defmethod xref-backend-apropos ((_backend (eql elpy)) regex)
  2407. (elpy-xref--apropos regex))
  2408. (defun elpy-xref--apropos (regex)
  2409. "Return identifiers matching REGEX."
  2410. (let ((ids (elpy-rpc-get-names))
  2411. (case-fold-search nil))
  2412. (cl-loop
  2413. for id in ids
  2414. for name = (alist-get 'name id)
  2415. for filename = (alist-get 'filename id)
  2416. for pos = (+ (alist-get 'offset id) 1)
  2417. if (string-match regex name)
  2418. collect (with-current-buffer (find-file-noselect filename)
  2419. (goto-char pos)
  2420. (save-excursion
  2421. (let* ((linenumber (line-number-at-pos))
  2422. (line (buffer-substring
  2423. (line-beginning-position)
  2424. (line-end-position)))
  2425. (summary (format elpy-xref--format-references linenumber line))
  2426. (loc (xref-make-elpy-location filename pos)))
  2427. (xref-make summary loc)))))))
  2428. )
  2429. ;;;;;;;;;;;
  2430. ;;; Modules
  2431. (defvar elpy-modules-initialized-p nil
  2432. "Boolean, set to true if modules were run with `global-init'.")
  2433. (defun elpy-modules-run (command &rest args)
  2434. "Run COMMAND with ARGS for all modules in `elpy-modules'."
  2435. (dolist (module elpy-modules)
  2436. (apply module command args)))
  2437. (defun elpy-modules-global-init ()
  2438. "Run the global-init method of Elpy modules.
  2439. Make sure this only happens once."
  2440. (unless elpy-modules-initialized-p
  2441. (elpy-modules-run 'global-init)
  2442. (setq elpy-modules-initialized-p t)))
  2443. (defun elpy-modules-global-stop ()
  2444. "Run the global-stop method of Elpy modules.
  2445. Make sure this only happens once per global-init call."
  2446. (when elpy-modules-initialized-p
  2447. (elpy-modules-run 'global-stop)
  2448. (setq elpy-modules-initialized-p nil)))
  2449. (defun elpy-modules-buffer-init ()
  2450. "Run the buffer-init method of Elpy modules.
  2451. Make sure global-init is called first."
  2452. (elpy-modules-global-init)
  2453. (elpy-modules-run 'buffer-init))
  2454. (defun elpy-modules-buffer-stop ()
  2455. "Run the buffer-stop method of Elpy modules."
  2456. (elpy-modules-run 'buffer-stop))
  2457. (defun elpy-modules-remove-modeline-lighter (modename)
  2458. "Remove the lighter for MODENAME.
  2459. It should not be necessary to see (Python Elpy yas company ElDoc) all the
  2460. time.
  2461. If you need your modeline, you can set the variable `elpy-remove-modeline-lighter' to nil"
  2462. (interactive)
  2463. (when elpy-remove-modeline-lighter
  2464. (cond
  2465. ((eq modename 'eldoc-minor-mode)
  2466. (setq eldoc-minor-mode-string nil))
  2467. (t
  2468. (let ((cell (assq modename minor-mode-alist)))
  2469. (when cell
  2470. (setcdr cell
  2471. (list ""))))))))
  2472. ;;;;;;;;;;;;;;;;;;;;;;;;;
  2473. ;;; Module: Sane Defaults
  2474. (defun elpy-module-sane-defaults (command &rest _args)
  2475. "Module for sane Emacs default for python."
  2476. (pcase command
  2477. (`buffer-init
  2478. ;; Set `forward-sexp-function' to nil in python-mode. See
  2479. ;; http://debbugs.gnu.org/db/13/13642.html
  2480. (set (make-local-variable 'forward-sexp-function) nil)
  2481. ;; PEP8 recommends two spaces in front of inline comments.
  2482. (set (make-local-variable 'comment-inline-offset) 2))
  2483. (`buffer-stop
  2484. (kill-local-variable 'forward-sexp-function)
  2485. (kill-local-variable 'comment-inline-offset))))
  2486. ;;;;;;;;;;;;;;;;;;;
  2487. ;;; Module: Company
  2488. (defun elpy-module-company (command &rest _args)
  2489. "Module to support company-mode completions."
  2490. (pcase command
  2491. (`global-init
  2492. (require 'company)
  2493. (require 'company-capf)
  2494. (elpy-modules-remove-modeline-lighter 'company-mode)
  2495. (define-key company-active-map (kbd "C-d")
  2496. 'company-show-doc-buffer)
  2497. (add-hook 'inferior-python-mode-hook
  2498. (lambda ()
  2499. ;; Workaround for company bug
  2500. ;; (https://github.com/company-mode/company-mode/issues/759)
  2501. (setq-local company-transformers
  2502. (remove 'company-sort-by-occurrence
  2503. company-transformers))
  2504. ;; Be sure to trigger completion for one character variable
  2505. ;; (i.e. `a.`)
  2506. (setq-local company-minimum-prefix-length 2))))
  2507. (`buffer-init
  2508. ;; We want immediate completions from company.
  2509. (set (make-local-variable 'company-idle-delay)
  2510. 0.1)
  2511. ;; And annotations should be right-aligned.
  2512. (set (make-local-variable 'company-tooltip-align-annotations)
  2513. t)
  2514. ;; Also, dabbrev in comments and strings is nice.
  2515. (set (make-local-variable 'company-dabbrev-code-everywhere)
  2516. t)
  2517. ;; Add our own backend and remove a bunch of backends that
  2518. ;; interfere in Python mode.
  2519. (set (make-local-variable 'company-backends)
  2520. (cons 'elpy-company-backend
  2521. (delq 'company-semantic
  2522. (delq 'company-ropemacs
  2523. (delq 'company-capf
  2524. (mapcar #'identity company-backends))))))
  2525. (company-mode 1)
  2526. (when (> (buffer-size) elpy-rpc-ignored-buffer-size)
  2527. (message
  2528. (concat "Buffer %s larger than elpy-rpc-ignored-buffer-size (%d)."
  2529. " Elpy will turn off completion.")
  2530. (buffer-name) elpy-rpc-ignored-buffer-size)))
  2531. (`buffer-stop
  2532. (company-mode -1)
  2533. (kill-local-variable 'company-idle-delay)
  2534. (kill-local-variable 'company-tooltip-align-annotations)
  2535. (kill-local-variable 'company-backends))
  2536. ))
  2537. (defvar elpy-company--cache nil
  2538. "Buffer-local cache for candidate information.")
  2539. (make-variable-buffer-local 'elpy-company--cache)
  2540. (defun elpy-company--cache-clear ()
  2541. "Clear and initialize the cache."
  2542. (if elpy-company--cache
  2543. (clrhash elpy-company--cache)
  2544. (setq elpy-company--cache
  2545. (make-hash-table :test #'equal))))
  2546. (defun elpy-company--cache-annotation (name)
  2547. "Return the cached annotation for NAME."
  2548. (when elpy-company--cache
  2549. (cdr (assq 'annotation (gethash name elpy-company--cache)))))
  2550. (defun elpy-company--cache-meta (name)
  2551. "Return the cached annotation for NAME."
  2552. (when elpy-company--cache
  2553. (cdr (assq 'meta (gethash name elpy-company--cache)))))
  2554. (defun elpy-company--cache-name (name)
  2555. "Return the cached name for NAME.
  2556. Confused yet? We pass \"our\" name, that is, prefix + suffix,
  2557. here, and return the \"name\" as used by the backend."
  2558. (when elpy-company--cache
  2559. (cdr (assq 'name (gethash name elpy-company--cache)))))
  2560. (defun elpy-company--cache-completions (prefix result)
  2561. "Store RESULT in the candidate cache and return candidates."
  2562. (elpy-company--cache-clear)
  2563. (mapcar (lambda (completion)
  2564. (let* ((suffix (cdr (assq 'name completion)))
  2565. (name (concat (s-chop-suffix (company-grab-symbol) prefix) suffix)))
  2566. (puthash name completion elpy-company--cache)
  2567. name))
  2568. result))
  2569. (defun elpy-company--python-exception-p (name)
  2570. "Check whether NAME is a Python exception."
  2571. (member name '("ArithmeticError"
  2572. "AssertionError"
  2573. "AttributeError"
  2574. "BlockingIOError"
  2575. "BrokenPipeError"
  2576. "BufferError"
  2577. "BytesWarning"
  2578. "ChildProcessError"
  2579. "ConnectionAbortedError"
  2580. "ConnectionError"
  2581. "ConnectionRefusedError"
  2582. "ConnectionResetError"
  2583. "DeprecationWarning"
  2584. "EOFError"
  2585. "EnvironmentError"
  2586. "Exception"
  2587. "FileExistsError"
  2588. "FileNotFoundError"
  2589. "FloatingPointError"
  2590. "FutureWarning"
  2591. "IOError"
  2592. "ImportError"
  2593. "ImportWarning"
  2594. "IndentationError"
  2595. "IndexError"
  2596. "InterruptedError"
  2597. "IsADirectoryError"
  2598. "KeyError"
  2599. "LookupError"
  2600. "MemoryError"
  2601. "NameError"
  2602. "NotADirectoryError"
  2603. "NotImplementedError"
  2604. "OSError"
  2605. "OverflowError"
  2606. "PendingDeprecationWarning"
  2607. "PermissionError"
  2608. "ProcessLookupError"
  2609. "RecursionError"
  2610. "ReferenceError"
  2611. "ResourceWarning"
  2612. "RuntimeError"
  2613. "RuntimeWarning"
  2614. "StandardError"
  2615. "StopAsyncIteration"
  2616. "StopIteration"
  2617. "SyntaxError"
  2618. "SyntaxWarning"
  2619. "SystemError"
  2620. "TabError"
  2621. "TimeoutError"
  2622. "TypeError"
  2623. "UnboundLocalError"
  2624. "UnicodeDecodeError"
  2625. "UnicodeEncodeError"
  2626. "UnicodeError"
  2627. "UnicodeTranslateError"
  2628. "UnicodeWarning"
  2629. "UserWarning"
  2630. "ValueError"
  2631. "Warning"
  2632. "ZeroDivisionError")))
  2633. (defun elpy-company-post-complete-parens (annotation name)
  2634. "Complete functions, classes, and callable instances with parentheses.
  2635. Add parentheses in case ANNOTATION is \"class\", \"function\", or
  2636. \"instance\",unless the completion is already looking at a left
  2637. parenthesis,or unless NAME is a Python exception outside a reasonably
  2638. formed raise statement,or unless NAME is no callable instance."
  2639. (unless (looking-at-p "\(")
  2640. (cond ((string= annotation "function")
  2641. (insert "()")
  2642. (backward-char 1))
  2643. ((string= annotation "class")
  2644. (cond ((elpy-company--python-exception-p name)
  2645. (when (save-excursion
  2646. (backward-word 2)
  2647. (looking-at "\\_<raise\\_>"))
  2648. (insert "()")
  2649. (backward-char 1)))
  2650. (t
  2651. (insert "()")
  2652. (backward-char 1))))
  2653. ((string= annotation "instance")
  2654. ;; The jedi backend annotates some callables as instances (e.g. numpy
  2655. ;; and scipy) and `elpy-company--cache' does not allow to identify
  2656. ;; callable instances.
  2657. ;; It looks easy to modify `elpy-company--cache' cheaply for the jedi
  2658. ;; backend to eliminate the `elpy-rpc-get-calltip' call below.
  2659. (insert "()")
  2660. (backward-char 1)
  2661. (unless (elpy-rpc-get-calltip)
  2662. (backward-char 1)
  2663. (delete-char 2))))))
  2664. (defun elpy-company--add-interpreter-completions-candidates (candidates)
  2665. "Add completions candidates from the shell to the list of candidates.
  2666. Get completions candidates at point from the shell, normalize them to look
  2667. like what elpy-company returns, merge them with the CANDIDATES list
  2668. and return the list."
  2669. ;; Check if prompt available
  2670. (if (not (and elpy-get-info-from-shell
  2671. (elpy-shell--check-if-shell-available)))
  2672. candidates
  2673. ;; Completion need the cursor to be at the end of the shell buffer
  2674. (save-excursion
  2675. (with-current-buffer (process-buffer (python-shell-get-process))
  2676. (goto-char (point-max)))
  2677. ;; Try to get the info with timeout
  2678. (let* ((new-candidates (with-timeout (elpy-get-info-from-shell-timeout
  2679. '(nil nil nil))
  2680. (python-completion-complete-at-point)))
  2681. (start (nth 0 new-candidates))
  2682. (end (nth 1 new-candidates))
  2683. (completion-list (nth 2 new-candidates)))
  2684. (if (not (and start end))
  2685. candidates
  2686. ;; Add the new candidates to the current ones
  2687. (let ((candidate-names (cl-map 'list
  2688. (lambda (el) (cdr (assoc 'name el)))
  2689. candidates))
  2690. (new-candidate-names (all-completions
  2691. (buffer-substring start end)
  2692. completion-list)))
  2693. (cl-loop
  2694. for pytel-cand in new-candidate-names
  2695. for pytel-cand = (replace-regexp-in-string "($" "" pytel-cand)
  2696. for pytel-cand = (replace-regexp-in-string "^.*\\." "" pytel-cand)
  2697. for pytel-cand = (string-trim pytel-cand)
  2698. unless (member pytel-cand candidate-names)
  2699. do (push (list (cons 'name pytel-cand)) candidates)
  2700. ))
  2701. candidates)))))
  2702. (defun elpy-company-backend (command &optional arg &rest ignored)
  2703. "A company-mode backend for Elpy."
  2704. (interactive (list 'interactive))
  2705. (pcase command
  2706. (`interactive
  2707. (company-begin-backend 'elpy-company-backend))
  2708. ;; init => Called once per buffer
  2709. ;; prefix => return the prefix at point
  2710. (`prefix
  2711. (when (and elpy-mode
  2712. (not (company-in-string-or-comment)))
  2713. (company-grab-symbol-cons "\\." 1)))
  2714. ;; candidates <prefix> => return candidates for this prefix
  2715. (`candidates
  2716. (cons :async
  2717. (lambda (callback)
  2718. (elpy-rpc-get-completions
  2719. (lambda (result)
  2720. ;; add completion candidates from python.el
  2721. (setq result
  2722. (elpy-company--add-interpreter-completions-candidates
  2723. result))
  2724. (elpy-company--cache-clear)
  2725. (funcall
  2726. callback
  2727. (cond
  2728. ;; The backend returned something
  2729. (result
  2730. (elpy-company--cache-completions arg result))
  2731. ;; Nothing from the backend, try dabbrev-code.
  2732. ((> (length arg) company-minimum-prefix-length)
  2733. (elpy--sort-and-strip-duplicates
  2734. (company-dabbrev-code 'candidates arg)))
  2735. ;; Well, ok, let's go meh.
  2736. (t
  2737. nil))))))))
  2738. ;; sorted => t if the list is already sorted
  2739. (`sorted
  2740. t)
  2741. ;; duplicates => t if there could be duplicates
  2742. (`duplicates
  2743. nil)
  2744. ;; no-cache <prefix> => t if company shouldn't cache results
  2745. ;; meta <candidate> => short docstring for minibuffer
  2746. (`meta
  2747. (let ((meta (elpy-company--cache-meta arg)))
  2748. (when (and meta
  2749. (string-match "\\`\\(.*\n.*\\)\n.*" meta))
  2750. (setq meta (match-string 1 meta)))
  2751. meta))
  2752. ;; annotation <candidate> => short docstring for completion buffer
  2753. (`annotation
  2754. (elpy-company--cache-annotation arg))
  2755. ;; doc-buffer <candidate> => put doc buffer in `company-doc-buffer'
  2756. (`doc-buffer
  2757. (let* ((name (elpy-company--cache-name arg))
  2758. (doc (when name
  2759. (elpy-rpc-get-completion-docstring name))))
  2760. (when doc
  2761. (company-doc-buffer doc))))
  2762. ;; require-match => Never require a match, even if the user
  2763. ;; started to interact with company. See `company-require-match'.
  2764. (`require-match
  2765. 'never)
  2766. ;; location <candidate> => (buffer . point) or (file .
  2767. ;; line-number)
  2768. (`location
  2769. (let* ((name (elpy-company--cache-name arg))
  2770. (loc (when name
  2771. (elpy-rpc-get-completion-location name))))
  2772. (when loc
  2773. (cons (car loc)
  2774. (cadr loc)))))
  2775. ;; match <candidate> => for non-prefix based backends
  2776. ;; post-completion <candidate> => after insertion, for snippets
  2777. (`post-completion
  2778. (funcall elpy-company-post-completion-function
  2779. (elpy-company--cache-annotation arg)
  2780. (elpy-company--cache-name arg)))))
  2781. (defun elpy--sort-and-strip-duplicates (seq)
  2782. "Sort SEQ and remove any duplicates."
  2783. (sort (delete-dups seq)
  2784. (lambda (a b)
  2785. (string< a b))))
  2786. ;;;;;;;;;;;;;;;;;
  2787. ;;; Module: ElDoc
  2788. (defun elpy-module-eldoc (command &rest _args)
  2789. "Module to support ElDoc for Python files."
  2790. (pcase command
  2791. (`global-init
  2792. (require 'eldoc)
  2793. (elpy-modules-remove-modeline-lighter 'eldoc-minor-mode))
  2794. (`buffer-init
  2795. (eldoc-add-command-completions "python-indent-dedent-line-backspace")
  2796. (set (make-local-variable 'company-frontends)
  2797. (remq 'company-echo-metadata-frontend company-frontends))
  2798. ;; New (Emacs >= 28) vs old eldoc API
  2799. (if (and (version< "28.0.0" emacs-version)
  2800. (boundp 'eldoc-documentation-functions))
  2801. (add-hook 'eldoc-documentation-functions
  2802. 'elpy-eldoc-documentation nil t)
  2803. (set (make-local-variable 'eldoc-documentation-function)
  2804. 'elpy-eldoc-documentation))
  2805. (eldoc-mode 1))
  2806. (`buffer-stop
  2807. (eldoc-mode -1)
  2808. (kill-local-variable 'eldoc-documentation-function))))
  2809. (defun elpy-eldoc-documentation (&optional callback &rest _more)
  2810. "Return some interesting information for the code at point.
  2811. This function is meant to be added to `eldoc-documentation-functions'
  2812. \(for Emacs >= 28) or set in `eldoc-documentation-function' (for older
  2813. Emacs versions).
  2814. This will return flymake errors for the line at point if there are
  2815. any. If not, this will do an asynchronous call to the RPC backend to
  2816. get a call tip, and display that using `eldoc-message'. If the backend
  2817. has no call tip, this will display the current class and method
  2818. instead.
  2819. If specified, CALLBACK is the function called to display the
  2820. documentation (only used for Emacs >= 28)."
  2821. (let ((cb (or callback
  2822. (lambda (doc &rest plist)
  2823. (let ((thing (plist-get plist :thing))
  2824. (face (plist-get plist :face)))
  2825. (when thing
  2826. (setq thing (format "%s: "
  2827. (propertize thing
  2828. 'face
  2829. 'font-lock-function-name-face)))
  2830. (setq doc
  2831. (if (version<= emacs-version "25")
  2832. (format "%s%s" thing doc)
  2833. (let ((eldoc-echo-area-use-multiline-p nil))
  2834. (eldoc-docstring-format-sym-doc thing doc)))))
  2835. (eldoc-message doc)))))
  2836. (flymake-error (elpy-flymake-error-at-point)))
  2837. (if flymake-error
  2838. flymake-error
  2839. (elpy-rpc-get-calltip-or-oneline-docstring
  2840. (lambda (info)
  2841. (cond
  2842. ;; INFO is a string, just display it
  2843. ((stringp info)
  2844. (funcall cb info))
  2845. ;; INFO is a calltip
  2846. ((string= (cdr (assq 'kind info)) "calltip")
  2847. (let ((name (cdr (assq 'name info)))
  2848. (index (cdr (assq 'index info)))
  2849. (params (cdr (assq 'params info))))
  2850. (when index
  2851. (setf (nth index params)
  2852. (propertize (nth index params)
  2853. 'face
  2854. 'eldoc-highlight-function-argument)))
  2855. (let* ((prefix (propertize name 'face
  2856. 'font-lock-function-name-face))
  2857. (args (format "%s(%s)" prefix
  2858. (mapconcat #'identity params ", "))))
  2859. (funcall cb args))))
  2860. ;; INFO is a oneline docstring
  2861. ((string= (cdr (assq 'kind info)) "oneline_doc")
  2862. (let ((name (cdr (assq 'name info)))
  2863. (docs (cdr (assq 'doc info))))
  2864. (funcall cb docs
  2865. :thing name
  2866. :face 'font-lock-function-name-face)))
  2867. ;; INFO is nil, maybe display the current function
  2868. (t
  2869. (if elpy-eldoc-show-current-function
  2870. (let ((current-defun (python-info-current-defun)))
  2871. (when current-defun
  2872. (eldoc-message
  2873. (concat "In: "
  2874. (propertize
  2875. (format "%s()" current-defun)
  2876. 'face 'font-lock-function-name-face)))))
  2877. (eldoc-message ""))))))
  2878. (if callback
  2879. ;; New protocol: return non-nil, non-string
  2880. t
  2881. ;; Old protocol: return the last message until we're done
  2882. eldoc-last-message))))
  2883. ;;;;;;;;;;;;;;;;;;;
  2884. ;;; Module: Folding
  2885. (defun elpy-module-folding (command &rest _args)
  2886. "Module allowing code folding in Python."
  2887. (pcase command
  2888. (`global-init
  2889. (elpy-modules-remove-modeline-lighter 'hs-minor-mode))
  2890. (`buffer-init
  2891. (hs-minor-mode 1)
  2892. (setq-local hs-set-up-overlay 'elpy-folding--display-code-line-counts)
  2893. (setq-local hs-allow-nesting t)
  2894. (define-key elpy-mode-map [left-fringe mouse-1]
  2895. 'elpy-folding--click-fringe)
  2896. (define-key elpy-mode-map (kbd "<mouse-1>") 'elpy-folding--click-text)
  2897. (elpy-folding--mark-foldable-lines)
  2898. (add-to-list 'after-change-functions 'elpy-folding--mark-foldable-lines))
  2899. (`buffer-stop
  2900. (hs-minor-mode -1)
  2901. (kill-local-variable 'hs-set-up-overlay)
  2902. (kill-local-variable 'hs-allow-nesting)
  2903. (define-key elpy-mode-map [left-fringe mouse-1] nil)
  2904. (define-key elpy-mode-map (kbd "<mouse-1>") nil)
  2905. (remove 'elpy-folding--mark-foldable-lines after-change-functions)
  2906. (cl-loop for prop in '(elpy-hs-folded elpy-hs-foldable elpy-hs-fringe)
  2907. do (remove-overlays (point-min) (point-max) prop t)))))
  2908. ;; Fringe and folding indicators
  2909. (when (fboundp 'define-fringe-bitmap)
  2910. (define-fringe-bitmap 'elpy-folding-fringe-marker
  2911. (vector #b00000000
  2912. #b00000000
  2913. #b00000000
  2914. #b11000011
  2915. #b11100111
  2916. #b01111110
  2917. #b00111100
  2918. #b00011000))
  2919. (define-fringe-bitmap 'elpy-folding-fringe-foldable-marker
  2920. (vector #b00100000
  2921. #b00010000
  2922. #b00001000
  2923. #b00000100
  2924. #b00000100
  2925. #b00001000
  2926. #b00010000
  2927. #b00100000)))
  2928. (defcustom elpy-folding-fringe-face 'elpy-folding-fringe-face
  2929. "Face for folding bitmaps appearing on the fringe."
  2930. :type 'face
  2931. :group 'elpy)
  2932. (defface elpy-folding-fringe-face
  2933. '((t (:inherit 'font-lock-comment-face
  2934. :box (:line-width 1 :style released-button))))
  2935. "Face for folding bitmaps appearing on the fringe."
  2936. :group 'elpy)
  2937. (defcustom elpy-folding-face 'elpy-folding-face
  2938. "Face for the folded region indicator."
  2939. :type 'face
  2940. :group 'elpy)
  2941. (defface elpy-folding-face
  2942. '((t (:inherit 'font-lock-comment-face :box t)))
  2943. "Face for the folded region indicator."
  2944. :group 'elpy)
  2945. (defcustom elpy-folding-fringe-indicators t
  2946. "Non-nil if Elpy should display folding fringe indicators."
  2947. :set (lambda (var val) ;
  2948. (set-default var val)
  2949. (dolist (buffer (buffer-list))
  2950. (when (and (with-current-buffer buffer elpy-mode)
  2951. (member 'elpy-folding--mark-foldable-lines
  2952. after-change-functions))
  2953. (elpy-folding--mark-foldable-lines)))))
  2954. (defvar elpy-folding-docstring-regex "[uU]?[rR]?\"\"\""
  2955. "Regular expression matching docstrings openings and closings.")
  2956. (defvar elpy-docstring-block-start-regexp
  2957. "^\\s-*[uU]?[rR]?\"\"\"\n?\\s-*"
  2958. "Version of `hs-block-start-regexp' for docstrings.")
  2959. (defface elpy-codecell-boundary '((t :inherit 'highlight))
  2960. "Face for elpy codecell boundary."
  2961. :group 'elpy-mode)
  2962. ;; Indicators
  2963. (defun elpy-folding--display-code-line-counts (ov)
  2964. "Display a folded region indicator with the number of folded lines.
  2965. Meant to be used as `hs-set-up-overlay'."
  2966. (let* ((marker-string "*fringe-dummy*")
  2967. (marker-length (length marker-string)))
  2968. (cond
  2969. ((eq 'code (overlay-get ov 'hs))
  2970. (let* ((nmb-line (count-lines (overlay-start ov) (overlay-end ov)))
  2971. (display-string (format "(%d)..." nmb-line)))
  2972. ;; fringe indicator
  2973. (when elpy-folding-fringe-indicators
  2974. (put-text-property 0 marker-length 'display
  2975. (list 'left-fringe 'elpy-folding-fringe-marker
  2976. 'elpy-folding-fringe-face)
  2977. marker-string)
  2978. (overlay-put ov 'before-string marker-string)
  2979. (overlay-put ov 'elpy-hs-fringe t))
  2980. ;; folding indicator
  2981. (put-text-property 0 (length display-string)
  2982. 'face 'elpy-folding-face display-string)
  2983. (put-text-property 0 (length display-string)
  2984. 'mouse-face 'highlight display-string)
  2985. (overlay-put ov 'display display-string)
  2986. (overlay-put ov 'elpy-hs-folded t)))
  2987. ;; for docstring and comments, we don't display the number of line
  2988. ((or (eq 'docstring (overlay-get ov 'hs))
  2989. (eq 'comment (overlay-get ov 'hs)))
  2990. (let ((display-string "..."))
  2991. (put-text-property 0 (length display-string)
  2992. 'mouse-face 'highlight display-string)
  2993. (overlay-put ov 'display display-string)
  2994. (overlay-put ov 'elpy-hs-folded t))))))
  2995. (defun elpy-folding--mark-foldable-lines (&optional beg end rm-text-len)
  2996. "Add a fringe indicator for foldable lines.
  2997. Meant to be used as a hook to `after-change-functions'."
  2998. (when elpy-folding-fringe-indicators
  2999. (save-excursion
  3000. (save-restriction
  3001. (save-match-data
  3002. (when (and beg end)
  3003. (narrow-to-region (progn (goto-char beg)
  3004. (line-beginning-position))
  3005. (progn (goto-char end)
  3006. (line-end-position))))
  3007. (remove-overlays (point-min) (point-max) 'elpy-hs-foldable t)
  3008. (goto-char (point-min))
  3009. (while (re-search-forward
  3010. python-nav-beginning-of-defun-regexp nil t)
  3011. (let* ((beg (line-beginning-position))
  3012. (end (line-end-position))
  3013. (ov (make-overlay beg end))
  3014. (marker-string "*fringe-dummy*")
  3015. (marker-length (length marker-string)))
  3016. (when (version<= "25.2" emacs-version)
  3017. (put-text-property 0 marker-length
  3018. 'display
  3019. (list
  3020. 'left-fringe
  3021. 'elpy-folding-fringe-foldable-marker
  3022. 'elpy-folding-fringe-face)
  3023. marker-string)
  3024. (overlay-put ov 'before-string marker-string))
  3025. (overlay-put ov 'elpy-hs-foldable t))))))))
  3026. ;; Mouse interaction
  3027. (defun elpy-folding--click-fringe (event)
  3028. "Hide or show block on fringe click."
  3029. (interactive "e")
  3030. (hs-life-goes-on
  3031. (when elpy-folding-fringe-indicators
  3032. (mouse-set-point event)
  3033. (let* ((folded (save-excursion
  3034. (end-of-line)
  3035. (cl-remove-if-not (lambda (ov)
  3036. (overlay-get ov 'elpy-hs-folded))
  3037. (overlays-at (point)))))
  3038. (foldable (cl-remove-if-not (lambda (ov)
  3039. (overlay-get ov 'elpy-hs-foldable))
  3040. (overlays-at (point)))))
  3041. (if folded
  3042. (hs-show-block)
  3043. (if foldable
  3044. (hs-hide-block)))))))
  3045. (defun elpy-folding--click-text (event)
  3046. "Show block on click."
  3047. (interactive "e")
  3048. (hs-life-goes-on
  3049. (save-excursion
  3050. (let ((window (posn-window (event-end event)))
  3051. (pos (posn-point (event-end event))))
  3052. (with-current-buffer (window-buffer window)
  3053. (goto-char pos)
  3054. (when (hs-overlay-at (point))
  3055. (hs-show-block)
  3056. (deactivate-mark)))))))
  3057. ;; Hidding docstrings
  3058. (defun elpy-folding--hide-docstring-region (beg end)
  3059. "Hide a region from BEG to END, marking it as a docstring.
  3060. BEG and END have to be respectively on the first and last line
  3061. of the docstring, their values are adapted to hide only the
  3062. docstring body."
  3063. (hs-life-goes-on
  3064. ;; do not fold oneliners
  3065. (when (not (save-excursion
  3066. (goto-char beg)
  3067. (beginning-of-line)
  3068. (re-search-forward
  3069. (concat elpy-folding-docstring-regex
  3070. ".*"
  3071. elpy-folding-docstring-regex)
  3072. (line-end-position) t)))
  3073. ;; get begining position (do not fold first doc line)
  3074. (save-excursion
  3075. (goto-char beg)
  3076. (when (save-excursion
  3077. (beginning-of-line)
  3078. (re-search-forward
  3079. (concat elpy-folding-docstring-regex
  3080. "[[:space:]]*$")
  3081. (line-end-position) t))
  3082. (forward-line 1))
  3083. (beginning-of-line)
  3084. (back-to-indentation)
  3085. (setq beg (point))
  3086. (setq ov-beg (line-end-position)))
  3087. ;; get end position
  3088. (save-excursion
  3089. (goto-char end)
  3090. (setq end (line-beginning-position))
  3091. (setq ov-end (line-end-position)))
  3092. (hs-discard-overlays ov-beg ov-end)
  3093. (hs-make-overlay ov-beg ov-end 'docstring (- beg ov-beg) (- end ov-end))
  3094. (run-hooks 'hs-hide-hook)
  3095. (goto-char beg))))
  3096. (defun elpy-folding--hide-docstring-at-point ()
  3097. "Hide the docstring at point."
  3098. (hs-life-goes-on
  3099. (let ((hs-block-start-regexp elpy-docstring-block-start-regexp))
  3100. (when (and (python-info-docstring-p) (not (hs-already-hidden-p)))
  3101. (let (beg end line-beg line-end)
  3102. ;; Get first doc line
  3103. (if (not (save-excursion (forward-line -1)
  3104. (python-info-docstring-p)))
  3105. (setq beg (line-beginning-position))
  3106. (forward-line -1)
  3107. (end-of-line)
  3108. (re-search-backward (concat "^[[:space:]]*"
  3109. elpy-folding-docstring-regex)
  3110. nil t)
  3111. (setq beg (line-beginning-position)))
  3112. ;; Go to docstring opening (to be sure to be inside the docstring)
  3113. (re-search-forward elpy-folding-docstring-regex nil t)
  3114. (setq line-beg (line-number-at-pos))
  3115. ;; Get last line
  3116. (if (not (save-excursion (forward-line 1)
  3117. (python-info-docstring-p)))
  3118. (progn
  3119. (setq end (line-end-position))
  3120. (setq line-end (line-number-at-pos)))
  3121. (re-search-forward elpy-folding-docstring-regex nil t)
  3122. (setq end (line-end-position))
  3123. (setq line-end (line-number-at-pos)))
  3124. ;; hide the docstring
  3125. (when (not (= line-end line-beg))
  3126. (elpy-folding--hide-docstring-region beg end)))))))
  3127. (defun elpy-folding--show-docstring-at-point ()
  3128. "Show docstring at point."
  3129. (hs-life-goes-on
  3130. (let ((hs-block-start-regexp elpy-docstring-block-start-regexp))
  3131. (when (python-info-docstring-p)
  3132. (hs-show-block)))))
  3133. (defvar-local elpy-folding-docstrings-hidden nil
  3134. "If docstrings are globally hidden or not.")
  3135. (defun elpy-folding-toggle-docstrings ()
  3136. "Fold or unfold every docstrings in the current buffer."
  3137. (interactive)
  3138. (if (not hs-minor-mode)
  3139. (message "Please enable the 'Folding module' to use this functionality.")
  3140. (hs-life-goes-on
  3141. (save-excursion
  3142. (goto-char (point-min))
  3143. (while (python-nav-forward-defun)
  3144. (search-forward-regexp ")\\s-*:" nil t)
  3145. (forward-line)
  3146. (when (and (python-info-docstring-p)
  3147. (progn
  3148. (beginning-of-line)
  3149. (search-forward-regexp elpy-folding-docstring-regex
  3150. nil t)))
  3151. (forward-char 2)
  3152. (back-to-indentation)
  3153. ;; be sure not to act on invisible docstrings
  3154. (unless (and (hs-overlay-at (point))
  3155. (not (eq (overlay-get (hs-overlay-at (point)) 'hs)
  3156. 'docstring)))
  3157. (if elpy-folding-docstrings-hidden
  3158. (elpy-folding--show-docstring-at-point)
  3159. (elpy-folding--hide-docstring-at-point)))))))
  3160. (setq elpy-folding-docstrings-hidden (not elpy-folding-docstrings-hidden))))
  3161. ;; Hiding comments
  3162. (defvar-local elpy-folding-comments-hidden nil
  3163. "If comments are globally hidden or not.")
  3164. (defun elpy-folding-toggle-comments ()
  3165. "Fold or unfold every comment blocks in the current buffer."
  3166. (interactive)
  3167. (if (not hs-minor-mode)
  3168. (message "Please enable the 'Folding module' to use this functionality.")
  3169. (hs-life-goes-on
  3170. (save-excursion
  3171. (goto-char (point-min))
  3172. (while (comment-search-forward (point-max) t)
  3173. ;; be suse not to act on invisible comments
  3174. (unless (and (hs-overlay-at (point))
  3175. (not (eq (overlay-get (hs-overlay-at (point)) 'hs)
  3176. 'comment)))
  3177. (if (not elpy-folding-comments-hidden)
  3178. ;; be sure to be on a multiline comment
  3179. (when (save-excursion (forward-line)
  3180. (comment-only-p (line-beginning-position)
  3181. (line-end-position)))
  3182. (hs-hide-block))
  3183. (hs-show-block)))
  3184. (python-util-forward-comment (buffer-size))))
  3185. (setq elpy-folding-comments-hidden (not elpy-folding-comments-hidden)))))
  3186. ;; Hiding leafs
  3187. ;; taken from https://www.emacswiki.org/emacs/HideShow
  3188. (defun elpy-folding--hide-leafs (beg end)
  3189. "Hide blocks that do not contain others blocks in region (BEG END)."
  3190. (hs-life-goes-on
  3191. (save-excursion
  3192. (goto-char beg)
  3193. ;; Find the current block beginning and end
  3194. (when (hs-find-block-beginning)
  3195. (setq beg (1+ (point)))
  3196. (funcall hs-forward-sexp-func 1)
  3197. (setq end (1- (point))))
  3198. ;; Show all branches if nesting not allowed
  3199. (unless hs-allow-nesting
  3200. (hs-discard-overlays beg end))
  3201. ;; recursively treat current block leafs
  3202. (let ((leaf t))
  3203. (while (progn
  3204. (forward-comment (buffer-size))
  3205. (and (< (point) end)
  3206. (re-search-forward hs-block-start-regexp end t)))
  3207. (setq pos (match-beginning hs-block-start-mdata-select))
  3208. (if (elpy-folding--hide-leafs pos end)
  3209. (save-excursion
  3210. (goto-char pos)
  3211. (hs-hide-block-at-point t)))
  3212. (setq leaf nil))
  3213. (goto-char end)
  3214. (run-hooks 'hs-hide-hook)
  3215. leaf))))
  3216. (defun elpy-folding-hide-leafs ()
  3217. "Hide all blocks that do not contain other blocks."
  3218. (interactive)
  3219. (if (not hs-minor-mode)
  3220. (message "Please enable the 'Folding module' to use this functionality.")
  3221. (hs-life-goes-on
  3222. (let ((beg (save-excursion
  3223. (goto-char (if (use-region-p) (region-beginning) (point-min)))
  3224. (line-beginning-position)))
  3225. (end (save-excursion
  3226. (goto-char (if (use-region-p) (region-end) (point-max)))
  3227. (1+ (line-end-position)))))
  3228. (elpy-folding--hide-leafs beg end)))))
  3229. ;; DWIM functions
  3230. (defun elpy-folding--hide-region (beg end)
  3231. "Hide the region betwwen BEG and END."
  3232. (hs-life-goes-on
  3233. (save-excursion
  3234. (let ((beg-eol (progn (goto-char beg) (line-end-position)))
  3235. (end-eol (progn (goto-char end) (line-end-position))))
  3236. (hs-discard-overlays beg-eol end-eol)
  3237. (hs-make-overlay beg-eol end-eol 'code (- beg beg-eol) (- end end-eol))
  3238. (run-hooks 'hs-hide-hook)
  3239. (deactivate-mark)))))
  3240. (defun elpy-folding-toggle-at-point ()
  3241. "Fold/Unfold the block, comment or docstring at point.
  3242. If a region is selected, fold that region."
  3243. (interactive)
  3244. (if (not hs-minor-mode)
  3245. (message "Please enable the 'Folding module' to use this functionality.")
  3246. (hs-life-goes-on
  3247. ;; Use selected region
  3248. (if (use-region-p)
  3249. (elpy-folding--hide-region (region-beginning) (region-end))
  3250. ;; Adapt starting regexp if on a docstring
  3251. (let ((hs-block-start-regexp
  3252. (if (python-info-docstring-p)
  3253. elpy-docstring-block-start-regexp
  3254. hs-block-start-regexp)))
  3255. ;; Hide or fold
  3256. (cond
  3257. ((hs-already-hidden-p)
  3258. (hs-show-block))
  3259. ((python-info-docstring-p)
  3260. (elpy-folding--hide-docstring-at-point))
  3261. (t
  3262. (hs-hide-block))))))))
  3263. ;;;;;;;;;;;;;;;;;;;
  3264. ;;; Module: Flymake
  3265. (defun elpy-module-flymake (command &rest _args)
  3266. "Enable Flymake support for Python."
  3267. (pcase command
  3268. (`global-init
  3269. (require 'flymake)
  3270. ;; flymake modeline is quite useful for emacs > 26.1
  3271. (when (version< emacs-version "26.1")
  3272. (elpy-modules-remove-modeline-lighter 'flymake-mode))
  3273. ;; Add our initializer function.
  3274. (unless (version<= "26.1" emacs-version)
  3275. (add-to-list 'flymake-allowed-file-name-masks
  3276. '("\\.py\\'" elpy-flymake-python-init))))
  3277. (`buffer-init
  3278. ;; Avoid fringes clash between flymake and folding indicators
  3279. (if (and (member 'elpy-module-folding elpy-modules)
  3280. elpy-folding-fringe-indicators)
  3281. (setq-local flymake-fringe-indicator-position 'right-fringe)
  3282. (setq-local flymake-fringe-indicator-position 'left-fringe))
  3283. ;; For emacs > 26.1, python.el natively supports flymake,
  3284. ;; so we just tell python.el to use the wanted syntax checker
  3285. (when (version<= "26.1" emacs-version)
  3286. (setq-local python-flymake-command
  3287. (let ((command (split-string elpy-syntax-check-command)))
  3288. (if (string= (file-name-nondirectory (car command))
  3289. "flake8")
  3290. (append command '("-"))
  3291. command))))
  3292. ;; `flymake-no-changes-timeout': The original value of 0.5 is too
  3293. ;; short for Python code, as that will result in the current line
  3294. ;; to be highlighted most of the time, and that's annoying. This
  3295. ;; value might be on the long side, but at least it does not, in
  3296. ;; general, interfere with normal interaction.
  3297. (set (make-local-variable 'flymake-no-changes-timeout)
  3298. 60)
  3299. ;; `flymake-start-syntax-check-on-newline': This should be nil for
  3300. ;; Python, as;; most lines with a colon at the end will mean the
  3301. ;; next line is always highlighted as error, which is not helpful
  3302. ;; and mostly annoying.
  3303. (set (make-local-variable 'flymake-start-syntax-check-on-newline)
  3304. nil)
  3305. ;; Enable warning faces for flake8 output.
  3306. ;; Useless for emacs >= 26.1, as warning are handled fine
  3307. ;; COMPAT: Obsolete variable as of 24.4
  3308. (cond
  3309. ((version<= "26.1" emacs-version)
  3310. (setq-default python-flymake-msg-alist
  3311. '(("^W[0-9]+" . :warning)
  3312. ("^E[0-9]+" . :error))))
  3313. ((boundp 'flymake-warning-predicate)
  3314. (set (make-local-variable 'flymake-warning-predicate) "^W[0-9]"))
  3315. (t
  3316. (set (make-local-variable 'flymake-warning-re) "^W[0-9]")))
  3317. ;; for emacs >= 26.1, elpy relies on `python-flymake-command`, and
  3318. ;; doesn't need `python-check-command` anymore.
  3319. (when (and (buffer-file-name)
  3320. (or (version<= "26.1" emacs-version)
  3321. (executable-find python-check-command)))
  3322. (flymake-mode 1)))
  3323. (`buffer-stop
  3324. (flymake-mode -1)
  3325. (kill-local-variable 'flymake-no-changes-timeout)
  3326. (kill-local-variable 'flymake-start-syntax-check-on-newline)
  3327. ;; Disable warning faces for flake8 output.
  3328. ;; Useless for emacs >= 26.1, as warning are handled fine
  3329. ;; COMPAT: Obsolete variable as of 24.4
  3330. (cond
  3331. ((version<= "26.1" emacs-version) t)
  3332. ((boundp 'flymake-warning-predicate)
  3333. (kill-local-variable 'flymake-warning-predicate))
  3334. (t
  3335. (kill-local-variable 'flymake-warning-re))))))
  3336. (defun elpy-flymake-python-init ()
  3337. ;; Make sure it's not a remote buffer as flymake would not work
  3338. (unless (file-remote-p buffer-file-name)
  3339. (let* ((temp-file (flymake-init-create-temp-buffer-copy
  3340. 'flymake-create-temp-inplace)))
  3341. (list python-check-command
  3342. (list temp-file)
  3343. ;; Run flake8 from / to avoid import problems (#169)
  3344. "/"))))
  3345. (defun elpy-flymake-next-error ()
  3346. "Move forward to the next Flymake error and show a description."
  3347. (interactive)
  3348. (flymake-goto-next-error)
  3349. (elpy-flymake-show-error))
  3350. (defun elpy-flymake-previous-error ()
  3351. "Move backward to the previous Flymake error and show a description."
  3352. (interactive)
  3353. (flymake-goto-prev-error)
  3354. (elpy-flymake-show-error))
  3355. (defun elpy-flymake-show-error ()
  3356. "Show the flymake error message at point."
  3357. (interactive)
  3358. (let ((error-message (elpy-flymake-error-at-point)))
  3359. (when error-message
  3360. (message "%s" error-message))))
  3361. (defun elpy-flymake-error-at-point ()
  3362. "Return the flymake error at point, or nil if there is none."
  3363. (cond ((boundp 'flymake-err-info) ; emacs < 26
  3364. (let* ((lineno (line-number-at-pos))
  3365. (err-info (car (flymake-find-err-info flymake-err-info
  3366. lineno))))
  3367. (when err-info
  3368. (mapconcat #'flymake-ler-text
  3369. err-info
  3370. ", "))))
  3371. ((and (fboundp 'flymake-diagnostic-text)
  3372. (fboundp 'flymake-diagnostics)) ; emacs >= 26
  3373. (let ((diag (flymake-diagnostics (point))))
  3374. (when diag
  3375. (mapconcat #'flymake-diagnostic-text diag ", "))))))
  3376. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  3377. ;;; Module: Highlight Indentation
  3378. (defun elpy-module-highlight-indentation (command &rest _args)
  3379. "Module to highlight indentation in Python files."
  3380. (pcase command
  3381. (`global-init
  3382. (require 'highlight-indentation))
  3383. (`buffer-init
  3384. (highlight-indentation-mode 1))
  3385. (`buffer-stop
  3386. (highlight-indentation-mode -1))))
  3387. ;;;;;;;;;;;;;;;;;;
  3388. ;;; Module: pyvenv
  3389. (defun elpy-module-pyvenv (command &rest _args)
  3390. "Module to display the current virtualenv in the mode line."
  3391. (pcase command
  3392. (`global-init
  3393. (pyvenv-mode 1))
  3394. (`global-stop
  3395. (pyvenv-mode -1))))
  3396. ;;;;;;;;;;;;;;;;;;;;;
  3397. ;;; Module: Yasnippet
  3398. (defun elpy-module-yasnippet (command &rest _args)
  3399. "Module to enable YASnippet snippets."
  3400. (pcase command
  3401. (`global-init
  3402. (require 'yasnippet)
  3403. (elpy-modules-remove-modeline-lighter 'yas-minor-mode)
  3404. ;; We provide some YASnippet snippets. Add them.
  3405. ;; yas-snippet-dirs can be a string for a single directory. Make
  3406. ;; sure it's a list in that case so we can add our own entry.
  3407. (unless (listp yas-snippet-dirs)
  3408. (setq yas-snippet-dirs (list yas-snippet-dirs)))
  3409. (add-to-list 'yas-snippet-dirs
  3410. (concat (file-name-directory (locate-library "elpy"))
  3411. "snippets/")
  3412. t)
  3413. ;; Now load yasnippets.
  3414. (yas-reload-all))
  3415. (`global-stop
  3416. (setq yas-snippet-dirs
  3417. (delete (concat (file-name-directory (locate-library "elpy"))
  3418. "snippets/")
  3419. yas-snippet-dirs)))
  3420. (`buffer-init
  3421. (yas-minor-mode 1))
  3422. (`buffer-stop
  3423. (yas-minor-mode -1))))
  3424. ;;;;;;;;;;;;;;;;;;;;;;;;;;;
  3425. ;;; Module: Elpy-Django
  3426. (defun elpy-module-django (command &rest _args)
  3427. "Module to provide Django support."
  3428. (pcase command
  3429. (`global-init
  3430. (add-to-list 'elpy-project-root-finder-functions
  3431. 'elpy-project-find-django-root t))
  3432. (`global-stop
  3433. (setq elpy-project-root-finder-functions
  3434. (remove 'elpy-project-find-django-root
  3435. elpy-project-root-finder-functions)))
  3436. (`buffer-init
  3437. (elpy-django-setup))
  3438. (`buffer-stop
  3439. (elpy-django -1))))
  3440. ;;;;;;;;;;;;;;;;;;;;;;;;;;;
  3441. ;;; Module: Autodoc
  3442. (defun elpy-module-autodoc (command &rest _args)
  3443. "Module to automatically update documentation."
  3444. (pcase command
  3445. (`buffer-init
  3446. (add-hook 'pre-command-hook 'elpy-autodoc--pre-command nil t)
  3447. (add-hook 'post-command-hook 'elpy-autodoc--post-command nil t)
  3448. (make-local-variable 'company-frontends)
  3449. (add-to-list 'company-frontends 'elpy-autodoc--frontend :append))
  3450. (`buffer-stop
  3451. (remove-hook 'pre-command-hook 'elpy-autodoc--pre-command t)
  3452. (remove-hook 'post-command-hook 'elpy-autodoc--post-command t)
  3453. (setq company-frontends (remove 'elpy-autodoc--frontend company-frontends)))))
  3454. ;; Auto refresh documentation on cursor motion
  3455. (defvar elpy-autodoc--timer nil
  3456. "Timer to refresh documentation.")
  3457. (defcustom elpy-autodoc-delay .5
  3458. "The idle delay in seconds until documentation is refreshed automatically."
  3459. :type '(choice (const :tag "immediate (0)" 0)
  3460. (number :tag "seconds"))
  3461. :group 'elpy
  3462. :group 'elpy-autodoc)
  3463. (defun elpy-autodoc--pre-command ()
  3464. "Cancel autodoc timer on user action."
  3465. (when elpy-autodoc--timer
  3466. (cancel-timer elpy-autodoc--timer)
  3467. (setq elpy-autodoc--timer nil)))
  3468. (defun elpy-autodoc--post-command ()
  3469. "Set up autodoc timer after user action."
  3470. (when elpy-autodoc-delay
  3471. (setq elpy-autodoc--timer
  3472. (run-with-timer elpy-autodoc-delay nil
  3473. 'elpy-autodoc--refresh-doc))))
  3474. (defun elpy-autodoc--refresh-doc ()
  3475. "Refresh the doc asynchronously with the symbol at point."
  3476. (when (get-buffer-window "*Python Doc*")
  3477. (elpy-rpc-get-docstring 'elpy-autodoc--show-doc
  3478. (lambda (_reason) nil))))
  3479. (defun elpy-autodoc--show-doc (doc)
  3480. "Display DOC (if any) but only if the doc buffer is currently visible."
  3481. (when (and doc (get-buffer-window "*Python Doc*"))
  3482. (elpy-doc--show doc)))
  3483. ;; Auto refresh documentation in company candidate selection
  3484. (defun elpy-autodoc--frontend (command)
  3485. "Elpy autodoc front-end for refreshing documentation."
  3486. (pcase command
  3487. (`post-command
  3488. (when elpy-autodoc-delay
  3489. (when elpy-autodoc--timer
  3490. (cancel-timer elpy-autodoc--timer))
  3491. (setq elpy-autodoc--timer
  3492. (run-with-timer elpy-autodoc-delay
  3493. nil
  3494. 'elpy-autodoc--refresh-doc-from-company))))
  3495. (`hide
  3496. (when elpy-autodoc--timer
  3497. (cancel-timer elpy-autodoc--timer)))))
  3498. (defun elpy-autodoc--refresh-doc-from-company ()
  3499. "Refresh the doc asynchronously using the current company candidate."
  3500. (let* ((symbol (nth company-selection company-candidates))
  3501. (doc (elpy-rpc-get-completion-docstring symbol)))
  3502. (elpy-autodoc--show-doc doc)))
  3503. ;;;;;;;;;;;;;;;;;;;;;;;;;;;
  3504. ;;; Backwards compatibility
  3505. ;; TODO Some/most of this compatibility code can now go, as minimum required
  3506. ;; Emacs version is 24.4.
  3507. ;; Functions for Emacs 24 before 24.3
  3508. (unless (fboundp 'python-info-current-defun)
  3509. (defalias 'python-info-current-defun 'python-current-defun))
  3510. (unless (fboundp 'python-nav-forward-statement)
  3511. (defun python-nav-forward-statement (&rest ignored)
  3512. "Function added in Emacs 24.3"
  3513. (error "Enhanced Python navigation only available in Emacs 24.3+")))
  3514. (unless (fboundp 'python-nav-backward-up-list)
  3515. (defun python-nav-backward-up-list ()
  3516. "Compatibility function for older Emacsen"
  3517. (ignore-errors
  3518. (backward-up-list))))
  3519. (unless (fboundp 'python-shell-calculate-exec-path)
  3520. (defun python-shell-calculate-exec-path ()
  3521. "Compatibility function for older Emacsen."
  3522. exec-path))
  3523. (unless (fboundp 'python-shell-calculate-process-environment)
  3524. (defun python-shell-calculate-process-environment ()
  3525. "Compatibility function for older Emacsen."
  3526. process-environment))
  3527. (unless (fboundp 'python-shell-get-process-name)
  3528. (defun python-shell-get-process-name (_dedicated)
  3529. "Compatibility function for older Emacsen."
  3530. "Python"))
  3531. (unless (fboundp 'python-shell-parse-command)
  3532. (defun python-shell-parse-command ()
  3533. "Compatibility function for older Emacsen."
  3534. python-python-command))
  3535. (unless (fboundp 'python-shell-send-buffer)
  3536. (defun python-shell-send-buffer (&optional _arg)
  3537. (python-send-buffer)))
  3538. (unless (fboundp 'python-shell-send-string)
  3539. (defalias 'python-shell-send-string 'python-send-string))
  3540. (unless (fboundp 'python-indent-shift-right)
  3541. (defalias 'python-indent-shift-right 'python-shift-right))
  3542. (unless (fboundp 'python-indent-shift-left)
  3543. (defalias 'python-indent-shift-left 'python-shift-left))
  3544. ;; Emacs 24.2 made `locate-dominating-file' accept a predicate instead
  3545. ;; of a string. Simply overwrite the current one, it's
  3546. ;; backwards-compatible. The code below is taken from Emacs 24.3.
  3547. (when (or (< emacs-major-version 24)
  3548. (and (= emacs-major-version 24)
  3549. (<= emacs-minor-version 2)))
  3550. (defun locate-dominating-file (file name)
  3551. "Look up the directory hierarchy from FILE for a directory containing NAME.
  3552. Stop at the first parent directory containing a file NAME,
  3553. and return the directory. Return nil if not found.
  3554. Instead of a string, NAME can also be a predicate taking one argument
  3555. \(a directory) and returning a non-nil value if that directory is the one for
  3556. which we're looking."
  3557. ;; We used to use the above locate-dominating-files code, but the
  3558. ;; directory-files call is very costly, so we're much better off doing
  3559. ;; multiple calls using the code in here.
  3560. ;;
  3561. ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
  3562. ;; `name' in /home or in /.
  3563. (setq file (abbreviate-file-name file))
  3564. (let ((root nil)
  3565. ;; `user' is not initialized outside the loop because
  3566. ;; `file' may not exist, so we may have to walk up part of the
  3567. ;; hierarchy before we find the "initial UID". Note: currently unused
  3568. ;; (user nil)
  3569. try)
  3570. (while (not (or root
  3571. (null file)
  3572. ;; FIXME: Disabled this heuristic because it is sometimes
  3573. ;; inappropriate.
  3574. ;; As a heuristic, we stop looking up the hierarchy of
  3575. ;; directories as soon as we find a directory belonging
  3576. ;; to another user. This should save us from looking in
  3577. ;; things like /net and /afs. This assumes that all the
  3578. ;; files inside a project belong to the same user.
  3579. ;; (let ((prev-user user))
  3580. ;; (setq user (nth 2 (file-attributes file)))
  3581. ;; (and prev-user (not (equal user prev-user))))
  3582. (string-match locate-dominating-stop-dir-regexp file)))
  3583. (setq try (if (stringp name)
  3584. (file-exists-p (expand-file-name name file))
  3585. (funcall name file)))
  3586. (cond (try (setq root file))
  3587. ((equal file (setq file (file-name-directory
  3588. (directory-file-name file))))
  3589. (setq file nil))))
  3590. (if root (file-name-as-directory root))))
  3591. )
  3592. ;; highlight-indentation 0.5 does not use modes yet
  3593. (unless (fboundp 'highlight-indentation-mode)
  3594. (defun highlight-indentation-mode (on-or-off)
  3595. (cond
  3596. ((and (> on-or-off 0)
  3597. (not highlight-indent-active))
  3598. (highlight-indentation))
  3599. ((and (<= on-or-off 0)
  3600. highlight-indent-active)
  3601. (highlight-indentation)))))
  3602. ;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=25753#44
  3603. (when (version< emacs-version "25.2")
  3604. (defun python-shell-completion-native-try ()
  3605. "Return non-nil if can trigger native completion."
  3606. (let ((python-shell-completion-native-enable t)
  3607. (python-shell-completion-native-output-timeout
  3608. python-shell-completion-native-try-output-timeout))
  3609. (python-shell-completion-native-get-completions
  3610. (get-buffer-process (current-buffer))
  3611. nil "_"))))
  3612. ;; python.el in Emacs 24 does not have functions to determine buffer encoding.
  3613. ;; In these versions, we fix the encoding to utf-8 (safe choice when no encoding
  3614. ;; is defined since Python 2 uses ASCII and Python 3 UTF-8).
  3615. (unless (fboundp 'python-info-encoding)
  3616. (defun python-info-encoding ()
  3617. 'utf-8))
  3618. ;; first-prompt-hook has been added in emacs 25.
  3619. ;; for earlier versions, make sure Elpy's setup code is
  3620. ;; still send to the python shell.
  3621. (unless (boundp 'python-shell-first-prompt-hook)
  3622. (add-hook 'inferior-python-mode-hook
  3623. (lambda ()
  3624. (when (elpy-project-root)
  3625. (let ((process (get-buffer-process (current-buffer))))
  3626. (python-shell-send-string
  3627. (format "import sys;sys.path.append('%s');del sys"
  3628. (elpy-project-root))
  3629. process))))))
  3630. ;; Added in Emacs 25
  3631. (unless (fboundp 'python-shell-comint-end-of-output-p)
  3632. (defun python-shell-comint-end-of-output-p (output)
  3633. "Return non-nil if OUTPUT is ends with input prompt."
  3634. (string-match
  3635. ;; XXX: It seems on macOS an extra carriage return is attached
  3636. ;; at the end of output, this handles that too.
  3637. (concat
  3638. "\r?\n?"
  3639. ;; Remove initial caret from calculated regexp
  3640. (replace-regexp-in-string
  3641. (rx string-start ?^) ""
  3642. python-shell--prompt-calculated-input-regexp)
  3643. (rx eos))
  3644. output)))
  3645. (unless (fboundp 'python-info-docstring-p)
  3646. (defun python-info-docstring-p (&optional syntax-ppss)
  3647. "Return non-nil if point is in a docstring."
  3648. (save-excursion
  3649. (and (progn (python-nav-beginning-of-statement)
  3650. (looking-at "\\(\"\\|'\\)"))
  3651. (progn (forward-line -1)
  3652. (beginning-of-line)
  3653. (python-info-looking-at-beginning-of-defun))))))
  3654. (provide 'elpy)
  3655. ;;; elpy.el ends here