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.

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