Klimi's new dotfiles with stow.
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.

1229 line
49 KiB

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