aboutsummaryrefslogtreecommitdiffstats
path: root/lisp/progmodes/python.el
diff options
context:
space:
mode:
Diffstat (limited to 'lisp/progmodes/python.el')
-rw-r--r--lisp/progmodes/python.el507
1 files changed, 373 insertions, 134 deletions
diff --git a/lisp/progmodes/python.el b/lisp/progmodes/python.el
index 1187636c663..89ef12d49eb 100644
--- a/lisp/progmodes/python.el
+++ b/lisp/progmodes/python.el
@@ -4,7 +4,7 @@
4 4
5;; Author: Fabián E. Gallina <fabian@anue.biz> 5;; Author: Fabián E. Gallina <fabian@anue.biz>
6;; URL: https://github.com/fgallina/python.el 6;; URL: https://github.com/fgallina/python.el
7;; Version: 0.24.2 7;; Version: 0.24.4
8;; Maintainer: emacs-devel@gnu.org 8;; Maintainer: emacs-devel@gnu.org
9;; Created: Jul 2010 9;; Created: Jul 2010
10;; Keywords: languages 10;; Keywords: languages
@@ -62,57 +62,80 @@
62;; (add-hook 'python-mode-hook 62;; (add-hook 'python-mode-hook
63;; (lambda () (setq forward-sexp-function nil))) 63;; (lambda () (setq forward-sexp-function nil)))
64 64
65;; Shell interaction: is provided and allows you to execute easily any 65;; Shell interaction: is provided and allows opening Python shells
66;; block of code of your current buffer in an inferior Python process. 66;; inside Emacs and executing any block of code of your current buffer
67;; in that inferior Python process.
68
69;; Besides that only the standard CPython (2.x and 3.x) shell and
70;; IPython are officially supported out of the box, the interaction
71;; should support any other readline based Python shells as well
72;; (e.g. Jython and Pypy have been reported to work). You can change
73;; your default interpreter and commandline arguments by setting the
74;; `python-shell-interpreter' and `python-shell-interpreter-args'
75;; variables. This example enables IPython globally:
76
77;; (setq python-shell-interpreter "ipython"
78;; python-shell-interpreter-args "-i")
79
80;; Using the "console" subcommand to start IPython in server-client
81;; mode is known to fail intermittently due a bug on IPython itself
82;; (see URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=18052#27').
83;; There seems to be a race condition in the IPython server (A.K.A
84;; kernel) when code is sent while it is still initializing, sometimes
85;; causing the shell to get stalled. With that said, if an IPython
86;; kernel is already running, "console --existing" seems to work fine.
87
88;; Running IPython on Windows needs more tweaking. The way you should
89;; set `python-shell-interpreter' and `python-shell-interpreter-args'
90;; is as follows (of course you need to modify the paths according to
91;; your system):
92
93;; (setq python-shell-interpreter "C:\\Python27\\python.exe"
94;; python-shell-interpreter-args
95;; "-i C:\\Python27\\Scripts\\ipython-script.py")
96
97;; If you are experiencing missing or delayed output in your shells,
98;; that's likely caused by your Operating System's pipe buffering
99;; (e.g. this is known to happen running CPython 3.3.4 in Windows 7.
100;; See URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17304'). To
101;; fix this, using CPython's "-u" commandline argument or setting the
102;; "PYTHONUNBUFFERED" environment variable should help: See URL
103;; `https://docs.python.org/3/using/cmdline.html#cmdoption-u'.
104
105;; The interaction relies upon having prompts for input (e.g. ">>> "
106;; and "... " in standard Python shell) and output (e.g. "Out[1]: " in
107;; IPython) detected properly. Failing that Emacs may hang but, in
108;; the case that happens, you can recover with \\[keyboard-quit]. To
109;; avoid this issue, a two-step prompt autodetection mechanism is
110;; provided: the first step is manual and consists of a collection of
111;; regular expressions matching common prompts for Python shells
112;; stored in `python-shell-prompt-input-regexps' and
113;; `python-shell-prompt-output-regexps', and dir-local friendly vars
114;; `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
115;; `python-shell-prompt-output-regexp' which are appended to the
116;; former automatically when a shell spawns; the second step is
117;; automatic and depends on the `python-shell-prompt-detect' helper
118;; function. See its docstring for details on global variables that
119;; modify its behavior.
67 120
68;; Shell completion: hitting tab will try to complete the current 121;; Shell completion: hitting tab will try to complete the current
69;; word. Shell completion is implemented in a manner that if you 122;; word. Shell completion is implemented in such way that if you
70;; change the `python-shell-interpreter' to any other (for example 123;; change the `python-shell-interpreter' it should be possible to
71;; IPython) it should be easy to integrate another way to calculate 124;; integrate custom logic to calculate completions. To achieve this
72;; completions. You just need to specify your custom 125;; you just need to set `python-shell-completion-setup-code' and
73;; `python-shell-completion-setup-code' and 126;; `python-shell-completion-string-code'. The default provided code,
74;; `python-shell-completion-string-code'. 127;; enables autocompletion for both CPython and IPython (and ideally
75 128;; any readline based Python shell). This code depends on the
76;; Here is a complete example of the settings you would use for
77;; iPython 0.11:
78
79;; (setq
80;; python-shell-interpreter "ipython"
81;; python-shell-interpreter-args ""
82;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
83;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
84;; python-shell-completion-setup-code
85;; "from IPython.core.completerlib import module_completion"
86;; python-shell-completion-module-string-code
87;; "';'.join(module_completion('''%s'''))\n"
88;; python-shell-completion-string-code
89;; "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
90
91;; For iPython 0.10 everything would be the same except for
92;; `python-shell-completion-string-code' and
93;; `python-shell-completion-module-string-code':
94
95;; (setq python-shell-completion-string-code
96;; "';'.join(__IP.complete('''%s'''))\n"
97;; python-shell-completion-module-string-code "")
98
99;; Unfortunately running iPython on Windows needs some more tweaking.
100;; The way you must set `python-shell-interpreter' and
101;; `python-shell-interpreter-args' is as follows:
102
103;; (setq
104;; python-shell-interpreter "C:\\Python27\\python.exe"
105;; python-shell-interpreter-args
106;; "-i C:\\Python27\\Scripts\\ipython-script.py")
107
108;; That will spawn the iPython process correctly (Of course you need
109;; to modify the paths according to your system).
110
111;; Please note that the default completion system depends on the
112;; readline module, so if you are using some Operating System that 129;; readline module, so if you are using some Operating System that
113;; bundles Python without it (like Windows) just install the 130;; bundles Python without it (like Windows), installing pyreadline
114;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and 131;; from URL `http://ipython.scipy.org/moin/PyReadline/Intro' should
115;; you should be good to go. 132;; suffice. To troubleshoot why you are not getting any completions
133;; you can try the following in your Python shell:
134
135;; >>> import readline, rlcompleter
136
137;; If you see an error, then you need to either install pyreadline or
138;; setup custom code that avoids that dependency.
116 139
117;; Shell virtualenv support: The shell also contains support for 140;; Shell virtualenv support: The shell also contains support for
118;; virtualenvs and other special environment modifications thanks to 141;; virtualenvs and other special environment modifications thanks to
@@ -211,7 +234,9 @@
211;;; Code: 234;;; Code:
212 235
213(require 'ansi-color) 236(require 'ansi-color)
237(require 'cl-lib)
214(require 'comint) 238(require 'comint)
239(require 'json)
215 240
216;; Avoid compiler warnings 241;; Avoid compiler warnings
217(defvar view-return-to-alist) 242(defvar view-return-to-alist)
@@ -1705,33 +1730,60 @@ position, else returns nil."
1705 :type 'string 1730 :type 'string
1706 :group 'python) 1731 :group 'python)
1707 1732
1733(defcustom python-shell-interpreter-interactive-arg "-i"
1734 "Interpreter argument to force it to run interactively."
1735 :type 'string
1736 :version "24.4")
1737
1738(defcustom python-shell-prompt-detect-enabled t
1739 "Non-nil enables autodetection of interpreter prompts."
1740 :type 'boolean
1741 :safe 'booleanp
1742 :version "24.4")
1743
1744(defcustom python-shell-prompt-detect-failure-warning t
1745 "Non-nil enables warnings when detection of prompts fail."
1746 :type 'boolean
1747 :safe 'booleanp
1748 :version "24.4")
1749
1750(defcustom python-shell-prompt-input-regexps
1751 '(">>> " "\\.\\.\\. " ; Python
1752 "In \\[[0-9]+\\]: " ; IPython
1753 ;; Using ipdb outside IPython may fail to cleanup and leave static
1754 ;; IPython prompts activated, this adds some safeguard for that.
1755 "In : " "\\.\\.\\.: ")
1756 "List of regular expressions matching input prompts."
1757 :type '(repeat string)
1758 :version "24.4")
1759
1760(defcustom python-shell-prompt-output-regexps
1761 '("" ; Python
1762 "Out\\[[0-9]+\\]: " ; IPython
1763 "Out :") ; ipdb safeguard
1764 "List of regular expressions matching output prompts."
1765 :type '(repeat string)
1766 :version "24.4")
1767
1708(defcustom python-shell-prompt-regexp ">>> " 1768(defcustom python-shell-prompt-regexp ">>> "
1709 "Regular expression matching top-level input prompt of Python shell. 1769 "Regular expression matching top level input prompt of Python shell.
1710It should not contain a caret (^) at the beginning." 1770It should not contain a caret (^) at the beginning."
1711 :type 'string 1771 :type 'string)
1712 :group 'python
1713 :safe 'stringp)
1714 1772
1715(defcustom python-shell-prompt-block-regexp "[.][.][.] " 1773(defcustom python-shell-prompt-block-regexp "\\.\\.\\. "
1716 "Regular expression matching block input prompt of Python shell. 1774 "Regular expression matching block input prompt of Python shell.
1717It should not contain a caret (^) at the beginning." 1775It should not contain a caret (^) at the beginning."
1718 :type 'string 1776 :type 'string)
1719 :group 'python
1720 :safe 'stringp)
1721 1777
1722(defcustom python-shell-prompt-output-regexp "" 1778(defcustom python-shell-prompt-output-regexp ""
1723 "Regular expression matching output prompt of Python shell. 1779 "Regular expression matching output prompt of Python shell.
1724It should not contain a caret (^) at the beginning." 1780It should not contain a caret (^) at the beginning."
1725 :type 'string 1781 :type 'string)
1726 :group 'python
1727 :safe 'stringp)
1728 1782
1729(defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ " 1783(defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1730 "Regular expression matching pdb input prompt of Python shell. 1784 "Regular expression matching pdb input prompt of Python shell.
1731It should not contain a caret (^) at the beginning." 1785It should not contain a caret (^) at the beginning."
1732 :type 'string 1786 :type 'string)
1733 :group 'python
1734 :safe 'stringp)
1735 1787
1736(defcustom python-shell-enable-font-lock t 1788(defcustom python-shell-enable-font-lock t
1737 "Should syntax highlighting be enabled in the Python shell buffer? 1789 "Should syntax highlighting be enabled in the Python shell buffer?
@@ -1801,6 +1853,167 @@ virtualenv."
1801 :type '(alist string) 1853 :type '(alist string)
1802 :group 'python) 1854 :group 'python)
1803 1855
1856(defvar python-shell--prompt-calculated-input-regexp nil
1857 "Calculated input prompt regexp for inferior python shell.
1858Do not set this variable directly, instead use
1859`python-shell-prompt-set-calculated-regexps'.")
1860
1861(defvar python-shell--prompt-calculated-output-regexp nil
1862 "Calculated output prompt regexp for inferior python shell.
1863Do not set this variable directly, instead use
1864`python-shell-set-prompt-regexp'.")
1865
1866(defun python-shell-prompt-detect ()
1867 "Detect prompts for the current `python-shell-interpreter'.
1868When prompts can be retrieved successfully from the
1869`python-shell-interpreter' run with
1870`python-shell-interpreter-interactive-arg', returns a list of
1871three elements, where the first two are input prompts and the
1872last one is an output prompt. When no prompts can be detected
1873and `python-shell-prompt-detect-failure-warning' is non-nil,
1874shows a warning with instructions to avoid hangs and returns nil.
1875When `python-shell-prompt-detect-enabled' is nil avoids any
1876detection and just returns nil."
1877 (when python-shell-prompt-detect-enabled
1878 (let* ((process-environment (python-shell-calculate-process-environment))
1879 (exec-path (python-shell-calculate-exec-path))
1880 (code (concat
1881 "import sys\n"
1882 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
1883 ;; JSON is built manually for compatibility
1884 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
1885 "print (ps_json)\n"
1886 "sys.exit(0)\n"))
1887 (output
1888 (with-temp-buffer
1889 ;; TODO: improve error handling by using
1890 ;; `condition-case' and displaying the error message to
1891 ;; the user in the no-prompts warning.
1892 (ignore-errors
1893 (let ((code-file (python-shell--save-temp-file code)))
1894 ;; Use `process-file' as it is remote-host friendly.
1895 (process-file
1896 (executable-find python-shell-interpreter)
1897 code-file
1898 '(t nil)
1899 nil
1900 python-shell-interpreter-interactive-arg)
1901 ;; Try to cleanup
1902 (delete-file code-file)))
1903 (buffer-string)))
1904 (prompts
1905 (catch 'prompts
1906 (dolist (line (split-string output "\n" t))
1907 (let ((res
1908 ;; Check if current line is a valid JSON array
1909 (and (string= (substring line 0 2) "[\"")
1910 (ignore-errors
1911 ;; Return prompts as a list, not vector
1912 (append (json-read-from-string line) nil)))))
1913 ;; The list must contain 3 strings, where the first
1914 ;; is the input prompt, the second is the block
1915 ;; prompt and the last one is the output prompt. The
1916 ;; input prompt is the only one that can't be empty.
1917 (when (and (= (length res) 3)
1918 (cl-every #'stringp res)
1919 (not (string= (car res) "")))
1920 (throw 'prompts res))))
1921 nil)))
1922 (when (and (not prompts)
1923 python-shell-prompt-detect-failure-warning)
1924 (warn
1925 (concat
1926 "Python shell prompts cannot be detected.\n"
1927 "If your emacs session hangs when starting python shells\n"
1928 "recover with `keyboard-quit' and then try fixing the\n"
1929 "interactive flag for your interpreter by adjusting the\n"
1930 "`python-shell-interpreter-interactive-arg' or add regexps\n"
1931 "matching shell prompts in the directory-local friendly vars:\n"
1932 " + `python-shell-prompt-regexp'\n"
1933 " + `python-shell-prompt-block-regexp'\n"
1934 " + `python-shell-prompt-output-regexp'\n"
1935 "Or alternatively in:\n"
1936 " + `python-shell-prompt-input-regexps'\n"
1937 " + `python-shell-prompt-output-regexps'")))
1938 prompts)))
1939
1940(defun python-shell-prompt-validate-regexps ()
1941 "Validate all user provided regexps for prompts.
1942Signals `user-error' if any of these vars contain invalid
1943regexps: `python-shell-prompt-regexp',
1944`python-shell-prompt-block-regexp',
1945`python-shell-prompt-pdb-regexp',
1946`python-shell-prompt-output-regexp',
1947`python-shell-prompt-input-regexps',
1948`python-shell-prompt-output-regexps'."
1949 (dolist (symbol (list 'python-shell-prompt-input-regexps
1950 'python-shell-prompt-output-regexps
1951 'python-shell-prompt-regexp
1952 'python-shell-prompt-block-regexp
1953 'python-shell-prompt-pdb-regexp
1954 'python-shell-prompt-output-regexp))
1955 (dolist (regexp (let ((regexps (symbol-value symbol)))
1956 (if (listp regexps)
1957 regexps
1958 (list regexps))))
1959 (when (not (python-util-valid-regexp-p regexp))
1960 (user-error "Invalid regexp %s in `%s'"
1961 regexp symbol)))))
1962
1963(defun python-shell-prompt-set-calculated-regexps ()
1964 "Detect and set input and output prompt regexps.
1965Build and set the values for `python-shell-input-prompt-regexp'
1966and `python-shell-output-prompt-regexp' using the values from
1967`python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
1968`python-shell-prompt-pdb-regexp',
1969`python-shell-prompt-output-regexp',
1970`python-shell-prompt-input-regexps',
1971`python-shell-prompt-output-regexps' and detected prompts from
1972`python-shell-prompt-detect'."
1973 (when (not (and python-shell--prompt-calculated-input-regexp
1974 python-shell--prompt-calculated-output-regexp))
1975 (let* ((detected-prompts (python-shell-prompt-detect))
1976 (input-prompts nil)
1977 (output-prompts nil)
1978 (build-regexp
1979 (lambda (prompts)
1980 (concat "^\\("
1981 (mapconcat #'identity
1982 (sort prompts
1983 (lambda (a b)
1984 (let ((length-a (length a))
1985 (length-b (length b)))
1986 (if (= length-a length-b)
1987 (string< a b)
1988 (> (length a) (length b))))))
1989 "\\|")
1990 "\\)"))))
1991 ;; Validate ALL regexps
1992 (python-shell-prompt-validate-regexps)
1993 ;; Collect all user defined input prompts
1994 (dolist (prompt (append python-shell-prompt-input-regexps
1995 (list python-shell-prompt-regexp
1996 python-shell-prompt-block-regexp
1997 python-shell-prompt-pdb-regexp)))
1998 (cl-pushnew prompt input-prompts :test #'string=))
1999 ;; Collect all user defined output prompts
2000 (dolist (prompt (cons python-shell-prompt-output-regexp
2001 python-shell-prompt-output-regexps))
2002 (cl-pushnew prompt output-prompts :test #'string=))
2003 ;; Collect detected prompts if any
2004 (when detected-prompts
2005 (dolist (prompt (butlast detected-prompts))
2006 (setq prompt (regexp-quote prompt))
2007 (cl-pushnew prompt input-prompts :test #'string=))
2008 (cl-pushnew (regexp-quote
2009 (car (last detected-prompts)))
2010 output-prompts :test #'string=))
2011 ;; Set input and output prompt regexps from collected prompts
2012 (setq python-shell--prompt-calculated-input-regexp
2013 (funcall build-regexp input-prompts)
2014 python-shell--prompt-calculated-output-regexp
2015 (funcall build-regexp output-prompts)))))
2016
1804(defun python-shell-get-process-name (dedicated) 2017(defun python-shell-get-process-name (dedicated)
1805 "Calculate the appropriate process name for inferior Python process. 2018 "Calculate the appropriate process name for inferior Python process.
1806If DEDICATED is t and the variable `buffer-file-name' is non-nil 2019If DEDICATED is t and the variable `buffer-file-name' is non-nil
@@ -1823,10 +2036,10 @@ uniqueness for different types of configurations."
1823 python-shell-internal-buffer-name 2036 python-shell-internal-buffer-name
1824 (md5 2037 (md5
1825 (concat 2038 (concat
1826 (python-shell-parse-command) 2039 python-shell-interpreter
1827 python-shell-prompt-regexp 2040 python-shell-interpreter-args
1828 python-shell-prompt-block-regexp 2041 python-shell--prompt-calculated-input-regexp
1829 python-shell-prompt-output-regexp 2042 python-shell--prompt-calculated-output-regexp
1830 (mapconcat #'symbol-value python-shell-setup-codes "") 2043 (mapconcat #'symbol-value python-shell-setup-codes "")
1831 (mapconcat #'identity python-shell-process-environment "") 2044 (mapconcat #'identity python-shell-process-environment "")
1832 (mapconcat #'identity python-shell-extra-pythonpaths "") 2045 (mapconcat #'identity python-shell-extra-pythonpaths "")
@@ -1920,12 +2133,19 @@ initialization of the interpreter via `python-shell-setup-codes'
1920variable. 2133variable.
1921 2134
1922\(Type \\[describe-mode] in the process buffer for a list of commands.)" 2135\(Type \\[describe-mode] in the process buffer for a list of commands.)"
1923 (and python-shell--parent-buffer 2136 (let ((interpreter python-shell-interpreter)
1924 (python-util-clone-local-variables python-shell--parent-buffer)) 2137 (args python-shell-interpreter-args))
1925 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)" 2138 (when python-shell--parent-buffer
1926 python-shell-prompt-regexp 2139 (python-util-clone-local-variables python-shell--parent-buffer))
1927 python-shell-prompt-block-regexp 2140 ;; Users can override default values for these vars when calling
1928 python-shell-prompt-pdb-regexp)) 2141 ;; `run-python'. This ensures new values let-bound in
2142 ;; `python-shell-make-comint' are locally set.
2143 (set (make-local-variable 'python-shell-interpreter) interpreter)
2144 (set (make-local-variable 'python-shell-interpreter-args) args))
2145 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp) nil)
2146 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp) nil)
2147 (python-shell-prompt-set-calculated-regexps)
2148 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp)
1929 (setq mode-line-process '(":%s")) 2149 (setq mode-line-process '(":%s"))
1930 (make-local-variable 'comint-output-filter-functions) 2150 (make-local-variable 'comint-output-filter-functions)
1931 (add-hook 'comint-output-filter-functions 2151 (add-hook 'comint-output-filter-functions
@@ -1988,10 +2208,20 @@ killed."
1988 (exec-path (python-shell-calculate-exec-path))) 2208 (exec-path (python-shell-calculate-exec-path)))
1989 (when (not (comint-check-proc proc-buffer-name)) 2209 (when (not (comint-check-proc proc-buffer-name))
1990 (let* ((cmdlist (split-string-and-unquote cmd)) 2210 (let* ((cmdlist (split-string-and-unquote cmd))
2211 (interpreter (car cmdlist))
2212 (args (cdr cmdlist))
1991 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name 2213 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1992 (car cmdlist) nil (cdr cmdlist))) 2214 interpreter nil args))
1993 (python-shell--parent-buffer (current-buffer)) 2215 (python-shell--parent-buffer (current-buffer))
1994 (process (get-buffer-process buffer))) 2216 (process (get-buffer-process buffer))
2217 ;; As the user may have overriden default values for
2218 ;; these vars on `run-python', let-binding them allows
2219 ;; to have the new right values in all setup code
2220 ;; that's is done in `inferior-python-mode', which is
2221 ;; important, especially for prompt detection.
2222 (python-shell-interpreter interpreter)
2223 (python-shell-interpreter-args
2224 (mapconcat #'identity args " ")))
1995 (with-current-buffer buffer 2225 (with-current-buffer buffer
1996 (inferior-python-mode)) 2226 (inferior-python-mode))
1997 (accept-process-output process) 2227 (accept-process-output process)
@@ -2063,8 +2293,12 @@ startup."
2063 "Return inferior Python process for current buffer." 2293 "Return inferior Python process for current buffer."
2064 (get-buffer-process (python-shell-get-buffer))) 2294 (get-buffer-process (python-shell-get-buffer)))
2065 2295
2066(defun python-shell-get-or-create-process () 2296(defun python-shell-get-or-create-process (&optional cmd dedicated show)
2067 "Get or create an inferior Python process for current buffer and return it." 2297 "Get or create an inferior Python process for current buffer and return it.
2298Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2299are used to start the shell. If those arguments are not
2300provided, `run-python' is called interactively and the user will
2301be asked for their values."
2068 (let* ((dedicated-proc-name (python-shell-get-process-name t)) 2302 (let* ((dedicated-proc-name (python-shell-get-process-name t))
2069 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name)) 2303 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
2070 (global-proc-name (python-shell-get-process-name nil)) 2304 (global-proc-name (python-shell-get-process-name nil))
@@ -2072,7 +2306,11 @@ startup."
2072 (dedicated-running (comint-check-proc dedicated-proc-buffer-name)) 2306 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
2073 (global-running (comint-check-proc global-proc-buffer-name))) 2307 (global-running (comint-check-proc global-proc-buffer-name)))
2074 (when (and (not dedicated-running) (not global-running)) 2308 (when (and (not dedicated-running) (not global-running))
2075 (if (call-interactively 'run-python) 2309 (if (if (not cmd)
2310 ;; XXX: Refactor code such that calling `run-python'
2311 ;; interactively is not needed anymore.
2312 (call-interactively 'run-python)
2313 (run-python cmd dedicated show))
2076 (setq dedicated-running t) 2314 (setq dedicated-running t)
2077 (setq global-running t))) 2315 (setq global-running t)))
2078 ;; Always prefer dedicated 2316 ;; Always prefer dedicated
@@ -2155,10 +2393,13 @@ detecting a prompt at the end of the buffer."
2155 (when (string-match 2393 (when (string-match
2156 ;; XXX: It seems on OSX an extra carriage return is attached 2394 ;; XXX: It seems on OSX an extra carriage return is attached
2157 ;; at the end of output, this handles that too. 2395 ;; at the end of output, this handles that too.
2158 (format "\r?\n\\(?:%s\\|%s\\|%s\\)$" 2396 (concat
2159 python-shell-prompt-regexp 2397 "\r?\n"
2160 python-shell-prompt-block-regexp 2398 ;; Remove initial caret from calculated regexp
2161 python-shell-prompt-pdb-regexp) 2399 (replace-regexp-in-string
2400 (rx string-start ?^) ""
2401 python-shell--prompt-calculated-input-regexp)
2402 "$")
2162 python-shell-output-filter-buffer) 2403 python-shell-output-filter-buffer)
2163 ;; Output ends when `python-shell-output-filter-buffer' contains 2404 ;; Output ends when `python-shell-output-filter-buffer' contains
2164 ;; the prompt attached at the end of it. 2405 ;; the prompt attached at the end of it.
@@ -2166,10 +2407,10 @@ detecting a prompt at the end of the buffer."
2166 python-shell-output-filter-buffer 2407 python-shell-output-filter-buffer
2167 (substring python-shell-output-filter-buffer 2408 (substring python-shell-output-filter-buffer
2168 0 (match-beginning 0))) 2409 0 (match-beginning 0)))
2169 (when (and (> (length python-shell-prompt-output-regexp) 0) 2410 (when (string-match
2170 (string-match (concat "^" python-shell-prompt-output-regexp) 2411 python-shell--prompt-calculated-output-regexp
2171 python-shell-output-filter-buffer)) 2412 python-shell-output-filter-buffer)
2172 ;; Some shells, like iPython might append a prompt before the 2413 ;; Some shells, like IPython might append a prompt before the
2173 ;; output, clean that. 2414 ;; output, clean that.
2174 (setq python-shell-output-filter-buffer 2415 (setq python-shell-output-filter-buffer
2175 (substring python-shell-output-filter-buffer (match-end 0))))) 2416 (substring python-shell-output-filter-buffer (match-end 0)))))
@@ -2379,23 +2620,35 @@ This function takes the list of setup code to send from the
2379 2620
2380(defcustom python-shell-completion-setup-code 2621(defcustom python-shell-completion-setup-code
2381 "try: 2622 "try:
2382 import readline 2623 import readline, rlcompleter
2383except ImportError: 2624except ImportError:
2384 def __COMPLETER_all_completions(text): [] 2625 def __PYTHON_EL_get_completions(text):
2626 return []
2385else: 2627else:
2386 import rlcompleter 2628 def __PYTHON_EL_get_completions(text):
2387 readline.set_completer(rlcompleter.Completer().complete)
2388 def __COMPLETER_all_completions(text):
2389 import sys
2390 completions = [] 2629 completions = []
2391 try: 2630 try:
2392 i = 0 2631 splits = text.split()
2393 while True: 2632 is_module = splits and splits[0] in ('from', 'import')
2394 res = readline.get_completer()(text, i) 2633 is_ipython = getattr(
2395 if not res: break 2634 __builtins__, '__IPYTHON__',
2396 i += 1 2635 getattr(__builtins__, '__IPYTHON__active', False))
2397 completions.append(res) 2636 if is_module:
2398 except NameError: 2637 from IPython.core.completerlib import module_completion
2638 completions = module_completion(text.strip())
2639 elif is_ipython and getattr(__builtins__, '__IP', None):
2640 completions = __IP.complete(text)
2641 elif is_ipython and getattr(__builtins__, 'get_ipython', None):
2642 completions = get_ipython().Completer.all_completions(text)
2643 else:
2644 i = 0
2645 while True:
2646 res = readline.get_completer()(text, i)
2647 if not res:
2648 break
2649 i += 1
2650 completions.append(res)
2651 except:
2399 pass 2652 pass
2400 return completions" 2653 return completions"
2401 "Code used to setup completion in inferior Python processes." 2654 "Code used to setup completion in inferior Python processes."
@@ -2403,24 +2656,18 @@ else:
2403 :group 'python) 2656 :group 'python)
2404 2657
2405(defcustom python-shell-completion-string-code 2658(defcustom python-shell-completion-string-code
2406 "';'.join(__COMPLETER_all_completions('''%s'''))\n" 2659 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
2407 "Python code used to get a string of completions separated by semicolons." 2660 "Python code used to get a string of completions separated by semicolons.
2661The string passed to the function is the current python name or
2662the full statement in the case of imports."
2408 :type 'string 2663 :type 'string
2409 :group 'python) 2664 :group 'python)
2410 2665
2411(defcustom python-shell-completion-module-string-code "" 2666(define-obsolete-variable-alias
2412 "Python code used to get completions separated by semicolons for imports. 2667 'python-shell-completion-module-string-code
2413 2668 'python-shell-completion-string-code
2414For IPython v0.11, add the following line to 2669 "24.4"
2415`python-shell-completion-setup-code': 2670 "Completion string code must also autocomplete modules.")
2416
2417from IPython.core.completerlib import module_completion
2418
2419and use the following as the value of this variable:
2420
2421';'.join(module_completion('''%s'''))\n"
2422 :type 'string
2423 :group 'python)
2424 2671
2425(defcustom python-shell-completion-pdb-string-code 2672(defcustom python-shell-completion-pdb-string-code
2426 "';'.join(globals().keys() + locals().keys())" 2673 "';'.join(globals().keys() + locals().keys())"
@@ -2443,33 +2690,23 @@ LINE is used to detect the context on how to complete given INPUT."
2443 (re-search-backward "^") 2690 (re-search-backward "^")
2444 (python-util-forward-comment) 2691 (python-util-forward-comment)
2445 (point)))))) 2692 (point))))))
2446 (completion-context 2693 (completion-code
2447 ;; Check whether a prompt matches a pdb string, an import 2694 ;; Check whether a prompt matches a pdb string, an import
2448 ;; statement or just the standard prompt and use the 2695 ;; statement or just the standard prompt and use the
2449 ;; correct python-shell-completion-*-code string 2696 ;; correct python-shell-completion-*-code string
2450 (cond ((and (> (length python-shell-completion-pdb-string-code) 0) 2697 (cond ((and (> (length python-shell-completion-pdb-string-code) 0)
2451 (string-match 2698 (string-match
2452 (concat "^" python-shell-prompt-pdb-regexp) prompt)) 2699 (concat "^" python-shell-prompt-pdb-regexp) prompt))
2453 'pdb) 2700 python-shell-completion-pdb-string-code)
2454 ((and (>
2455 (length python-shell-completion-module-string-code) 0)
2456 (string-match
2457 (concat "^" python-shell-prompt-regexp) prompt)
2458 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line))
2459 'import)
2460 ((string-match 2701 ((string-match
2461 (concat "^" python-shell-prompt-regexp) prompt) 2702 python-shell--prompt-calculated-input-regexp prompt)
2462 'default) 2703 python-shell-completion-string-code)
2463 (t nil))) 2704 (t nil)))
2464 (completion-code
2465 (pcase completion-context
2466 (`pdb python-shell-completion-pdb-string-code)
2467 (`import python-shell-completion-module-string-code)
2468 (`default python-shell-completion-string-code)
2469 (_ nil)))
2470 (input 2705 (input
2471 (if (eq completion-context 'import) 2706 (if (string-match
2472 (replace-regexp-in-string "^[ \t]+" "" line) 2707 (python-rx (+ space) (or "from" "import") space)
2708 line)
2709 line
2473 input))) 2710 input)))
2474 (and completion-code 2711 (and completion-code
2475 (> (length input) 0) 2712 (> (length input) 0)
@@ -3710,6 +3947,10 @@ returned as is."
3710 "" 3947 ""
3711 string)) 3948 string))
3712 3949
3950(defun python-util-valid-regexp-p (regexp)
3951 "Return non-nil if REGEXP is valid."
3952 (ignore-errors (string-match regexp "") t))
3953
3713 3954
3714(defun python-electric-pair-string-delimiter () 3955(defun python-electric-pair-string-delimiter ()
3715 (when (and electric-pair-mode 3956 (when (and electric-pair-mode
@@ -3794,8 +4035,6 @@ returned as is."
3794 ,(lambda (_arg) 4035 ,(lambda (_arg)
3795 (python-nav-end-of-defun)) nil)) 4036 (python-nav-end-of-defun)) nil))
3796 4037
3797 (set (make-local-variable 'mode-require-final-newline) t)
3798
3799 (set (make-local-variable 'outline-regexp) 4038 (set (make-local-variable 'outline-regexp)
3800 (python-rx (* space) block-start)) 4039 (python-rx (* space) block-start))
3801 (set (make-local-variable 'outline-heading-end-regexp) ":[^\n]*\n") 4040 (set (make-local-variable 'outline-heading-end-regexp) ":[^\n]*\n")