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.

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