blob: 6ee2bab1b4768f041483f9f8cc135ade25c09a8b [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Barry Warsaw71534602001-02-20 23:07:56 +00005;; Author: 1995-2001 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
Barry Warsawa97a3f31997-11-04 18:47:06 +00007;; Maintainer: python-mode@python.org
8;; Created: Feb 1992
9;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000010
Barry Warsawe275c422001-06-19 18:24:42 +000011(defconst py-version "$Revision$"
Barry Warsawc72c11c1997-08-09 06:42:08 +000012 "`python-mode' version number.")
13
Barry Warsawcfec3591995-03-10 15:58:16 +000014;; This software is provided as-is, without express or implied
15;; warranty. Permission to use, copy, modify, distribute or sell this
16;; software, without fee, for any purpose and by any individual or
17;; organization, is hereby granted, provided that the above copyright
18;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000019
20;;; Commentary:
Barry Warsaw755c6711996-08-01 20:02:55 +000021
Barry Warsaw7b0f5681995-03-08 21:33:04 +000022;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000023;; by Tim Peters after an original idea by Michael A. Guravage. Tim
Barry Warsawf7039e21998-08-20 22:10:46 +000024;; subsequently left the net; in 1995, Barry Warsaw inherited the mode
Barry Warsaw38e21e71998-10-27 22:09:25 +000025;; and is the current maintainer. Tim's now back but disavows all
26;; responsibility for the mode. Smart Tim :-)
Barry Warsaw7b0f5681995-03-08 21:33:04 +000027
Barry Warsaw4f577d22001-04-11 20:23:17 +000028;; pdbtrack support contributed by Ken Manheimer, April 2001.
29
30;; This version of python-mode.el has only been tested with XEmacs
31;; 21.1.14 and Emacs 20.7 as these are the latest versions of these
32;; Emacsen as of this writing (11-Apr-2001). I have no intent to test
33;; it with earlier Emacsen, but I will accept patches if they are
34;; small and reasonable. Please use the SourceForge Python project to
35;; submit bugs or patches:
36;;
37;; http://sourceforge.net/projects/python
Barry Warsaw37231521997-12-11 17:23:13 +000038
39;; FOR MORE INFORMATION:
40
Barry Warsaw4f577d22001-04-11 20:23:17 +000041;; There is some information on python-mode.el at
42
Barry Warsawf7039e21998-08-20 22:10:46 +000043;; http://www.python.org/emacs/python-mode/
44;;
Barry Warsaw4f577d22001-04-11 20:23:17 +000045;; but this link is fairly out of date, due to the current difficulty
46;; in updating that site. It does contain links to other packages that
47;; you might find useful, such as pdb interfaces, OO-Browser links,
48;; etc. Eventually, we'll be able to update it much more easily.
Barry Warsaw37231521997-12-11 17:23:13 +000049
50;; BUG REPORTING:
Barry Warsaw7ae77681994-12-12 20:38:05 +000051
Barry Warsaw4f577d22001-04-11 20:23:17 +000052;; As mentioned above, please use the SourceForge Python project for
53;; submitting bug reports or patches. The old recommendation, to use
54;; C-c C-b will still work, but those reports have a higher chance of
55;; getting buried in my mailbox. Please include a complete, but
Barry Warsawaffc0ca1997-11-03 16:59:38 +000056;; concise code sample and a recipe for reproducing the bug. Send
57;; suggestions and other comments to python-mode@python.org.
58
59;; When in a Python mode buffer, do a C-h m for more help. It's
Barry Warsaw37231521997-12-11 17:23:13 +000060;; doubtful that a texinfo manual would be very useful, but if you
61;; want to contribute one, I'll certainly accept it!
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000062
Barry Warsaw7b0f5681995-03-08 21:33:04 +000063;;; Code:
64
Barry Warsaw6dfbe5d1998-08-20 21:51:27 +000065(require 'comint)
Barry Warsawc72c11c1997-08-09 06:42:08 +000066(require 'custom)
Barry Warsaw4f577d22001-04-11 20:23:17 +000067(require 'cl)
Barry Warsawc72c11c1997-08-09 06:42:08 +000068
Barry Warsaw7b0f5681995-03-08 21:33:04 +000069
70;; user definable variables
71;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000072
Barry Warsawc72c11c1997-08-09 06:42:08 +000073(defgroup python nil
74 "Support for the Python programming language, <http://www.python.org/>"
Barry Warsaw5ed843f1999-07-28 22:06:06 +000075 :group 'languages
76 :prefix "py-")
Barry Warsaw7ae77681994-12-12 20:38:05 +000077
Barry Warsawc72c11c1997-08-09 06:42:08 +000078(defcustom py-python-command "python"
79 "*Shell command used to start Python interpreter."
80 :type 'string
81 :group 'python)
82
Barry Warsawa2398801998-04-09 23:28:20 +000083(defcustom py-jpython-command "jpython"
84 "*Shell command used to start the JPython interpreter."
85 :type 'string
Barry Warsaw5ed843f1999-07-28 22:06:06 +000086 :group 'python
87 :tag "JPython Command")
Barry Warsawa2398801998-04-09 23:28:20 +000088
Barry Warsawaa384fd1999-02-16 23:36:16 +000089(defcustom py-default-interpreter 'cpython
90 "*Which Python interpreter is used by default.
91The value for this variable can be either `cpython' or `jpython'.
92
93When the value is `cpython', the variables `py-python-command' and
94`py-python-command-args' are consulted to determine the interpreter
95and arguments to use.
96
97When the value is `jpython', the variables `py-jpython-command' and
98`py-jpython-command-args' are consulted to determine the interpreter
99and arguments to use.
100
Barry Warsaw11f21561999-07-28 21:59:43 +0000101Note that this variable is consulted only the first time that a Python
102mode buffer is visited during an Emacs session. After that, use
Barry Warsawaa384fd1999-02-16 23:36:16 +0000103\\[py-toggle-shells] to change the interpreter shell."
104 :type '(choice (const :tag "Python (a.k.a. CPython)" cpython)
105 (const :tag "JPython" jpython))
106 :group 'python)
107
Barry Warsaw8f972b71998-02-05 20:45:49 +0000108(defcustom py-python-command-args '("-i")
109 "*List of string arguments to be used when starting a Python shell."
110 :type '(repeat string)
111 :group 'python)
112
Barry Warsawa2398801998-04-09 23:28:20 +0000113(defcustom py-jpython-command-args '("-i")
114 "*List of string arguments to be used when starting a JPython shell."
115 :type '(repeat string)
Barry Warsaw5ed843f1999-07-28 22:06:06 +0000116 :group 'python
117 :tag "JPython Command Args")
Barry Warsawa2398801998-04-09 23:28:20 +0000118
Barry Warsawc72c11c1997-08-09 06:42:08 +0000119(defcustom py-indent-offset 4
Barry Warsaw41a05c71998-08-10 16:33:12 +0000120 "*Amount of offset per level of indentation.
121`\\[py-guess-indent-offset]' can usually guess a good value when
122you're editing someone else's Python code."
Barry Warsawc72c11c1997-08-09 06:42:08 +0000123 :type 'integer
124 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000125
Barry Warsawfd4c9e82001-06-18 23:40:35 +0000126(defcustom py-continuation-offset 4
127 "*Additional amount of offset to give for continuation lines.
128Continuation lines are those that immediately follow a backslash
129terminated line."
130 :type 'integer
131 :group 'python)
132
Barry Warsaw742a5111998-03-13 17:29:15 +0000133(defcustom py-smart-indentation t
134 "*Should `python-mode' try to automagically set some indentation variables?
135When this variable is non-nil, two things happen when a buffer is set
136to `python-mode':
137
Barry Warsawc0d2d511999-06-03 22:18:59 +0000138 1. `py-indent-offset' is guessed from existing code in the buffer.
Barry Warsaw639eea61998-03-16 18:12:13 +0000139 Only guessed values between 2 and 8 are considered. If a valid
Barry Warsaw742a5111998-03-13 17:29:15 +0000140 guess can't be made (perhaps because you are visiting a new
Barry Warsaw639eea61998-03-16 18:12:13 +0000141 file), then the value in `py-indent-offset' is used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000142
Barry Warsaw639eea61998-03-16 18:12:13 +0000143 2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
144 equal `tab-width' (`indent-tabs-mode' is never turned on by
145 Python mode). This means that for newly written code, tabs are
146 only inserted in indentation if one tab is one indentation
147 level, otherwise only spaces are used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000148
Barry Warsaw8046bef1998-03-13 20:04:52 +0000149Note that both these settings occur *after* `python-mode-hook' is run,
150so if you want to defeat the automagic configuration, you must also
151set `py-smart-indentation' to nil in your `python-mode-hook'."
Barry Warsaw742a5111998-03-13 17:29:15 +0000152 :type 'boolean
153 :group 'python)
154
Barry Warsawc72c11c1997-08-09 06:42:08 +0000155(defcustom py-align-multiline-strings-p t
156 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000157When this flag is non-nil, continuation lines are lined up under the
158preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000159lines are aligned to column zero."
160 :type '(choice (const :tag "Align under preceding line" t)
161 (const :tag "Align to column zero" nil))
162 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000163
Barry Warsaw218eb751998-09-22 19:51:47 +0000164(defcustom py-block-comment-prefix "##"
Barry Warsaw867a32a1996-03-07 18:30:26 +0000165 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000166This should follow the convention for non-indenting comment lines so
167that the indentation commands won't get confused (i.e., the string
168should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsaw218eb751998-09-22 19:51:47 +0000169`...' is arbitrary). However, this string should not end in whitespace."
Barry Warsawc72c11c1997-08-09 06:42:08 +0000170 :type 'string
171 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000172
Barry Warsawc72c11c1997-08-09 06:42:08 +0000173(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000174 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000175
Barry Warsaw6d627751996-03-06 18:41:38 +0000176When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000177if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000178
179When t, lines that begin with a single `#' are a hint to subsequent
180line indentation. If the previous line is such a comment line (as
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000181opposed to one that starts with `py-block-comment-prefix'), then its
Barry Warsaw6d627751996-03-06 18:41:38 +0000182indentation is used as a hint for this line's indentation. Lines that
183begin with `py-block-comment-prefix' are ignored for indentation
184purposes.
185
186When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000187indentation hints, unless the comment character is in column zero."
188 :type '(choice
189 (const :tag "Skip all comment lines (fast)" nil)
190 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000191 (const :tag "Single # `sets' indentation except at column zero"
192 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000193 )
194 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000195
Barry Warsaw516b6201997-08-09 06:43:20 +0000196(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000197 (let ((ok '(lambda (x)
198 (and x
199 (setq x (expand-file-name x)) ; always true
200 (file-directory-p x)
201 (file-writable-p x)
202 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000203 (or (funcall ok (getenv "TMPDIR"))
204 (funcall ok "/usr/tmp")
205 (funcall ok "/tmp")
206 (funcall ok ".")
207 (error
Barry Warsaw6c6db0a1998-02-25 16:33:56 +0000208 "Couldn't find a usable temp directory -- set `py-temp-directory'")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000209 "*Directory used for temp files created by a *Python* process.
210By default, the first directory from this list that exists and that you
211can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000212/usr/tmp, /tmp, or the current directory."
213 :type 'string
214 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000215
Barry Warsaw516b6201997-08-09 06:43:20 +0000216(defcustom py-beep-if-tab-change t
Barry Warsaw41a05c71998-08-10 16:33:12 +0000217 "*Ring the bell if `tab-width' is changed.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000218If a comment of the form
219
220 \t# vi:set tabsize=<number>:
221
222is found before the first code line when the file is entered, and the
223current value of (the general Emacs variable) `tab-width' does not
224equal <number>, `tab-width' is set to <number>, a message saying so is
225displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000226the Emacs bell is also rung as a warning."
227 :type 'boolean
228 :group 'python)
229
Barry Warsaw9981d221997-12-03 05:25:48 +0000230(defcustom py-jump-on-exception t
231 "*Jump to innermost exception frame in *Python Output* buffer.
Barry Warsaw12c92941998-08-10 21:44:37 +0000232When this variable is non-nil and an exception occurs when running
Barry Warsaw9981d221997-12-03 05:25:48 +0000233Python code synchronously in a subprocess, jump immediately to the
Barry Warsaw12c92941998-08-10 21:44:37 +0000234source code of the innermost traceback frame."
Barry Warsaw3bfed5b1998-05-19 16:25:04 +0000235 :type 'boolean
236 :group 'python)
237
238(defcustom py-ask-about-save t
239 "If not nil, ask about which buffers to save before executing some code.
240Otherwise, all modified buffers are saved without asking."
241 :type 'boolean
242 :group 'python)
Barry Warsaw9981d221997-12-03 05:25:48 +0000243
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000244(defcustom py-backspace-function 'backward-delete-char-untabify
245 "*Function called by `py-electric-backspace' when deleting backwards."
246 :type 'function
247 :group 'python)
248
249(defcustom py-delete-function 'delete-char
250 "*Function called by `py-electric-delete' when deleting forwards."
251 :type 'function
252 :group 'python)
253
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000254(defcustom py-imenu-show-method-args-p nil
255 "*Controls echoing of arguments of functions & methods in the Imenu buffer.
256When non-nil, arguments are printed."
257 :type 'boolean
258 :group 'python)
259(make-variable-buffer-local 'py-indent-offset)
260
Barry Warsaw4f577d22001-04-11 20:23:17 +0000261(defcustom py-pdbtrack-do-tracking-p t
262 "*Controls whether the pdbtrack feature is enabled or not.
263When non-nil, pdbtrack is enabled in all comint-based buffers,
264e.g. shell buffers and the *Python* buffer. When using pdb to debug a
265Python program, pdbtrack notices the pdb prompt and displays the
266source file and line that the program is stopped at, much the same way
267as gud-mode does for debugging C programs with gdb."
268 :type 'boolean
269 :group 'python)
270(make-variable-buffer-local 'py-pdbtrack-do-tracking-p)
271
272(defcustom py-pdbtrack-minor-mode-string " PDB"
273 "*String to use in the minor mode list when pdbtrack is enabled."
274 :type 'string
275 :group 'python)
276
Barry Warsawc0ecb531998-01-20 21:43:34 +0000277;; Not customizable
278(defvar py-master-file nil
279 "If non-nil, execute the named file instead of the buffer's file.
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000280The intent is to allow you to set this variable in the file's local
Barry Warsawc0ecb531998-01-20 21:43:34 +0000281variable section, e.g.:
282
283 # Local Variables:
284 # py-master-file: \"master.py\"
285 # End:
286
Barry Warsaw41a05c71998-08-10 16:33:12 +0000287so that typing \\[py-execute-buffer] in that buffer executes the named
Barry Warsaw1bbc0311998-10-27 21:54:56 +0000288master file instead of the buffer's file. If the file name has a
289relative path, the value of variable `default-directory' for the
290buffer is prepended to come up with a file name.")
Barry Warsawc0ecb531998-01-20 21:43:34 +0000291(make-variable-buffer-local 'py-master-file)
292
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000293
Barry Warsawc72c11c1997-08-09 06:42:08 +0000294
295;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
296;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
297
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000298(defconst py-emacs-features
299 (let (features)
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000300 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000301 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000302There are many flavors of Emacs out there, with different levels of
303support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000304
Barry Warsawfb07f401997-02-24 03:37:22 +0000305(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000306 (let ((kw1 (mapconcat 'identity
307 '("and" "assert" "break" "class"
308 "continue" "def" "del" "elif"
309 "else" "except" "exec" "for"
310 "from" "global" "if" "import"
311 "in" "is" "lambda" "not"
312 "or" "pass" "print" "raise"
Barry Warsawe275c422001-06-19 18:24:42 +0000313 "return" "while" "yield"
Barry Warsawb8f11661997-11-06 14:35:15 +0000314 )
315 "\\|"))
316 (kw2 (mapconcat 'identity
317 '("else:" "except:" "finally:" "try:")
318 "\\|"))
319 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000320 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000321 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000322 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
323 ;; block introducing keywords with immediately following colons.
324 ;; Yes "except" is in both lists.
325 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsawe0c182f2000-12-27 17:41:47 +0000326 ;; `as' but only in "import foo as bar"
327 '("[ \t]*\\(\\bfrom\\b.*\\)?\\bimport\\b.*\\b\\(as\\)\\b" . 2)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000328 ;; classes
329 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
330 1 font-lock-type-face)
331 ;; functions
332 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
333 1 font-lock-function-name-face)
334 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000335 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000336(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
337
Barry Warsawe467bfb1997-11-26 05:40:58 +0000338;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000339(defvar py-file-queue nil
340 "Queue of Python temp files awaiting execution.
341Currently-active file is at the head of the list.")
342
Barry Warsaw4f577d22001-04-11 20:23:17 +0000343(defvar py-pdbtrack-is-tracking-p nil)
344
345
Barry Warsawc72c11c1997-08-09 06:42:08 +0000346
347;; Constants
348
Barry Warsawc72c11c1997-08-09 06:42:08 +0000349(defconst py-stringlit-re
350 (concat
Barry Warsaw751f4931998-05-19 16:06:21 +0000351 ;; These fail if backslash-quote ends the string (not worth
352 ;; fixing?). They precede the short versions so that the first two
353 ;; quotes don't look like an empty short string.
354 ;;
355 ;; (maybe raw), long single quoted triple quoted strings (SQTQ),
356 ;; with potential embedded single quotes
357 "[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
358 "\\|"
359 ;; (maybe raw), long double quoted triple quoted strings (DQTQ),
360 ;; with potential embedded double quotes
361 "[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
362 "\\|"
363 "[rR]?'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
Barry Warsawc72c11c1997-08-09 06:42:08 +0000364 "\\|" ; or
Barry Warsaw751f4931998-05-19 16:06:21 +0000365 "[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\"" ; double-quoted
Barry Warsaw41a05c71998-08-10 16:33:12 +0000366 )
367 "Regular expression matching a Python string literal.")
Barry Warsaw751f4931998-05-19 16:06:21 +0000368
Barry Warsawc72c11c1997-08-09 06:42:08 +0000369(defconst py-continued-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000370 ;; This is tricky because a trailing backslash does not mean
371 ;; continuation if it's in a comment
Barry Warsawc72c11c1997-08-09 06:42:08 +0000372 (concat
373 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
Barry Warsaw41a05c71998-08-10 16:33:12 +0000374 "\\\\$")
375 "Regular expression matching Python backslash continuation lines.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000376
Barry Warsaw41a05c71998-08-10 16:33:12 +0000377(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw71c3adb1998-08-10 16:34:33 +0000378 "Regular expression matching a blank or comment line.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000379
Barry Warsawc72c11c1997-08-09 06:42:08 +0000380(defconst py-outdent-re
381 (concat "\\(" (mapconcat 'identity
382 '("else:"
383 "except\\(\\s +.*\\)?:"
384 "finally:"
385 "elif\\s +.*:")
386 "\\|")
Barry Warsaw41a05c71998-08-10 16:33:12 +0000387 "\\)")
388 "Regular expression matching statements to be dedented one level.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000389
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000390(defconst py-block-closing-keywords-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000391 "\\(return\\|raise\\|break\\|continue\\|pass\\)"
392 "Regular expression matching keywords which typically close a block.")
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000393
Barry Warsawc72c11c1997-08-09 06:42:08 +0000394(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000395 (concat
396 "\\("
397 (mapconcat 'identity
398 (list "try:"
399 "except\\(\\s +.*\\)?:"
400 "while\\s +.*:"
401 "for\\s +.*:"
402 "if\\s +.*:"
403 "elif\\s +.*:"
404 (concat py-block-closing-keywords-re "[ \t\n]")
405 )
406 "\\|")
Barry Warsaw41a05c71998-08-10 16:33:12 +0000407 "\\)")
408 "Regular expression matching lines not to dedent after.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000409
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000410(defconst py-defun-start-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000411 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*="
412 ;; If you change this, you probably have to change py-current-defun
413 ;; as well. This is only used by py-current-defun to find the name
414 ;; for add-log.el.
Barry Warsaw71c3adb1998-08-10 16:34:33 +0000415 "Regular expression matching a function, method, or variable assignment.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000416
Barry Warsaw41a05c71998-08-10 16:33:12 +0000417(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)"
418 ;; If you change this, you probably have to change py-current-defun
419 ;; as well. This is only used by py-current-defun to find the name
420 ;; for add-log.el.
421 "Regular expression for finding a class name.")
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000422
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000423(defconst py-traceback-line-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000424 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)"
425 "Regular expression that describes tracebacks.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000426
Barry Warsaw4f577d22001-04-11 20:23:17 +0000427;; pdbtrack contants
428(defconst py-pdbtrack-stack-entry-regexp
429 "> \\([^(]+\\)(\\([0-9]+\\))[?a-zA-Z0-9_]+()"
430 "Regular expression pdbtrack uses to find a stack trace entry.")
431
432(defconst py-pdbtrack-input-prompt "\n[(<]?pdb[>)]? "
433 "Regular expression pdbtrack uses to recognize a pdb prompt.")
434
435(defconst py-pdbtrack-track-range 10000
436 "Max number of characters from end of buffer to search for stack entry.")
437
Barry Warsawc72c11c1997-08-09 06:42:08 +0000438
439
Barry Warsawc72c11c1997-08-09 06:42:08 +0000440;; Major mode boilerplate
441
Barry Warsaw7ae77681994-12-12 20:38:05 +0000442;; define a mode-specific abbrev table for those who use such things
443(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000444 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000445(define-abbrev-table 'python-mode-abbrev-table nil)
446
Barry Warsaw7ae77681994-12-12 20:38:05 +0000447(defvar python-mode-hook nil
448 "*Hook called by `python-mode'.")
449
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000450;; In previous version of python-mode.el, the hook was incorrectly
451;; called py-mode-hook, and was not defvar'd. Deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000452(and (fboundp 'make-obsolete-variable)
453 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
454
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000455(defvar py-mode-map ()
456 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000457(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000458 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000459 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000460 ;; electric keys
461 (define-key py-mode-map ":" 'py-electric-colon)
462 ;; indentation level modifiers
463 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
464 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
465 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
466 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
467 ;; subprocess commands
468 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
Barry Warsaw820273d1998-05-19 15:54:45 +0000469 (define-key py-mode-map "\C-c\C-m" 'py-execute-import-or-reload)
Barry Warsaw1d0364b1998-05-19 16:15:26 +0000470 (define-key py-mode-map "\C-c\C-s" 'py-execute-string)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000471 (define-key py-mode-map "\C-c|" 'py-execute-region)
Barry Warsaw820273d1998-05-19 15:54:45 +0000472 (define-key py-mode-map "\e\C-x" 'py-execute-def-or-class)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000473 (define-key py-mode-map "\C-c!" 'py-shell)
Barry Warsawa2398801998-04-09 23:28:20 +0000474 (define-key py-mode-map "\C-c\C-t" 'py-toggle-shells)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000475 ;; Caution! Enter here at your own risk. We are trying to support
476 ;; several behaviors and it gets disgusting. :-( This logic ripped
477 ;; largely from CC Mode.
478 ;;
479 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
480 ;; backwards deletion behavior to DEL, which both Delete and
481 ;; Backspace get translated to. There's no way to separate this
482 ;; behavior in a clean way, so deal with it! Besides, it's been
483 ;; this way since the dawn of time.
484 (if (not (boundp 'delete-key-deletes-forward))
485 (define-key py-mode-map "\177" 'py-electric-backspace)
486 ;; However, XEmacs 20 actually achieved enlightenment. It is
487 ;; possible to sanely define both backward and forward deletion
488 ;; behavior under X separately (TTYs are forever beyond hope, but
489 ;; who cares? XEmacs 20 does the right thing with these too).
490 (define-key py-mode-map [delete] 'py-electric-delete)
491 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000492 ;; Separate M-BS from C-M-h. The former should remain
493 ;; backward-kill-word.
494 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000495 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000496 ;; Miscellaneous
497 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
498 (define-key py-mode-map "\C-c\t" 'py-indent-region)
Barry Warsaw4f577d22001-04-11 20:23:17 +0000499 (define-key py-mode-map "\C-c\C-d" 'py-pdbtrack-toggle-stack-tracking)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000500 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
501 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
502 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000503 (define-key py-mode-map "\C-c#" 'py-comment-region)
504 (define-key py-mode-map "\C-c?" 'py-describe-mode)
505 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
Barry Warsawab0e86c1998-05-19 15:31:46 +0000506 (define-key py-mode-map "\e\C-a" 'py-beginning-of-def-or-class)
507 (define-key py-mode-map "\e\C-e" 'py-end-of-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000508 (define-key py-mode-map "\C-c-" 'py-up-exception)
509 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsawf8ddb6a1999-01-18 21:49:39 +0000510 ;; stuff that is `standard' but doesn't interface well with
511 ;; python-mode, which forces us to rebind to special commands
512 (define-key py-mode-map "\C-xnd" 'py-narrow-to-defun)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000513 ;; information
514 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
515 (define-key py-mode-map "\C-c\C-v" 'py-version)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000516 ;; shadow global bindings for newline-and-indent w/ the py- version.
517 ;; BAW - this is extremely bad form, but I'm not going to change it
518 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000519 (mapcar #'(lambda (key)
520 (define-key py-mode-map key 'py-newline-and-indent))
521 (where-is-internal 'newline-and-indent))
Barry Warsawf19feb81999-01-21 17:06:11 +0000522 ;; Force RET to be py-newline-and-indent even if it didn't get
523 ;; mapped by the above code. motivation: Emacs' default binding for
524 ;; RET is `newline' and C-j is `newline-and-indent'. Most Pythoneers
525 ;; expect RET to do a `py-newline-and-indent' and any Emacsers who
526 ;; dislike this are probably knowledgeable enough to do a rebind.
527 ;; However, we do *not* change C-j since many Emacsers have already
528 ;; swapped RET and C-j and they don't want C-j bound to `newline' to
529 ;; change.
530 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000531 )
532
533(defvar py-mode-output-map nil
Barry Warsaw41a05c71998-08-10 16:33:12 +0000534 "Keymap used in *Python Output* buffers.")
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000535(if py-mode-output-map
536 nil
537 (setq py-mode-output-map (make-sparse-keymap))
538 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
539 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
540 ;; TBD: Disable all self-inserting keys. This is bogus, we should
541 ;; really implement this as *Python Output* buffer being read-only
542 (mapcar #' (lambda (key)
543 (define-key py-mode-output-map key
544 #'(lambda () (interactive) (beep))))
545 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000546 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000547
Barry Warsaw6dfbe5d1998-08-20 21:51:27 +0000548(defvar py-shell-map nil
549 "Keymap used in *Python* shell buffers.")
550(if py-shell-map
551 nil
552 (setq py-shell-map (copy-keymap comint-mode-map))
553 (define-key py-shell-map [tab] 'tab-to-tab-stop)
554 (define-key py-shell-map "\C-c-" 'py-up-exception)
555 (define-key py-shell-map "\C-c=" 'py-down-exception)
556 )
557
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000558(defvar py-mode-syntax-table nil
559 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000560(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000561 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000562 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000563 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
564 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
565 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
566 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
567 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
568 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
569 ;; Add operator symbols misassigned in the std table
570 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
571 (modify-syntax-entry ?\% "." py-mode-syntax-table)
572 (modify-syntax-entry ?\& "." py-mode-syntax-table)
573 (modify-syntax-entry ?\* "." py-mode-syntax-table)
574 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
575 (modify-syntax-entry ?\- "." py-mode-syntax-table)
576 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
577 (modify-syntax-entry ?\< "." py-mode-syntax-table)
578 (modify-syntax-entry ?\= "." py-mode-syntax-table)
579 (modify-syntax-entry ?\> "." py-mode-syntax-table)
580 (modify-syntax-entry ?\| "." py-mode-syntax-table)
581 ;; For historical reasons, underscore is word class instead of
582 ;; symbol class. GNU conventions say it should be symbol class, but
583 ;; there's a natural conflict between what major mode authors want
584 ;; and what users expect from `forward-word' and `backward-word'.
585 ;; Guido and I have hashed this out and have decided to keep
586 ;; underscore in word class. If you're tempted to change it, try
587 ;; binding M-f and M-b to py-forward-into-nomenclature and
Barry Warsawaa384fd1999-02-16 23:36:16 +0000588 ;; py-backward-into-nomenclature instead. This doesn't help in all
589 ;; situations where you'd want the different behavior
590 ;; (e.g. backward-kill-word).
Barry Warsawc72c11c1997-08-09 06:42:08 +0000591 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
592 ;; Both single quote and double quote are string delimiters
593 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
594 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
595 ;; backquote is open and close paren
596 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
597 ;; comment delimiters
598 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
599 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
600 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000601
Barry Warsawb3e81d51996-09-04 15:12:42 +0000602
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000603
Barry Warsawbc3760b1998-09-14 16:16:18 +0000604;; Utilities
605
606(defmacro py-safe (&rest body)
607 "Safely execute BODY, return nil if an error occurred."
608 (` (condition-case nil
609 (progn (,@ body))
610 (error nil))))
611
612(defsubst py-keep-region-active ()
613 "Keep the region active in XEmacs."
614 ;; Ignore byte-compiler warnings you might see. Also note that
615 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
616 ;; to take explicit action.
617 (and (boundp 'zmacs-region-stays)
618 (setq zmacs-region-stays t)))
619
620(defsubst py-point (position)
621 "Returns the value of point at certain commonly referenced POSITIONs.
622POSITION can be one of the following symbols:
623
624 bol -- beginning of line
625 eol -- end of line
626 bod -- beginning of def or class
627 eod -- end of def or class
628 bob -- beginning of buffer
629 eob -- end of buffer
630 boi -- back to indentation
631 bos -- beginning of statement
632
633This function does not modify point or mark."
634 (let ((here (point)))
635 (cond
636 ((eq position 'bol) (beginning-of-line))
637 ((eq position 'eol) (end-of-line))
638 ((eq position 'bod) (py-beginning-of-def-or-class))
639 ((eq position 'eod) (py-end-of-def-or-class))
640 ;; Kind of funny, I know, but useful for py-up-exception.
641 ((eq position 'bob) (beginning-of-buffer))
642 ((eq position 'eob) (end-of-buffer))
643 ((eq position 'boi) (back-to-indentation))
644 ((eq position 'bos) (py-goto-initial-line))
645 (t (error "Unknown buffer position requested: %s" position))
646 )
647 (prog1
648 (point)
649 (goto-char here))))
650
651(defsubst py-highlight-line (from to file line)
652 (cond
653 ((fboundp 'make-extent)
654 ;; XEmacs
655 (let ((e (make-extent from to)))
656 (set-extent-property e 'mouse-face 'highlight)
657 (set-extent-property e 'py-exc-info (cons file line))
658 (set-extent-property e 'keymap py-mode-output-map)))
659 (t
660 ;; Emacs -- Please port this!
661 )
662 ))
663
664(defun py-in-literal (&optional lim)
665 "Return non-nil if point is in a Python literal (a comment or string).
666Optional argument LIM indicates the beginning of the containing form,
667i.e. the limit on how far back to scan."
668 ;; This is the version used for non-XEmacs, which has a nicer
669 ;; interface.
670 ;;
671 ;; WARNING: Watch out for infinite recursion.
672 (let* ((lim (or lim (py-point 'bod)))
673 (state (parse-partial-sexp lim (point))))
674 (cond
675 ((nth 3 state) 'string)
676 ((nth 4 state) 'comment)
677 (t nil))))
678
679;; XEmacs has a built-in function that should make this much quicker.
680;; In this case, lim is ignored
681(defun py-fast-in-literal (&optional lim)
682 "Fast version of `py-in-literal', used only by XEmacs.
683Optional LIM is ignored."
684 ;; don't have to worry about context == 'block-comment
685 (buffer-syntactic-context))
686
687(if (fboundp 'buffer-syntactic-context)
688 (defalias 'py-in-literal 'py-fast-in-literal))
689
690
691
Barry Warsaw42f707f1996-07-29 21:05:05 +0000692;; Menu definitions, only relevent if you have the easymenu.el package
693;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000694(defvar py-menu nil
695 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000696This menu will get created automatically if you have the `easymenu'
697package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000698
Barry Warsawc72c11c1997-08-09 06:42:08 +0000699(and (py-safe (require 'easymenu) t)
700 (easy-menu-define
701 py-menu py-mode-map "Python Mode menu"
702 '("Python"
703 ["Comment Out Region" py-comment-region (mark)]
704 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
705 "-"
706 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000707 ["Mark current def" py-mark-def-or-class t]
708 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000709 "-"
710 ["Shift region left" py-shift-region-left (mark)]
711 ["Shift region right" py-shift-region-right (mark)]
712 "-"
Barry Warsaw820273d1998-05-19 15:54:45 +0000713 ["Import/reload file" py-execute-import-or-reload t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000714 ["Execute buffer" py-execute-buffer t]
715 ["Execute region" py-execute-region (mark)]
Barry Warsaw820273d1998-05-19 15:54:45 +0000716 ["Execute def or class" py-execute-def-or-class (mark)]
Barry Warsaw1d0364b1998-05-19 16:15:26 +0000717 ["Execute string" py-execute-string t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000718 ["Start interpreter..." py-shell t]
719 "-"
720 ["Go to start of block" py-goto-block-up t]
Barry Warsawab0e86c1998-05-19 15:31:46 +0000721 ["Go to start of class" (py-beginning-of-def-or-class t) t]
722 ["Move to end of class" (py-end-of-def-or-class t) t]
723 ["Move to start of def" py-beginning-of-def-or-class t]
724 ["Move to end of def" py-end-of-def-or-class t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000725 "-"
726 ["Describe mode" py-describe-mode t]
727 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000728
Barry Warsaw81437461996-08-01 19:48:02 +0000729
730
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000731;; Imenu definitions
732(defvar py-imenu-class-regexp
Barry Warsaw81437461996-08-01 19:48:02 +0000733 (concat ; <<classes>>
734 "\\(" ;
735 "^[ \t]*" ; newline and maybe whitespace
736 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
737 ; possibly multiple superclasses
Barry Warsaw3179fe01998-04-04 21:36:53 +0000738 "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
Barry Warsaw81437461996-08-01 19:48:02 +0000739 "[ \t]*:" ; and the final :
740 "\\)" ; >>classes<<
741 )
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000742 "Regexp for Python classes for use with the Imenu package."
Barry Warsaw81437461996-08-01 19:48:02 +0000743 )
744
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000745(defvar py-imenu-method-regexp
Barry Warsaw81437461996-08-01 19:48:02 +0000746 (concat ; <<methods and functions>>
747 "\\(" ;
748 "^[ \t]*" ; new line and maybe whitespace
749 "\\(def[ \t]+" ; function definitions start with def
750 "\\([a-zA-Z0-9_]+\\)" ; name is here
751 ; function arguments...
Barry Warsaw1d5f9881998-10-28 04:08:13 +0000752;; "[ \t]*(\\([-+/a-zA-Z0-9_=,\* \t\n.()\"'#]*\\))"
753 "[ \t]*(\\([^:#]*\\))"
Barry Warsaw81437461996-08-01 19:48:02 +0000754 "\\)" ; end of def
755 "[ \t]*:" ; and then the :
756 "\\)" ; >>methods and functions<<
757 )
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000758 "Regexp for Python methods/functions for use with the Imenu package."
Barry Warsaw81437461996-08-01 19:48:02 +0000759 )
760
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000761(defvar py-imenu-method-no-arg-parens '(2 8)
762 "Indices into groups of the Python regexp for use with Imenu.
Barry Warsaw81437461996-08-01 19:48:02 +0000763
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000764Using these values will result in smaller Imenu lists, as arguments to
Barry Warsaw81437461996-08-01 19:48:02 +0000765functions are not listed.
766
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000767See the variable `py-imenu-show-method-args-p' for more
Barry Warsaw81437461996-08-01 19:48:02 +0000768information.")
769
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000770(defvar py-imenu-method-arg-parens '(2 7)
Barry Warsaw1bbc0311998-10-27 21:54:56 +0000771 "Indices into groups of the Python regexp for use with imenu.
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000772Using these values will result in large Imenu lists, as arguments to
Barry Warsaw81437461996-08-01 19:48:02 +0000773functions are listed.
774
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000775See the variable `py-imenu-show-method-args-p' for more
Barry Warsaw81437461996-08-01 19:48:02 +0000776information.")
777
778;; Note that in this format, this variable can still be used with the
779;; imenu--generic-function. Otherwise, there is no real reason to have
780;; it.
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000781(defvar py-imenu-generic-expression
Barry Warsaw81437461996-08-01 19:48:02 +0000782 (cons
783 (concat
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000784 py-imenu-class-regexp
Barry Warsaw81437461996-08-01 19:48:02 +0000785 "\\|" ; or...
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000786 py-imenu-method-regexp
Barry Warsaw81437461996-08-01 19:48:02 +0000787 )
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000788 py-imenu-method-no-arg-parens)
789 "Generic Python expression which may be used directly with Imenu.
Barry Warsaw81437461996-08-01 19:48:02 +0000790Used by setting the variable `imenu-generic-expression' to this value.
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000791Also, see the function \\[py-imenu-create-index] for a better
792alternative for finding the index.")
Barry Warsaw81437461996-08-01 19:48:02 +0000793
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000794;; These next two variables are used when searching for the Python
Barry Warsaw81437461996-08-01 19:48:02 +0000795;; class/definitions. Just saving some time in accessing the
796;; generic-python-expression, really.
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000797(defvar py-imenu-generic-regexp nil)
798(defvar py-imenu-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000799
800
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000801(defun py-imenu-create-index-function ()
802 "Python interface function for the Imenu package.
803Finds all Python classes and functions/methods. Calls function
804\\[py-imenu-create-index-engine]. See that function for the details
805of how this works."
806 (setq py-imenu-generic-regexp (car py-imenu-generic-expression)
807 py-imenu-generic-parens (if py-imenu-show-method-args-p
808 py-imenu-method-arg-parens
809 py-imenu-method-no-arg-parens))
Barry Warsaw81437461996-08-01 19:48:02 +0000810 (goto-char (point-min))
Barry Warsaw1d5f9881998-10-28 04:08:13 +0000811 ;; Warning: When the buffer has no classes or functions, this will
812 ;; return nil, which seems proper according to the Imenu API, but
813 ;; causes an error in the XEmacs port of Imenu. Sigh.
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000814 (py-imenu-create-index-engine nil))
Barry Warsaw81437461996-08-01 19:48:02 +0000815
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000816(defun py-imenu-create-index-engine (&optional start-indent)
817 "Function for finding Imenu definitions in Python.
Barry Warsaw81437461996-08-01 19:48:02 +0000818
819Finds all definitions (classes, methods, or functions) in a Python
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000820file for the Imenu package.
Barry Warsaw81437461996-08-01 19:48:02 +0000821
822Returns a possibly nested alist of the form
823
824 (INDEX-NAME . INDEX-POSITION)
825
826The second element of the alist may be an alist, producing a nested
827list as in
828
829 (INDEX-NAME . INDEX-ALIST)
830
831This function should not be called directly, as it calls itself
832recursively and requires some setup. Rather this is the engine for
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000833the function \\[py-imenu-create-index-function].
Barry Warsaw81437461996-08-01 19:48:02 +0000834
835It works recursively by looking for all definitions at the current
836indention level. When it finds one, it adds it to the alist. If it
837finds a definition at a greater indentation level, it removes the
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000838previous definition from the alist. In its place it adds all
Barry Warsaw81437461996-08-01 19:48:02 +0000839definitions found at the next indentation level. When it finds a
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000840definition that is less indented then the current level, it returns
841the alist it has created thus far.
Barry Warsaw81437461996-08-01 19:48:02 +0000842
843The optional argument START-INDENT indicates the starting indentation
844at which to continue looking for Python classes, methods, or
845functions. If this is not supplied, the function uses the indentation
846of the first definition found."
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000847 (let (index-alist
848 sub-method-alist
Barry Warsaw81437461996-08-01 19:48:02 +0000849 looking-p
850 def-name prev-name
851 cur-indent def-pos
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000852 (class-paren (first py-imenu-generic-parens))
853 (def-paren (second py-imenu-generic-parens)))
Barry Warsaw81437461996-08-01 19:48:02 +0000854 (setq looking-p
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000855 (re-search-forward py-imenu-generic-regexp (point-max) t))
Barry Warsaw81437461996-08-01 19:48:02 +0000856 (while looking-p
857 (save-excursion
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000858 ;; used to set def-name to this value but generic-extract-name
859 ;; is new to imenu-1.14. this way it still works with
860 ;; imenu-1.11
861 ;;(imenu--generic-extract-name py-imenu-generic-parens))
Barry Warsaw81437461996-08-01 19:48:02 +0000862 (let ((cur-paren (if (match-beginning class-paren)
863 class-paren def-paren)))
864 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000865 (buffer-substring-no-properties (match-beginning cur-paren)
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000866 (match-end cur-paren))))
Barry Warsaw93c88cc1998-08-18 02:00:44 +0000867 (save-match-data
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000868 (py-beginning-of-def-or-class 'either))
Barry Warsaw81437461996-08-01 19:48:02 +0000869 (beginning-of-line)
870 (setq cur-indent (current-indentation)))
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000871 ;; HACK: want to go to the next correct definition location. We
872 ;; explicitly list them here but it would be better to have them
873 ;; in a list.
Barry Warsaw81437461996-08-01 19:48:02 +0000874 (setq def-pos
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000875 (or (match-beginning class-paren)
876 (match-beginning def-paren)))
Barry Warsaw81437461996-08-01 19:48:02 +0000877 ;; if we don't have a starting indent level, take this one
878 (or start-indent
879 (setq start-indent cur-indent))
Barry Warsaw81437461996-08-01 19:48:02 +0000880 ;; if we don't have class name yet, take this one
881 (or prev-name
882 (setq prev-name def-name))
Barry Warsaw81437461996-08-01 19:48:02 +0000883 ;; what level is the next definition on? must be same, deeper
884 ;; or shallower indentation
885 (cond
886 ;; at the same indent level, add it to the list...
887 ((= start-indent cur-indent)
Barry Warsaw81437461996-08-01 19:48:02 +0000888 (push (cons def-name def-pos) index-alist))
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000889 ;; deeper indented expression, recurse
Barry Warsaw81437461996-08-01 19:48:02 +0000890 ((< start-indent cur-indent)
Barry Warsaw81437461996-08-01 19:48:02 +0000891 ;; the point is currently on the expression we're supposed to
892 ;; start on, so go back to the last expression. The recursive
893 ;; call will find this place again and add it to the correct
894 ;; list
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000895 (re-search-backward py-imenu-generic-regexp (point-min) 'move)
896 (setq sub-method-alist (py-imenu-create-index-engine cur-indent))
Barry Warsaw81437461996-08-01 19:48:02 +0000897 (if sub-method-alist
898 ;; we put the last element on the index-alist on the start
899 ;; of the submethod alist so the user can still get to it.
900 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000901 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000902 (cons save-elmt sub-method-alist))
903 index-alist))))
Barry Warsaw81437461996-08-01 19:48:02 +0000904 ;; found less indented expression, we're done.
905 (t
906 (setq looking-p nil)
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000907 (re-search-backward py-imenu-generic-regexp (point-min) t)))
908 ;; end-cond
Barry Warsaw81437461996-08-01 19:48:02 +0000909 (setq prev-name def-name)
910 (and looking-p
911 (setq looking-p
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000912 (re-search-forward py-imenu-generic-regexp
Barry Warsaw81437461996-08-01 19:48:02 +0000913 (point-max) 'move))))
914 (nreverse index-alist)))
915
Barry Warsaw42f707f1996-07-29 21:05:05 +0000916
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000917;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000918(defun python-mode ()
919 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000920To submit a problem report, enter `\\[py-submit-bug-report]' from a
921`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
922documentation. To see what version of `python-mode' you are running,
923enter `\\[py-version]'.
924
925This mode knows about Python indentation, tokens, comments and
926continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000927
928COMMANDS
929\\{py-mode-map}
930VARIABLES
931
Barry Warsaw42f707f1996-07-29 21:05:05 +0000932py-indent-offset\t\tindentation increment
Barry Warsaw41a05c71998-08-10 16:33:12 +0000933py-block-comment-prefix\t\tcomment string used by `comment-region'
Barry Warsaw42f707f1996-07-29 21:05:05 +0000934py-python-command\t\tshell command to invoke Python interpreter
Barry Warsaw42f707f1996-07-29 21:05:05 +0000935py-temp-directory\t\tdirectory used for temp files (if needed)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000936py-beep-if-tab-change\t\tring the bell if `tab-width' is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000937 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000938 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000939 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000940 (make-local-variable 'font-lock-defaults)
941 (make-local-variable 'paragraph-separate)
942 (make-local-variable 'paragraph-start)
943 (make-local-variable 'require-final-newline)
944 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000945 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000946 (make-local-variable 'comment-start-skip)
947 (make-local-variable 'comment-column)
Barry Warsaw003932a1998-07-07 15:11:24 +0000948 (make-local-variable 'comment-indent-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000949 (make-local-variable 'indent-region-function)
950 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000951 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000952 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000953 (set-syntax-table py-mode-syntax-table)
Barry Warsaw003932a1998-07-07 15:11:24 +0000954 (setq major-mode 'python-mode
955 mode-name "Python"
956 local-abbrev-table python-mode-abbrev-table
957 font-lock-defaults '(python-font-lock-keywords)
958 paragraph-separate "^[ \t]*$"
959 paragraph-start "^[ \t]*$"
960 require-final-newline t
961 comment-start "# "
962 comment-end ""
963 comment-start-skip "# *"
964 comment-column 40
965 comment-indent-function 'py-comment-indent-function
966 indent-region-function 'py-indent-region
967 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000968 ;; tell add-log.el how to find the current function/method/variable
969 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000970 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000971 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000972 ;; add the menu
973 (if py-menu
974 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000975 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000976 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000977 (setq comment-multi-line nil))
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000978 ;; Install Imenu if available
Barry Warsaw742a5111998-03-13 17:29:15 +0000979 (when (py-safe (require 'imenu))
Barry Warsaw6839d3a1998-10-28 00:10:45 +0000980 (setq imenu-create-index-function #'py-imenu-create-index-function)
981 (setq imenu-generic-expression py-imenu-generic-expression)
Barry Warsaw742a5111998-03-13 17:29:15 +0000982 (if (fboundp 'imenu-add-to-menubar)
983 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
984 )
985 ;; Run the mode hook. Note that py-mode-hook is deprecated.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000986 (if python-mode-hook
987 (run-hooks 'python-mode-hook)
Barry Warsaw742a5111998-03-13 17:29:15 +0000988 (run-hooks 'py-mode-hook))
989 ;; Now do the automagical guessing
990 (if py-smart-indentation
991 (let ((offset py-indent-offset))
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000992 ;; It's okay if this fails to guess a good value
Barry Warsaw742a5111998-03-13 17:29:15 +0000993 (if (and (py-safe (py-guess-indent-offset))
994 (<= py-indent-offset 8)
995 (>= py-indent-offset 2))
996 (setq offset py-indent-offset))
997 (setq py-indent-offset offset)
Barry Warsaw639eea61998-03-16 18:12:13 +0000998 ;; Only turn indent-tabs-mode off if tab-width !=
999 ;; py-indent-offset. Never turn it on, because the user must
1000 ;; have explicitly turned it off.
1001 (if (/= tab-width py-indent-offset)
1002 (setq indent-tabs-mode nil))
Barry Warsaw11f21561999-07-28 21:59:43 +00001003 ))
1004 ;; Set the default shell if not already set
1005 (when (null py-which-shell)
1006 (py-toggle-shells py-default-interpreter))
1007 )
Barry Warsaw7ae77681994-12-12 20:38:05 +00001008
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001009
Barry Warsawb91b7431995-03-14 15:55:20 +00001010;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001011(defun py-outdent-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00001012 "Returns non-nil if the current line should dedent one level."
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001013 (save-excursion
1014 (and (progn (back-to-indentation)
1015 (looking-at py-outdent-re))
Barry Warsaw1a1c6bb1999-01-09 17:22:38 +00001016 ;; short circuit infloop on illegal construct
1017 (not (bobp))
Barry Warsawf06777d1998-01-21 05:36:18 +00001018 (progn (forward-line -1)
1019 (py-goto-initial-line)
1020 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001021 (while (or (looking-at py-blank-or-comment-re)
1022 (bobp))
1023 (backward-to-indentation 1))
1024 (not (looking-at py-no-outdent-re)))
1025 )))
1026
Barry Warsawb91b7431995-03-14 15:55:20 +00001027(defun py-electric-colon (arg)
1028 "Insert a colon.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001029In certain cases the line is dedented appropriately. If a numeric
1030argument ARG is provided, that many colons are inserted
1031non-electrically. Electric behavior is inhibited inside a string or
1032comment."
Barry Warsawb91b7431995-03-14 15:55:20 +00001033 (interactive "P")
1034 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001035 ;; are we in a string or comment?
1036 (if (save-excursion
1037 (let ((pps (parse-partial-sexp (save-excursion
Barry Warsawab0e86c1998-05-19 15:31:46 +00001038 (py-beginning-of-def-or-class)
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001039 (point))
1040 (point))))
1041 (not (or (nth 3 pps) (nth 4 pps)))))
1042 (save-excursion
1043 (let ((here (point))
1044 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001045 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001046 (if (and (not arg)
1047 (py-outdent-p)
1048 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +00001049 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001050 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001051 )
1052 (setq outdent py-indent-offset))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001053 ;; Don't indent, only dedent. This assumes that any lines
1054 ;; that are already dedented relative to
1055 ;; py-compute-indentation were put there on purpose. It's
1056 ;; highly annoying to have `:' indent for you. Use TAB, C-c
1057 ;; C-l or C-c C-r to adjust. TBD: Is there a better way to
1058 ;; determine this???
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001059 (if (< (current-indentation) indent) nil
1060 (goto-char here)
1061 (beginning-of-line)
1062 (delete-horizontal-space)
1063 (indent-to (- indent outdent))
1064 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001065
1066
Barry Warsawa97a3f31997-11-04 18:47:06 +00001067;; Python subprocess utilities and filters
1068(defun py-execute-file (proc filename)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001069 "Send to Python interpreter process PROC \"execfile('FILENAME')\".
1070Make that process's buffer visible and force display. Also make
1071comint believe the user typed this string so that
1072`kill-output-from-shell' does The Right Thing."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001073 (let ((curbuf (current-buffer))
1074 (procbuf (process-buffer proc))
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001075; (comint-scroll-to-bottom-on-output t)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001076 (msg (format "## working on region in file %s...\n" filename))
Barry Warsaw02e5f691998-09-24 23:48:40 +00001077 (cmd (format "execfile(r'%s')\n" filename)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001078 (unwind-protect
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001079 (save-excursion
Barry Warsawa97a3f31997-11-04 18:47:06 +00001080 (set-buffer procbuf)
1081 (goto-char (point-max))
1082 (move-marker (process-mark proc) (point))
1083 (funcall (process-filter proc) proc msg))
1084 (set-buffer curbuf))
1085 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001086
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001087(defun py-comint-output-filter-function (string)
1088 "Watch output for Python prompt and exec next file waiting in queue.
1089This function is appropriate for `comint-output-filter-functions'."
Barry Warsaw014e0e21998-11-17 19:24:47 +00001090 ;; TBD: this should probably use split-string
Barry Warsaw4f94c731998-09-25 19:40:10 +00001091 (when (and (or (string-equal string ">>> ")
Barry Warsaw4f94c731998-09-25 19:40:10 +00001092 (and (>= (length string) 5)
1093 (string-equal (substring string -5) "\n>>> ")))
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001094 py-file-queue)
1095 (py-safe (delete-file (car py-file-queue)))
1096 (setq py-file-queue (cdr py-file-queue))
1097 (if py-file-queue
1098 (let ((pyproc (get-buffer-process (current-buffer))))
1099 (py-execute-file pyproc (car py-file-queue))))
1100 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001101
Barry Warsaw4f577d22001-04-11 20:23:17 +00001102(defun py-pdbtrack-overlay-arrow (activation)
1103 "Activate or de arrow at beginning-of-line in current buffer."
1104 ;; This was derived/simplified from edebug-overlay-arrow
1105 (cond (activation
1106 (setq overlay-arrow-position (make-marker))
1107 (setq overlay-arrow-string "=>")
1108 (set-marker overlay-arrow-position (py-point 'bol) (current-buffer))
1109 (setq py-pdbtrack-is-tracking-p t))
1110 (overlay-arrow-position
1111 (setq overlay-arrow-position nil)
1112 (setq py-pdbtrack-is-tracking-p nil))
1113 ))
1114
1115(defun py-pdbtrack-track-stack-file (text)
1116 "Show the file indicated by the pdb stack entry line, in a separate window.
1117
1118Activity is disabled if the buffer-local variable
1119`py-pdbtrack-do-tracking-p' is nil.
1120
1121We depend on the pdb input prompt matching `py-pdbtrack-input-prompt'
1122at the beginning of the line."
1123 ;; Instead of trying to piece things together from partial text
1124 ;; (which can be almost useless depending on Emacs version), we
1125 ;; monitor to the point where we have the next pdb prompt, and then
1126 ;; check all text from comint-last-input-end to process-mark.
1127 ;;
1128 ;; KLM: It might be nice to provide an optional override, so this
1129 ;; routine could be fed debugger output strings as the text
1130 ;; argument, for deliberate application elsewhere.
1131 ;;
1132 ;; KLM: We're very conservative about clearing the overlay arrow, to
1133 ;; minimize residue. This means, for instance, that executing other
1134 ;; pdb commands wipes out the highlight.
1135 (let* ((origbuf (current-buffer))
1136 (currproc (get-buffer-process origbuf)))
1137 (if (not (and currproc py-pdbtrack-do-tracking-p))
1138 (py-pdbtrack-overlay-arrow nil)
1139 (let* (;(origdir default-directory)
1140 (procmark (process-mark currproc))
1141 (block (buffer-substring (max comint-last-input-end
1142 (- procmark
1143 py-pdbtrack-track-range))
1144 procmark))
1145 fname lineno)
1146 (if (not (string-match (concat py-pdbtrack-input-prompt "$") block))
1147 (py-pdbtrack-overlay-arrow nil)
1148 (if (not (string-match
1149 (concat ".*" py-pdbtrack-stack-entry-regexp ".*")
1150 block))
1151 (py-pdbtrack-overlay-arrow nil)
1152 (setq fname (match-string 1 block)
1153 lineno (match-string 2 block))
1154 (if (file-exists-p fname)
1155 (progn
1156 (find-file-other-window fname)
1157 (goto-line (string-to-int lineno))
Barry Warsawc8c1a5b2001-04-11 22:27:41 +00001158 (message "pdbtrack: line %s, file %s" lineno fname)
Barry Warsaw4f577d22001-04-11 20:23:17 +00001159 (py-pdbtrack-overlay-arrow t)
1160 (pop-to-buffer origbuf t) )
1161 (if (= (elt fname 0) ?\<)
Barry Warsawc8c1a5b2001-04-11 22:27:41 +00001162 (message "pdbtrack: (Non-file source: '%s')" fname)
1163 (message "pdbtrack: File not found: %s" fname))
Barry Warsaw4f577d22001-04-11 20:23:17 +00001164 )))))))
1165
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001166(defun py-postprocess-output-buffer (buf)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001167 "Highlight exceptions found in BUF.
1168If an exception occurred return t, otherwise return nil. BUF must exist."
Barry Warsawf9b99f41998-03-26 16:08:59 +00001169 (let (line file bol err-p)
Barry Warsaw9981d221997-12-03 05:25:48 +00001170 (save-excursion
1171 (set-buffer buf)
1172 (beginning-of-buffer)
1173 (while (re-search-forward py-traceback-line-re nil t)
1174 (setq file (match-string 1)
1175 line (string-to-int (match-string 2))
1176 bol (py-point 'bol))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001177 (py-highlight-line bol (py-point 'eol) file line)))
1178 (when (and py-jump-on-exception line)
1179 (beep)
1180 (py-jump-to-exception file line)
1181 (setq err-p t))
1182 err-p))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001183
Barry Warsaw9981d221997-12-03 05:25:48 +00001184
Barry Warsawa97a3f31997-11-04 18:47:06 +00001185
1186;;; Subprocess commands
1187
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001188;; only used when (memq 'broken-temp-names py-emacs-features)
1189(defvar py-serial-number 0)
1190(defvar py-exception-buffer nil)
1191(defconst py-output-buffer "*Python Output*")
Barry Warsawa2398801998-04-09 23:28:20 +00001192(make-variable-buffer-local 'py-output-buffer)
1193
1194;; for toggling between CPython and JPython
Barry Warsawaa384fd1999-02-16 23:36:16 +00001195(defvar py-which-shell nil)
Barry Warsawa2398801998-04-09 23:28:20 +00001196(defvar py-which-args py-python-command-args)
1197(defvar py-which-bufname "Python")
1198(make-variable-buffer-local 'py-which-shell)
1199(make-variable-buffer-local 'py-which-args)
1200(make-variable-buffer-local 'py-which-bufname)
1201
1202(defun py-toggle-shells (arg)
1203 "Toggles between the CPython and JPython shells.
Barry Warsaw11f21561999-07-28 21:59:43 +00001204
Barry Warsaw41a05c71998-08-10 16:33:12 +00001205With positive argument ARG (interactively \\[universal-argument]),
1206uses the CPython shell, with negative ARG uses the JPython shell, and
Barry Warsaw11f21561999-07-28 21:59:43 +00001207with a zero argument, toggles the shell.
1208
1209Programmatically, ARG can also be one of the symbols `cpython' or
1210`jpython', equivalent to positive arg and negative arg respectively."
Barry Warsawa2398801998-04-09 23:28:20 +00001211 (interactive "P")
1212 ;; default is to toggle
1213 (if (null arg)
1214 (setq arg 0))
Barry Warsaw11f21561999-07-28 21:59:43 +00001215 ;; preprocess arg
1216 (cond
1217 ((equal arg 0)
1218 ;; toggle
1219 (if (string-equal py-which-bufname "Python")
1220 (setq arg -1)
1221 (setq arg 1)))
1222 ((equal arg 'cpython) (setq arg 1))
1223 ((equal arg 'jpython) (setq arg -1)))
Barry Warsawa2398801998-04-09 23:28:20 +00001224 (let (msg)
1225 (cond
1226 ((< 0 arg)
1227 ;; set to CPython
1228 (setq py-which-shell py-python-command
1229 py-which-args py-python-command-args
1230 py-which-bufname "Python"
1231 msg "CPython"
1232 mode-name "Python"))
1233 ((> 0 arg)
1234 (setq py-which-shell py-jpython-command
1235 py-which-args py-jpython-command-args
1236 py-which-bufname "JPython"
1237 msg "JPython"
1238 mode-name "JPython"))
1239 )
Barry Warsawea609c11998-04-10 16:08:26 +00001240 (message "Using the %s shell" msg)
Barry Warsawa2398801998-04-09 23:28:20 +00001241 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001242
Barry Warsawa97a3f31997-11-04 18:47:06 +00001243;;;###autoload
Barry Warsaw3b4e2f01999-02-16 23:52:46 +00001244(defun py-shell (&optional argprompt)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001245 "Start an interactive Python interpreter in another window.
1246This is like Shell mode, except that Python is running in the window
1247instead of a shell. See the `Interactive Shell' and `Shell Mode'
1248sections of the Emacs manual for details, especially for the key
1249bindings active in the `*Python*' buffer.
1250
Barry Warsaw3b4e2f01999-02-16 23:52:46 +00001251With optional \\[universal-argument], the user is prompted for the
1252flags to pass to the Python interpreter. This has no effect when this
1253command is used to switch to an existing process, only when a new
1254process is started. If you use this, you will probably want to ensure
1255that the current arguments are retained (they will be included in the
1256prompt). This argument is ignored when this function is called
1257programmatically, or when running in Emacs 19.34 or older.
1258
Barry Warsawa2398801998-04-09 23:28:20 +00001259Note: You can toggle between using the CPython interpreter and the
1260JPython interpreter by hitting \\[py-toggle-shells]. This toggles
1261buffer local variables which control whether all your subshell
1262interactions happen to the `*JPython*' or `*Python*' buffers (the
1263latter is the name used for the CPython buffer).
1264
Barry Warsawa97a3f31997-11-04 18:47:06 +00001265Warning: Don't use an interactive Python if you change sys.ps1 or
1266sys.ps2 from their default values, or if you're running code that
1267prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1268distinguish your output from Python's output, and assumes that `>>> '
1269at the start of a line is a prompt from Python. Similarly, the Emacs
1270Shell mode code assumes that both `>>> ' and `... ' at the start of a
1271line are Python prompts. Bad things can happen if you fool either
1272mode.
1273
1274Warning: If you do any editing *in* the process buffer *while* the
1275buffer is accepting output from Python, do NOT attempt to `undo' the
1276changes. Some of the output (nowhere near the parts you changed!) may
1277be lost if you do. This appears to be an Emacs bug, an unfortunate
1278interaction between undo and process filters; the same problem exists in
1279non-Python process buffers using the default (Emacs-supplied) process
1280filter."
Barry Warsaw3b4e2f01999-02-16 23:52:46 +00001281 (interactive "P")
Barry Warsaw50765ab1999-08-10 21:49:00 +00001282 ;; Set the default shell if not already set
1283 (when (null py-which-shell)
1284 (py-toggle-shells py-default-interpreter))
Barry Warsaw3b4e2f01999-02-16 23:52:46 +00001285 (let ((args py-which-args))
1286 (when (and argprompt
1287 (interactive-p)
1288 (fboundp 'split-string))
1289 ;; TBD: Perhaps force "-i" in the final list?
1290 (setq args (split-string
1291 (read-string (concat py-which-bufname
1292 " arguments: ")
1293 (concat
1294 (mapconcat 'identity py-which-args " ") " ")
1295 ))))
1296 (switch-to-buffer-other-window
1297 (apply 'make-comint py-which-bufname py-which-shell nil args))
1298 (make-local-variable 'comint-prompt-regexp)
1299 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
1300 (add-hook 'comint-output-filter-functions
1301 'py-comint-output-filter-function)
Barry Warsaw4f577d22001-04-11 20:23:17 +00001302 ;; pdbtrack
1303 (add-hook 'comint-output-filter-functions 'py-pdbtrack-track-stack-file)
1304 (setq py-pdbtrack-do-tracking-p t)
Barry Warsaw3b4e2f01999-02-16 23:52:46 +00001305 (set-syntax-table py-mode-syntax-table)
1306 (use-local-map py-shell-map)
1307 ))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001308
Barry Warsawa97a3f31997-11-04 18:47:06 +00001309(defun py-clear-queue ()
1310 "Clear the queue of temporary files waiting to execute."
1311 (interactive)
1312 (let ((n (length py-file-queue)))
1313 (mapcar 'delete-file py-file-queue)
1314 (setq py-file-queue nil)
1315 (message "%d pending files de-queued." n)))
1316
Barry Warsaw820273d1998-05-19 15:54:45 +00001317
Barry Warsawa97a3f31997-11-04 18:47:06 +00001318(defun py-execute-region (start end &optional async)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001319 "Execute the region in a Python interpreter.
1320
Barry Warsawa97a3f31997-11-04 18:47:06 +00001321The region is first copied into a temporary file (in the directory
1322`py-temp-directory'). If there is no Python interpreter shell
1323running, this file is executed synchronously using
Barry Warsaw41a05c71998-08-10 16:33:12 +00001324`shell-command-on-region'. If the program is long running, use
1325\\[universal-argument] to run the command asynchronously in its own
1326buffer.
1327
1328When this function is used programmatically, arguments START and END
1329specify the region to execute, and optional third argument ASYNC, if
1330non-nil, specifies to run the command asynchronously in its own
1331buffer.
Barry Warsawa97a3f31997-11-04 18:47:06 +00001332
1333If the Python interpreter shell is running, the region is execfile()'d
1334in that shell. If you try to execute regions too quickly,
1335`python-mode' will queue them up and execute them one at a time when
1336it sees a `>>> ' prompt from Python. Each time this happens, the
1337process buffer is popped into a window (if it's not already in some
1338window) so you can see it, and a comment of the form
1339
1340 \t## working on region in file <name>...
1341
1342is inserted at the end. See also the command `py-clear-queue'."
1343 (interactive "r\nP")
1344 (or (< start end)
1345 (error "Region is empty"))
Barry Warsaw014e0e21998-11-17 19:24:47 +00001346 (let* ((proc (get-process py-which-bufname))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001347 (temp (if (memq 'broken-temp-names py-emacs-features)
Barry Warsaw1b344241998-08-07 22:24:16 +00001348 (let
1349 ((sn py-serial-number)
1350 (pid (and (fboundp 'emacs-pid) (emacs-pid))))
1351 (setq py-serial-number (1+ py-serial-number))
1352 (if pid
1353 (format "python-%d-%d" sn pid)
1354 (format "python-%d" sn)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001355 (make-temp-name "python-")))
Barry Warsawcaee2fe2000-05-23 05:47:43 +00001356 (file (expand-file-name temp py-temp-directory))
1357 (cur (current-buffer))
1358 (buf (get-buffer-create file)))
1359 ;; Write the contents of the buffer, watching out for indented regions.
1360 (save-excursion
1361 (goto-char start)
Barry Warsaw99eadf42000-06-23 20:24:25 +00001362 (let ((needs-if (/= (py-point 'bol) (py-point 'boi))))
Barry Warsawcaee2fe2000-05-23 05:47:43 +00001363 (set-buffer buf)
Barry Warsaw99eadf42000-06-23 20:24:25 +00001364 (when needs-if
1365 (insert "if 1:\n"))
1366 (insert-buffer-substring cur start end)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001367 (cond
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001368 ;; always run the code in its own asynchronous subprocess
Barry Warsawa97a3f31997-11-04 18:47:06 +00001369 (async
Barry Warsawcaee2fe2000-05-23 05:47:43 +00001370 ;; User explicitly wants this to run in its own async subprocess
1371 (save-excursion
1372 (set-buffer buf)
1373 (write-region (point-min) (point-max) file nil 'nomsg))
Barry Warsaw34d83171998-11-20 03:04:07 +00001374 (let* ((buf (generate-new-buffer-name py-output-buffer))
1375 ;; TBD: a horrible hack, but why create new Custom variables?
1376 (arg (if (string-equal py-which-bufname "Python")
1377 "-u" "")))
1378 (start-process py-which-bufname buf py-which-shell arg file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001379 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001380 (py-postprocess-output-buffer buf)
Barry Warsawcaee2fe2000-05-23 05:47:43 +00001381 ;; TBD: clean up the temporary file!
Barry Warsawa97a3f31997-11-04 18:47:06 +00001382 ))
1383 ;; if the Python interpreter shell is running, queue it up for
1384 ;; execution there.
1385 (proc
1386 ;; use the existing python shell
Barry Warsawcaee2fe2000-05-23 05:47:43 +00001387 (save-excursion
1388 (set-buffer buf)
1389 (write-region (point-min) (point-max) file nil 'nomsg))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001390 (if (not py-file-queue)
1391 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001392 (message "File %s queued for execution" file))
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001393 (setq py-file-queue (append py-file-queue (list file)))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001394 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001395 (t
Barry Warsaw34d83171998-11-20 03:04:07 +00001396 ;; TBD: a horrible hack, buy why create new Custom variables?
1397 (let ((cmd (concat py-which-shell
1398 (if (string-equal py-which-bufname "JPython")
1399 " -" ""))))
1400 ;; otherwise either run it synchronously in a subprocess
Barry Warsawcaee2fe2000-05-23 05:47:43 +00001401 (save-excursion
1402 (set-buffer buf)
1403 (shell-command-on-region (point-min) (point-max)
1404 cmd py-output-buffer))
Barry Warsaw34d83171998-11-20 03:04:07 +00001405 ;; shell-command-on-region kills the output buffer if it never
1406 ;; existed and there's no output from the command
1407 (if (not (get-buffer py-output-buffer))
1408 (message "No output.")
1409 (setq py-exception-buffer (current-buffer))
1410 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1411 (pop-to-buffer py-output-buffer)
1412 (if err-p
1413 (pop-to-buffer py-exception-buffer)))
Barry Warsawcaee2fe2000-05-23 05:47:43 +00001414 ))
1415 ;; TBD: delete the buffer
1416 )
Barry Warsaw71534602001-02-20 23:07:56 +00001417 )
1418 ;; Clean up after ourselves.
1419 (kill-buffer buf)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001420
Barry Warsaw820273d1998-05-19 15:54:45 +00001421
1422;; Code execution commands
Barry Warsawa97a3f31997-11-04 18:47:06 +00001423(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001424 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001425If the file local variable `py-master-file' is non-nil, execute the
1426named file instead of the buffer's file.
1427
Barry Warsaw7ae77681994-12-12 20:38:05 +00001428If there is a *Python* process buffer it is used. If a clipping
1429restriction is in effect, only the accessible portion of the buffer is
1430sent. A trailing newline will be supplied if needed.
1431
Barry Warsaw41a05c71998-08-10 16:33:12 +00001432See the `\\[py-execute-region]' docs for an account of some
1433subtleties, including the use of the optional ASYNC argument."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001434 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001435 (if py-master-file
1436 (let* ((filename (expand-file-name py-master-file))
1437 (buffer (or (get-file-buffer filename)
1438 (find-file-noselect filename))))
1439 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001440 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001441
Barry Warsaw820273d1998-05-19 15:54:45 +00001442(defun py-execute-import-or-reload (&optional async)
1443 "Import the current buffer's file in a Python interpreter.
1444
1445If the file has already been imported, then do reload instead to get
Barry Warsaw7c29b231998-07-07 17:45:38 +00001446the latest version.
1447
1448If the file's name does not end in \".py\", then do execfile instead.
1449
1450If the current buffer is not visiting a file, do `py-execute-buffer'
1451instead.
1452
1453If the file local variable `py-master-file' is non-nil, import or
1454reload the named file instead of the buffer's file. The file may be
1455saved based on the value of `py-execute-import-or-reload-save-p'.
Barry Warsaw820273d1998-05-19 15:54:45 +00001456
Barry Warsaw41a05c71998-08-10 16:33:12 +00001457See the `\\[py-execute-region]' docs for an account of some
1458subtleties, including the use of the optional ASYNC argument.
Barry Warsaw820273d1998-05-19 15:54:45 +00001459
Barry Warsaw7c29b231998-07-07 17:45:38 +00001460This may be preferable to `\\[py-execute-buffer]' because:
Barry Warsaw820273d1998-05-19 15:54:45 +00001461
1462 - Definitions stay in their module rather than appearing at top
1463 level, where they would clutter the global namespace and not affect
1464 uses of qualified names (MODULE.NAME).
1465
1466 - The Python debugger gets line number information about the functions."
1467 (interactive "P")
1468 ;; Check file local variable py-master-file
1469 (if py-master-file
1470 (let* ((filename (expand-file-name py-master-file))
1471 (buffer (or (get-file-buffer filename)
1472 (find-file-noselect filename))))
1473 (set-buffer buffer)))
1474 (let ((file (buffer-file-name (current-buffer))))
1475 (if file
1476 (progn
Barry Warsaw3bfed5b1998-05-19 16:25:04 +00001477 ;; Maybe save some buffers
1478 (save-some-buffers (not py-ask-about-save) nil)
Barry Warsaw820273d1998-05-19 15:54:45 +00001479 (py-execute-string
1480 (if (string-match "\\.py$" file)
1481 (let ((f (file-name-sans-extension
1482 (file-name-nondirectory file))))
1483 (format "if globals().has_key('%s'):\n reload(%s)\nelse:\n import %s\n"
1484 f f f))
Barry Warsaw02e5f691998-09-24 23:48:40 +00001485 (format "execfile(r'%s')\n" file))
Barry Warsaw820273d1998-05-19 15:54:45 +00001486 async))
1487 ;; else
1488 (py-execute-buffer async))))
1489
1490
1491(defun py-execute-def-or-class (&optional async)
1492 "Send the current function or class definition to a Python interpreter.
1493
1494If there is a *Python* process buffer it is used.
1495
Barry Warsaw41a05c71998-08-10 16:33:12 +00001496See the `\\[py-execute-region]' docs for an account of some
1497subtleties, including the use of the optional ASYNC argument."
Barry Warsaw820273d1998-05-19 15:54:45 +00001498 (interactive "P")
1499 (save-excursion
1500 (py-mark-def-or-class)
1501 ;; mark is before point
1502 (py-execute-region (mark) (point) async)))
1503
1504
1505(defun py-execute-string (string &optional async)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001506 "Send the argument STRING to a Python interpreter.
Barry Warsaw820273d1998-05-19 15:54:45 +00001507
1508If there is a *Python* process buffer it is used.
1509
Barry Warsaw41a05c71998-08-10 16:33:12 +00001510See the `\\[py-execute-region]' docs for an account of some
1511subtleties, including the use of the optional ASYNC argument."
Barry Warsaw820273d1998-05-19 15:54:45 +00001512 (interactive "sExecute Python command: ")
1513 (save-excursion
1514 (set-buffer (get-buffer-create
1515 (generate-new-buffer-name " *Python Command*")))
1516 (insert string)
1517 (py-execute-region (point-min) (point-max) async)))
1518
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001519
1520
1521(defun py-jump-to-exception (file line)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001522 "Jump to the Python code in FILE at LINE."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001523 (let ((buffer (cond ((string-equal file "<stdin>")
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001524 (if (consp py-exception-buffer)
1525 (cdr py-exception-buffer)
1526 py-exception-buffer))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001527 ((and (consp py-exception-buffer)
1528 (string-equal file (car py-exception-buffer)))
1529 (cdr py-exception-buffer))
1530 ((py-safe (find-file-noselect file)))
1531 ;; could not figure out what file the exception
1532 ;; is pointing to, so prompt for it
1533 (t (find-file (read-file-name "Exception file: "
1534 nil
1535 file t))))))
1536 (pop-to-buffer buffer)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001537 ;; Force Python mode
Barry Warsaw820273d1998-05-19 15:54:45 +00001538 (if (not (eq major-mode 'python-mode))
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001539 (python-mode))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001540 (goto-line line)
1541 (message "Jumping to exception in file %s on line %d" file line)))
1542
1543(defun py-mouseto-exception (event)
Barry Warsaw12c92941998-08-10 21:44:37 +00001544 "Jump to the code which caused the Python exception at EVENT.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001545EVENT is usually a mouse click."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001546 (interactive "e")
1547 (cond
1548 ((fboundp 'event-point)
1549 ;; XEmacs
1550 (let* ((point (event-point event))
1551 (buffer (event-buffer event))
1552 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1553 (info (and e (extent-property e 'py-exc-info))))
1554 (message "Event point: %d, info: %s" point info)
1555 (and info
1556 (py-jump-to-exception (car info) (cdr info)))
1557 ))
1558 ;; Emacs -- Please port this!
1559 ))
1560
1561(defun py-goto-exception ()
1562 "Go to the line indicated by the traceback."
1563 (interactive)
1564 (let (file line)
1565 (save-excursion
1566 (beginning-of-line)
1567 (if (looking-at py-traceback-line-re)
1568 (setq file (match-string 1)
1569 line (string-to-int (match-string 2)))))
1570 (if (not file)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001571 (error "Not on a traceback line"))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001572 (py-jump-to-exception file line)))
1573
1574(defun py-find-next-exception (start buffer searchdir errwhere)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001575 "Find the next Python exception and jump to the code that caused it.
1576START is the buffer position in BUFFER from which to begin searching
1577for an exception. SEARCHDIR is a function, either
1578`re-search-backward' or `re-search-forward' indicating the direction
1579to search. ERRWHERE is used in an error message if the limit (top or
1580bottom) of the trackback stack is encountered."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001581 (let (file line)
1582 (save-excursion
1583 (set-buffer buffer)
1584 (goto-char (py-point start))
1585 (if (funcall searchdir py-traceback-line-re nil t)
1586 (setq file (match-string 1)
1587 line (string-to-int (match-string 2)))))
1588 (if (and file line)
1589 (py-jump-to-exception file line)
1590 (error "%s of traceback" errwhere))))
1591
1592(defun py-down-exception (&optional bottom)
1593 "Go to the next line down in the traceback.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001594With \\[univeral-argument] (programmatically, optional argument
1595BOTTOM), jump to the bottom (innermost) exception in the exception
1596stack."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001597 (interactive "P")
1598 (let* ((proc (get-process "Python"))
1599 (buffer (if proc "*Python*" py-output-buffer)))
1600 (if bottom
1601 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1602 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1603
1604(defun py-up-exception (&optional top)
1605 "Go to the previous line up in the traceback.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001606With \\[universal-argument] (programmatically, optional argument TOP)
1607jump to the top (outermost) exception in the exception stack."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001608 (interactive "P")
1609 (let* ((proc (get-process "Python"))
1610 (buffer (if proc "*Python*" py-output-buffer)))
1611 (if top
1612 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001613 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001614
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001615
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001616;; Electric deletion
1617(defun py-electric-backspace (arg)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001618 "Delete preceding character or levels of indentation.
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001619Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001620with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001621
Barry Warsaw41a05c71998-08-10 16:33:12 +00001622If point is at the leftmost column, delete the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001623
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001624Otherwise, if point is at the leftmost non-whitespace character of a
1625line that is neither a continuation line nor a non-indenting comment
1626line, or if point is at the end of a blank line, this command reduces
1627the indentation to match that of the line that opened the current
1628block of code. The line that opened the block is displayed in the
Barry Warsaw41a05c71998-08-10 16:33:12 +00001629echo area to help you keep track of where you are. With
1630\\[universal-argument] dedents that many blocks (but not past column
1631zero).
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001632
1633Otherwise the preceding character is deleted, converting a tab to
1634spaces if needed so that only a single column position is deleted.
Barry Warsawfa2def21999-05-24 21:43:37 +00001635\\[universal-argument] specifies how many characters to delete;
1636default is 1.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001637
1638When used programmatically, argument ARG specifies the number of
1639blocks to dedent, or the number of characters to delete, as indicated
1640above."
Barry Warsaw03970731996-07-03 23:12:52 +00001641 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001642 (if (or (/= (current-indentation) (current-column))
1643 (bolp)
1644 (py-continuation-line-p)
Barry Warsawfa2def21999-05-24 21:43:37 +00001645; (not py-honor-comment-indentation)
1646; (looking-at "#[^ \t\n]") ; non-indenting #
1647 )
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001648 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001649 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001650 ;; force non-blank so py-goto-block-up doesn't ignore it
1651 (insert-char ?* 1)
1652 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001653 (let ((base-indent 0) ; indentation of base line
1654 (base-text "") ; and text of base line
1655 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001656 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001657 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001658 (condition-case nil ; in case no enclosing block
1659 (progn
1660 (py-goto-block-up 'no-mark)
1661 (setq base-indent (current-indentation)
1662 base-text (py-suck-up-leading-text)
1663 base-found-p t))
1664 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001665 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001666 (delete-char 1) ; toss the dummy character
1667 (delete-horizontal-space)
1668 (indent-to base-indent)
1669 (if base-found-p
1670 (message "Closes block: %s" base-text)))))
1671
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001672
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001673(defun py-electric-delete (arg)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001674 "Delete preceding or following character or levels of whitespace.
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001675
1676The behavior of this function depends on the variable
1677`delete-key-deletes-forward'. If this variable is nil (or does not
Barry Warsaw41a05c71998-08-10 16:33:12 +00001678exist, as in older Emacsen and non-XEmacs versions), then this
1679function behaves identically to \\[c-electric-backspace].
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001680
1681If `delete-key-deletes-forward' is non-nil and is supported in your
1682Emacs, then deletion occurs in the forward direction, by calling the
Barry Warsaw41a05c71998-08-10 16:33:12 +00001683function in `py-delete-function'.
1684
1685\\[universal-argument] (programmatically, argument ARG) specifies the
1686number of characters to delete (default is 1)."
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001687 (interactive "*p")
Barry Warsaw1d7b0fa1999-01-15 02:12:31 +00001688 (if (or (and (fboundp 'delete-forward-p) ;XEmacs 21
1689 (delete-forward-p))
1690 (and (boundp 'delete-key-deletes-forward) ;XEmacs 20
1691 delete-key-deletes-forward))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001692 (funcall py-delete-function arg)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001693 (py-electric-backspace arg)))
1694
1695;; required for pending-del and delsel modes
1696(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1697(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1698(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1699(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1700
1701
1702
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001703(defun py-indent-line (&optional arg)
1704 "Fix the indentation of the current line according to Python rules.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001705With \\[universal-argument] (programmatically, the optional argument
1706ARG non-nil), ignore dedenting rules for block closing statements
1707(e.g. return, raise, break, continue, pass)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001708
1709This function is normally bound to `indent-line-function' so
1710\\[indent-for-tab-command] will call it."
1711 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001712 (let* ((ci (current-indentation))
1713 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001714 (need (py-compute-indentation (not arg))))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001715 ;; see if we need to dedent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001716 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001717 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001718 (if (/= ci need)
1719 (save-excursion
1720 (beginning-of-line)
1721 (delete-horizontal-space)
1722 (indent-to need)))
1723 (if move-to-indentation-p (back-to-indentation))))
1724
1725(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001726 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001727This is just `strives to' because correct indentation can't be computed
1728from scratch for Python code. In general, deletes the whitespace before
1729point, inserts a newline, and takes an educated guess as to how you want
1730the new line indented."
1731 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001732 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001733 (if (< ci (current-column)) ; if point beyond indentation
1734 (newline-and-indent)
1735 ;; else try to act like newline-and-indent "normally" acts
1736 (beginning-of-line)
1737 (insert-char ?\n 1)
1738 (move-to-column ci))))
1739
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001740(defun py-compute-indentation (honor-block-close-p)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001741 "Compute Python indentation.
1742When HONOR-BLOCK-CLOSE-P is non-nil, statements such as `return',
1743`raise', `break', `continue', and `pass' force one level of
1744dedenting."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001745 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001746 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001747 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001748 (pps (parse-partial-sexp bod (point)))
Barry Warsaw9c1696c1998-12-15 04:36:22 +00001749 (boipps (parse-partial-sexp bod (py-point 'boi)))
1750 placeholder)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001751 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001752 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001753 ((or (and (nth 3 pps) (nth 3 boipps))
1754 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001755 (save-excursion
1756 (if (not py-align-multiline-strings-p) 0
1757 ;; skip back over blank & non-indenting comment lines
1758 ;; note: will skip a blank or non-indenting comment line
1759 ;; that happens to be a continuation line too
1760 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1761 (back-to-indentation)
1762 (current-column))))
1763 ;; are we on a continuation line?
1764 ((py-continuation-line-p)
1765 (let ((startpos (point))
1766 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001767 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001768 (if open-bracket-pos
1769 (progn
1770 ;; align with first item in list; else a normal
1771 ;; indent beyond the line with the open bracket
1772 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1773 ;; is the first list item on the same line?
1774 (skip-chars-forward " \t")
1775 (if (null (memq (following-char) '(?\n ?# ?\\)))
1776 ; yes, so line up with it
1777 (current-column)
1778 ;; first list item on another line, or doesn't exist yet
1779 (forward-line 1)
1780 (while (and (< (point) startpos)
1781 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1782 (forward-line 1))
Barry Warsaw92166d91998-04-01 21:59:41 +00001783 (if (and (< (point) startpos)
1784 (/= startpos
1785 (save-excursion
1786 (goto-char (1+ open-bracket-pos))
Barry Warsaw77d1fce1998-04-16 20:04:59 +00001787 (forward-comment (point-max))
Barry Warsaw92166d91998-04-01 21:59:41 +00001788 (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001789 ;; again mimic the first list item
1790 (current-indentation)
1791 ;; else they're about to enter the first item
1792 (goto-char open-bracket-pos)
Barry Warsaw9c1696c1998-12-15 04:36:22 +00001793 (setq placeholder (point))
1794 (py-goto-initial-line)
1795 (py-goto-beginning-of-tqs
1796 (save-excursion (nth 3 (parse-partial-sexp
1797 placeholder (point)))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001798 (+ (current-indentation) py-indent-offset))))
1799
1800 ;; else on backslash continuation line
1801 (forward-line -1)
1802 (if (py-continuation-line-p) ; on at least 3rd line in block
1803 (current-indentation) ; so just continue the pattern
1804 ;; else started on 2nd line in block, so indent more.
1805 ;; if base line is an assignment with a start on a RHS,
1806 ;; indent to 2 beyond the leftmost "="; else skip first
1807 ;; chunk of non-whitespace characters on base line, + 1 more
1808 ;; column
1809 (end-of-line)
Barry Warsawfd4c9e82001-06-18 23:40:35 +00001810 (setq endpos (point)
1811 searching t)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001812 (back-to-indentation)
1813 (setq startpos (point))
1814 ;; look at all "=" from left to right, stopping at first
1815 ;; one not nested in a list or string
1816 (while searching
1817 (skip-chars-forward "^=" endpos)
1818 (if (= (point) endpos)
1819 (setq searching nil)
1820 (forward-char 1)
1821 (setq state (parse-partial-sexp startpos (point)))
1822 (if (and (zerop (car state)) ; not in a bracket
1823 (null (nth 3 state))) ; & not in a string
1824 (progn
1825 (setq searching nil) ; done searching in any case
1826 (setq found
1827 (not (or
1828 (eq (following-char) ?=)
1829 (memq (char-after (- (point) 2))
1830 '(?< ?> ?!)))))))))
1831 (if (or (not found) ; not an assignment
1832 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1833 (progn
1834 (goto-char startpos)
1835 (skip-chars-forward "^ \t\n")))
Barry Warsawfd4c9e82001-06-18 23:40:35 +00001836 (+ (current-column) py-continuation-offset 1)
1837 ))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001838
1839 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001840 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001841
Barry Warsawa7891711996-08-01 15:53:09 +00001842 ;; Dfn: "Indenting comment line". A line containing only a
1843 ;; comment, but which is treated like a statement for
1844 ;; indentation calculation purposes. Such lines are only
1845 ;; treated specially by the mode; they are not treated
1846 ;; specially by the Python interpreter.
1847
1848 ;; The rules for indenting comment lines are a line where:
1849 ;; - the first non-whitespace character is `#', and
1850 ;; - the character following the `#' is whitespace, and
Barry Warsaw41a05c71998-08-10 16:33:12 +00001851 ;; - the line is dedented with respect to (i.e. to the left
Barry Warsawa7891711996-08-01 15:53:09 +00001852 ;; of) the indentation of the preceding non-blank line.
1853
1854 ;; The first non-blank line following an indenting comment
1855 ;; line is given the same amount of indentation as the
1856 ;; indenting comment line.
1857
1858 ;; All other comment-only lines are ignored for indentation
1859 ;; purposes.
1860
1861 ;; Are we looking at a comment-only line which is *not* an
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001862 ;; indenting comment line? If so, we assume that it's been
Barry Warsawa7891711996-08-01 15:53:09 +00001863 ;; placed at the desired indentation, so leave it alone.
1864 ;; Indenting comment lines are aligned as statements down
1865 ;; below.
1866 ((and (looking-at "[ \t]*#[^ \t\n]")
1867 ;; NOTE: this test will not be performed in older Emacsen
1868 (fboundp 'forward-comment)
1869 (<= (current-indentation)
1870 (save-excursion
1871 (forward-comment (- (point-max)))
1872 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001873 (current-indentation))
1874
1875 ;; else indentation based on that of the statement that
1876 ;; precedes us; use the first line of that statement to
1877 ;; establish the base, in case the user forced a non-std
1878 ;; indentation for the continuation lines (if any)
1879 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001880 ;; skip back over blank & non-indenting comment lines note:
1881 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001882 ;; happens to be a continuation line too. use fast Emacs 19
1883 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001884 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001885 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001886 (forward-comment (- (point-max)))
Barry Warsaw218eb751998-09-22 19:51:47 +00001887 (let ((prefix-re (concat py-block-comment-prefix "[ \t]*"))
1888 done)
Barry Warsaw6d627751996-03-06 18:41:38 +00001889 (while (not done)
Barry Warsaw12c92941998-08-10 21:44:37 +00001890 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#\\)" nil 'move)
1891 (setq done (or (bobp)
1892 (and (eq py-honor-comment-indentation t)
1893 (save-excursion
1894 (back-to-indentation)
Barry Warsaw218eb751998-09-22 19:51:47 +00001895 (not (looking-at prefix-re))
Barry Warsaw12c92941998-08-10 21:44:37 +00001896 ))
1897 (and (not (eq py-honor-comment-indentation t))
1898 (save-excursion
1899 (back-to-indentation)
1900 (not (zerop (current-column)))))
1901 ))
Barry Warsaw6d627751996-03-06 18:41:38 +00001902 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001903 ;; if we landed inside a string, go to the beginning of that
1904 ;; string. this handles triple quoted, multi-line spanning
1905 ;; strings.
Barry Warsaw9c1696c1998-12-15 04:36:22 +00001906 (py-goto-beginning-of-tqs (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawc210e691998-01-20 22:52:56 +00001907 ;; now skip backward over continued lines
Barry Warsaw9c1696c1998-12-15 04:36:22 +00001908 (setq placeholder (point))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001909 (py-goto-initial-line)
Barry Warsaw9c1696c1998-12-15 04:36:22 +00001910 ;; we may *now* have landed in a TQS, so find the beginning of
1911 ;; this string.
1912 (py-goto-beginning-of-tqs
1913 (save-excursion (nth 3 (parse-partial-sexp
1914 placeholder (point)))))
Barry Warsawf831d811996-07-31 20:42:59 +00001915 (+ (current-indentation)
1916 (if (py-statement-opens-block-p)
1917 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001918 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001919 (- py-indent-offset)
1920 0)))
1921 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001922
1923(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001924 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001925
1926By default, make a buffer-local copy of `py-indent-offset' with the
1927new value, so that other Python buffers are not affected. With
1928\\[universal-argument] (programmatically, optional argument GLOBAL),
1929change the global value of `py-indent-offset'. This affects all
1930Python buffers (that don't have their own buffer-local copy), both
1931those currently existing and those created later in the Emacs session.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001932
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001933Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001934There's no excuse for such foolishness, but sometimes you have to deal
1935with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001936`py-indent-offset' to what it thinks it was when they created the
1937mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001938
1939Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001940looking for a line that opens a block of code. `py-indent-offset' is
1941set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001942statement following it. If the search doesn't succeed going forward,
1943it's tried again going backward."
1944 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001945 (let (new-value
1946 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001947 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001948 (found nil)
1949 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001950 (py-goto-initial-line)
1951 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001952 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1953 (not (py-in-literal restart)))
1954 (setq restart (point))
1955 (py-goto-initial-line)
1956 (if (py-statement-opens-block-p)
1957 (setq found t)
1958 (goto-char restart))))
1959 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001960 (goto-char start)
1961 (py-goto-initial-line)
1962 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001963 (setq found (and
1964 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1965 (or (py-goto-initial-line) t) ; always true -- side effect
1966 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001967 (setq colon-indent (current-indentation)
1968 found (and found (zerop (py-next-statement 1)))
1969 new-value (- (current-indentation) colon-indent))
1970 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001971 (if (not found)
1972 (error "Sorry, couldn't guess a value for py-indent-offset")
1973 (funcall (if global 'kill-local-variable 'make-local-variable)
1974 'py-indent-offset)
1975 (setq py-indent-offset new-value)
Barry Warsawd35c2551998-09-25 00:08:38 +00001976 (or noninteractive
1977 (message "%s value of py-indent-offset set to %d"
1978 (if global "Global" "Local")
1979 py-indent-offset)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001980 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001981
Barry Warsaw003932a1998-07-07 15:11:24 +00001982(defun py-comment-indent-function ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00001983 "Python version of `comment-indent-function'."
1984 ;; This is required when filladapt is turned off. Without it, when
1985 ;; filladapt is not used, comments which start in column zero
1986 ;; cascade one character to the right
Barry Warsaw003932a1998-07-07 15:11:24 +00001987 (save-excursion
1988 (beginning-of-line)
1989 (let ((eol (py-point 'eol)))
1990 (and comment-start-skip
1991 (re-search-forward comment-start-skip eol t)
1992 (setq eol (match-beginning 0)))
1993 (goto-char eol)
1994 (skip-chars-backward " \t")
1995 (max comment-column (+ (current-column) (if (bolp) 0 1)))
1996 )))
1997
Barry Warsawf8ddb6a1999-01-18 21:49:39 +00001998(defun py-narrow-to-defun (&optional class)
1999 "Make text outside current defun invisible.
2000The defun visible is the one that contains point or follows point.
2001Optional CLASS is passed directly to `py-beginning-of-def-or-class'."
2002 (interactive "P")
2003 (save-excursion
2004 (widen)
2005 (py-end-of-def-or-class class)
2006 (let ((end (point)))
2007 (py-beginning-of-def-or-class class)
2008 (narrow-to-region (point) end))))
2009
Barry Warsaw003932a1998-07-07 15:11:24 +00002010
Barry Warsaw7ae77681994-12-12 20:38:05 +00002011(defun py-shift-region (start end count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002012 "Indent lines from START to END by COUNT spaces."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002013 (save-excursion
Barry Warsaw41a05c71998-08-10 16:33:12 +00002014 (goto-char end)
2015 (beginning-of-line)
2016 (setq end (point))
2017 (goto-char start)
2018 (beginning-of-line)
2019 (setq start (point))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002020 (indent-rigidly start end count)))
2021
2022(defun py-shift-region-left (start end &optional count)
2023 "Shift region of Python code to the left.
2024The lines from the line containing the start of the current region up
2025to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002026shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002027
2028If a prefix argument is given, the region is instead shifted by that
Barry Warsaw41a05c71998-08-10 16:33:12 +00002029many columns. With no active region, dedent only the current line.
2030You cannot dedent the region if any line is already at column zero."
Barry Warsawdea4a291996-07-03 22:59:12 +00002031 (interactive
2032 (let ((p (point))
2033 (m (mark))
2034 (arg current-prefix-arg))
2035 (if m
2036 (list (min p m) (max p m) arg)
2037 (list p (save-excursion (forward-line 1) (point)) arg))))
2038 ;; if any line is at column zero, don't shift the region
2039 (save-excursion
2040 (goto-char start)
2041 (while (< (point) end)
2042 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00002043 (if (and (zerop (current-column))
2044 (not (looking-at "\\s *$")))
Barry Warsaw41a05c71998-08-10 16:33:12 +00002045 (error "Region is at left edge"))
Barry Warsawdea4a291996-07-03 22:59:12 +00002046 (forward-line 1)))
2047 (py-shift-region start end (- (prefix-numeric-value
2048 (or count py-indent-offset))))
2049 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002050
2051(defun py-shift-region-right (start end &optional count)
2052 "Shift region of Python code to the right.
2053The lines from the line containing the start of the current region up
2054to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002055shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002056
2057If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00002058many columns. With no active region, indent only the current line."
2059 (interactive
2060 (let ((p (point))
2061 (m (mark))
2062 (arg current-prefix-arg))
2063 (if m
2064 (list (min p m) (max p m) arg)
2065 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002066 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00002067 (or count py-indent-offset)))
2068 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002069
2070(defun py-indent-region (start end &optional indent-offset)
2071 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00002072
Barry Warsaw7ae77681994-12-12 20:38:05 +00002073The lines from the line containing the start of the current region up
2074to (but not including) the line containing the end of the region are
2075reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002076character in the first column, the first line is left alone and the
2077rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00002078region is reindented with respect to the (closest code or indenting
2079comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002080
2081This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002082control structures are introduced or removed, or to reformat code
2083using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002084
2085If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002086the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00002087used.
2088
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002089Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00002090is called! This function does not compute proper indentation from
2091scratch (that's impossible in Python), it merely adjusts the existing
2092indentation to be correct in context.
2093
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002094Warning: This function really has no idea what to do with
2095non-indenting comment lines, and shifts them as if they were indenting
2096comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002097
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002098Special cases: whitespace is deleted from blank lines; continuation
2099lines are shifted by the same amount their initial line was shifted,
2100in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00002101initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002102 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002103 (save-excursion
2104 (goto-char end) (beginning-of-line) (setq end (point-marker))
2105 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002106 (let ((py-indent-offset (prefix-numeric-value
2107 (or indent-offset py-indent-offset)))
2108 (indents '(-1)) ; stack of active indent levels
2109 (target-column 0) ; column to which to indent
2110 (base-shifted-by 0) ; amount last base line was shifted
2111 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002112 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002113 0))
2114 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002115 (while (< (point) end)
2116 (setq ci (current-indentation))
2117 ;; figure out appropriate target column
2118 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002119 ((or (eq (following-char) ?#) ; comment in column 1
2120 (looking-at "[ \t]*$")) ; entirely blank
2121 (setq target-column 0))
2122 ((py-continuation-line-p) ; shift relative to base line
2123 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002124 (t ; new base line
2125 (if (> ci (car indents)) ; going deeper; push it
2126 (setq indents (cons ci indents))
2127 ;; else we should have seen this indent before
2128 (setq indents (memq ci indents)) ; pop deeper indents
2129 (if (null indents)
2130 (error "Bad indentation in region, at line %d"
2131 (save-restriction
2132 (widen)
2133 (1+ (count-lines 1 (point)))))))
2134 (setq target-column (+ indent-base
2135 (* py-indent-offset
2136 (- (length indents) 2))))
2137 (setq base-shifted-by (- target-column ci))))
2138 ;; shift as needed
2139 (if (/= ci target-column)
2140 (progn
2141 (delete-horizontal-space)
2142 (indent-to target-column)))
2143 (forward-line 1))))
2144 (set-marker end nil))
2145
Barry Warsawa7891711996-08-01 15:53:09 +00002146(defun py-comment-region (beg end &optional arg)
2147 "Like `comment-region' but uses double hash (`#') comment starter."
2148 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00002149 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00002150 (comment-region beg end arg)))
2151
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002152
2153;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00002154(defun py-previous-statement (count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002155 "Go to the start of the COUNTth preceding Python statement.
2156By default, goes to the previous statement. If there is no such
2157statement, goes to the first statement. Return count of statements
2158left to move. `Statements' do not include blank, comment, or
2159continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002160 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002161 (if (< count 0) (py-next-statement (- count))
2162 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002163 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002164 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002165 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002166 (> count 0)
2167 (zerop (forward-line -1))
2168 (py-goto-statement-at-or-above))
2169 (setq count (1- count)))
2170 (if (> count 0) (goto-char start)))
2171 count))
2172
2173(defun py-next-statement (count)
2174 "Go to the start of next Python statement.
2175If the statement at point is the i'th Python statement, goes to the
2176start of statement i+COUNT. If there is no such statement, goes to the
2177last statement. Returns count of statements left to move. `Statements'
2178do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002179 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002180 (if (< count 0) (py-previous-statement (- count))
2181 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002182 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002183 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002184 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002185 (> count 0)
2186 (py-goto-statement-below))
2187 (setq count (1- count)))
2188 (if (> count 0) (goto-char start)))
2189 count))
2190
2191(defun py-goto-block-up (&optional nomark)
2192 "Move up to start of current block.
2193Go to the statement that starts the smallest enclosing block; roughly
2194speaking, this will be the closest preceding statement that ends with a
2195colon and is indented less than the statement you started on. If
2196successful, also sets the mark to the starting point.
2197
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002198`\\[py-mark-block]' can be used afterward to mark the whole code
2199block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002200
2201If called from a program, the mark will not be set if optional argument
2202NOMARK is not nil."
2203 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002204 (let ((start (point))
2205 (found nil)
2206 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002207 (py-goto-initial-line)
2208 ;; if on blank or non-indenting comment line, use the preceding stmt
2209 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2210 (progn
2211 (py-goto-statement-at-or-above)
2212 (setq found (py-statement-opens-block-p))))
2213 ;; search back for colon line indented less
2214 (setq initial-indent (current-indentation))
2215 (if (zerop initial-indent)
2216 ;; force fast exit
2217 (goto-char (point-min)))
2218 (while (not (or found (bobp)))
2219 (setq found
2220 (and
2221 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2222 (or (py-goto-initial-line) t) ; always true -- side effect
2223 (< (current-indentation) initial-indent)
2224 (py-statement-opens-block-p))))
2225 (if found
2226 (progn
2227 (or nomark (push-mark start))
2228 (back-to-indentation))
2229 (goto-char start)
2230 (error "Enclosing block not found"))))
2231
Barry Warsawab0e86c1998-05-19 15:31:46 +00002232(defun py-beginning-of-def-or-class (&optional class count)
2233 "Move point to start of `def' or `class'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002234
2235Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsawab0e86c1998-05-19 15:31:46 +00002236arg, looks for a `class' instead. The docs below assume the `def'
2237case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002238Programmatically, if CLASS is `either', then moves to either `class'
2239or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002240
Barry Warsawab0e86c1998-05-19 15:31:46 +00002241When second optional argument is given programmatically, move to the
2242COUNTth start of `def'.
2243
2244If point is in a `def' statement already, and after the `d', simply
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002245moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002246
Barry Warsawab0e86c1998-05-19 15:31:46 +00002247Otherwise (i.e. when point is not in a `def' statement, or at or
2248before the `d' of a `def' statement), searches for the closest
2249preceding `def' statement, and leaves point at its start. If no such
2250statement can be found, leaves point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002251
Barry Warsawab0e86c1998-05-19 15:31:46 +00002252Returns t iff a `def' statement is found by these rules.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002253
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002254Note that doing this command repeatedly will take you closer to the
2255start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002256
Barry Warsaw7c29b231998-07-07 17:45:38 +00002257To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002258 (interactive "P") ; raw prefix arg
Barry Warsaw6839d3a1998-10-28 00:10:45 +00002259 (setq count (or count 1))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002260 (let ((at-or-before-p (<= (current-column) (current-indentation)))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002261 (start-of-line (goto-char (py-point 'bol)))
2262 (start-of-stmt (goto-char (py-point 'bos)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002263 (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
2264 (class "^[ \t]*class\\>")
2265 (t "^[ \t]*def\\>")))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002266 )
2267 ;; searching backward
2268 (if (and (< 0 count)
2269 (or (/= start-of-stmt start-of-line)
2270 (not at-or-before-p)))
2271 (end-of-line))
2272 ;; search forward
2273 (if (and (> 0 count)
2274 (zerop (current-column))
2275 (looking-at start-re))
2276 (end-of-line))
Barry Warsawddc46961999-07-27 21:40:02 +00002277 (if (re-search-backward start-re nil 'move count)
2278 (goto-char (match-beginning 0)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002279
Barry Warsawab0e86c1998-05-19 15:31:46 +00002280;; Backwards compatibility
2281(defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002282
Barry Warsawab0e86c1998-05-19 15:31:46 +00002283(defun py-end-of-def-or-class (&optional class count)
2284 "Move point beyond end of `def' or `class' body.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002285
Barry Warsawab0e86c1998-05-19 15:31:46 +00002286By default, looks for an appropriate `def'. If you supply a prefix
2287arg, looks for a `class' instead. The docs below assume the `def'
2288case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002289Programmatically, if CLASS is `either', then moves to either `class'
2290or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002291
Barry Warsawab0e86c1998-05-19 15:31:46 +00002292When second optional argument is given programmatically, move to the
2293COUNTth end of `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002294
Barry Warsawab0e86c1998-05-19 15:31:46 +00002295If point is in a `def' statement already, this is the `def' we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002296
Barry Warsawab0e86c1998-05-19 15:31:46 +00002297Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2298contains the statement you started on, that's the `def' we use.
2299
2300Otherwise, we search forward for the closest following `def', and use that.
2301
2302If a `def' can be found by these rules, point is moved to the start of
2303the line immediately following the `def' block, and the position of the
2304start of the `def' is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002305
2306Else point is moved to the end of the buffer, and nil is returned.
2307
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002308Note that doing this command repeatedly will take you closer to the
2309end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002310
Barry Warsaw7c29b231998-07-07 17:45:38 +00002311To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002312 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002313 (if (and count (/= count 1))
2314 (py-beginning-of-def-or-class (- 1 count)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002315 (let ((start (progn (py-goto-initial-line) (point)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002316 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2317 (class "class")
2318 (t "def")))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002319 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002320 ;; move point to start of appropriate def/class
2321 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2322 (setq state 'at-beginning)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002323 ;; else see if py-beginning-of-def-or-class hits container
2324 (if (and (py-beginning-of-def-or-class class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002325 (progn (py-goto-beyond-block)
2326 (> (point) start)))
2327 (setq state 'at-end)
2328 ;; else search forward
2329 (goto-char start)
2330 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2331 (progn (setq state 'at-beginning)
2332 (beginning-of-line)))))
2333 (cond
2334 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2335 ((eq state 'at-end) t)
2336 ((eq state 'not-found) nil)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002337 (t (error "Internal error in `py-end-of-def-or-class'")))))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002338
2339;; Backwards compabitility
Barry Warsaw820273d1998-05-19 15:54:45 +00002340(defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002341
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002342
2343;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002344(defun py-mark-block (&optional extend just-move)
2345 "Mark following block of lines. With prefix arg, mark structure.
2346Easier to use than explain. It sets the region to an `interesting'
2347block of succeeding lines. If point is on a blank line, it goes down to
2348the next non-blank line. That will be the start of the region. The end
2349of the region depends on the kind of line at the start:
2350
2351 - If a comment, the region will include all succeeding comment lines up
2352 to (but not including) the next non-comment line (if any).
2353
2354 - Else if a prefix arg is given, and the line begins one of these
2355 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002356
2357 if elif else try except finally for while def class
2358
Barry Warsaw7ae77681994-12-12 20:38:05 +00002359 the region will be set to the body of the structure, including
2360 following blocks that `belong' to it, but excluding trailing blank
2361 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002362 and all (if any) of the following `except' and `finally' blocks
2363 that belong to the `try' structure will be in the region. Ditto
2364 for if/elif/else, for/else and while/else structures, and (a bit
2365 degenerate, since they're always one-block structures) def and
2366 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002367
2368 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002369 block (see list above), and the block is not a `one-liner' (i.e.,
2370 the statement ends with a colon, not with code), the region will
2371 include all succeeding lines up to (but not including) the next
2372 code statement (if any) that's indented no more than the starting
2373 line, except that trailing blank and comment lines are excluded.
2374 E.g., if the starting line begins a multi-statement `def'
2375 structure, the region will be set to the full function definition,
2376 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002377
2378 - Else the region will include all succeeding lines up to (but not
2379 including) the next blank line, or code or indenting-comment line
2380 indented strictly less than the starting line. Trailing indenting
2381 comment lines are included in this case, but not trailing blank
2382 lines.
2383
2384A msg identifying the location of the mark is displayed in the echo
2385area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2386
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002387If called from a program, optional argument EXTEND plays the role of
2388the prefix arg, and if optional argument JUST-MOVE is not nil, just
2389moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002390 (interactive "P") ; raw prefix arg
2391 (py-goto-initial-line)
2392 ;; skip over blank lines
2393 (while (and
2394 (looking-at "[ \t]*$") ; while blank line
2395 (not (eobp))) ; & somewhere to go
2396 (forward-line 1))
2397 (if (eobp)
2398 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002399 (let ((initial-pos (point))
2400 (initial-indent (current-indentation))
2401 last-pos ; position of last stmt in region
2402 (followers
2403 '((if elif else) (elif elif else) (else)
2404 (try except finally) (except except) (finally)
2405 (for else) (while else)
2406 (def) (class) ) )
2407 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002408
2409 (cond
2410 ;; if comment line, suck up the following comment lines
2411 ((looking-at "[ \t]*#")
2412 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2413 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2414 (setq last-pos (point)))
2415
2416 ;; else if line is a block line and EXTEND given, suck up
2417 ;; the whole structure
2418 ((and extend
2419 (setq first-symbol (py-suck-up-first-keyword) )
2420 (assq first-symbol followers))
2421 (while (and
2422 (or (py-goto-beyond-block) t) ; side effect
2423 (forward-line -1) ; side effect
2424 (setq last-pos (point)) ; side effect
2425 (py-goto-statement-below)
2426 (= (current-indentation) initial-indent)
2427 (setq next-symbol (py-suck-up-first-keyword))
2428 (memq next-symbol (cdr (assq first-symbol followers))))
2429 (setq first-symbol next-symbol)))
2430
2431 ;; else if line *opens* a block, search for next stmt indented <=
2432 ((py-statement-opens-block-p)
2433 (while (and
2434 (setq last-pos (point)) ; always true -- side effect
2435 (py-goto-statement-below)
2436 (> (current-indentation) initial-indent))
2437 nil))
2438
2439 ;; else plain code line; stop at next blank line, or stmt or
2440 ;; indenting comment line indented <
2441 (t
2442 (while (and
2443 (setq last-pos (point)) ; always true -- side effect
2444 (or (py-goto-beyond-final-line) t)
2445 (not (looking-at "[ \t]*$")) ; stop at blank line
2446 (or
2447 (>= (current-indentation) initial-indent)
2448 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2449 nil)))
2450
2451 ;; skip to end of last stmt
2452 (goto-char last-pos)
2453 (py-goto-beyond-final-line)
2454
2455 ;; set mark & display
2456 (if just-move
2457 () ; just return
2458 (push-mark (point) 'no-msg)
2459 (forward-line -1)
2460 (message "Mark set after: %s" (py-suck-up-leading-text))
2461 (goto-char initial-pos))))
2462
Barry Warsaw2518c671997-11-05 00:51:08 +00002463(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002464 "Set region to body of def (or class, with prefix arg) enclosing point.
2465Pushes the current mark, then point, on the mark ring (all language
2466modes do this, but although it's handy it's never documented ...).
2467
2468In most Emacs language modes, this function bears at least a
Barry Warsawab0e86c1998-05-19 15:31:46 +00002469hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2470`\\[py-beginning-of-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002471
2472And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002473Turned out that was more confusing than useful: the `goto start' and
2474`goto end' commands are usually used to search through a file, and
2475people expect them to act a lot like `search backward' and `search
2476forward' string-search commands. But because Python `def' and `class'
2477can nest to arbitrary levels, finding the smallest def containing
2478point cannot be done via a simple backward search: the def containing
2479point may not be the closest preceding def, or even the closest
2480preceding def that's indented less. The fancy algorithm required is
2481appropriate for the usual uses of this `mark' command, but not for the
2482`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002483
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002484So the def marked by this command may not be the one either of the
2485`goto' commands find: If point is on a blank or non-indenting comment
2486line, moves back to start of the closest preceding code statement or
2487indenting comment line. If this is a `def' statement, that's the def
2488we use. Else searches for the smallest enclosing `def' block and uses
2489that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002490
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002491When an enclosing def is found: The mark is left immediately beyond
2492the last line of the def block. Point is left at the start of the
2493def, except that: if the def is preceded by a number of comment lines
2494followed by (at most) one optional blank line, point is left at the
2495start of the comments; else if the def is preceded by a blank line,
2496point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002497
2498The intent is to mark the containing def/class and its associated
2499documentation, to make moving and duplicating functions and classes
2500pleasant."
2501 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002502 (let ((start (point))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002503 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2504 (class "class")
2505 (t "def"))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002506 (push-mark start)
2507 (if (not (py-go-up-tree-to-keyword which))
2508 (progn (goto-char start)
Barry Warsaw7c29b231998-07-07 17:45:38 +00002509 (error "Enclosing %s not found"
2510 (if (eq class 'either)
2511 "def or class"
2512 which)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002513 ;; else enclosing def/class found
2514 (setq start (point))
2515 (py-goto-beyond-block)
2516 (push-mark (point))
2517 (goto-char start)
2518 (if (zerop (forward-line -1)) ; if there is a preceding line
2519 (progn
2520 (if (looking-at "[ \t]*$") ; it's blank
2521 (setq start (point)) ; so reset start point
2522 (goto-char start)) ; else try again
2523 (if (zerop (forward-line -1))
2524 (if (looking-at "[ \t]*#") ; a comment
2525 ;; look back for non-comment line
2526 ;; tricky: note that the regexp matches a blank
2527 ;; line, cuz \n is in the 2nd character class
2528 (and
2529 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2530 (forward-line 1))
2531 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002532 (goto-char start)))))))
2533 (exchange-point-and-mark)
2534 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002535
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002536;; ripped from cc-mode
2537(defun py-forward-into-nomenclature (&optional arg)
2538 "Move forward to end of a nomenclature section or word.
Barry Warsaw41a05c71998-08-10 16:33:12 +00002539With \\[universal-argument] (programmatically, optional argument ARG),
2540do it that many times.
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002541
2542A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2543 (interactive "p")
2544 (let ((case-fold-search nil))
2545 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002546 (re-search-forward
2547 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2548 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002549 (while (and (< arg 0)
2550 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002551 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002552 (point-min) 0))
2553 (forward-char 1)
2554 (setq arg (1+ arg)))))
2555 (py-keep-region-active))
2556
2557(defun py-backward-into-nomenclature (&optional arg)
2558 "Move backward to beginning of a nomenclature section or word.
2559With optional ARG, move that many times. If ARG is negative, move
2560forward.
2561
2562A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2563 (interactive "p")
2564 (py-forward-into-nomenclature (- arg))
2565 (py-keep-region-active))
2566
2567
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002568
Barry Warsaw4f577d22001-04-11 20:23:17 +00002569;; pdbtrack functions
2570(defun py-pdbtrack-toggle-stack-tracking (arg)
2571 (interactive "P")
2572 (if (not (get-buffer-process (current-buffer)))
2573 (error "No process associated with buffer '%s'" (current-buffer)))
2574 ;; missing or 0 is toggle, >0 turn on, <0 turn off
2575 (if (or (not arg)
2576 (zerop (setq arg (prefix-numeric-value arg))))
2577 (setq py-pdbtrack-do-tracking-p (not py-pdbtrack-do-tracking-p))
2578 (setq py-pdbtrack-do-tracking-p (> arg 0)))
2579 (message "%sabled Python's pdbtrack"
2580 (if py-pdbtrack-do-tracking-p "En" "Dis")))
2581
2582(defun turn-on-pdbtrack ()
2583 (interactive)
2584 (py-pdbtrack-toggle-stack-tracking 1))
2585
2586(defun turn-off-pdbtrack ()
2587 (interactive)
2588 (py-pdbtrack-toggle-stack-tracking 0))
2589
2590
2591
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002592;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002593
2594;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002595;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2596;; out of the right places, along with the keys they're on & current
2597;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002598(defun py-dump-help-string (str)
2599 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002600 (let ((locals (buffer-local-variables))
2601 funckind funcname func funcdoc
2602 (start 0) mstart end
2603 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002604 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2605 (setq mstart (match-beginning 0) end (match-end 0)
2606 funckind (substring str (match-beginning 1) (match-end 1))
2607 funcname (substring str (match-beginning 2) (match-end 2))
2608 func (intern funcname))
2609 (princ (substitute-command-keys (substring str start mstart)))
2610 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002611 ((equal funckind "c") ; command
2612 (setq funcdoc (documentation func)
2613 keys (concat
2614 "Key(s): "
2615 (mapconcat 'key-description
2616 (where-is-internal func py-mode-map)
2617 ", "))))
2618 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002619 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002620 keys (if (assq func locals)
2621 (concat
2622 "Local/Global values: "
2623 (prin1-to-string (symbol-value func))
2624 " / "
2625 (prin1-to-string (default-value func)))
2626 (concat
2627 "Value: "
2628 (prin1-to-string (symbol-value func))))))
2629 (t ; unexpected
2630 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002631 (princ (format "\n-> %s:\t%s\t%s\n\n"
2632 (if (equal funckind "c") "Command" "Variable")
2633 funcname keys))
2634 (princ funcdoc)
2635 (terpri)
2636 (setq start end))
2637 (princ (substitute-command-keys (substring str start))))
2638 (print-help-return-message)))
2639
2640(defun py-describe-mode ()
2641 "Dump long form of Python-mode docs."
2642 (interactive)
2643 (py-dump-help-string "Major mode for editing Python files.
2644Knows about Python indentation, tokens, comments and continuation lines.
2645Paragraphs are separated by blank lines only.
2646
2647Major sections below begin with the string `@'; specific function and
2648variable docs begin with `->'.
2649
2650@EXECUTING PYTHON CODE
2651
Barry Warsaw820273d1998-05-19 15:54:45 +00002652\\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002653\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2654\\[py-execute-region]\tsends the current region
Barry Warsaw820273d1998-05-19 15:54:45 +00002655\\[py-execute-def-or-class]\tsends the current function or class definition
2656\\[py-execute-string]\tsends an arbitrary string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002657\\[py-shell]\tstarts a Python interpreter window; this will be used by
Barry Warsaw820273d1998-05-19 15:54:45 +00002658\tsubsequent Python execution commands
2659%c:py-execute-import-or-reload
Barry Warsaw7ae77681994-12-12 20:38:05 +00002660%c:py-execute-buffer
2661%c:py-execute-region
Barry Warsaw820273d1998-05-19 15:54:45 +00002662%c:py-execute-def-or-class
2663%c:py-execute-string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002664%c:py-shell
2665
2666@VARIABLES
2667
2668py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002669py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002670
2671py-python-command\tshell command to invoke Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002672py-temp-directory\tdirectory used for temp files (if needed)
2673
2674py-beep-if-tab-change\tring the bell if tab-width is changed
2675%v:py-indent-offset
2676%v:py-block-comment-prefix
2677%v:py-python-command
Barry Warsaw7ae77681994-12-12 20:38:05 +00002678%v:py-temp-directory
2679%v:py-beep-if-tab-change
2680
2681@KINDS OF LINES
2682
2683Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002684preceding line ends with a backslash that's not part of a comment, or
2685the paren/bracket/brace nesting level at the start of the line is
2686non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002687
2688An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002689possibly blanks or tabs), a `comment line' (leftmost non-blank
2690character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002691
2692Comment Lines
2693
2694Although all comment lines are treated alike by Python, Python mode
2695recognizes two kinds that act differently with respect to indentation.
2696
2697An `indenting comment line' is a comment line with a blank, tab or
2698nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002699treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002700indenting comment line will be indented like the comment line. All
2701other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002702following the initial `#') are `non-indenting comment lines', and
2703their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002704
2705Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002706whenever possible. Non-indenting comment lines are useful in cases
2707like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002708
2709\ta = b # a very wordy single-line comment that ends up being
2710\t #... continued onto another line
2711
2712\tif a == b:
2713##\t\tprint 'panic!' # old code we've `commented out'
2714\t\treturn a
2715
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002716Since the `#...' and `##' comment lines have a non-whitespace
2717character following the initial `#', Python mode ignores them when
2718computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002719
2720Continuation Lines and Statements
2721
2722The Python-mode commands generally work on statements instead of on
2723individual lines, where a `statement' is a comment or blank line, or a
2724code line and all of its following continuation lines (if any)
2725considered as a single logical unit. The commands in this mode
2726generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002727statement containing point, even if point happens to be in the middle
2728of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002729
2730
2731@INDENTATION
2732
2733Primarily for entering new code:
2734\t\\[indent-for-tab-command]\t indent line appropriately
2735\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002736\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002737
2738Primarily for reindenting existing code:
2739\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2740\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2741
2742\t\\[py-indent-region]\t reindent region to match its context
2743\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2744\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2745
2746Unlike most programming languages, Python uses indentation, and only
2747indentation, to specify block structure. Hence the indentation supplied
2748automatically by Python-mode is just an educated guess: only you know
2749the block structure you intend, so only you can supply correct
2750indentation.
2751
2752The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2753the indentation of preceding statements. E.g., assuming
2754py-indent-offset is 4, after you enter
2755\tif a > 0: \\[py-newline-and-indent]
2756the cursor will be moved to the position of the `_' (_ is not a
2757character in the file, it's just used here to indicate the location of
2758the cursor):
2759\tif a > 0:
2760\t _
2761If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2762to
2763\tif a > 0:
2764\t c = d
2765\t _
2766Python-mode cannot know whether that's what you intended, or whether
2767\tif a > 0:
2768\t c = d
2769\t_
2770was your intent. In general, Python-mode either reproduces the
2771indentation of the (closest code or indenting-comment) preceding
2772statement, or adds an extra py-indent-offset blanks if the preceding
2773statement has `:' as its last significant (non-whitespace and non-
2774comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002775\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002776
2777Continuation lines are given extra indentation. If you don't like the
2778suggested indentation, change it to something you do like, and Python-
2779mode will strive to indent later lines of the statement in the same way.
2780
2781If a line is a continuation line by virtue of being in an unclosed
2782paren/bracket/brace structure (`list', for short), the suggested
2783indentation depends on whether the current line contains the first item
2784in the list. If it does, it's indented py-indent-offset columns beyond
2785the indentation of the line containing the open bracket. If you don't
2786like that, change it by hand. The remaining items in the list will mimic
2787whatever indentation you give to the first item.
2788
2789If a line is a continuation line because the line preceding it ends with
2790a backslash, the third and following lines of the statement inherit their
2791indentation from the line preceding them. The indentation of the second
2792line in the statement depends on the form of the first (base) line: if
2793the base line is an assignment statement with anything more interesting
2794than the backslash following the leftmost assigning `=', the second line
2795is indented two columns beyond that `='. Else it's indented to two
2796columns beyond the leftmost solid chunk of non-whitespace characters on
2797the base line.
2798
2799Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2800repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2801structure you intend.
2802%c:indent-for-tab-command
2803%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002804%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002805
2806
2807The next function may be handy when editing code you didn't write:
2808%c:py-guess-indent-offset
2809
2810
2811The remaining `indent' functions apply to a region of Python code. They
2812assume the block structure (equals indentation, in Python) of the region
2813is correct, and alter the indentation in various ways while preserving
2814the block structure:
2815%c:py-indent-region
2816%c:py-shift-region-left
2817%c:py-shift-region-right
2818
2819@MARKING & MANIPULATING REGIONS OF CODE
2820
2821\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002822\\[py-mark-def-or-class]\t mark smallest enclosing def
2823\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002824\\[comment-region]\t comment out region of code
2825\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002826%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002827%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002828%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002829
2830@MOVING POINT
2831
2832\\[py-previous-statement]\t move to statement preceding point
2833\\[py-next-statement]\t move to statement following point
2834\\[py-goto-block-up]\t move up to start of current block
Barry Warsawab0e86c1998-05-19 15:31:46 +00002835\\[py-beginning-of-def-or-class]\t move to start of def
2836\\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
2837\\[py-end-of-def-or-class]\t move to end of def
2838\\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002839
2840The first two move to one statement beyond the statement that contains
2841point. A numeric prefix argument tells them to move that many
2842statements instead. Blank lines, comment lines, and continuation lines
2843do not count as `statements' for these commands. So, e.g., you can go
2844to the first code statement in a file by entering
2845\t\\[beginning-of-buffer]\t to move to the top of the file
2846\t\\[py-next-statement]\t to skip over initial comments and blank lines
2847Or do `\\[py-previous-statement]' with a huge prefix argument.
2848%c:py-previous-statement
2849%c:py-next-statement
2850%c:py-goto-block-up
Barry Warsawab0e86c1998-05-19 15:31:46 +00002851%c:py-beginning-of-def-or-class
2852%c:py-end-of-def-or-class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002853
2854@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2855
2856`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2857
2858`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2859overall class and def structure of a module.
2860
2861`\\[back-to-indentation]' moves point to a line's first non-blank character.
2862
2863`\\[indent-relative]' is handy for creating odd indentation.
2864
2865@OTHER EMACS HINTS
2866
2867If you don't like the default value of a variable, change its value to
2868whatever you do like by putting a `setq' line in your .emacs file.
2869E.g., to set the indentation increment to 4, put this line in your
2870.emacs:
2871\t(setq py-indent-offset 4)
2872To see the value of a variable, do `\\[describe-variable]' and enter the variable
2873name at the prompt.
2874
2875When entering a key sequence like `C-c C-n', it is not necessary to
2876release the CONTROL key after doing the `C-c' part -- it suffices to
2877press the CONTROL key, press and release `c' (while still holding down
2878CONTROL), press and release `n' (while still holding down CONTROL), &
2879then release CONTROL.
2880
2881Entering Python mode calls with no arguments the value of the variable
2882`python-mode-hook', if that value exists and is not nil; for backward
2883compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2884the Elisp manual for details.
2885
2886Obscure: When python-mode is first loaded, it looks for all bindings
2887to newline-and-indent in the global keymap, and shadows them with
2888local bindings to py-newline-and-indent."))
2889
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002890
2891;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002892(defvar py-parse-state-re
2893 (concat
2894 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2895 "\\|"
2896 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002897
Barry Warsaw7ae77681994-12-12 20:38:05 +00002898(defun py-parse-state ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002899 "Return the parse state at point (see `parse-partial-sexp' docs)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002900 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002901 (let ((here (point))
Barry Warsaw68d486c2001-02-24 00:09:17 +00002902 in-listcomp pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002903 (while (not done)
2904 ;; back up to the first preceding line (if any; else start of
2905 ;; buffer) that begins with a popular Python keyword, or a
2906 ;; non- whitespace and non-comment character. These are good
2907 ;; places to start parsing to see whether where we started is
2908 ;; at a non-zero nesting level. It may be slow for people who
2909 ;; write huge code blocks or huge lists ... tough beans.
2910 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw68d486c2001-02-24 00:09:17 +00002911 ;; Watch out for landing inside a list comprehension
2912 (save-excursion
2913 (if (and (looking-at "[ \t]*\\<\\(if\\|for\\)\\>")
2914 (py-safe (progn (up-list -1) t))
2915 (eq (char-after) ?\[))
2916 (setq in-listcomp (point))
2917 (setq in-listcomp nil)))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002918 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002919 ;; In XEmacs, we have a much better way to test for whether
2920 ;; we're in a triple-quoted string or not. Emacs does not
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002921 ;; have this built-in function, which is its loss because
Barry Warsawf64b4051998-02-12 16:52:14 +00002922 ;; without scanning from the beginning of the buffer, there's
2923 ;; no accurate way to determine this otherwise.
2924 (if (not (fboundp 'buffer-syntactic-context))
2925 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002926 (progn
2927 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002928 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002929 (setq done (or (not (nth 3 pps))
Barry Warsaw53db8591999-05-24 19:57:32 +00002930 (bobp)))
2931 ;; Just go ahead and short circuit the test back to the
2932 ;; beginning of the buffer. This will be slow, but not
2933 ;; nearly as slow as looping through many
2934 ;; re-search-backwards.
2935 (if (not done)
2936 (goto-char (point-min))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002937 ;; XEmacs
2938 (setq done (or (not (buffer-syntactic-context))
2939 (bobp)))
Barry Warsaw68d486c2001-02-24 00:09:17 +00002940 (when in-listcomp
2941 (goto-char in-listcomp)
2942 (setq done nil))
Barry Warsawf64b4051998-02-12 16:52:14 +00002943 (when done
2944 (setq pps (parse-partial-sexp (point) here)))
2945 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002946 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002947
Barry Warsaw7ae77681994-12-12 20:38:05 +00002948(defun py-nesting-level ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002949 "Return the buffer position of the last unclosed enclosing list.
2950If nesting level is zero, return nil."
Barry Warsawf64b4051998-02-12 16:52:14 +00002951 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002952 (if (zerop (car status))
2953 nil ; not in a nest
2954 (car (cdr status))))) ; char# of open bracket
2955
Barry Warsaw7ae77681994-12-12 20:38:05 +00002956(defun py-backslash-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002957 "Return t iff preceding line ends with backslash that is not in a comment."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002958 (save-excursion
2959 (beginning-of-line)
2960 (and
2961 ;; use a cheap test first to avoid the regexp if possible
2962 ;; use 'eq' because char-after may return nil
2963 (eq (char-after (- (point) 2)) ?\\ )
2964 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002965 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002966 (looking-at py-continued-re))))
2967
Barry Warsaw7ae77681994-12-12 20:38:05 +00002968(defun py-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002969 "Return t iff current line is a continuation line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002970 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002971 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002972 (or (py-backslash-continuation-line-p)
2973 (py-nesting-level))))
2974
Barry Warsaw9c1696c1998-12-15 04:36:22 +00002975(defun py-goto-beginning-of-tqs (delim)
2976 "Go to the beginning of the triple quoted string we find ourselves in.
2977DELIM is the TQS string delimiter character we're searching backwards
2978for."
Barry Warsaw3c34bb32000-10-27 05:00:25 +00002979 (let ((skip (and delim (make-string 1 delim)))
2980 (continue t))
Barry Warsaw9c1696c1998-12-15 04:36:22 +00002981 (when skip
2982 (save-excursion
Barry Warsaw3c34bb32000-10-27 05:00:25 +00002983 (while continue
2984 (py-safe (search-backward skip))
2985 (setq continue (and (not (bobp))
2986 (= (char-before) ?\\))))
2987 (if (and (= (char-before) delim)
2988 (= (char-before (1- (point))) delim))
Barry Warsaw9c1696c1998-12-15 04:36:22 +00002989 (setq skip (make-string 3 delim))))
2990 ;; we're looking at a triple-quoted string
2991 (py-safe (search-backward skip)))))
2992
Barry Warsaw7ae77681994-12-12 20:38:05 +00002993(defun py-goto-initial-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002994 "Go to the initial line of the current statement.
2995Usually this is the line we're on, but if we're on the 2nd or
2996following lines of a continuation block, we need to go up to the first
2997line of the block."
2998 ;; Tricky: We want to avoid quadratic-time behavior for long
2999 ;; continued blocks, whether of the backslash or open-bracket
3000 ;; varieties, or a mix of the two. The following manages to do that
3001 ;; in the usual cases.
3002 ;;
3003 ;; Also, if we're sitting inside a triple quoted string, this will
3004 ;; drop us at the line that begins the string.
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00003005 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00003006 (while (py-continuation-line-p)
3007 (beginning-of-line)
3008 (if (py-backslash-continuation-line-p)
3009 (while (py-backslash-continuation-line-p)
3010 (forward-line -1))
3011 ;; else zip out of nested brackets/braces/parens
3012 (while (setq open-bracket-pos (py-nesting-level))
3013 (goto-char open-bracket-pos)))))
3014 (beginning-of-line))
3015
Barry Warsaw7ae77681994-12-12 20:38:05 +00003016(defun py-goto-beyond-final-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003017 "Go to the point just beyond the fine line of the current statement.
3018Usually this is the start of the next line, but if this is a
3019multi-line statement we need to skip over the continuation lines."
3020 ;; Tricky: Again we need to be clever to avoid quadratic time
3021 ;; behavior.
3022 ;;
3023 ;; XXX: Not quite the right solution, but deals with multi-line doc
3024 ;; strings
Barry Warsaw751f4931998-05-19 16:06:21 +00003025 (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
3026 (goto-char (match-end 0)))
3027 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +00003028 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003029 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00003030 (while (and (py-continuation-line-p)
3031 (not (eobp)))
3032 ;; skip over the backslash flavor
3033 (while (and (py-backslash-continuation-line-p)
3034 (not (eobp)))
3035 (forward-line 1))
3036 ;; if in nest, zip to the end of the nest
3037 (setq state (py-parse-state))
3038 (if (and (not (zerop (car state)))
3039 (not (eobp)))
3040 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00003041 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00003042 (forward-line 1))))))
3043
Barry Warsaw7ae77681994-12-12 20:38:05 +00003044(defun py-statement-opens-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003045 "Return t iff the current statement opens a block.
3046I.e., iff it ends with a colon that is not in a comment. Point should
3047be at the start of a statement."
Barry Warsaw7ae77681994-12-12 20:38:05 +00003048 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003049 (let ((start (point))
3050 (finish (progn (py-goto-beyond-final-line) (1- (point))))
3051 (searching t)
3052 (answer nil)
3053 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00003054 (goto-char start)
3055 (while searching
3056 ;; look for a colon with nothing after it except whitespace, and
3057 ;; maybe a comment
3058 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
3059 finish t)
3060 (if (eq (point) finish) ; note: no `else' clause; just
3061 ; keep searching if we're not at
3062 ; the end yet
3063 ;; sure looks like it opens a block -- but it might
3064 ;; be in a comment
3065 (progn
3066 (setq searching nil) ; search is done either way
3067 (setq state (parse-partial-sexp start
3068 (match-beginning 0)))
3069 (setq answer (not (nth 4 state)))))
3070 ;; search failed: couldn't find another interesting colon
3071 (setq searching nil)))
3072 answer)))
3073
Barry Warsawf831d811996-07-31 20:42:59 +00003074(defun py-statement-closes-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003075 "Return t iff the current statement closes a block.
3076I.e., if the line starts with `return', `raise', `break', `continue',
3077and `pass'. This doesn't catch embedded statements."
Barry Warsawf831d811996-07-31 20:42:59 +00003078 (let ((here (point)))
Barry Warsawa8f99ba1999-05-24 18:37:57 +00003079 (py-goto-initial-line)
Barry Warsawc0d2d511999-06-03 22:18:59 +00003080 (back-to-indentation)
Barry Warsawf831d811996-07-31 20:42:59 +00003081 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00003082 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00003083 (goto-char here))))
3084
Barry Warsaw7ae77681994-12-12 20:38:05 +00003085(defun py-goto-beyond-block ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003086 "Go to point just beyond the final line of block begun by the current line.
3087This is the same as where `py-goto-beyond-final-line' goes unless
3088we're on colon line, in which case we go to the end of the block.
3089Assumes point is at the beginning of the line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00003090 (if (py-statement-opens-block-p)
3091 (py-mark-block nil 'just-move)
3092 (py-goto-beyond-final-line)))
3093
Barry Warsaw7ae77681994-12-12 20:38:05 +00003094(defun py-goto-statement-at-or-above ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003095 "Go to the start of the first statement at or preceding point.
3096Return t if there is such a statement, otherwise nil. `Statement'
3097does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00003098 (py-goto-initial-line)
3099 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003100 ;; skip back over blank & comment lines
3101 ;; note: will skip a blank or comment line that happens to be
3102 ;; a continuation line too
3103 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
3104 (progn (py-goto-initial-line) t)
3105 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00003106 t))
3107
Barry Warsaw7ae77681994-12-12 20:38:05 +00003108(defun py-goto-statement-below ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003109 "Go to start of the first statement following the statement containing point.
3110Return t if there is such a statement, otherwise nil. `Statement'
3111does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00003112 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003113 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00003114 (py-goto-beyond-final-line)
3115 (while (and
3116 (looking-at py-blank-or-comment-re)
3117 (not (eobp)))
3118 (forward-line 1))
3119 (if (eobp)
3120 (progn (goto-char start) nil)
3121 t)))
3122
Barry Warsaw7ae77681994-12-12 20:38:05 +00003123(defun py-go-up-tree-to-keyword (key)
Barry Warsaw41a05c71998-08-10 16:33:12 +00003124 "Go to begining of statement starting with KEY, at or preceding point.
3125
3126KEY is a regular expression describing a Python keyword. Skip blank
3127lines and non-indenting comments. If the statement found starts with
3128KEY, then stop, otherwise go back to first enclosing block starting
3129with KEY. If successful, leave point at the start of the KEY line and
3130return t. Otherwise, leav point at an undefined place and return nil."
Barry Warsaw7ae77681994-12-12 20:38:05 +00003131 ;; skip blanks and non-indenting #
3132 (py-goto-initial-line)
3133 (while (and
3134 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
3135 (zerop (forward-line -1))) ; go back
3136 nil)
3137 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003138 (let* ((re (concat "[ \t]*" key "\\b"))
3139 (case-fold-search nil) ; let* so looking-at sees this
3140 (found (looking-at re))
3141 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00003142 (while (not (or found dead))
3143 (condition-case nil ; in case no enclosing block
3144 (py-goto-block-up 'no-mark)
3145 (error (setq dead t)))
3146 (or dead (setq found (looking-at re))))
3147 (beginning-of-line)
3148 found))
3149
Barry Warsaw7ae77681994-12-12 20:38:05 +00003150(defun py-suck-up-leading-text ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003151 "Return string in buffer from start of indentation to end of line.
3152Prefix with \"...\" if leading whitespace was skipped."
Barry Warsaw7ae77681994-12-12 20:38:05 +00003153 (save-excursion
3154 (back-to-indentation)
3155 (concat
3156 (if (bolp) "" "...")
3157 (buffer-substring (point) (progn (end-of-line) (point))))))
3158
Barry Warsaw7ae77681994-12-12 20:38:05 +00003159(defun py-suck-up-first-keyword ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003160 "Return first keyword on the line as a Lisp symbol.
3161`Keyword' is defined (essentially) as the regular expression
3162([a-z]+). Returns nil if none was found."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003163 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00003164 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
3165 (intern (buffer-substring (match-beginning 1) (match-end 1)))
3166 nil)))
3167
Barry Warsawb3e81d51996-09-04 15:12:42 +00003168(defun py-current-defun ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003169 "Python value for `add-log-current-defun-function'.
3170This tells add-log.el how to find the current function/method/variable."
Barry Warsawb3e81d51996-09-04 15:12:42 +00003171 (save-excursion
3172 (if (re-search-backward py-defun-start-re nil t)
3173 (or (match-string 3)
3174 (let ((method (match-string 2)))
3175 (if (and (not (zerop (length (match-string 1))))
3176 (re-search-backward py-class-start-re nil t))
3177 (concat (match-string 1) "." method)
3178 method)))
3179 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003180
3181
Barry Warsawfec75d61995-07-05 23:26:15 +00003182(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00003183 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003184
Barry Warsaw850437a1995-03-08 21:50:28 +00003185(defun py-version ()
3186 "Echo the current version of `python-mode' in the minibuffer."
3187 (interactive)
3188 (message "Using `python-mode' version %s" py-version)
3189 (py-keep-region-active))
3190
3191;; only works under Emacs 19
3192;(eval-when-compile
3193; (require 'reporter))
3194
3195(defun py-submit-bug-report (enhancement-p)
3196 "Submit via mail a bug report on `python-mode'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00003197With \\[universal-argument] (programmatically, argument ENHANCEMENT-P
3198non-nil) just submit an enhancement request."
Barry Warsaw850437a1995-03-08 21:50:28 +00003199 (interactive
3200 (list (not (y-or-n-p
Barry Warsaw41a05c71998-08-10 16:33:12 +00003201 "Is this a bug report (hit `n' to send other comments)? "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00003202 (let ((reporter-prompt-for-summary-p (if enhancement-p
3203 "(Very) brief summary: "
3204 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00003205 (require 'reporter)
3206 (reporter-submit-bug-report
3207 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00003208 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00003209 ;; varlist
3210 (if enhancement-p nil
3211 '(py-python-command
3212 py-indent-offset
3213 py-block-comment-prefix
Barry Warsaw850437a1995-03-08 21:50:28 +00003214 py-temp-directory
3215 py-beep-if-tab-change))
3216 nil ;pre-hooks
3217 nil ;post-hooks
3218 "Dear Barry,") ;salutation
3219 (if enhancement-p nil
3220 (set-mark (point))
3221 (insert
3222"Please replace this text with a sufficiently large code sample\n\
3223and an exact recipe so that I can reproduce your problem. Failure\n\
3224to do so may mean a greater delay in fixing your bug.\n\n")
3225 (exchange-point-and-mark)
3226 (py-keep-region-active))))
3227
3228
Barry Warsaw47384781997-11-26 05:27:45 +00003229(defun py-kill-emacs-hook ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003230 "Delete files in `py-file-queue'.
3231These are Python temporary files awaiting execution."
Barry Warsaw47384781997-11-26 05:27:45 +00003232 (mapcar #'(lambda (filename)
3233 (py-safe (delete-file filename)))
3234 py-file-queue))
3235
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003236;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00003237(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw4f577d22001-04-11 20:23:17 +00003238(add-hook 'comint-output-filter-functions 'py-pdbtrack-track-stack-file)
3239
3240;; Add a designator to the minor mode strings
3241(or (assq 'py-pdbtrack-minor-mode-string minor-mode-alist)
3242 (push '(py-pdbtrack-is-tracking-p py-pdbtrack-minor-mode-string)
3243 minor-mode-alist))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003244
3245
3246
3247(provide 'python-mode)
3248;;; python-mode.el ends here