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.

1358 lines
55 KiB

  1. ;;; elpy-shell.el --- Interactive Python support for elpy -*- lexical-binding: t -*-
  2. ;;
  3. ;; Copyright (C) 2012-2019 Jorgen Schaefer
  4. ;;
  5. ;; Author: Jorgen Schaefer <contact@jorgenschaefer.de>, Rainer Gemulla <rgemulla@gmx.de>, Gaby Launay <gaby.launay@protonmail.com>
  6. ;; URL: https://github.com/jorgenschaefer/elpy
  7. ;;
  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. ;;
  13. ;; This program is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;;
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. ;;
  21. ;;; Commentary:
  22. ;;
  23. ;; Adds support for interactive Python to elpy
  24. ;;
  25. ;;; Code:
  26. (eval-when-compile (require 'subr-x))
  27. (require 'python)
  28. ;;;;;;;;;;;;;;;;;;;;;;
  29. ;;; User customization
  30. (defcustom elpy-dedicated-shells nil
  31. "Non-nil if Elpy should use dedicated shells.
  32. Elpy can use a unique Python shell for all buffers and support
  33. manually started dedicated shells. Setting this option to non-nil
  34. force the creation of dedicated shells for each buffers."
  35. :type 'boolean
  36. :group 'elpy)
  37. (make-obsolete-variable 'elpy-dedicated-shells
  38. "Dedicated shells are no longer supported by Elpy.
  39. You can use `(add-hook 'elpy-mode-hook (lambda () (elpy-shell-toggle-dedicated-shell 1)))' to achieve the same result."
  40. "1.17.0")
  41. (defcustom elpy-shell-display-buffer-after-send nil ;
  42. "Whether to display the Python shell after sending something to it."
  43. :type 'boolean
  44. :group 'elpy)
  45. (defcustom elpy-shell-echo-output 'when-shell-not-visible
  46. "Whether to echo the Python shell output in the echo area after input has been sent to the shell.
  47. Possible choices are nil (=never), `when-shell-not-visible', or
  48. t (=always)."
  49. :type '(choice (const :tag "Never" nil)
  50. (const :tag "When shell not visible" when-shell-not-visible)
  51. (const :tag "Always" t))
  52. :group 'elpy)
  53. (defcustom elpy-shell-capture-last-multiline-output t
  54. "Whether to capture the output of the last Python statement when sending multiple statements to the Python shell.
  55. If nil, no output is captured (nor echoed in the shell) when
  56. sending multiple statements. This is the default behavior of
  57. python.el. If non-nil and the last statement is an expression,
  58. captures its output so that it is echoed in the shell."
  59. :type 'boolean
  60. :group 'elpy)
  61. (make-obsolete-variable 'elpy-shell-capture-last-multiline-output
  62. "The last multiline output is now always captured."
  63. "February 2019")
  64. (defcustom elpy-shell-echo-input t
  65. "Whether to echo input sent to the Python shell as input in the
  66. shell buffer.
  67. Truncation of long inputs can be controlled via
  68. `elpy-shell-echo-input-lines-head' and
  69. `elpy-shell-echo-input-lines-tail'."
  70. :type 'boolean
  71. :group 'elpy)
  72. (defcustom elpy-shell-echo-input-cont-prompt t
  73. "Whether to show a continuation prompt when echoing multi-line
  74. input to the Python shell."
  75. :type 'boolean
  76. :group 'elpy)
  77. (defcustom elpy-shell-echo-input-lines-head 10
  78. "Maximum number of lines to show before truncating input echoed
  79. in the Python shell."
  80. :type 'integer
  81. :group 'elpy)
  82. (defcustom elpy-shell-echo-input-lines-tail 10
  83. "Maximum number of lines to show after truncating input echoed
  84. in the Python shell."
  85. :type 'integer
  86. :group 'elpy)
  87. (defcustom elpy-shell-starting-directory 'project-root
  88. "Directory in which Python shells will be started.
  89. Can be `project-root' (default) to use the current project root,
  90. `current-directory' to use the buffer current directory, or a
  91. string indicating a specific path.
  92. \\<elpy-mode-map>
  93. Running python interpeters need to be restarted (with
  94. \\[elpy-shell-kill] followed by \\[elpy-shell-switch-to-shell]) for
  95. this option to be taken into account."
  96. :type '(choice (const :tag "Project root" project-root)
  97. (const :tag "Current directory" current-directory)
  98. (string :tag "Specific directory"))
  99. :group 'elpy)
  100. (defcustom elpy-shell-use-project-root t
  101. "Whether to use project root as default directory when starting a Python shells.
  102. The project root is determined using `elpy-project-root`. If this
  103. variable is set to nil, the current directory is used instead."
  104. :type 'boolean
  105. :group 'elpy)
  106. (make-obsolete-variable 'elpy-shell-use-project-root
  107. 'elpy-shell-starting-directory
  108. "1.32.0")
  109. (defcustom elpy-shell-cell-boundary-regexp
  110. (concat "^\\(?:"
  111. "##.*" "\\|"
  112. "#\\s-*<.+>" "\\|"
  113. "#\\s-*\\(?:In\\|Out\\)\\[.*\\]:"
  114. "\\)\\s-*$")
  115. "Regular expression for matching a line indicating the boundary
  116. of a cell (beginning or ending). By default, lines starting with
  117. ``##`` are treated as a cell boundaries, as are the boundaries in
  118. Python files exported from IPython or Jupyter notebooks (e.g.,
  119. ``# <markdowncell>``, ``# In[1]:'', or ``# Out[1]:``).
  120. Note that `elpy-shell-cell-beginning-regexp' must also match
  121. the first boundary of the code cell."
  122. :type 'string
  123. :group 'elpy)
  124. (defcustom elpy-shell-codecell-beginning-regexp
  125. (concat "^\\(?:"
  126. "##.*" "\\|"
  127. "#\\s-*<codecell>" "\\|"
  128. "#\\s-*In\\[.*\\]:"
  129. "\\)\\s-*$")
  130. "Regular expression for matching a line indicating the
  131. beginning of a code cell. By default, lines starting with ``##``
  132. are treated as beginnings of a code cell, as are the code cell
  133. beginnings (and only the code cell beginnings) in Python files
  134. exported from IPython or Jupyter notebooks (e.g., ``#
  135. <codecell>`` or ``# In[1]:``).
  136. Note that `elpy-shell-cell-boundary-regexp' must also match
  137. the code cell beginnings defined here."
  138. :type 'string
  139. :group 'elpy)
  140. (defcustom elpy-shell-add-to-shell-history nil
  141. "If Elpy should make the code sent to the shell available in the
  142. shell history. This allows to use `comint-previous-input' in the
  143. python shell to get back the pieces of code sent by Elpy. This affects
  144. the following functions:
  145. - `elpy-shell-send-statement'
  146. - `elpy-shell-send-top-statement'
  147. - `elpy-shell-send-group'
  148. - `elpy-shell-send-codecell'
  149. - `elpy-shell-send-region-or-buffer'."
  150. :type 'boolean
  151. :group 'elpy)
  152. ;;;;;;;;;;;;;;;;;;
  153. ;;; Shell commands
  154. (defvar elpy--shell-last-py-buffer nil
  155. "Help keep track of python buffer when changing to pyshell.")
  156. (defun elpy-shell-display-buffer ()
  157. "Display inferior Python process buffer."
  158. (display-buffer (process-buffer (elpy-shell-get-or-create-process))
  159. nil
  160. 'visible))
  161. ;; better name would be pop-to-shell
  162. (defun elpy-shell-switch-to-shell ()
  163. "Switch to inferior Python process buffer."
  164. (interactive)
  165. (setq elpy--shell-last-py-buffer (buffer-name))
  166. (pop-to-buffer (process-buffer (elpy-shell-get-or-create-process))))
  167. (defun elpy-shell-switch-to-buffer ()
  168. "Switch from inferior Python process buffer to recent Python buffer."
  169. (interactive)
  170. (pop-to-buffer elpy--shell-last-py-buffer))
  171. (defun elpy-shell-switch-to-shell-in-current-window ()
  172. (interactive)
  173. (setq elpy--shell-last-py-buffer (buffer-name))
  174. (switch-to-buffer (process-buffer (elpy-shell-get-or-create-process))))
  175. (defun elpy-shell-switch-to-buffer-in-current-window ()
  176. (interactive)
  177. (switch-to-buffer elpy--shell-last-py-buffer))
  178. (defun elpy-shell-kill (&optional kill-buff)
  179. "Kill the current python shell.
  180. If KILL-BUFF is non-nil, also kill the associated buffer."
  181. (interactive)
  182. (let ((shell-buffer (python-shell-get-buffer)))
  183. (cond
  184. (shell-buffer
  185. (delete-process shell-buffer)
  186. (when kill-buff
  187. (kill-buffer shell-buffer))
  188. (message "Killed %s shell" shell-buffer))
  189. (t
  190. (message "No python shell to kill")))))
  191. (defun elpy-shell-kill-all (&optional kill-buffers ask-for-each-one)
  192. "Kill all active python shells.
  193. If KILL-BUFFERS is non-nil, also kill the associated buffers.
  194. If ASK-FOR-EACH-ONE is non-nil, ask before killing each python process."
  195. (interactive)
  196. (let ((python-buffer-list ()))
  197. ;; Get active python shell buffers and kill inactive ones (if asked)
  198. (cl-loop for buffer being the buffers do
  199. (when (and (buffer-name buffer)
  200. (string-match (rx bol "*Python" (opt "[" (* (not (any "]"))) "]") "*" eol)
  201. (buffer-name buffer)))
  202. (if (get-buffer-process buffer)
  203. (push buffer python-buffer-list)
  204. (when kill-buffers
  205. (kill-buffer buffer)))))
  206. (cond
  207. ;; Ask for each buffers and kill
  208. ((and python-buffer-list ask-for-each-one)
  209. (cl-loop for buffer in python-buffer-list do
  210. (when (y-or-n-p (format "Kill %s ? " buffer))
  211. (delete-process buffer)
  212. (when kill-buffers
  213. (kill-buffer buffer)))))
  214. ;; Ask and kill every buffers
  215. (python-buffer-list
  216. (if (y-or-n-p (format "Kill %s python shells ? " (length python-buffer-list)))
  217. (cl-loop for buffer in python-buffer-list do
  218. (delete-process buffer)
  219. (when kill-buffers
  220. (kill-buffer buffer)))))
  221. ;; No shell to close
  222. (t
  223. (message "No python shell to close")))))
  224. (defun elpy-shell-get-or-create-process (&optional sit)
  225. "Get or create an inferior Python process for current buffer and return it.
  226. If SIT is non-nil, sit for that many seconds after creating a
  227. Python process. This allows the process to start up."
  228. (let* ((process-connection-type
  229. (if (string-equal system-type "darwin") nil t)) ;; see https://github.com/jorgenschaefer/elpy/pull/1671
  230. (bufname (format "*%s*" (python-shell-get-process-name nil)))
  231. (proc (get-buffer-process bufname)))
  232. (if proc
  233. proc
  234. (unless (executable-find python-shell-interpreter)
  235. (error "Python shell interpreter `%s' cannot be found. Please set `python-shell-interpreter' to a valid python binary."
  236. python-shell-interpreter))
  237. (let ((default-directory
  238. (cond ((eq elpy-shell-starting-directory 'project-root)
  239. (or (elpy-project-root)
  240. default-directory))
  241. ((eq elpy-shell-starting-directory 'current-directory)
  242. default-directory)
  243. ((stringp elpy-shell-starting-directory)
  244. (file-name-as-directory
  245. (expand-file-name elpy-shell-starting-directory)))
  246. (t
  247. (error "Wrong value for `elpy-shell-starting-directory', please check this variable documentation and set it to a proper value")))))
  248. ;; We cannot use `run-python` directly, as it selects the new shell
  249. ;; buffer. See https://github.com/jorgenschaefer/elpy/issues/1848
  250. (python-shell-make-comint
  251. (python-shell-parse-command)
  252. (python-shell-get-process-name nil)
  253. t))
  254. (when sit (sit-for sit))
  255. (get-buffer-process bufname))))
  256. (defun elpy-shell--send-setup-code ()
  257. "Send setup code for the shell."
  258. (let ((process (python-shell-get-process)))
  259. (when (elpy-project-root)
  260. (python-shell-send-string-no-output
  261. (format "import sys;sys.path.append('%s');del sys"
  262. (elpy-project-root))
  263. process))))
  264. (defun elpy-shell-toggle-dedicated-shell (&optional arg)
  265. "Toggle the use of a dedicated python shell for the current buffer.
  266. if ARG is positive, enable the use of a dedicated shell.
  267. if ARG is negative or 0, disable the use of a dedicated shell."
  268. (interactive)
  269. (let ((arg (or arg
  270. (if (local-variable-p 'python-shell-buffer-name) 0 1))))
  271. (if (<= arg 0)
  272. (kill-local-variable 'python-shell-buffer-name)
  273. (setq-local python-shell-buffer-name
  274. (format "Python[%s]"
  275. (file-name-sans-extension
  276. (buffer-name)))))))
  277. (defun elpy-shell-set-local-shell (&optional shell-name)
  278. "Associate the current buffer to a specific shell.
  279. Meaning that the code from the current buffer will be sent to this shell.
  280. If SHELL-NAME is not specified, ask with completion for a shell name.
  281. If SHELL-NAME is \"Global\", associate the current buffer to the main python
  282. shell (often \"*Python*\" shell)."
  283. (interactive)
  284. (let* ((current-shell-name (if (local-variable-p 'python-shell-buffer-name)
  285. (progn
  286. (string-match "Python\\[\\(.*?\\)\\]"
  287. python-shell-buffer-name)
  288. (match-string 1 python-shell-buffer-name))
  289. "Global"))
  290. (shell-names (cl-loop
  291. for buffer in (buffer-list)
  292. for buffer-name = (file-name-sans-extension (substring-no-properties (buffer-name buffer)))
  293. if (string-match "\\*Python\\[\\(.*?\\)\\]\\*" buffer-name)
  294. collect (match-string 1 buffer-name)))
  295. (candidates (remove current-shell-name
  296. (delete-dups
  297. (append (list (file-name-sans-extension
  298. (buffer-name)) "Global")
  299. shell-names))))
  300. (prompt (format "Shell name (current: %s): " current-shell-name))
  301. (shell-name (or shell-name (completing-read prompt candidates))))
  302. (if (string= shell-name "Global")
  303. (kill-local-variable 'python-shell-buffer-name)
  304. (setq-local python-shell-buffer-name (format "Python[%s]" shell-name)))))
  305. (defun elpy-shell--ensure-shell-running ()
  306. "Ensure that the Python shell for the current buffer is running.
  307. If the shell is not running, waits until the first prompt is visible and
  308. commands can be sent to the shell."
  309. (with-current-buffer (process-buffer (elpy-shell-get-or-create-process))
  310. (let ((cumtime 0))
  311. (while (and (when (boundp 'python-shell--first-prompt-received)
  312. (not python-shell--first-prompt-received))
  313. (< cumtime 3))
  314. (sleep-for 0.1)
  315. (setq cumtime (+ cumtime 0.1)))))
  316. (elpy-shell-get-or-create-process))
  317. (defun elpy-shell--string-without-indentation (string)
  318. "Return the current string, but without indentation."
  319. (if (string-empty-p string)
  320. string
  321. (let ((indent-level nil)
  322. (indent-tabs-mode nil))
  323. (with-temp-buffer
  324. (insert string)
  325. (goto-char (point-min))
  326. (while (< (point) (point-max))
  327. (cond
  328. ((or (elpy-shell--current-line-only-whitespace-p)
  329. (python-info-current-line-comment-p)))
  330. ((not indent-level)
  331. (setq indent-level (current-indentation)))
  332. ((and indent-level
  333. (< (current-indentation) indent-level))
  334. (error (message "X%sX" (thing-at-point 'line)))))
  335. ;; (error "Can't adjust indentation, consecutive lines indented less than starting line")))
  336. (forward-line))
  337. (indent-rigidly (point-min)
  338. (point-max)
  339. (- indent-level))
  340. ;; 'indent-rigidly' introduces tabs despite the fact that 'indent-tabs-mode' is nil
  341. ;; 'untabify' fix that
  342. (untabify (point-min) (point-max))
  343. (buffer-string)))))
  344. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  345. ;; Flash input sent to shell
  346. ;; functions for flashing a region; only flashes when package eval-sexp-fu is
  347. ;; loaded and its minor mode enabled
  348. (defun elpy-shell--flash-and-message-region (begin end)
  349. "Displays information about code fragments sent to the shell.
  350. BEGIN and END refer to the region of the current buffer
  351. containing the code being sent. Displays a message with the code
  352. on the first line of that region. If `eval-sexp-fu-flash-mode' is
  353. active, additionally flashes that region briefly."
  354. (when (> end begin)
  355. (save-excursion
  356. (let* ((bounds
  357. (save-excursion
  358. (goto-char begin)
  359. (bounds-of-thing-at-point 'line)))
  360. (begin (max begin (car bounds)))
  361. (end (min end (cdr bounds)))
  362. (code-on-first-line (string-trim (buffer-substring begin end))))
  363. (goto-char begin)
  364. (end-of-line)
  365. (if (<= end (point))
  366. (message "Sent: %s" code-on-first-line)
  367. (message "Sent: %s..." code-on-first-line))
  368. (when (bound-and-true-p eval-sexp-fu-flash-mode)
  369. (cl-multiple-value-bind (_bounds hi unhi _eflash)
  370. (eval-sexp-fu-flash (cons begin end))
  371. (eval-sexp-fu-flash-doit (lambda () t) hi unhi)))))))
  372. ;;;;;;;;;;;;;;;;;;;
  373. ;; Helper functions
  374. (defun elpy-shell--current-line-else-or-elif-p ()
  375. (eq (string-match-p "\\s-*el\\(?:se:\\|if[^\w]\\)" (thing-at-point 'line)) 0))
  376. (defun elpy-shell--current-line-decorator-p ()
  377. (eq (string-match-p "^\\s-*@[A-Za-z]" (thing-at-point 'line)) 0))
  378. (defun elpy-shell--current-line-decorated-defun-p ()
  379. (save-excursion (python-nav-backward-statement)
  380. (elpy-shell--current-line-decorator-p)))
  381. (defun elpy-shell--current-line-indented-p ()
  382. (eq (string-match-p "\\s-+[^\\s-]+" (thing-at-point 'line)) 0))
  383. (defun elpy-shell--current-line-only-whitespace-p ()
  384. "Whether the current line contains only whitespace characters (or is empty)."
  385. (eq (string-match-p "\\s-*$" (thing-at-point 'line)) 0))
  386. (defun elpy-shell--current-line-code-line-p ()
  387. (and (not (elpy-shell--current-line-only-whitespace-p))
  388. (not (python-info-current-line-comment-p))))
  389. (defun elpy-shell--current-line-defun-p ()
  390. "Whether a function definition starts at the current line."
  391. (eq (string-match-p
  392. "\\s-*\\(?:def\\|async\\s-+def\\)\\s\-"
  393. (thing-at-point 'line))
  394. 0))
  395. (defun elpy-shell--current-line-defclass-p ()
  396. "Whether a class definition starts at the current line."
  397. (eq (string-match-p
  398. "\\s-*class\\s\-"
  399. (thing-at-point 'line))
  400. 0))
  401. (defun elpy-shell--skip-to-next-code-line (&optional backwards)
  402. "Move the point to the next line containing code.
  403. If the current line has code, point is not moved. If BACKWARDS is
  404. non-nil, skips backwards."
  405. (if backwards
  406. (while (and (not (elpy-shell--current-line-code-line-p))
  407. (not (eq (point) (point-min))))
  408. (forward-line -1))
  409. (while (and (not (elpy-shell--current-line-code-line-p))
  410. (not (eq (point) (point-max))))
  411. (forward-line))))
  412. (defun elpy-shell--check-if-shell-available ()
  413. "Check if the associated python shell is available.
  414. Return non-nil is the shell is running and not busy, nil otherwise."
  415. (and (python-shell-get-process)
  416. (with-current-buffer (process-buffer (python-shell-get-process))
  417. (save-excursion
  418. (goto-char (point-max))
  419. (let ((inhibit-field-text-motion t))
  420. (python-shell-comint-end-of-output-p
  421. (buffer-substring (line-beginning-position)
  422. (line-end-position))))))))
  423. ;;;;;;;;;;
  424. ;; Echoing
  425. (defmacro elpy-shell--with-maybe-echo (body)
  426. ;; Echoing is apparently buggy for emacs < 25...
  427. (if (<= 25 emacs-major-version)
  428. `(elpy-shell--with-maybe-echo-output
  429. (elpy-shell--with-maybe-echo-input
  430. ,body))
  431. body))
  432. (defmacro elpy-shell--with-maybe-echo-input (body)
  433. "Run BODY so that it adheres `elpy-shell-echo-input' and `elpy-shell-display-buffer'."
  434. `(progn
  435. (elpy-shell--enable-echo)
  436. (prog1
  437. (if elpy-shell-display-buffer-after-send
  438. (prog1 (progn ,body)
  439. (elpy-shell-display-buffer))
  440. (cl-flet ((elpy-shell-display-buffer () ()))
  441. (progn ,body)))
  442. (elpy-shell--disable-echo))))
  443. (defvar-local elpy-shell--capture-output nil
  444. "Non-nil when the Python shell should capture output for display in the echo area.")
  445. (defvar-local elpy-shell--captured-output nil
  446. "Current captured output of the Python shell.")
  447. (defmacro elpy-shell--with-maybe-echo-output (body)
  448. "Run BODY and grab shell output according to `elpy-shell-echo-output'."
  449. `(cl-letf (((symbol-function 'python-shell-send-file)
  450. (if elpy-shell-echo-output
  451. (symbol-function 'elpy-shell-send-file)
  452. (symbol-function 'python-shell-send-file))))
  453. (let* ((process (elpy-shell--ensure-shell-running))
  454. (process-buf (process-buffer process))
  455. (shell-visible (or elpy-shell-display-buffer-after-send
  456. (get-buffer-window process-buf))))
  457. (with-current-buffer process-buf
  458. (setq-local elpy-shell--capture-output
  459. (and elpy-shell-echo-output
  460. (or (not (eq elpy-shell-echo-output 'when-shell-not-visible))
  461. (not shell-visible)))))
  462. (progn ,body))))
  463. (defun elpy-shell--enable-output-filter ()
  464. (add-hook 'comint-output-filter-functions 'elpy-shell--output-filter nil t))
  465. (defun elpy-shell--output-filter (string)
  466. "Filter used in `elpy-shell--with-maybe-echo-output' to grab output.
  467. No actual filtering is performed. STRING is the output received
  468. to this point from the process. If `elpy-shell--capture-output'
  469. is set, captures and messages shell output in the echo area (once
  470. complete). Otherwise, does nothing."
  471. ;; capture the output and message it when complete
  472. (when elpy-shell--capture-output
  473. ;; remember the new output
  474. (setq-local elpy-shell--captured-output
  475. (concat elpy-shell--captured-output (ansi-color-filter-apply string)))
  476. ;; Output ends when `elpy-shell--captured-output' contains
  477. ;; the prompt attached at the end of it. If so, message it.
  478. (when (python-shell-comint-end-of-output-p elpy-shell--captured-output)
  479. (let ((output (substring
  480. elpy-shell--captured-output
  481. 0 (match-beginning 0)))
  482. (message-log-max))
  483. (if (string-match-p "Traceback (most recent call last):" output)
  484. (message "Exception during evaluation.")
  485. (if (string-empty-p output)
  486. (message "No output was produced.")
  487. (message "%s" (replace-regexp-in-string "\n\\'" "" output))))
  488. (setq-local elpy-shell--captured-output nil))))
  489. ;; return input unmodified
  490. string)
  491. (defun elpy-shell--insert-and-font-lock (string face &optional no-font-lock)
  492. "Inject STRING into the Python shell buffer."
  493. (let ((from-point (point)))
  494. (insert string)
  495. (if (not no-font-lock)
  496. (add-text-properties from-point (point)
  497. (list 'front-sticky t 'font-lock-face face)))))
  498. (defun elpy-shell--append-to-shell-output (string &optional no-font-lock prepend-cont-prompt)
  499. "Append the given STRING to the output of the Python shell buffer.
  500. Unless NO-FONT-LOCK is set, formats STRING as shell input.
  501. Prepends a continuation promt if PREPEND-CONT-PROMPT is set."
  502. (unless (string-empty-p string)
  503. (let* ((process (elpy-shell-get-or-create-process))
  504. (process-buf (process-buffer process))
  505. (mark-point (process-mark process)))
  506. (with-current-buffer process-buf
  507. (save-excursion
  508. (goto-char mark-point)
  509. (if prepend-cont-prompt
  510. (let* ((column (+ (- (point)
  511. (let ((inhibit-field-text-motion t))
  512. (forward-line -1)
  513. (end-of-line)
  514. (point)))
  515. 1))
  516. (prompt (concat (make-string (max 0 (- column 6)) ? ) "... "))
  517. (lines (split-string string "\n")))
  518. (goto-char mark-point)
  519. (elpy-shell--insert-and-font-lock
  520. (car lines) 'comint-highlight-input no-font-lock)
  521. (when (cdr lines)
  522. ;; no additional newline at end for multiline
  523. (dolist (line (cdr lines))
  524. (insert "\n")
  525. (let ((from-point (point)))
  526. (elpy-shell--insert-and-font-lock
  527. prompt 'comint-highlight-prompt no-font-lock)
  528. (add-text-properties
  529. from-point (point)
  530. '(field output inhibit-line-move-field-capture t
  531. rear-nonsticky t)))
  532. (elpy-shell--insert-and-font-lock
  533. line 'comint-highlight-input no-font-lock)))
  534. ;; but put one for single line
  535. (insert "\n"))
  536. (elpy-shell--insert-and-font-lock
  537. string 'comint-highlight-input no-font-lock))
  538. (set-marker (process-mark process) (point)))))))
  539. (defun elpy-shell--string-head-lines (string n)
  540. "Extract the first N lines from STRING."
  541. (let* ((line "\\(?:\\(?:.*\n\\)\\|\\(?:.+\\'\\)\\)")
  542. (lines (concat line "\\{" (number-to-string n) "\\}"))
  543. (regexp (concat "\\`" "\\(" lines "\\)")))
  544. (if (string-match regexp string)
  545. (match-string 1 string)
  546. string)))
  547. (defun elpy-shell--string-tail-lines (string n)
  548. "Extract the last N lines from STRING."
  549. (let* ((line "\\(?:\\(?:.*\n\\)\\|\\(?:.+\\'\\)\\)")
  550. (lines (concat line "\\{" (number-to-string n) "\\}"))
  551. (regexp (concat "\\(" lines "\\)" "\\'")))
  552. (if (string-match regexp string)
  553. (match-string 1 string)
  554. string)))
  555. (defun elpy-shell--python-shell-send-string-echo-advice (string &optional _process _msg)
  556. "Advice to enable echoing of input in the Python shell."
  557. (interactive)
  558. (let* ((append-string ; strip setup code from Elpy
  559. (if (string-match "import sys, codecs, os, ast;__pyfile = codecs.open.*$" string)
  560. (replace-match "" nil nil string)
  561. string))
  562. (append-string ; strip setup code from python.el
  563. (if (string-match "import codecs, os;__pyfile = codecs.open(.*;exec(compile(__code, .*$" append-string)
  564. (replace-match "" nil nil append-string)
  565. append-string))
  566. (append-string ; here too
  567. (if (string-match "^# -\\*- coding: utf-8 -\\*-\n*$" append-string)
  568. (replace-match "" nil nil append-string)
  569. append-string))
  570. (append-string ; Strip "if True:", added when sending regions
  571. (if (string-match "^if True:$" append-string)
  572. (replace-match "" nil nil append-string)
  573. append-string))
  574. (append-string ; strip newlines from beginning and white space from end
  575. (string-trim-right
  576. (if (string-match "\\`\n+" append-string)
  577. (replace-match "" nil nil append-string)
  578. append-string)))
  579. (append-string ; Dedent region
  580. (elpy-shell--string-without-indentation append-string))
  581. (head (elpy-shell--string-head-lines append-string elpy-shell-echo-input-lines-head))
  582. (tail (elpy-shell--string-tail-lines append-string elpy-shell-echo-input-lines-tail))
  583. (append-string (if (> (length append-string) (+ (length head) (length tail)))
  584. (concat head "...\n" tail)
  585. append-string)))
  586. ;; append the modified string to the shell output; prepend a newline for
  587. ;; multi-line strings
  588. (if elpy-shell-echo-input-cont-prompt
  589. (elpy-shell--append-to-shell-output append-string nil t)
  590. (elpy-shell--append-to-shell-output
  591. (concat (if (string-match "\n" append-string) "\n" "")
  592. append-string
  593. "\n")))))
  594. (defun elpy-shell--enable-echo ()
  595. "Enable input echoing when `elpy-shell-echo-input' is set."
  596. (when elpy-shell-echo-input
  597. (advice-add 'python-shell-send-string
  598. :before 'elpy-shell--python-shell-send-string-echo-advice)))
  599. (defun elpy-shell--disable-echo ()
  600. "Disable input echoing."
  601. (advice-remove 'python-shell-send-string
  602. 'elpy-shell--python-shell-send-string-echo-advice))
  603. (defun elpy-shell-send-file (file-name &optional process temp-file-name
  604. delete msg)
  605. "Like `python-shell-send-file' but evaluates last expression separately.
  606. See `python-shell-send-file' for a description of the
  607. arguments. This function differs in that it breaks up the
  608. Python code in FILE-NAME into statements. If the last statement
  609. is a Python expression, it is evaluated separately in 'eval'
  610. mode. This way, the interactive python shell can capture (and
  611. print) the output of the last expression."
  612. (interactive
  613. (list
  614. (read-file-name "File to send: ") ; file-name
  615. nil ; process
  616. nil ; temp-file-name
  617. nil ; delete
  618. t)) ; msg
  619. (let* ((process (or process (python-shell-get-process-or-error msg)))
  620. (encoding (with-temp-buffer
  621. (insert-file-contents
  622. (or temp-file-name file-name))
  623. (python-info-encoding)))
  624. (file-name (expand-file-name
  625. (or (file-remote-p file-name 'localname)
  626. file-name)))
  627. (temp-file-name (when temp-file-name
  628. (expand-file-name
  629. (or (file-remote-p temp-file-name 'localname)
  630. temp-file-name)))))
  631. (python-shell-send-string
  632. (format
  633. (concat
  634. "import sys, codecs, os, ast;"
  635. "__pyfile = codecs.open('''%s''', encoding='''%s''');"
  636. "__code = __pyfile.read().encode('''%s''');"
  637. "__pyfile.close();"
  638. (when (and delete temp-file-name)
  639. (format "os.remove('''%s''');" temp-file-name))
  640. "__block = ast.parse(__code, '''%s''', mode='exec');"
  641. ;; Has to ba a oneliner, which make conditionnal statements a bit complicated...
  642. " __block.body = (__block.body if not isinstance(__block.body[0], ast.If) else __block.body if not isinstance(__block.body[0].test, ast.Name) else __block.body if not __block.body[0].test.id == 'True' else __block.body[0].body) if sys.version_info[0] < 3 else (__block.body if not isinstance(__block.body[0], ast.If) else __block.body if not isinstance(__block.body[0].test, ast.NameConstant) else __block.body if not __block.body[0].test.value is True else __block.body[0].body);"
  643. "__last = __block.body[-1];" ;; the last statement
  644. "__isexpr = isinstance(__last,ast.Expr);" ;; is it an expression?
  645. "_ = __block.body.pop() if __isexpr else None;" ;; if so, remove it
  646. "exec(compile(__block, '''%s''', mode='exec'));" ;; execute everything else
  647. "eval(compile(ast.Expression(__last.value), '''%s''', mode='eval')) if __isexpr else None" ;; if it was an expression, it has been removed; now evaluate it
  648. )
  649. (or temp-file-name file-name) encoding encoding file-name file-name file-name)
  650. process)))
  651. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  652. ;; Navigation commands for sending
  653. (defun elpy-shell--nav-beginning-of-statement ()
  654. "Move the point to the beginning of the current or next Python statement.
  655. If the current line starts with a statement, behaves exactly like
  656. `python-nav-beginning-of-statement'. If the line is part of a
  657. statement but not a statement itself, goes backwards to the
  658. beginning of the statement. If the current line is not a code
  659. line, skips forward to the next code line and navigates from
  660. there."
  661. (elpy-shell--skip-to-next-code-line)
  662. (python-nav-beginning-of-statement)
  663. (let ((p))
  664. (while (and (not (eq p (point)))
  665. (or (elpy-shell--current-line-else-or-elif-p)
  666. (elpy-shell--current-line-decorated-defun-p)))
  667. (elpy-nav-backward-block)
  668. (setq p (point)))))
  669. (defun elpy-shell--nav-end-of-statement ()
  670. "Move the point to the end of the current Python statement.
  671. Assumes that the point is precisely at the beginning of a
  672. statement (e.g., after calling
  673. `elpy-shell--nav-beginning-of-statement')."
  674. (let ((continue t)
  675. (p))
  676. (while (and (not (eq p (point)))
  677. continue)
  678. ;; if on a decorator, move to the associated function
  679. (when (elpy-shell--current-line-decorator-p)
  680. (elpy-nav-forward-block))
  681. ;; check if there is a another block at the same indentation level
  682. (setq p (point))
  683. (elpy-nav-forward-block)
  684. ;; if not, go to the end of the block and done
  685. (if (eq p (point))
  686. (progn
  687. (python-nav-end-of-block)
  688. (setq continue nil))
  689. ;; otherwise check if its an else/elif clause
  690. (unless (elpy-shell--current-line-else-or-elif-p)
  691. (forward-line -1)
  692. (elpy-shell--skip-to-next-code-line t)
  693. (setq continue nil)))))
  694. (end-of-line))
  695. (defun elpy-shell--nav-beginning-of-top-statement ()
  696. "Move the point to the beginning of the current or next top-level statement.
  697. If the point is within a top-level statement, moves to its
  698. beginning. Otherwise, moves to the beginning of the next top-level
  699. statement."
  700. (interactive)
  701. (elpy-shell--nav-beginning-of-statement)
  702. (let ((p))
  703. (while (and (not (eq p (point)))
  704. (elpy-shell--current-line-indented-p))
  705. (forward-line -1)
  706. (elpy-shell--skip-to-next-code-line t)
  707. (elpy-shell--nav-beginning-of-statement))))
  708. (defun elpy-shell--nav-beginning-of-def (def-p)
  709. "Move point to the beginning of the current definition.
  710. DEF-P is a predicate function that decides whether the current
  711. line starts a definition.
  712. It the current line starts a definition, uses this definition. If
  713. the current line does not start a definition and is a code line,
  714. searches for the definition that contains the current line.
  715. Otherwise, searches for the definition that contains the next
  716. code line.
  717. If a definition is found, moves point to the start of the
  718. definition and returns t. Otherwise, retains point position and
  719. returns nil."
  720. (if (funcall def-p)
  721. (progn
  722. (python-nav-beginning-of-statement)
  723. t)
  724. (let ((beg-ts (save-excursion
  725. (elpy-shell--skip-to-next-code-line t)
  726. (elpy-shell--nav-beginning-of-top-statement)
  727. (point)))
  728. (orig-p (point))
  729. (max-indent (save-excursion
  730. (elpy-shell--skip-to-next-code-line)
  731. (- (current-indentation) 1)))
  732. (found))
  733. (while (and (not found)
  734. (>= (point) beg-ts))
  735. (if (and (funcall def-p)
  736. (<= (current-indentation) max-indent))
  737. (setq found t)
  738. (when (elpy-shell--current-line-code-line-p)
  739. (setq max-indent (min max-indent
  740. (- (current-indentation) 1))))
  741. (forward-line -1)))
  742. (if found
  743. (python-nav-beginning-of-statement)
  744. (goto-char orig-p))
  745. found)))
  746. (defun elpy-shell--nav-beginning-of-defun ()
  747. "Move point to the beginning of the current function definition.
  748. If a definition is found, moves point to the start of the
  749. definition and returns t. Otherwise, retains point position and
  750. returns nil.
  751. See `elpy-shell--nav-beginning-of-def' for details."
  752. (when (or (elpy-shell--nav-beginning-of-def 'elpy-shell--current-line-defun-p)
  753. (elpy-shell--current-line-decorator-p))
  754. (when (elpy-shell--current-line-decorated-defun-p)
  755. (python-nav-backward-statement))
  756. t))
  757. (defun elpy-shell--nav-beginning-of-defclass ()
  758. "Move point to the beginning of the current class definition.
  759. If a definition is found, moves point to the start of the
  760. definition and returns t. Otherwise, retains point position and
  761. returns nil.
  762. See `elpy-shell--nav-beginning-of-def' for details."
  763. (elpy-shell--nav-beginning-of-def 'elpy-shell--current-line-defclass-p))
  764. (defun elpy-shell--nav-beginning-of-group ()
  765. "Move point to the beginning of the current or next group of top-level statements.
  766. A sequence of top-level statements is a group if they are not
  767. separated by empty lines. Empty lines within each top-level
  768. statement are ignored.
  769. If the point is within a top-level statement, moves to the
  770. beginning of the group containing this statement. Otherwise, moves
  771. to the first top-level statement below point."
  772. (elpy-shell--nav-beginning-of-top-statement)
  773. (while (not (or (elpy-shell--current-line-only-whitespace-p)
  774. (eq (point) (point-min))))
  775. (unless (python-info-current-line-comment-p)
  776. (elpy-shell--nav-beginning-of-top-statement))
  777. (forward-line -1)
  778. (beginning-of-line))
  779. (when (elpy-shell--current-line-only-whitespace-p)
  780. (forward-line 1)
  781. (beginning-of-line)))
  782. ;;;;;;;;;;;;;;;;;
  783. ;;; Send commands
  784. (defun elpy-shell-send-statement-and-step ()
  785. "Send current or next statement to Python shell and step.
  786. If the current line is part of a statement, sends this statement.
  787. Otherwise, skips forward to the next code line and sends the
  788. corresponding statement."
  789. (interactive)
  790. (elpy-shell--ensure-shell-running)
  791. (elpy-shell--nav-beginning-of-statement)
  792. ;; Make sure there is a statement to send
  793. (unless (looking-at "[[:space:]]*$")
  794. (unless elpy-shell-echo-input (elpy-shell--append-to-shell-output "\n"))
  795. (let ((beg (save-excursion (beginning-of-line) (point)))
  796. (end (progn (elpy-shell--nav-end-of-statement) (point))))
  797. (unless (eq beg end)
  798. (elpy-shell--flash-and-message-region beg end)
  799. (elpy-shell--add-to-shell-history (buffer-substring beg end))
  800. (elpy-shell--with-maybe-echo
  801. (python-shell-send-string
  802. (python-shell-buffer-substring beg end)))))
  803. (python-nav-forward-statement)))
  804. (defun elpy-shell-send-top-statement-and-step ()
  805. "Send the current or next top-level statement to the Python shell and step.
  806. If the current line is part of a top-level statement, sends this
  807. top-level statement. Otherwise, skips forward to the next code
  808. line and sends the corresponding top-level statement."
  809. (interactive)
  810. (elpy-shell--ensure-shell-running)
  811. (let* ((beg (progn (elpy-shell--nav-beginning-of-top-statement) (point)))
  812. (end (progn (elpy-shell--nav-end-of-statement) (point))))
  813. (elpy-shell--flash-and-message-region beg end)
  814. (if (string-match-p "\\`[^\n]*\\'" (buffer-substring beg end))
  815. ;; single line
  816. (elpy-shell-send-statement-and-step)
  817. ;; multiple lines
  818. (elpy-shell--add-to-shell-history (buffer-substring beg end))
  819. (elpy-shell--with-maybe-echo
  820. (python-shell-send-string (python-shell-buffer-substring beg end)))
  821. (setq mark-active nil)
  822. (python-nav-forward-statement))))
  823. (defun elpy-shell-send-defun-and-step ()
  824. "Send the function definition that contains the current line
  825. to the Python shell and steps.
  826. See `elpy-shell--nav-beginning-of-def' for details."
  827. (interactive)
  828. (if (elpy-shell--nav-beginning-of-defun)
  829. (elpy-shell-send-statement-and-step)
  830. (message "There is no function definition that includes the current line.")))
  831. (defun elpy-shell-send-defclass-and-step ()
  832. "Send the class definition that contains the current line to
  833. the Python shell and steps.
  834. See `elpy-shell--nav-beginning-of-def' for details."
  835. (interactive)
  836. (if (elpy-shell--nav-beginning-of-defclass)
  837. (elpy-shell-send-statement-and-step)
  838. (message "There is no class definition that includes the current line.")))
  839. (defun elpy-shell-send-group-and-step ()
  840. "Send the current or next group of top-level statements to the Python shell and step.
  841. A sequence of top-level statements is a group if they are not
  842. separated by empty lines. Empty lines within each top-level
  843. statement are ignored.
  844. If the point is within a top-level statement, send the group
  845. around this statement. Otherwise, go to the top-level statement
  846. below point and send the group around this statement."
  847. (interactive)
  848. (elpy-shell--ensure-shell-running)
  849. (let* ((beg (progn (elpy-shell--nav-beginning-of-group) (point)))
  850. (end (progn
  851. ;; go forward to end of group
  852. (unless (python-info-current-line-comment-p)
  853. (elpy-shell--nav-end-of-statement))
  854. (let ((p))
  855. (while (not (eq p (point)))
  856. (setq p (point))
  857. (forward-line)
  858. (if (elpy-shell--current-line-only-whitespace-p)
  859. (goto-char p) ;; done
  860. (unless (python-info-current-line-comment-p)
  861. (elpy-shell--nav-end-of-statement)))))
  862. (point))))
  863. (if (> end beg)
  864. (progn
  865. (elpy-shell--flash-and-message-region beg end)
  866. ;; send the region and jump to next statement
  867. (if (string-match-p "\\`[^\n]*\\'" (buffer-substring beg end))
  868. ;; single line
  869. (elpy-shell-send-statement-and-step)
  870. ;; multiple lines
  871. (unless elpy-shell-echo-input
  872. (elpy-shell--append-to-shell-output "\n"))
  873. (elpy-shell--add-to-shell-history (buffer-substring beg end))
  874. (elpy-shell--with-maybe-echo
  875. (python-shell-send-string
  876. (python-shell-buffer-substring beg end)))
  877. (python-nav-forward-statement)))
  878. (goto-char (point-max)))
  879. (setq mark-active nil)))
  880. (defun elpy-shell-send-codecell-and-step ()
  881. "Send the current code cell to the Python shell and step.
  882. Signals an error if the point is not inside a code cell.
  883. Cell beginnings and cell boundaries can be customized via the
  884. variables `elpy-shell-cell-boundary-regexp' and
  885. `elpy-shell-codecell-beginning-regexp', which see."
  886. (interactive)
  887. (let ((beg (save-excursion
  888. (end-of-line)
  889. (re-search-backward elpy-shell-cell-boundary-regexp nil t)
  890. (beginning-of-line)
  891. (and (string-match-p elpy-shell-codecell-beginning-regexp
  892. (thing-at-point 'line))
  893. (point))))
  894. (end (save-excursion
  895. (forward-line)
  896. (if (re-search-forward elpy-shell-cell-boundary-regexp nil t)
  897. (forward-line -1)
  898. (goto-char (point-max)))
  899. (end-of-line)
  900. (point))))
  901. (if beg
  902. (progn
  903. (elpy-shell--flash-and-message-region beg end)
  904. (unless elpy-shell-echo-input
  905. (elpy-shell--append-to-shell-output "\n"))
  906. (elpy-shell--add-to-shell-history (buffer-substring beg end))
  907. (elpy-shell--with-maybe-echo
  908. (python-shell-send-string (python-shell-buffer-substring beg end)))
  909. (goto-char end)
  910. (python-nav-forward-statement))
  911. (message "Not in a codecell."))))
  912. (defun elpy-shell-send-region-or-buffer-and-step (&optional arg)
  913. "Send the active region or the buffer to the Python shell and step.
  914. If there is an active region, send that. Otherwise, send the
  915. whole buffer.
  916. In Emacs 24.3 and later, without prefix argument and when there
  917. is no active region, this will escape the Python idiom of if
  918. __name__ == '__main__' to be false to avoid accidental execution
  919. of code. With prefix argument, this code is executed."
  920. (interactive "P")
  921. (if (use-region-p)
  922. (elpy-shell--flash-and-message-region (region-beginning) (region-end))
  923. (elpy-shell--flash-and-message-region (point-min) (point-max)))
  924. (elpy-shell--with-maybe-echo
  925. (elpy-shell--send-region-or-buffer-internal arg))
  926. (if (use-region-p)
  927. (goto-char (region-end))
  928. (goto-char (point-max))))
  929. (defun elpy-shell--send-region-or-buffer-internal (&optional arg)
  930. "Send the active region or the buffer to the Python shell and step.
  931. If there is an active region, send that. Otherwise, send the
  932. whole buffer.
  933. In Emacs 24.3 and later, without prefix argument and when there
  934. is no active region, this will escape the Python idiom of if
  935. __name__ == '__main__' to be false to avoid accidental execution
  936. of code. With prefix argument, this code is executed."
  937. (interactive "P")
  938. (elpy-shell--ensure-shell-running)
  939. (unless elpy-shell-echo-input (elpy-shell--append-to-shell-output "\n"))
  940. (let ((if-main-regex "^if +__name__ +== +[\"']__main__[\"'] *:")
  941. (has-if-main-and-removed nil))
  942. (if (use-region-p)
  943. (let ((region (python-shell-buffer-substring
  944. (region-beginning) (region-end)))
  945. (region-original (buffer-substring
  946. (region-beginning) (region-end))))
  947. (when (string-match "\t" region)
  948. (message "Region contained tabs, this might cause weird errors"))
  949. ;; python-shell-buffer-substring (intentionally?) does not accurately
  950. ;; respect (region-beginning); it always start on the first character
  951. ;; of the respective line even if that's before the region beginning
  952. ;; Here we post-process the output to remove the characters before
  953. ;; (region-beginning) and the start of the line. The end of the region
  954. ;; is handled correctly and needs no special treatment.
  955. (let* ((bounds (save-excursion
  956. (goto-char (region-beginning))
  957. (bounds-of-thing-at-point 'line)))
  958. (used-part (string-trim
  959. (buffer-substring-no-properties
  960. (car bounds)
  961. (min (cdr bounds) (region-end)))))
  962. (relevant-part (string-trim
  963. (buffer-substring-no-properties
  964. (max (car bounds) (region-beginning))
  965. (min (cdr bounds) (region-end))))))
  966. (setq region
  967. ;; replace just first match
  968. (replace-regexp-in-string
  969. (concat "\\(" (regexp-quote used-part) "\\)\\(?:.*\n?\\)*\\'")
  970. relevant-part
  971. region t t 1))
  972. (elpy-shell--add-to-shell-history region-original)
  973. (python-shell-send-string region)))
  974. (unless arg
  975. (save-excursion
  976. (goto-char (point-min))
  977. (setq has-if-main-and-removed (re-search-forward if-main-regex nil t))))
  978. (python-shell-send-buffer arg))
  979. (when has-if-main-and-removed
  980. (message (concat "Removed if __name__ == '__main__' construct, "
  981. "use a prefix argument to evaluate.")))))
  982. (defun elpy-shell-send-buffer-and-step (&optional arg)
  983. "Send entire buffer to Python shell.
  984. In Emacs 24.3 and later, without prefix argument, this will
  985. escape the Python idiom of if __name__ == '__main__' to be false
  986. to avoid accidental execution of code. With prefix argument, this
  987. code is executed."
  988. (interactive "P")
  989. (let ((p))
  990. (save-mark-and-excursion
  991. (deactivate-mark)
  992. (elpy-shell-send-region-or-buffer-and-step arg)
  993. (setq p (point)))
  994. (goto-char p)))
  995. (defun elpy-shell--add-to-shell-history (string)
  996. "Add STRING to the shell command history."
  997. (when elpy-shell-add-to-shell-history
  998. (with-current-buffer (process-buffer (elpy-shell-get-or-create-process))
  999. (comint-add-to-input-history (string-trim string)))))
  1000. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1001. ;; Send command variations (with/without step; with/without go)
  1002. (defun elpy-shell--send-with-step-go (step-fun step go my-prefix-arg)
  1003. "Run a function with STEP and/or GO.
  1004. STEP-FUN should be a function that sends something to the shell
  1005. and moves point to code position right after what has been sent.
  1006. When STEP is nil, keeps point position. When GO is non-nil,
  1007. switches focus to Python shell buffer."
  1008. (let ((orig (point)))
  1009. (setq current-prefix-arg my-prefix-arg)
  1010. (call-interactively step-fun)
  1011. (unless step
  1012. (goto-char orig)))
  1013. (when go
  1014. (elpy-shell-switch-to-shell)))
  1015. (defmacro elpy-shell--defun-step-go (fun-and-step)
  1016. "Defines fun, fun-and-go, fun-and-step-and-go for the given FUN-AND-STEP function."
  1017. (let ((name (string-remove-suffix "-and-step" (symbol-name fun-and-step))))
  1018. (list
  1019. 'progn
  1020. (let ((fun (intern name)))
  1021. `(defun ,fun (&optional arg)
  1022. ,(concat "Run `" (symbol-name fun-and-step) "' but retain point position.")
  1023. (interactive "P")
  1024. (elpy-shell--send-with-step-go ',fun-and-step nil nil arg)))
  1025. (let ((fun-and-go (intern (concat name "-and-go"))))
  1026. `(defun ,fun-and-go (&optional arg)
  1027. ,(concat "Run `" (symbol-name fun-and-step) "' but retain point position and switch to Python shell.")
  1028. (interactive "P")
  1029. (elpy-shell--send-with-step-go ',fun-and-step nil t arg)))
  1030. (let ((fun-and-step-and-go (intern (concat name "-and-step-and-go"))))
  1031. `(defun ,fun-and-step-and-go (&optional arg)
  1032. ,(concat "Run `" (symbol-name fun-and-step) "' and switch to Python shell.")
  1033. (interactive "P")
  1034. (elpy-shell--send-with-step-go ',fun-and-step t t arg))))))
  1035. (elpy-shell--defun-step-go elpy-shell-send-statement-and-step)
  1036. (elpy-shell--defun-step-go elpy-shell-send-top-statement-and-step)
  1037. (elpy-shell--defun-step-go elpy-shell-send-defun-and-step)
  1038. (elpy-shell--defun-step-go elpy-shell-send-defclass-and-step)
  1039. (elpy-shell--defun-step-go elpy-shell-send-group-and-step)
  1040. (elpy-shell--defun-step-go elpy-shell-send-codecell-and-step)
  1041. (elpy-shell--defun-step-go elpy-shell-send-region-or-buffer-and-step)
  1042. (elpy-shell--defun-step-go elpy-shell-send-buffer-and-step)
  1043. ;;;;;;;;;;;;;;;;;;;;;;;
  1044. ;; Debugging features
  1045. (when (version<= "25" emacs-version)
  1046. (defun elpy-pdb--refresh-breakpoints (lines)
  1047. "Add new breakpoints at lines LINES of the current buffer."
  1048. ;; Forget old breakpoints
  1049. (python-shell-send-string-no-output "import bdb as __bdb; __bdb.Breakpoint.bplist={}; __bdb.Breakpoint.next=1;__bdb.Breakpoint.bpbynumber=[None]")
  1050. (python-shell-send-string-no-output "import pdb; __pdbi = pdb.Pdb()")
  1051. (dolist (line lines)
  1052. (python-shell-send-string-no-output
  1053. (format "__pdbi.set_break('''%s''', %s)" (buffer-file-name) line))))
  1054. (defun elpy-pdb--start-pdb (&optional output)
  1055. "Start pdb on the current script.
  1056. if OUTPUT is non-nil, display the prompt after execution."
  1057. (let ((string (format "__pdbi._runscript('''%s''')" (buffer-file-name))))
  1058. (if output
  1059. (python-shell-send-string string)
  1060. (python-shell-send-string-no-output string))))
  1061. (defun elpy-pdb--get-breakpoint-positions ()
  1062. "Return a list of lines with breakpoints."
  1063. (let* ((overlays (overlay-lists))
  1064. (overlays (append (car overlays) (cdr overlays)))
  1065. (bp-lines '()))
  1066. (dolist (ov overlays)
  1067. (when (overlay-get ov 'elpy-breakpoint)
  1068. (push (line-number-at-pos (overlay-start ov))
  1069. bp-lines)))
  1070. bp-lines))
  1071. (defun elpy-pdb-debug-buffer (&optional arg)
  1072. "Run pdb on the current buffer.
  1073. If breakpoints are set in the current buffer, jump to the first one.
  1074. If no breakpoints are set, debug from the beginning of the script.
  1075. With a prefix argument, ignore the existing breakpoints."
  1076. (interactive "P")
  1077. (if (not (buffer-file-name))
  1078. (error "Debugging only work for buffers visiting a file")
  1079. (elpy-shell--ensure-shell-running)
  1080. (save-buffer)
  1081. (let ((bp-lines (elpy-pdb--get-breakpoint-positions)))
  1082. (if (or arg (= 0 (length bp-lines)))
  1083. (progn
  1084. (elpy-pdb--refresh-breakpoints '())
  1085. (elpy-pdb--start-pdb t))
  1086. (elpy-pdb--refresh-breakpoints bp-lines)
  1087. (elpy-pdb--start-pdb)
  1088. (python-shell-send-string "continue")))
  1089. (elpy-shell-display-buffer)))
  1090. (defun elpy-pdb-break-at-point ()
  1091. "Run pdb on the current buffer and break at the current line.
  1092. Ignore the existing breakpoints.
  1093. Pdb can directly exit if the current line is not a statement
  1094. that is actually run (blank line, comment line, ...)."
  1095. (interactive)
  1096. (if (not (buffer-file-name))
  1097. (error "Debugging only work for buffers visiting a file")
  1098. (elpy-shell--ensure-shell-running)
  1099. (save-buffer)
  1100. (elpy-pdb--refresh-breakpoints (list (line-number-at-pos)))
  1101. (elpy-pdb--start-pdb)
  1102. (python-shell-send-string "continue")
  1103. (elpy-shell-display-buffer)))
  1104. (defun elpy-pdb-debug-last-exception ()
  1105. "Run post-mortem pdb on the last exception."
  1106. (interactive)
  1107. (elpy-shell--ensure-shell-running)
  1108. ;; check if there is a last exception
  1109. (if (not (with-current-buffer (format "*%s*"
  1110. (python-shell-get-process-name nil))
  1111. (save-excursion
  1112. (goto-char (point-max))
  1113. (search-backward "Traceback (most recent call last):"
  1114. nil t))))
  1115. (error "No traceback on the current shell")
  1116. (python-shell-send-string
  1117. "import pdb as __pdb;__pdb.pm()"))
  1118. (elpy-shell-display-buffer))
  1119. ;; Fringe indicators
  1120. (when (fboundp 'define-fringe-bitmap)
  1121. (define-fringe-bitmap 'elpy-breakpoint-fringe-marker
  1122. (vector
  1123. #b00000000
  1124. #b00111100
  1125. #b01111110
  1126. #b01111110
  1127. #b01111110
  1128. #b01111110
  1129. #b00111100
  1130. #b00000000)))
  1131. (defcustom elpy-breakpoint-fringe-face 'elpy-breakpoint-fringe-face
  1132. "Face for breakpoint bitmaps appearing on the fringe."
  1133. :type 'face
  1134. :group 'elpy)
  1135. (defface elpy-breakpoint-fringe-face
  1136. '((t (:foreground "red"
  1137. :box (:line-width 1 :color "red" :style released-button))))
  1138. "Face for breakpoint bitmaps appearing on the fringe."
  1139. :group 'elpy)
  1140. (defun elpy-pdb-toggle-breakpoint-at-point (&optional arg)
  1141. "Add or remove a breakpoint at the current line.
  1142. With a prefix argument, remove all the breakpoints from the current
  1143. region or buffer."
  1144. (interactive "P")
  1145. (if arg
  1146. (elpy-pdb-clear-breakpoints)
  1147. (let ((overlays (overlays-in (line-beginning-position)
  1148. (line-end-position)))
  1149. bp-at-line)
  1150. ;; Check if already a breakpoint
  1151. (while overlays
  1152. (let ((overlay (pop overlays)))
  1153. (when (overlay-get overlay 'elpy-breakpoint)
  1154. (setq bp-at-line t))))
  1155. (if bp-at-line
  1156. ;; If so, remove it
  1157. (remove-overlays (line-beginning-position)
  1158. (line-end-position)
  1159. 'elpy-breakpoint t)
  1160. ;; Check it the line is empty
  1161. (if (not (save-excursion
  1162. (beginning-of-line)
  1163. (looking-at "[[:space:]]*$")))
  1164. ;; Else add a new breakpoint
  1165. (let* ((ov (make-overlay (line-beginning-position)
  1166. (+ 1 (line-beginning-position))))
  1167. (marker-string "*fringe-dummy*")
  1168. (marker-length (length marker-string)))
  1169. (put-text-property 0 marker-length
  1170. 'display
  1171. (list 'left-fringe
  1172. 'elpy-breakpoint-fringe-marker
  1173. 'elpy-breakpoint-fringe-face)
  1174. marker-string)
  1175. (overlay-put ov 'before-string marker-string)
  1176. (overlay-put ov 'priority 200)
  1177. (overlay-put ov 'elpy-breakpoint t)))))))
  1178. (defun elpy-pdb-clear-breakpoints ()
  1179. "Remove the breakpoints in the current region or buffer."
  1180. (if (use-region-p)
  1181. (remove-overlays (region-beginning) (region-end) 'elpy-breakpoint t)
  1182. (remove-overlays (point-min) (point-max) 'elpy-breakpoint t))))
  1183. ;;;;;;;;;;;;;;;;;;;;;;;
  1184. ;; Deprecated functions
  1185. (defun elpy-use-ipython (&optional _ipython)
  1186. "Deprecated; see https://elpy.readthedocs.io/en/latest/ide.html#interpreter-setup"
  1187. (error "elpy-use-ipython is deprecated; see https://elpy.readthedocs.io/en/latest/ide.html#interpreter-setup"))
  1188. (make-obsolete 'elpy-use-ipython nil "Jan 2017")
  1189. (defun elpy-use-cpython (&optional _cpython)
  1190. "Deprecated; see https://elpy.readthedocs.io/en/latest/ide.html#interpreter-setup"
  1191. (error "elpy-use-cpython is deprecated; see https://elpy.readthedocs.io/en/latest/ide.html#interpreter-setup"))
  1192. (make-obsolete 'elpy-use-cpython nil "Jan 2017")
  1193. (provide 'elpy-shell)
  1194. ;;; elpy-shell.el ends here