blob: b666c067a224203db3c95673796d8520f2ac3460 [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 Warsawf64b4051998-02-12 16:52:14 +00005;; Author: 1995-1998 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 Warsaw5204b4a1998-04-02 19:27:18 +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
25;; and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000026
Barry Warsaw37231521997-12-11 17:23:13 +000027;; This version of python-mode.el is no longer compatible with Emacs
Barry Warsawf7039e21998-08-20 22:10:46 +000028;; 18. I am striving to maintain compatibility with the X/Emacs 19
29;; lineage but as time goes on that becomes more and more difficult.
30;; I current recommend that you upgrade to the latest stable released
31;; version of your favorite branch: Emacs 20.2 or better, or XEmacs
32;; 20.4 or better (Emacs 20.3 and XEmacs 21.0 are in beta testing as
33;; of this writing 20-Aug-1998 but both appear to work fine with this
34;; version of python-mode.el). Even Windows users should be using at
35;; least NTEmacs 20.2, and XEmacs 21.0 will work very nicely on
36;; Windows when it is released.
Barry Warsaw37231521997-12-11 17:23:13 +000037
38;; FOR MORE INFORMATION:
39
Barry Warsawf7039e21998-08-20 22:10:46 +000040;; For more information on installing python-mode.el, especially with
41;; respect to compatibility information, please see
42;;
43;; http://www.python.org/emacs/python-mode/
44;;
45;; This site also contains links to other packages that you might find
46;; useful, such as pdb interfaces, OO-Browser links, etc.
Barry Warsaw37231521997-12-11 17:23:13 +000047
48;; BUG REPORTING:
Barry Warsaw7ae77681994-12-12 20:38:05 +000049
Barry Warsawaffc0ca1997-11-03 16:59:38 +000050;; To submit bug reports, use C-c C-b. Please include a complete, but
51;; concise code sample and a recipe for reproducing the bug. Send
52;; suggestions and other comments to python-mode@python.org.
53
54;; When in a Python mode buffer, do a C-h m for more help. It's
Barry Warsaw37231521997-12-11 17:23:13 +000055;; doubtful that a texinfo manual would be very useful, but if you
56;; want to contribute one, I'll certainly accept it!
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000057
Barry Warsaw37231521997-12-11 17:23:13 +000058;; TO DO LIST:
59
60;; - Better integration with pdb.py and gud-mode for debugging.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000061;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw9e277db1996-07-31 22:33:40 +000062;; - have py-execute-region on indented code act as if the region is
Barry Warsaw37231521997-12-11 17:23:13 +000063;; left justified. Avoids syntax errors.
64;; - add a py-goto-block-down, bound to C-c C-d
Barry Warsaw7ae77681994-12-12 20:38:05 +000065
Barry Warsaw7b0f5681995-03-08 21:33:04 +000066;;; Code:
67
Barry Warsaw6dfbe5d1998-08-20 21:51:27 +000068(require 'comint)
Barry Warsawc72c11c1997-08-09 06:42:08 +000069(require 'custom)
Barry Warsaw8529ebb1997-12-01 20:03:12 +000070(eval-when-compile
Barry Warsaw673d05f1997-12-02 21:51:57 +000071 (require 'cl)
Barry Warsawb6c1f1f1998-03-19 22:33:06 +000072 (if (not (and (condition-case nil
73 (require 'custom)
74 (error nil))
75 ;; Stock Emacs 19.34 has a broken/old Custom library
76 ;; that does more harm than good. Fortunately, it is
77 ;; missing defcustom
78 (fboundp 'defcustom)))
Barry Warsaw673d05f1997-12-02 21:51:57 +000079 (error "STOP! STOP! STOP! STOP!
80
81The Custom library was not found or is out of date. A more current
82version is required. Please download and install the latest version
83of the Custom library from:
84
85 <http://www.dina.kvl.dk/~abraham/custom/>
86
87See the Python Mode home page for details:
88
89 <http://www.python.org/ftp/emacs/>
90")))
91
Barry Warsawc72c11c1997-08-09 06:42:08 +000092
Barry Warsaw7b0f5681995-03-08 21:33:04 +000093
94;; user definable variables
95;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +000096
Barry Warsawc72c11c1997-08-09 06:42:08 +000097(defgroup python nil
98 "Support for the Python programming language, <http://www.python.org/>"
99 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000100
Barry Warsawc72c11c1997-08-09 06:42:08 +0000101(defcustom py-python-command "python"
102 "*Shell command used to start Python interpreter."
103 :type 'string
104 :group 'python)
105
Barry Warsawa2398801998-04-09 23:28:20 +0000106(defcustom py-jpython-command "jpython"
107 "*Shell command used to start the JPython interpreter."
108 :type 'string
109 :group 'python)
110
Barry Warsaw8f972b71998-02-05 20:45:49 +0000111(defcustom py-python-command-args '("-i")
112 "*List of string arguments to be used when starting a Python shell."
113 :type '(repeat string)
114 :group 'python)
115
Barry Warsawa2398801998-04-09 23:28:20 +0000116(defcustom py-jpython-command-args '("-i")
117 "*List of string arguments to be used when starting a JPython shell."
118 :type '(repeat string)
119 :group 'python)
120
Barry Warsawc72c11c1997-08-09 06:42:08 +0000121(defcustom py-indent-offset 4
Barry Warsaw41a05c71998-08-10 16:33:12 +0000122 "*Amount of offset per level of indentation.
123`\\[py-guess-indent-offset]' can usually guess a good value when
124you're editing someone else's Python code."
Barry Warsawc72c11c1997-08-09 06:42:08 +0000125 :type 'integer
126 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000127
Barry Warsaw742a5111998-03-13 17:29:15 +0000128(defcustom py-smart-indentation t
129 "*Should `python-mode' try to automagically set some indentation variables?
130When this variable is non-nil, two things happen when a buffer is set
131to `python-mode':
132
133 1. `py-indent-offset' is guess from existing code in the buffer.
Barry Warsaw639eea61998-03-16 18:12:13 +0000134 Only guessed values between 2 and 8 are considered. If a valid
Barry Warsaw742a5111998-03-13 17:29:15 +0000135 guess can't be made (perhaps because you are visiting a new
Barry Warsaw639eea61998-03-16 18:12:13 +0000136 file), then the value in `py-indent-offset' is used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000137
Barry Warsaw639eea61998-03-16 18:12:13 +0000138 2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
139 equal `tab-width' (`indent-tabs-mode' is never turned on by
140 Python mode). This means that for newly written code, tabs are
141 only inserted in indentation if one tab is one indentation
142 level, otherwise only spaces are used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000143
Barry Warsaw8046bef1998-03-13 20:04:52 +0000144Note that both these settings occur *after* `python-mode-hook' is run,
145so if you want to defeat the automagic configuration, you must also
146set `py-smart-indentation' to nil in your `python-mode-hook'."
Barry Warsaw742a5111998-03-13 17:29:15 +0000147 :type 'boolean
148 :group 'python)
149
Barry Warsawc72c11c1997-08-09 06:42:08 +0000150(defcustom py-align-multiline-strings-p t
151 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000152When this flag is non-nil, continuation lines are lined up under the
153preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000154lines are aligned to column zero."
155 :type '(choice (const :tag "Align under preceding line" t)
156 (const :tag "Align to column zero" nil))
157 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000158
Barry Warsawc72c11c1997-08-09 06:42:08 +0000159(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000160 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000161This should follow the convention for non-indenting comment lines so
162that the indentation commands won't get confused (i.e., the string
163should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000164`...' is arbitrary)."
165 :type 'string
166 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000167
Barry Warsawc72c11c1997-08-09 06:42:08 +0000168(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000169 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000170
Barry Warsaw6d627751996-03-06 18:41:38 +0000171When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000172if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000173
174When t, lines that begin with a single `#' are a hint to subsequent
175line indentation. If the previous line is such a comment line (as
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000176opposed to one that starts with `py-block-comment-prefix'), then its
Barry Warsaw6d627751996-03-06 18:41:38 +0000177indentation is used as a hint for this line's indentation. Lines that
178begin with `py-block-comment-prefix' are ignored for indentation
179purposes.
180
181When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000182indentation hints, unless the comment character is in column zero."
183 :type '(choice
184 (const :tag "Skip all comment lines (fast)" nil)
185 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000186 (const :tag "Single # `sets' indentation except at column zero"
187 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000188 )
189 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000190
Barry Warsaw516b6201997-08-09 06:43:20 +0000191(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000192 (let ((ok '(lambda (x)
193 (and x
194 (setq x (expand-file-name x)) ; always true
195 (file-directory-p x)
196 (file-writable-p x)
197 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000198 (or (funcall ok (getenv "TMPDIR"))
199 (funcall ok "/usr/tmp")
200 (funcall ok "/tmp")
201 (funcall ok ".")
202 (error
Barry Warsaw6c6db0a1998-02-25 16:33:56 +0000203 "Couldn't find a usable temp directory -- set `py-temp-directory'")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000204 "*Directory used for temp files created by a *Python* process.
205By default, the first directory from this list that exists and that you
206can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000207/usr/tmp, /tmp, or the current directory."
208 :type 'string
209 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000210
Barry Warsaw516b6201997-08-09 06:43:20 +0000211(defcustom py-beep-if-tab-change t
Barry Warsaw41a05c71998-08-10 16:33:12 +0000212 "*Ring the bell if `tab-width' is changed.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000213If a comment of the form
214
215 \t# vi:set tabsize=<number>:
216
217is found before the first code line when the file is entered, and the
218current value of (the general Emacs variable) `tab-width' does not
219equal <number>, `tab-width' is set to <number>, a message saying so is
220displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000221the Emacs bell is also rung as a warning."
222 :type 'boolean
223 :group 'python)
224
Barry Warsaw9981d221997-12-03 05:25:48 +0000225(defcustom py-jump-on-exception t
226 "*Jump to innermost exception frame in *Python Output* buffer.
Barry Warsaw12c92941998-08-10 21:44:37 +0000227When this variable is non-nil and an exception occurs when running
Barry Warsaw9981d221997-12-03 05:25:48 +0000228Python code synchronously in a subprocess, jump immediately to the
Barry Warsaw12c92941998-08-10 21:44:37 +0000229source code of the innermost traceback frame."
Barry Warsaw3bfed5b1998-05-19 16:25:04 +0000230 :type 'boolean
231 :group 'python)
232
233(defcustom py-ask-about-save t
234 "If not nil, ask about which buffers to save before executing some code.
235Otherwise, all modified buffers are saved without asking."
236 :type 'boolean
237 :group 'python)
Barry Warsaw9981d221997-12-03 05:25:48 +0000238
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000239(defcustom py-backspace-function 'backward-delete-char-untabify
240 "*Function called by `py-electric-backspace' when deleting backwards."
241 :type 'function
242 :group 'python)
243
244(defcustom py-delete-function 'delete-char
245 "*Function called by `py-electric-delete' when deleting forwards."
246 :type 'function
247 :group 'python)
248
Barry Warsawc0ecb531998-01-20 21:43:34 +0000249;; Not customizable
250(defvar py-master-file nil
251 "If non-nil, execute the named file instead of the buffer's file.
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000252The intent is to allow you to set this variable in the file's local
Barry Warsawc0ecb531998-01-20 21:43:34 +0000253variable section, e.g.:
254
255 # Local Variables:
256 # py-master-file: \"master.py\"
257 # End:
258
Barry Warsaw41a05c71998-08-10 16:33:12 +0000259so that typing \\[py-execute-buffer] in that buffer executes the named
260master file instead of the buffer's file. Note that if the file name
261has a relative path, the value of `default-directory' for the buffer
262is prepended to come up with a file name.")
Barry Warsawc0ecb531998-01-20 21:43:34 +0000263(make-variable-buffer-local 'py-master-file)
264
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000265
Barry Warsawc72c11c1997-08-09 06:42:08 +0000266
267;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
268;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
269
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000270(defconst py-emacs-features
271 (let (features)
272 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
273 ;; the same string.
274 (let ((tmp1 (make-temp-name ""))
275 (tmp2 (make-temp-name "")))
276 (if (string-equal tmp1 tmp2)
277 (push 'broken-temp-names features)))
278 ;; return the features
279 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000280 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000281There are many flavors of Emacs out there, with different levels of
282support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000283
Barry Warsawfb07f401997-02-24 03:37:22 +0000284(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000285 (let ((kw1 (mapconcat 'identity
286 '("and" "assert" "break" "class"
287 "continue" "def" "del" "elif"
288 "else" "except" "exec" "for"
289 "from" "global" "if" "import"
290 "in" "is" "lambda" "not"
291 "or" "pass" "print" "raise"
292 "return" "while"
293 )
294 "\\|"))
295 (kw2 (mapconcat 'identity
296 '("else:" "except:" "finally:" "try:")
297 "\\|"))
298 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000299 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000300 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000301 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
302 ;; block introducing keywords with immediately following colons.
303 ;; Yes "except" is in both lists.
304 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000305 ;; classes
306 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
307 1 font-lock-type-face)
308 ;; functions
309 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
310 1 font-lock-function-name-face)
311 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000312 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000313(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
314
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000315
Barry Warsaw81437461996-08-01 19:48:02 +0000316(defvar imenu-example--python-show-method-args-p nil
317 "*Controls echoing of arguments of functions & methods in the imenu buffer.
318When non-nil, arguments are printed.")
319
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000320(make-variable-buffer-local 'py-indent-offset)
321
Barry Warsawe467bfb1997-11-26 05:40:58 +0000322;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000323(defvar py-file-queue nil
324 "Queue of Python temp files awaiting execution.
325Currently-active file is at the head of the list.")
326
Barry Warsawc72c11c1997-08-09 06:42:08 +0000327
328;; Constants
329
Barry Warsawc72c11c1997-08-09 06:42:08 +0000330(defconst py-stringlit-re
331 (concat
Barry Warsaw751f4931998-05-19 16:06:21 +0000332 ;; These fail if backslash-quote ends the string (not worth
333 ;; fixing?). They precede the short versions so that the first two
334 ;; quotes don't look like an empty short string.
335 ;;
336 ;; (maybe raw), long single quoted triple quoted strings (SQTQ),
337 ;; with potential embedded single quotes
338 "[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
339 "\\|"
340 ;; (maybe raw), long double quoted triple quoted strings (DQTQ),
341 ;; with potential embedded double quotes
342 "[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
343 "\\|"
344 "[rR]?'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
Barry Warsawc72c11c1997-08-09 06:42:08 +0000345 "\\|" ; or
Barry Warsaw751f4931998-05-19 16:06:21 +0000346 "[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\"" ; double-quoted
Barry Warsaw41a05c71998-08-10 16:33:12 +0000347 )
348 "Regular expression matching a Python string literal.")
Barry Warsaw751f4931998-05-19 16:06:21 +0000349
Barry Warsawc72c11c1997-08-09 06:42:08 +0000350(defconst py-continued-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000351 ;; This is tricky because a trailing backslash does not mean
352 ;; continuation if it's in a comment
Barry Warsawc72c11c1997-08-09 06:42:08 +0000353 (concat
354 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
Barry Warsaw41a05c71998-08-10 16:33:12 +0000355 "\\\\$")
356 "Regular expression matching Python backslash continuation lines.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000357
Barry Warsaw41a05c71998-08-10 16:33:12 +0000358(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw71c3adb1998-08-10 16:34:33 +0000359 "Regular expression matching a blank or comment line.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000360
Barry Warsawc72c11c1997-08-09 06:42:08 +0000361(defconst py-outdent-re
362 (concat "\\(" (mapconcat 'identity
363 '("else:"
364 "except\\(\\s +.*\\)?:"
365 "finally:"
366 "elif\\s +.*:")
367 "\\|")
Barry Warsaw41a05c71998-08-10 16:33:12 +0000368 "\\)")
369 "Regular expression matching statements to be dedented one level.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000370
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000371(defconst py-block-closing-keywords-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000372 "\\(return\\|raise\\|break\\|continue\\|pass\\)"
373 "Regular expression matching keywords which typically close a block.")
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000374
Barry Warsawc72c11c1997-08-09 06:42:08 +0000375(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000376 (concat
377 "\\("
378 (mapconcat 'identity
379 (list "try:"
380 "except\\(\\s +.*\\)?:"
381 "while\\s +.*:"
382 "for\\s +.*:"
383 "if\\s +.*:"
384 "elif\\s +.*:"
385 (concat py-block-closing-keywords-re "[ \t\n]")
386 )
387 "\\|")
Barry Warsaw41a05c71998-08-10 16:33:12 +0000388 "\\)")
389 "Regular expression matching lines not to dedent after.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000390
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000391(defconst py-defun-start-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000392 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*="
393 ;; If you change this, you probably have to change py-current-defun
394 ;; as well. This is only used by py-current-defun to find the name
395 ;; for add-log.el.
Barry Warsaw71c3adb1998-08-10 16:34:33 +0000396 "Regular expression matching a function, method, or variable assignment.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000397
Barry Warsaw41a05c71998-08-10 16:33:12 +0000398(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)"
399 ;; If you change this, you probably have to change py-current-defun
400 ;; as well. This is only used by py-current-defun to find the name
401 ;; for add-log.el.
402 "Regular expression for finding a class name.")
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000403
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000404(defconst py-traceback-line-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000405 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)"
406 "Regular expression that describes tracebacks.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000407
408
409
Barry Warsawc72c11c1997-08-09 06:42:08 +0000410;; Major mode boilerplate
411
Barry Warsaw7ae77681994-12-12 20:38:05 +0000412;; define a mode-specific abbrev table for those who use such things
413(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000414 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000415(define-abbrev-table 'python-mode-abbrev-table nil)
416
Barry Warsaw7ae77681994-12-12 20:38:05 +0000417(defvar python-mode-hook nil
418 "*Hook called by `python-mode'.")
419
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000420;; In previous version of python-mode.el, the hook was incorrectly
421;; called py-mode-hook, and was not defvar'd. Deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000422(and (fboundp 'make-obsolete-variable)
423 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
424
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000425(defvar py-mode-map ()
426 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000427(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000428 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000429 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000430 ;; electric keys
431 (define-key py-mode-map ":" 'py-electric-colon)
432 ;; indentation level modifiers
433 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
434 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
435 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
436 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
437 ;; subprocess commands
438 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
Barry Warsaw820273d1998-05-19 15:54:45 +0000439 (define-key py-mode-map "\C-c\C-m" 'py-execute-import-or-reload)
Barry Warsaw1d0364b1998-05-19 16:15:26 +0000440 (define-key py-mode-map "\C-c\C-s" 'py-execute-string)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000441 (define-key py-mode-map "\C-c|" 'py-execute-region)
Barry Warsaw820273d1998-05-19 15:54:45 +0000442 (define-key py-mode-map "\e\C-x" 'py-execute-def-or-class)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000443 (define-key py-mode-map "\C-c!" 'py-shell)
Barry Warsawa2398801998-04-09 23:28:20 +0000444 (define-key py-mode-map "\C-c\C-t" 'py-toggle-shells)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000445 ;; Caution! Enter here at your own risk. We are trying to support
446 ;; several behaviors and it gets disgusting. :-( This logic ripped
447 ;; largely from CC Mode.
448 ;;
449 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
450 ;; backwards deletion behavior to DEL, which both Delete and
451 ;; Backspace get translated to. There's no way to separate this
452 ;; behavior in a clean way, so deal with it! Besides, it's been
453 ;; this way since the dawn of time.
454 (if (not (boundp 'delete-key-deletes-forward))
455 (define-key py-mode-map "\177" 'py-electric-backspace)
456 ;; However, XEmacs 20 actually achieved enlightenment. It is
457 ;; possible to sanely define both backward and forward deletion
458 ;; behavior under X separately (TTYs are forever beyond hope, but
459 ;; who cares? XEmacs 20 does the right thing with these too).
460 (define-key py-mode-map [delete] 'py-electric-delete)
461 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000462 ;; Separate M-BS from C-M-h. The former should remain
463 ;; backward-kill-word.
464 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000465 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000466 ;; Miscellaneous
467 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
468 (define-key py-mode-map "\C-c\t" 'py-indent-region)
469 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
470 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
471 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000472 (define-key py-mode-map "\C-c#" 'py-comment-region)
473 (define-key py-mode-map "\C-c?" 'py-describe-mode)
474 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
Barry Warsawab0e86c1998-05-19 15:31:46 +0000475 (define-key py-mode-map "\e\C-a" 'py-beginning-of-def-or-class)
476 (define-key py-mode-map "\e\C-e" 'py-end-of-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000477 (define-key py-mode-map "\C-c-" 'py-up-exception)
478 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000479 ;; information
480 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
481 (define-key py-mode-map "\C-c\C-v" 'py-version)
482 ;; py-newline-and-indent mappings
Barry Warsaw82aecb91998-01-21 05:14:24 +0000483 (define-key py-mode-map "\n" 'py-newline-and-indent)
484 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000485 ;; shadow global bindings for newline-and-indent w/ the py- version.
486 ;; BAW - this is extremely bad form, but I'm not going to change it
487 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000488 (mapcar #'(lambda (key)
489 (define-key py-mode-map key 'py-newline-and-indent))
490 (where-is-internal 'newline-and-indent))
491 )
492
493(defvar py-mode-output-map nil
Barry Warsaw41a05c71998-08-10 16:33:12 +0000494 "Keymap used in *Python Output* buffers.")
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000495(if py-mode-output-map
496 nil
497 (setq py-mode-output-map (make-sparse-keymap))
498 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
499 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
500 ;; TBD: Disable all self-inserting keys. This is bogus, we should
501 ;; really implement this as *Python Output* buffer being read-only
502 (mapcar #' (lambda (key)
503 (define-key py-mode-output-map key
504 #'(lambda () (interactive) (beep))))
505 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000506 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000507
Barry Warsaw6dfbe5d1998-08-20 21:51:27 +0000508(defvar py-shell-map nil
509 "Keymap used in *Python* shell buffers.")
510(if py-shell-map
511 nil
512 (setq py-shell-map (copy-keymap comint-mode-map))
513 (define-key py-shell-map [tab] 'tab-to-tab-stop)
514 (define-key py-shell-map "\C-c-" 'py-up-exception)
515 (define-key py-shell-map "\C-c=" 'py-down-exception)
516 )
517
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000518(defvar py-mode-syntax-table nil
519 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000520(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000521 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000522 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000523 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
524 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
525 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
526 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
527 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
528 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
529 ;; Add operator symbols misassigned in the std table
530 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
531 (modify-syntax-entry ?\% "." py-mode-syntax-table)
532 (modify-syntax-entry ?\& "." py-mode-syntax-table)
533 (modify-syntax-entry ?\* "." py-mode-syntax-table)
534 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
535 (modify-syntax-entry ?\- "." py-mode-syntax-table)
536 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
537 (modify-syntax-entry ?\< "." py-mode-syntax-table)
538 (modify-syntax-entry ?\= "." py-mode-syntax-table)
539 (modify-syntax-entry ?\> "." py-mode-syntax-table)
540 (modify-syntax-entry ?\| "." py-mode-syntax-table)
541 ;; For historical reasons, underscore is word class instead of
542 ;; symbol class. GNU conventions say it should be symbol class, but
543 ;; there's a natural conflict between what major mode authors want
544 ;; and what users expect from `forward-word' and `backward-word'.
545 ;; Guido and I have hashed this out and have decided to keep
546 ;; underscore in word class. If you're tempted to change it, try
547 ;; binding M-f and M-b to py-forward-into-nomenclature and
548 ;; py-backward-into-nomenclature instead.
549 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
550 ;; Both single quote and double quote are string delimiters
551 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
552 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
553 ;; backquote is open and close paren
554 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
555 ;; comment delimiters
556 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
557 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
558 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000559
Barry Warsawb3e81d51996-09-04 15:12:42 +0000560
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000561
Barry Warsawbc3760b1998-09-14 16:16:18 +0000562;; Utilities
563
564(defmacro py-safe (&rest body)
565 "Safely execute BODY, return nil if an error occurred."
566 (` (condition-case nil
567 (progn (,@ body))
568 (error nil))))
569
570(defsubst py-keep-region-active ()
571 "Keep the region active in XEmacs."
572 ;; Ignore byte-compiler warnings you might see. Also note that
573 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
574 ;; to take explicit action.
575 (and (boundp 'zmacs-region-stays)
576 (setq zmacs-region-stays t)))
577
578(defsubst py-point (position)
579 "Returns the value of point at certain commonly referenced POSITIONs.
580POSITION can be one of the following symbols:
581
582 bol -- beginning of line
583 eol -- end of line
584 bod -- beginning of def or class
585 eod -- end of def or class
586 bob -- beginning of buffer
587 eob -- end of buffer
588 boi -- back to indentation
589 bos -- beginning of statement
590
591This function does not modify point or mark."
592 (let ((here (point)))
593 (cond
594 ((eq position 'bol) (beginning-of-line))
595 ((eq position 'eol) (end-of-line))
596 ((eq position 'bod) (py-beginning-of-def-or-class))
597 ((eq position 'eod) (py-end-of-def-or-class))
598 ;; Kind of funny, I know, but useful for py-up-exception.
599 ((eq position 'bob) (beginning-of-buffer))
600 ((eq position 'eob) (end-of-buffer))
601 ((eq position 'boi) (back-to-indentation))
602 ((eq position 'bos) (py-goto-initial-line))
603 (t (error "Unknown buffer position requested: %s" position))
604 )
605 (prog1
606 (point)
607 (goto-char here))))
608
609(defsubst py-highlight-line (from to file line)
610 (cond
611 ((fboundp 'make-extent)
612 ;; XEmacs
613 (let ((e (make-extent from to)))
614 (set-extent-property e 'mouse-face 'highlight)
615 (set-extent-property e 'py-exc-info (cons file line))
616 (set-extent-property e 'keymap py-mode-output-map)))
617 (t
618 ;; Emacs -- Please port this!
619 )
620 ))
621
622(defun py-in-literal (&optional lim)
623 "Return non-nil if point is in a Python literal (a comment or string).
624Optional argument LIM indicates the beginning of the containing form,
625i.e. the limit on how far back to scan."
626 ;; This is the version used for non-XEmacs, which has a nicer
627 ;; interface.
628 ;;
629 ;; WARNING: Watch out for infinite recursion.
630 (let* ((lim (or lim (py-point 'bod)))
631 (state (parse-partial-sexp lim (point))))
632 (cond
633 ((nth 3 state) 'string)
634 ((nth 4 state) 'comment)
635 (t nil))))
636
637;; XEmacs has a built-in function that should make this much quicker.
638;; In this case, lim is ignored
639(defun py-fast-in-literal (&optional lim)
640 "Fast version of `py-in-literal', used only by XEmacs.
641Optional LIM is ignored."
642 ;; don't have to worry about context == 'block-comment
643 (buffer-syntactic-context))
644
645(if (fboundp 'buffer-syntactic-context)
646 (defalias 'py-in-literal 'py-fast-in-literal))
647
648
649
Barry Warsaw42f707f1996-07-29 21:05:05 +0000650;; Menu definitions, only relevent if you have the easymenu.el package
651;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000652(defvar py-menu nil
653 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000654This menu will get created automatically if you have the `easymenu'
655package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000656
Barry Warsawc72c11c1997-08-09 06:42:08 +0000657(and (py-safe (require 'easymenu) t)
658 (easy-menu-define
659 py-menu py-mode-map "Python Mode menu"
660 '("Python"
661 ["Comment Out Region" py-comment-region (mark)]
662 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
663 "-"
664 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000665 ["Mark current def" py-mark-def-or-class t]
666 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000667 "-"
668 ["Shift region left" py-shift-region-left (mark)]
669 ["Shift region right" py-shift-region-right (mark)]
670 "-"
Barry Warsaw820273d1998-05-19 15:54:45 +0000671 ["Import/reload file" py-execute-import-or-reload t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000672 ["Execute buffer" py-execute-buffer t]
673 ["Execute region" py-execute-region (mark)]
Barry Warsaw820273d1998-05-19 15:54:45 +0000674 ["Execute def or class" py-execute-def-or-class (mark)]
Barry Warsaw1d0364b1998-05-19 16:15:26 +0000675 ["Execute string" py-execute-string t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000676 ["Start interpreter..." py-shell t]
677 "-"
678 ["Go to start of block" py-goto-block-up t]
Barry Warsawab0e86c1998-05-19 15:31:46 +0000679 ["Go to start of class" (py-beginning-of-def-or-class t) t]
680 ["Move to end of class" (py-end-of-def-or-class t) t]
681 ["Move to start of def" py-beginning-of-def-or-class t]
682 ["Move to end of def" py-end-of-def-or-class t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000683 "-"
684 ["Describe mode" py-describe-mode t]
685 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000686
Barry Warsaw81437461996-08-01 19:48:02 +0000687
688
689;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
690(defvar imenu-example--python-class-regexp
691 (concat ; <<classes>>
692 "\\(" ;
693 "^[ \t]*" ; newline and maybe whitespace
694 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
695 ; possibly multiple superclasses
Barry Warsaw3179fe01998-04-04 21:36:53 +0000696 "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
Barry Warsaw81437461996-08-01 19:48:02 +0000697 "[ \t]*:" ; and the final :
698 "\\)" ; >>classes<<
699 )
700 "Regexp for Python classes for use with the imenu package."
701 )
702
703(defvar imenu-example--python-method-regexp
704 (concat ; <<methods and functions>>
705 "\\(" ;
706 "^[ \t]*" ; new line and maybe whitespace
707 "\\(def[ \t]+" ; function definitions start with def
708 "\\([a-zA-Z0-9_]+\\)" ; name is here
709 ; function arguments...
Barry Warsaw650e8a61998-08-10 21:46:24 +0000710 "[ \t]*(\\([-+/a-zA-Z0-9_=,\* \t\n.()\"'#]*\\))"
Barry Warsaw81437461996-08-01 19:48:02 +0000711 "\\)" ; end of def
712 "[ \t]*:" ; and then the :
713 "\\)" ; >>methods and functions<<
714 )
715 "Regexp for Python methods/functions for use with the imenu package."
716 )
717
718(defvar imenu-example--python-method-no-arg-parens '(2 8)
719 "Indicies into groups of the Python regexp for use with imenu.
720
721Using these values will result in smaller imenu lists, as arguments to
722functions are not listed.
723
724See the variable `imenu-example--python-show-method-args-p' for more
725information.")
726
727(defvar imenu-example--python-method-arg-parens '(2 7)
728 "Indicies into groups of the Python regexp for use with imenu.
729Using these values will result in large imenu lists, as arguments to
730functions are listed.
731
732See the variable `imenu-example--python-show-method-args-p' for more
733information.")
734
735;; Note that in this format, this variable can still be used with the
736;; imenu--generic-function. Otherwise, there is no real reason to have
737;; it.
738(defvar imenu-example--generic-python-expression
739 (cons
740 (concat
741 imenu-example--python-class-regexp
742 "\\|" ; or...
743 imenu-example--python-method-regexp
744 )
745 imenu-example--python-method-no-arg-parens)
746 "Generic Python expression which may be used directly with imenu.
747Used by setting the variable `imenu-generic-expression' to this value.
748Also, see the function \\[imenu-example--create-python-index] for a
749better alternative for finding the index.")
750
751;; These next two variables are used when searching for the python
752;; class/definitions. Just saving some time in accessing the
753;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000754(defvar imenu-example--python-generic-regexp nil)
755(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000756
757
Barry Warsaw81437461996-08-01 19:48:02 +0000758(defun imenu-example--create-python-index ()
759 "Python interface function for imenu package.
760Finds all python classes and functions/methods. Calls function
761\\[imenu-example--create-python-index-engine]. See that function for
762the details of how this works."
763 (setq imenu-example--python-generic-regexp
764 (car imenu-example--generic-python-expression))
765 (setq imenu-example--python-generic-parens
766 (if imenu-example--python-show-method-args-p
767 imenu-example--python-method-arg-parens
768 imenu-example--python-method-no-arg-parens))
769 (goto-char (point-min))
770 (imenu-example--create-python-index-engine nil))
771
772(defun imenu-example--create-python-index-engine (&optional start-indent)
773 "Function for finding imenu definitions in Python.
774
775Finds all definitions (classes, methods, or functions) in a Python
776file for the imenu package.
777
778Returns a possibly nested alist of the form
779
780 (INDEX-NAME . INDEX-POSITION)
781
782The second element of the alist may be an alist, producing a nested
783list as in
784
785 (INDEX-NAME . INDEX-ALIST)
786
787This function should not be called directly, as it calls itself
788recursively and requires some setup. Rather this is the engine for
789the function \\[imenu-example--create-python-index].
790
791It works recursively by looking for all definitions at the current
792indention level. When it finds one, it adds it to the alist. If it
793finds a definition at a greater indentation level, it removes the
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000794previous definition from the alist. In its place it adds all
Barry Warsaw81437461996-08-01 19:48:02 +0000795definitions found at the next indentation level. When it finds a
796definition that is less indented then the current level, it retuns the
797alist it has created thus far.
798
799The optional argument START-INDENT indicates the starting indentation
800at which to continue looking for Python classes, methods, or
801functions. If this is not supplied, the function uses the indentation
802of the first definition found."
803 (let ((index-alist '())
804 (sub-method-alist '())
805 looking-p
806 def-name prev-name
807 cur-indent def-pos
808 (class-paren (first imenu-example--python-generic-parens))
809 (def-paren (second imenu-example--python-generic-parens)))
810 (setq looking-p
811 (re-search-forward imenu-example--python-generic-regexp
812 (point-max) t))
813 (while looking-p
814 (save-excursion
815 ;; used to set def-name to this value but generic-extract-name is
816 ;; new to imenu-1.14. this way it still works with imenu-1.11
817 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
818 (let ((cur-paren (if (match-beginning class-paren)
819 class-paren def-paren)))
820 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000821 (buffer-substring-no-properties (match-beginning cur-paren)
822 (match-end cur-paren))))
Barry Warsaw93c88cc1998-08-18 02:00:44 +0000823 (save-match-data
824 (py-beginning-of-def-or-class))
Barry Warsaw81437461996-08-01 19:48:02 +0000825 (beginning-of-line)
826 (setq cur-indent (current-indentation)))
827
828 ;; HACK: want to go to the next correct definition location. we
829 ;; explicitly list them here. would be better to have them in a
830 ;; list.
831 (setq def-pos
832 (or (match-beginning class-paren)
833 (match-beginning def-paren)))
834
835 ;; if we don't have a starting indent level, take this one
836 (or start-indent
837 (setq start-indent cur-indent))
838
839 ;; if we don't have class name yet, take this one
840 (or prev-name
841 (setq prev-name def-name))
842
843 ;; what level is the next definition on? must be same, deeper
844 ;; or shallower indentation
845 (cond
846 ;; at the same indent level, add it to the list...
847 ((= start-indent cur-indent)
848
849 ;; if we don't have push, use the following...
850 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
851 (push (cons def-name def-pos) index-alist))
852
853 ;; deeper indented expression, recur...
854 ((< start-indent cur-indent)
855
856 ;; the point is currently on the expression we're supposed to
857 ;; start on, so go back to the last expression. The recursive
858 ;; call will find this place again and add it to the correct
859 ;; list
860 (re-search-backward imenu-example--python-generic-regexp
861 (point-min) 'move)
862 (setq sub-method-alist (imenu-example--create-python-index-engine
863 cur-indent))
864
865 (if sub-method-alist
866 ;; we put the last element on the index-alist on the start
867 ;; of the submethod alist so the user can still get to it.
868 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000869 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000870 (cons save-elmt sub-method-alist))
871 index-alist))))
872
873 ;; found less indented expression, we're done.
874 (t
875 (setq looking-p nil)
876 (re-search-backward imenu-example--python-generic-regexp
877 (point-min) t)))
878 (setq prev-name def-name)
879 (and looking-p
880 (setq looking-p
881 (re-search-forward imenu-example--python-generic-regexp
882 (point-max) 'move))))
883 (nreverse index-alist)))
884
Barry Warsaw42f707f1996-07-29 21:05:05 +0000885
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000886;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000887(defun python-mode ()
888 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000889To submit a problem report, enter `\\[py-submit-bug-report]' from a
890`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
891documentation. To see what version of `python-mode' you are running,
892enter `\\[py-version]'.
893
894This mode knows about Python indentation, tokens, comments and
895continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000896
897COMMANDS
898\\{py-mode-map}
899VARIABLES
900
Barry Warsaw42f707f1996-07-29 21:05:05 +0000901py-indent-offset\t\tindentation increment
Barry Warsaw41a05c71998-08-10 16:33:12 +0000902py-block-comment-prefix\t\tcomment string used by `comment-region'
Barry Warsaw42f707f1996-07-29 21:05:05 +0000903py-python-command\t\tshell command to invoke Python interpreter
Barry Warsaw42f707f1996-07-29 21:05:05 +0000904py-temp-directory\t\tdirectory used for temp files (if needed)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000905py-beep-if-tab-change\t\tring the bell if `tab-width' is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000906 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000907 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000908 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000909 (make-local-variable 'font-lock-defaults)
910 (make-local-variable 'paragraph-separate)
911 (make-local-variable 'paragraph-start)
912 (make-local-variable 'require-final-newline)
913 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000914 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000915 (make-local-variable 'comment-start-skip)
916 (make-local-variable 'comment-column)
Barry Warsaw003932a1998-07-07 15:11:24 +0000917 (make-local-variable 'comment-indent-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000918 (make-local-variable 'indent-region-function)
919 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000920 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000921 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000922 (set-syntax-table py-mode-syntax-table)
Barry Warsaw003932a1998-07-07 15:11:24 +0000923 (setq major-mode 'python-mode
924 mode-name "Python"
925 local-abbrev-table python-mode-abbrev-table
926 font-lock-defaults '(python-font-lock-keywords)
927 paragraph-separate "^[ \t]*$"
928 paragraph-start "^[ \t]*$"
929 require-final-newline t
930 comment-start "# "
931 comment-end ""
932 comment-start-skip "# *"
933 comment-column 40
934 comment-indent-function 'py-comment-indent-function
935 indent-region-function 'py-indent-region
936 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000937 ;; tell add-log.el how to find the current function/method/variable
938 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000939 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000940 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000941 ;; add the menu
942 (if py-menu
943 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000944 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000945 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000946 (setq comment-multi-line nil))
Barry Warsaw742a5111998-03-13 17:29:15 +0000947 ;; Install Imenu, only works for Emacs.
948 (when (py-safe (require 'imenu))
949 (make-variable-buffer-local 'imenu-create-index-function)
950 (setq imenu-create-index-function
951 (function imenu-example--create-python-index))
952 (setq imenu-generic-expression
953 imenu-example--generic-python-expression)
954 (if (fboundp 'imenu-add-to-menubar)
955 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
956 )
957 ;; Run the mode hook. Note that py-mode-hook is deprecated.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000958 (if python-mode-hook
959 (run-hooks 'python-mode-hook)
Barry Warsaw742a5111998-03-13 17:29:15 +0000960 (run-hooks 'py-mode-hook))
961 ;; Now do the automagical guessing
962 (if py-smart-indentation
963 (let ((offset py-indent-offset))
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000964 ;; It's okay if this fails to guess a good value
Barry Warsaw742a5111998-03-13 17:29:15 +0000965 (if (and (py-safe (py-guess-indent-offset))
966 (<= py-indent-offset 8)
967 (>= py-indent-offset 2))
968 (setq offset py-indent-offset))
969 (setq py-indent-offset offset)
Barry Warsaw639eea61998-03-16 18:12:13 +0000970 ;; Only turn indent-tabs-mode off if tab-width !=
971 ;; py-indent-offset. Never turn it on, because the user must
972 ;; have explicitly turned it off.
973 (if (/= tab-width py-indent-offset)
974 (setq indent-tabs-mode nil))
Barry Warsaw742a5111998-03-13 17:29:15 +0000975 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000976
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000977
Barry Warsawb91b7431995-03-14 15:55:20 +0000978;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000979(defun py-outdent-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +0000980 "Returns non-nil if the current line should dedent one level."
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000981 (save-excursion
982 (and (progn (back-to-indentation)
983 (looking-at py-outdent-re))
Barry Warsawf06777d1998-01-21 05:36:18 +0000984 (progn (forward-line -1)
985 (py-goto-initial-line)
986 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000987 (while (or (looking-at py-blank-or-comment-re)
988 (bobp))
989 (backward-to-indentation 1))
990 (not (looking-at py-no-outdent-re)))
991 )))
992
Barry Warsawb91b7431995-03-14 15:55:20 +0000993(defun py-electric-colon (arg)
994 "Insert a colon.
Barry Warsaw41a05c71998-08-10 16:33:12 +0000995In certain cases the line is dedented appropriately. If a numeric
996argument ARG is provided, that many colons are inserted
997non-electrically. Electric behavior is inhibited inside a string or
998comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000999 (interactive "P")
1000 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001001 ;; are we in a string or comment?
1002 (if (save-excursion
1003 (let ((pps (parse-partial-sexp (save-excursion
Barry Warsawab0e86c1998-05-19 15:31:46 +00001004 (py-beginning-of-def-or-class)
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001005 (point))
1006 (point))))
1007 (not (or (nth 3 pps) (nth 4 pps)))))
1008 (save-excursion
1009 (let ((here (point))
1010 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001011 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001012 (if (and (not arg)
1013 (py-outdent-p)
1014 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +00001015 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001016 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001017 )
1018 (setq outdent py-indent-offset))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001019 ;; Don't indent, only dedent. This assumes that any lines
1020 ;; that are already dedented relative to
1021 ;; py-compute-indentation were put there on purpose. It's
1022 ;; highly annoying to have `:' indent for you. Use TAB, C-c
1023 ;; C-l or C-c C-r to adjust. TBD: Is there a better way to
1024 ;; determine this???
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001025 (if (< (current-indentation) indent) nil
1026 (goto-char here)
1027 (beginning-of-line)
1028 (delete-horizontal-space)
1029 (indent-to (- indent outdent))
1030 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001031
1032
Barry Warsawa97a3f31997-11-04 18:47:06 +00001033;; Python subprocess utilities and filters
1034(defun py-execute-file (proc filename)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001035 "Send to Python interpreter process PROC \"execfile('FILENAME')\".
1036Make that process's buffer visible and force display. Also make
1037comint believe the user typed this string so that
1038`kill-output-from-shell' does The Right Thing."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001039 (let ((curbuf (current-buffer))
1040 (procbuf (process-buffer proc))
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001041; (comint-scroll-to-bottom-on-output t)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001042 (msg (format "## working on region in file %s...\n" filename))
1043 (cmd (format "execfile('%s')\n" filename)))
1044 (unwind-protect
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001045 (save-excursion
Barry Warsawa97a3f31997-11-04 18:47:06 +00001046 (set-buffer procbuf)
1047 (goto-char (point-max))
1048 (move-marker (process-mark proc) (point))
1049 (funcall (process-filter proc) proc msg))
1050 (set-buffer curbuf))
1051 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001052
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001053(defun py-comint-output-filter-function (string)
1054 "Watch output for Python prompt and exec next file waiting in queue.
1055This function is appropriate for `comint-output-filter-functions'."
1056 (when (and (string-equal ">>> " string)
1057 py-file-queue)
1058 (py-safe (delete-file (car py-file-queue)))
1059 (setq py-file-queue (cdr py-file-queue))
1060 (if py-file-queue
1061 (let ((pyproc (get-buffer-process (current-buffer))))
1062 (py-execute-file pyproc (car py-file-queue))))
1063 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001064
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001065(defun py-postprocess-output-buffer (buf)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001066 "Highlight exceptions found in BUF.
1067If an exception occurred return t, otherwise return nil. BUF must exist."
Barry Warsawf9b99f41998-03-26 16:08:59 +00001068 (let (line file bol err-p)
Barry Warsaw9981d221997-12-03 05:25:48 +00001069 (save-excursion
1070 (set-buffer buf)
1071 (beginning-of-buffer)
1072 (while (re-search-forward py-traceback-line-re nil t)
1073 (setq file (match-string 1)
1074 line (string-to-int (match-string 2))
1075 bol (py-point 'bol))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001076 (py-highlight-line bol (py-point 'eol) file line)))
1077 (when (and py-jump-on-exception line)
1078 (beep)
1079 (py-jump-to-exception file line)
1080 (setq err-p t))
1081 err-p))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001082
Barry Warsaw9981d221997-12-03 05:25:48 +00001083
Barry Warsawa97a3f31997-11-04 18:47:06 +00001084
1085;;; Subprocess commands
1086
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001087;; only used when (memq 'broken-temp-names py-emacs-features)
1088(defvar py-serial-number 0)
1089(defvar py-exception-buffer nil)
1090(defconst py-output-buffer "*Python Output*")
Barry Warsawa2398801998-04-09 23:28:20 +00001091(make-variable-buffer-local 'py-output-buffer)
1092
1093;; for toggling between CPython and JPython
1094(defvar py-which-shell py-python-command)
1095(defvar py-which-args py-python-command-args)
1096(defvar py-which-bufname "Python")
1097(make-variable-buffer-local 'py-which-shell)
1098(make-variable-buffer-local 'py-which-args)
1099(make-variable-buffer-local 'py-which-bufname)
1100
1101(defun py-toggle-shells (arg)
1102 "Toggles between the CPython and JPython shells.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001103With positive argument ARG (interactively \\[universal-argument]),
1104uses the CPython shell, with negative ARG uses the JPython shell, and
1105with a zero argument, toggles the shell."
Barry Warsawa2398801998-04-09 23:28:20 +00001106 (interactive "P")
1107 ;; default is to toggle
1108 (if (null arg)
1109 (setq arg 0))
1110 ;; toggle if zero
1111 (if (= arg 0)
1112 (if (string-equal py-which-bufname "Python")
1113 (setq arg -1)
1114 (setq arg 1)))
1115 (let (msg)
1116 (cond
1117 ((< 0 arg)
1118 ;; set to CPython
1119 (setq py-which-shell py-python-command
1120 py-which-args py-python-command-args
1121 py-which-bufname "Python"
1122 msg "CPython"
1123 mode-name "Python"))
1124 ((> 0 arg)
1125 (setq py-which-shell py-jpython-command
1126 py-which-args py-jpython-command-args
1127 py-which-bufname "JPython"
1128 msg "JPython"
1129 mode-name "JPython"))
1130 )
Barry Warsawea609c11998-04-10 16:08:26 +00001131 (message "Using the %s shell" msg)
Barry Warsawa2398801998-04-09 23:28:20 +00001132 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001133
Barry Warsawa97a3f31997-11-04 18:47:06 +00001134;;;###autoload
1135(defun py-shell ()
1136 "Start an interactive Python interpreter in another window.
1137This is like Shell mode, except that Python is running in the window
1138instead of a shell. See the `Interactive Shell' and `Shell Mode'
1139sections of the Emacs manual for details, especially for the key
1140bindings active in the `*Python*' buffer.
1141
Barry Warsawa2398801998-04-09 23:28:20 +00001142Note: You can toggle between using the CPython interpreter and the
1143JPython interpreter by hitting \\[py-toggle-shells]. This toggles
1144buffer local variables which control whether all your subshell
1145interactions happen to the `*JPython*' or `*Python*' buffers (the
1146latter is the name used for the CPython buffer).
1147
Barry Warsawa97a3f31997-11-04 18:47:06 +00001148Warning: Don't use an interactive Python if you change sys.ps1 or
1149sys.ps2 from their default values, or if you're running code that
1150prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1151distinguish your output from Python's output, and assumes that `>>> '
1152at the start of a line is a prompt from Python. Similarly, the Emacs
1153Shell mode code assumes that both `>>> ' and `... ' at the start of a
1154line are Python prompts. Bad things can happen if you fool either
1155mode.
1156
1157Warning: If you do any editing *in* the process buffer *while* the
1158buffer is accepting output from Python, do NOT attempt to `undo' the
1159changes. Some of the output (nowhere near the parts you changed!) may
1160be lost if you do. This appears to be an Emacs bug, an unfortunate
1161interaction between undo and process filters; the same problem exists in
1162non-Python process buffers using the default (Emacs-supplied) process
1163filter."
1164 ;; BAW - should undo be disabled in the python process buffer, if
1165 ;; this bug still exists?
1166 (interactive)
Barry Warsaw2518c671997-11-05 00:51:08 +00001167 (switch-to-buffer-other-window
Barry Warsawa2398801998-04-09 23:28:20 +00001168 (apply 'make-comint py-which-bufname py-which-shell nil py-which-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001169 (make-local-variable 'comint-prompt-regexp)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001170 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001171 (add-hook 'comint-output-filter-functions 'py-comint-output-filter-function)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001172 (set-syntax-table py-mode-syntax-table)
Barry Warsaw6dfbe5d1998-08-20 21:51:27 +00001173 (use-local-map py-shell-map)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001174 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001175
Barry Warsawa97a3f31997-11-04 18:47:06 +00001176(defun py-clear-queue ()
1177 "Clear the queue of temporary files waiting to execute."
1178 (interactive)
1179 (let ((n (length py-file-queue)))
1180 (mapcar 'delete-file py-file-queue)
1181 (setq py-file-queue nil)
1182 (message "%d pending files de-queued." n)))
1183
Barry Warsaw820273d1998-05-19 15:54:45 +00001184
Barry Warsawa97a3f31997-11-04 18:47:06 +00001185(defun py-execute-region (start end &optional async)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001186 "Execute the region in a Python interpreter.
1187
Barry Warsawa97a3f31997-11-04 18:47:06 +00001188The region is first copied into a temporary file (in the directory
1189`py-temp-directory'). If there is no Python interpreter shell
1190running, this file is executed synchronously using
Barry Warsaw41a05c71998-08-10 16:33:12 +00001191`shell-command-on-region'. If the program is long running, use
1192\\[universal-argument] to run the command asynchronously in its own
1193buffer.
1194
1195When this function is used programmatically, arguments START and END
1196specify the region to execute, and optional third argument ASYNC, if
1197non-nil, specifies to run the command asynchronously in its own
1198buffer.
Barry Warsawa97a3f31997-11-04 18:47:06 +00001199
1200If the Python interpreter shell is running, the region is execfile()'d
1201in that shell. If you try to execute regions too quickly,
1202`python-mode' will queue them up and execute them one at a time when
1203it sees a `>>> ' prompt from Python. Each time this happens, the
1204process buffer is popped into a window (if it's not already in some
1205window) so you can see it, and a comment of the form
1206
1207 \t## working on region in file <name>...
1208
1209is inserted at the end. See also the command `py-clear-queue'."
1210 (interactive "r\nP")
1211 (or (< start end)
1212 (error "Region is empty"))
1213 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001214 (temp (if (memq 'broken-temp-names py-emacs-features)
Barry Warsaw1b344241998-08-07 22:24:16 +00001215 (let
1216 ((sn py-serial-number)
1217 (pid (and (fboundp 'emacs-pid) (emacs-pid))))
1218 (setq py-serial-number (1+ py-serial-number))
1219 (if pid
1220 (format "python-%d-%d" sn pid)
1221 (format "python-%d" sn)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001222 (make-temp-name "python-")))
1223 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001224 (write-region start end file nil 'nomsg)
1225 (cond
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001226 ;; always run the code in its own asynchronous subprocess
Barry Warsawa97a3f31997-11-04 18:47:06 +00001227 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001228 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001229 (start-process "Python" buf py-python-command "-u" file)
1230 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001231 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001232 ))
1233 ;; if the Python interpreter shell is running, queue it up for
1234 ;; execution there.
1235 (proc
1236 ;; use the existing python shell
1237 (if (not py-file-queue)
1238 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001239 (message "File %s queued for execution" file))
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001240 (setq py-file-queue (append py-file-queue (list file)))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001241 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001242 (t
1243 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001244 (shell-command-on-region start end py-python-command py-output-buffer)
Barry Warsaw512af041998-03-25 23:27:17 +00001245 ;; shell-command-on-region kills the output buffer if it never
1246 ;; existed and there's no output from the command
1247 (if (not (get-buffer py-output-buffer))
1248 (message "No output.")
1249 (setq py-exception-buffer (current-buffer))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001250 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1251 (pop-to-buffer py-output-buffer)
1252 (if err-p
1253 (pop-to-buffer py-exception-buffer)))
Barry Warsaw512af041998-03-25 23:27:17 +00001254 ))
1255 )))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001256
Barry Warsaw820273d1998-05-19 15:54:45 +00001257
1258;; Code execution commands
Barry Warsawa97a3f31997-11-04 18:47:06 +00001259(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001260 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001261If the file local variable `py-master-file' is non-nil, execute the
1262named file instead of the buffer's file.
1263
Barry Warsaw7ae77681994-12-12 20:38:05 +00001264If there is a *Python* process buffer it is used. If a clipping
1265restriction is in effect, only the accessible portion of the buffer is
1266sent. A trailing newline will be supplied if needed.
1267
Barry Warsaw41a05c71998-08-10 16:33:12 +00001268See the `\\[py-execute-region]' docs for an account of some
1269subtleties, including the use of the optional ASYNC argument."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001270 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001271 (if py-master-file
1272 (let* ((filename (expand-file-name py-master-file))
1273 (buffer (or (get-file-buffer filename)
1274 (find-file-noselect filename))))
1275 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001276 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001277
Barry Warsaw820273d1998-05-19 15:54:45 +00001278(defun py-execute-import-or-reload (&optional async)
1279 "Import the current buffer's file in a Python interpreter.
1280
1281If the file has already been imported, then do reload instead to get
Barry Warsaw7c29b231998-07-07 17:45:38 +00001282the latest version.
1283
1284If the file's name does not end in \".py\", then do execfile instead.
1285
1286If the current buffer is not visiting a file, do `py-execute-buffer'
1287instead.
1288
1289If the file local variable `py-master-file' is non-nil, import or
1290reload the named file instead of the buffer's file. The file may be
1291saved based on the value of `py-execute-import-or-reload-save-p'.
Barry Warsaw820273d1998-05-19 15:54:45 +00001292
Barry Warsaw41a05c71998-08-10 16:33:12 +00001293See the `\\[py-execute-region]' docs for an account of some
1294subtleties, including the use of the optional ASYNC argument.
Barry Warsaw820273d1998-05-19 15:54:45 +00001295
Barry Warsaw7c29b231998-07-07 17:45:38 +00001296This may be preferable to `\\[py-execute-buffer]' because:
Barry Warsaw820273d1998-05-19 15:54:45 +00001297
1298 - Definitions stay in their module rather than appearing at top
1299 level, where they would clutter the global namespace and not affect
1300 uses of qualified names (MODULE.NAME).
1301
1302 - The Python debugger gets line number information about the functions."
1303 (interactive "P")
1304 ;; Check file local variable py-master-file
1305 (if py-master-file
1306 (let* ((filename (expand-file-name py-master-file))
1307 (buffer (or (get-file-buffer filename)
1308 (find-file-noselect filename))))
1309 (set-buffer buffer)))
1310 (let ((file (buffer-file-name (current-buffer))))
1311 (if file
1312 (progn
Barry Warsaw3bfed5b1998-05-19 16:25:04 +00001313 ;; Maybe save some buffers
1314 (save-some-buffers (not py-ask-about-save) nil)
Barry Warsaw820273d1998-05-19 15:54:45 +00001315 (py-execute-string
1316 (if (string-match "\\.py$" file)
1317 (let ((f (file-name-sans-extension
1318 (file-name-nondirectory file))))
1319 (format "if globals().has_key('%s'):\n reload(%s)\nelse:\n import %s\n"
1320 f f f))
1321 (format "execfile('%s')\n" file))
1322 async))
1323 ;; else
1324 (py-execute-buffer async))))
1325
1326
1327(defun py-execute-def-or-class (&optional async)
1328 "Send the current function or class definition to a Python interpreter.
1329
1330If there is a *Python* process buffer it is used.
1331
Barry Warsaw41a05c71998-08-10 16:33:12 +00001332See the `\\[py-execute-region]' docs for an account of some
1333subtleties, including the use of the optional ASYNC argument."
Barry Warsaw820273d1998-05-19 15:54:45 +00001334 (interactive "P")
1335 (save-excursion
1336 (py-mark-def-or-class)
1337 ;; mark is before point
1338 (py-execute-region (mark) (point) async)))
1339
1340
1341(defun py-execute-string (string &optional async)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001342 "Send the argument STRING to a Python interpreter.
Barry Warsaw820273d1998-05-19 15:54:45 +00001343
1344If there is a *Python* process buffer it is used.
1345
Barry Warsaw41a05c71998-08-10 16:33:12 +00001346See the `\\[py-execute-region]' docs for an account of some
1347subtleties, including the use of the optional ASYNC argument."
Barry Warsaw820273d1998-05-19 15:54:45 +00001348 (interactive "sExecute Python command: ")
1349 (save-excursion
1350 (set-buffer (get-buffer-create
1351 (generate-new-buffer-name " *Python Command*")))
1352 (insert string)
1353 (py-execute-region (point-min) (point-max) async)))
1354
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001355
1356
1357(defun py-jump-to-exception (file line)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001358 "Jump to the Python code in FILE at LINE."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001359 (let ((buffer (cond ((string-equal file "<stdin>")
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001360 (if (consp py-exception-buffer)
1361 (cdr py-exception-buffer)
1362 py-exception-buffer))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001363 ((and (consp py-exception-buffer)
1364 (string-equal file (car py-exception-buffer)))
1365 (cdr py-exception-buffer))
1366 ((py-safe (find-file-noselect file)))
1367 ;; could not figure out what file the exception
1368 ;; is pointing to, so prompt for it
1369 (t (find-file (read-file-name "Exception file: "
1370 nil
1371 file t))))))
1372 (pop-to-buffer buffer)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001373 ;; Force Python mode
Barry Warsaw820273d1998-05-19 15:54:45 +00001374 (if (not (eq major-mode 'python-mode))
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001375 (python-mode))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001376 (goto-line line)
1377 (message "Jumping to exception in file %s on line %d" file line)))
1378
1379(defun py-mouseto-exception (event)
Barry Warsaw12c92941998-08-10 21:44:37 +00001380 "Jump to the code which caused the Python exception at EVENT.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001381EVENT is usually a mouse click."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001382 (interactive "e")
1383 (cond
1384 ((fboundp 'event-point)
1385 ;; XEmacs
1386 (let* ((point (event-point event))
1387 (buffer (event-buffer event))
1388 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1389 (info (and e (extent-property e 'py-exc-info))))
1390 (message "Event point: %d, info: %s" point info)
1391 (and info
1392 (py-jump-to-exception (car info) (cdr info)))
1393 ))
1394 ;; Emacs -- Please port this!
1395 ))
1396
1397(defun py-goto-exception ()
1398 "Go to the line indicated by the traceback."
1399 (interactive)
1400 (let (file line)
1401 (save-excursion
1402 (beginning-of-line)
1403 (if (looking-at py-traceback-line-re)
1404 (setq file (match-string 1)
1405 line (string-to-int (match-string 2)))))
1406 (if (not file)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001407 (error "Not on a traceback line"))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001408 (py-jump-to-exception file line)))
1409
1410(defun py-find-next-exception (start buffer searchdir errwhere)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001411 "Find the next Python exception and jump to the code that caused it.
1412START is the buffer position in BUFFER from which to begin searching
1413for an exception. SEARCHDIR is a function, either
1414`re-search-backward' or `re-search-forward' indicating the direction
1415to search. ERRWHERE is used in an error message if the limit (top or
1416bottom) of the trackback stack is encountered."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001417 (let (file line)
1418 (save-excursion
1419 (set-buffer buffer)
1420 (goto-char (py-point start))
1421 (if (funcall searchdir py-traceback-line-re nil t)
1422 (setq file (match-string 1)
1423 line (string-to-int (match-string 2)))))
1424 (if (and file line)
1425 (py-jump-to-exception file line)
1426 (error "%s of traceback" errwhere))))
1427
1428(defun py-down-exception (&optional bottom)
1429 "Go to the next line down in the traceback.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001430With \\[univeral-argument] (programmatically, optional argument
1431BOTTOM), jump to the bottom (innermost) exception in the exception
1432stack."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001433 (interactive "P")
1434 (let* ((proc (get-process "Python"))
1435 (buffer (if proc "*Python*" py-output-buffer)))
1436 (if bottom
1437 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1438 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1439
1440(defun py-up-exception (&optional top)
1441 "Go to the previous line up in the traceback.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001442With \\[universal-argument] (programmatically, optional argument TOP)
1443jump to the top (outermost) exception in the exception stack."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001444 (interactive "P")
1445 (let* ((proc (get-process "Python"))
1446 (buffer (if proc "*Python*" py-output-buffer)))
1447 (if top
1448 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001449 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001450
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001451
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001452;; Electric deletion
1453(defun py-electric-backspace (arg)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001454 "Delete preceding character or levels of indentation.
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001455Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001456with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001457
Barry Warsaw41a05c71998-08-10 16:33:12 +00001458If point is at the leftmost column, delete the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001459
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001460Otherwise, if point is at the leftmost non-whitespace character of a
1461line that is neither a continuation line nor a non-indenting comment
1462line, or if point is at the end of a blank line, this command reduces
1463the indentation to match that of the line that opened the current
1464block of code. The line that opened the block is displayed in the
Barry Warsaw41a05c71998-08-10 16:33:12 +00001465echo area to help you keep track of where you are. With
1466\\[universal-argument] dedents that many blocks (but not past column
1467zero).
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001468
1469Otherwise the preceding character is deleted, converting a tab to
1470spaces if needed so that only a single column position is deleted.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001471\\[universal-argument] specifies how many characters to delete
1472(default is 1).
1473
1474When used programmatically, argument ARG specifies the number of
1475blocks to dedent, or the number of characters to delete, as indicated
1476above."
Barry Warsaw03970731996-07-03 23:12:52 +00001477 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001478 (if (or (/= (current-indentation) (current-column))
1479 (bolp)
1480 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001481 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001482 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001483 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001484 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001485 ;; force non-blank so py-goto-block-up doesn't ignore it
1486 (insert-char ?* 1)
1487 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001488 (let ((base-indent 0) ; indentation of base line
1489 (base-text "") ; and text of base line
1490 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001491 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001492 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001493 (condition-case nil ; in case no enclosing block
1494 (progn
1495 (py-goto-block-up 'no-mark)
1496 (setq base-indent (current-indentation)
1497 base-text (py-suck-up-leading-text)
1498 base-found-p t))
1499 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001500 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001501 (delete-char 1) ; toss the dummy character
1502 (delete-horizontal-space)
1503 (indent-to base-indent)
1504 (if base-found-p
1505 (message "Closes block: %s" base-text)))))
1506
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001507
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001508(defun py-electric-delete (arg)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001509 "Delete preceding or following character or levels of whitespace.
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001510
1511The behavior of this function depends on the variable
1512`delete-key-deletes-forward'. If this variable is nil (or does not
Barry Warsaw41a05c71998-08-10 16:33:12 +00001513exist, as in older Emacsen and non-XEmacs versions), then this
1514function behaves identically to \\[c-electric-backspace].
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001515
1516If `delete-key-deletes-forward' is non-nil and is supported in your
1517Emacs, then deletion occurs in the forward direction, by calling the
Barry Warsaw41a05c71998-08-10 16:33:12 +00001518function in `py-delete-function'.
1519
1520\\[universal-argument] (programmatically, argument ARG) specifies the
1521number of characters to delete (default is 1)."
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001522 (interactive "*p")
1523 (if (and (boundp 'delete-key-deletes-forward)
1524 delete-key-deletes-forward)
1525 (funcall py-delete-function arg)
1526 ;; else
1527 (py-electric-backspace arg)))
1528
1529;; required for pending-del and delsel modes
1530(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1531(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1532(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1533(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1534
1535
1536
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001537(defun py-indent-line (&optional arg)
1538 "Fix the indentation of the current line according to Python rules.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001539With \\[universal-argument] (programmatically, the optional argument
1540ARG non-nil), ignore dedenting rules for block closing statements
1541(e.g. return, raise, break, continue, pass)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001542
1543This function is normally bound to `indent-line-function' so
1544\\[indent-for-tab-command] will call it."
1545 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001546 (let* ((ci (current-indentation))
1547 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001548 (need (py-compute-indentation (not arg))))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001549 ;; see if we need to dedent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001550 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001551 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001552 (if (/= ci need)
1553 (save-excursion
1554 (beginning-of-line)
1555 (delete-horizontal-space)
1556 (indent-to need)))
1557 (if move-to-indentation-p (back-to-indentation))))
1558
1559(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001560 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001561This is just `strives to' because correct indentation can't be computed
1562from scratch for Python code. In general, deletes the whitespace before
1563point, inserts a newline, and takes an educated guess as to how you want
1564the new line indented."
1565 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001566 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001567 (if (< ci (current-column)) ; if point beyond indentation
1568 (newline-and-indent)
1569 ;; else try to act like newline-and-indent "normally" acts
1570 (beginning-of-line)
1571 (insert-char ?\n 1)
1572 (move-to-column ci))))
1573
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001574(defun py-compute-indentation (honor-block-close-p)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001575 "Compute Python indentation.
1576When HONOR-BLOCK-CLOSE-P is non-nil, statements such as `return',
1577`raise', `break', `continue', and `pass' force one level of
1578dedenting."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001579 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001580 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001581 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001582 (pps (parse-partial-sexp bod (point)))
1583 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001584 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001585 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001586 ((or (and (nth 3 pps) (nth 3 boipps))
1587 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001588 (save-excursion
1589 (if (not py-align-multiline-strings-p) 0
1590 ;; skip back over blank & non-indenting comment lines
1591 ;; note: will skip a blank or non-indenting comment line
1592 ;; that happens to be a continuation line too
1593 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1594 (back-to-indentation)
1595 (current-column))))
1596 ;; are we on a continuation line?
1597 ((py-continuation-line-p)
1598 (let ((startpos (point))
1599 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001600 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001601 (if open-bracket-pos
1602 (progn
1603 ;; align with first item in list; else a normal
1604 ;; indent beyond the line with the open bracket
1605 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1606 ;; is the first list item on the same line?
1607 (skip-chars-forward " \t")
1608 (if (null (memq (following-char) '(?\n ?# ?\\)))
1609 ; yes, so line up with it
1610 (current-column)
1611 ;; first list item on another line, or doesn't exist yet
1612 (forward-line 1)
1613 (while (and (< (point) startpos)
1614 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1615 (forward-line 1))
Barry Warsaw92166d91998-04-01 21:59:41 +00001616 (if (and (< (point) startpos)
1617 (/= startpos
1618 (save-excursion
1619 (goto-char (1+ open-bracket-pos))
Barry Warsaw77d1fce1998-04-16 20:04:59 +00001620 (forward-comment (point-max))
Barry Warsaw92166d91998-04-01 21:59:41 +00001621 (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001622 ;; again mimic the first list item
1623 (current-indentation)
1624 ;; else they're about to enter the first item
1625 (goto-char open-bracket-pos)
1626 (+ (current-indentation) py-indent-offset))))
1627
1628 ;; else on backslash continuation line
1629 (forward-line -1)
1630 (if (py-continuation-line-p) ; on at least 3rd line in block
1631 (current-indentation) ; so just continue the pattern
1632 ;; else started on 2nd line in block, so indent more.
1633 ;; if base line is an assignment with a start on a RHS,
1634 ;; indent to 2 beyond the leftmost "="; else skip first
1635 ;; chunk of non-whitespace characters on base line, + 1 more
1636 ;; column
1637 (end-of-line)
1638 (setq endpos (point) searching t)
1639 (back-to-indentation)
1640 (setq startpos (point))
1641 ;; look at all "=" from left to right, stopping at first
1642 ;; one not nested in a list or string
1643 (while searching
1644 (skip-chars-forward "^=" endpos)
1645 (if (= (point) endpos)
1646 (setq searching nil)
1647 (forward-char 1)
1648 (setq state (parse-partial-sexp startpos (point)))
1649 (if (and (zerop (car state)) ; not in a bracket
1650 (null (nth 3 state))) ; & not in a string
1651 (progn
1652 (setq searching nil) ; done searching in any case
1653 (setq found
1654 (not (or
1655 (eq (following-char) ?=)
1656 (memq (char-after (- (point) 2))
1657 '(?< ?> ?!)))))))))
1658 (if (or (not found) ; not an assignment
1659 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1660 (progn
1661 (goto-char startpos)
1662 (skip-chars-forward "^ \t\n")))
1663 (1+ (current-column))))))
1664
1665 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001666 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001667
Barry Warsawa7891711996-08-01 15:53:09 +00001668 ;; Dfn: "Indenting comment line". A line containing only a
1669 ;; comment, but which is treated like a statement for
1670 ;; indentation calculation purposes. Such lines are only
1671 ;; treated specially by the mode; they are not treated
1672 ;; specially by the Python interpreter.
1673
1674 ;; The rules for indenting comment lines are a line where:
1675 ;; - the first non-whitespace character is `#', and
1676 ;; - the character following the `#' is whitespace, and
Barry Warsaw41a05c71998-08-10 16:33:12 +00001677 ;; - the line is dedented with respect to (i.e. to the left
Barry Warsawa7891711996-08-01 15:53:09 +00001678 ;; of) the indentation of the preceding non-blank line.
1679
1680 ;; The first non-blank line following an indenting comment
1681 ;; line is given the same amount of indentation as the
1682 ;; indenting comment line.
1683
1684 ;; All other comment-only lines are ignored for indentation
1685 ;; purposes.
1686
1687 ;; Are we looking at a comment-only line which is *not* an
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001688 ;; indenting comment line? If so, we assume that it's been
Barry Warsawa7891711996-08-01 15:53:09 +00001689 ;; placed at the desired indentation, so leave it alone.
1690 ;; Indenting comment lines are aligned as statements down
1691 ;; below.
1692 ((and (looking-at "[ \t]*#[^ \t\n]")
1693 ;; NOTE: this test will not be performed in older Emacsen
1694 (fboundp 'forward-comment)
1695 (<= (current-indentation)
1696 (save-excursion
1697 (forward-comment (- (point-max)))
1698 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001699 (current-indentation))
1700
1701 ;; else indentation based on that of the statement that
1702 ;; precedes us; use the first line of that statement to
1703 ;; establish the base, in case the user forced a non-std
1704 ;; indentation for the continuation lines (if any)
1705 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001706 ;; skip back over blank & non-indenting comment lines note:
1707 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001708 ;; happens to be a continuation line too. use fast Emacs 19
1709 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001710 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001711 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001712 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001713 (let (done)
1714 (while (not done)
Barry Warsaw12c92941998-08-10 21:44:37 +00001715 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#\\)" nil 'move)
1716 (setq done (or (bobp)
1717 (and (eq py-honor-comment-indentation t)
1718 (save-excursion
1719 (back-to-indentation)
1720 (not (looking-at py-block-comment-prefix))
1721 ))
1722 (and (not (eq py-honor-comment-indentation t))
1723 (save-excursion
1724 (back-to-indentation)
1725 (not (zerop (current-column)))))
1726 ))
Barry Warsaw6d627751996-03-06 18:41:38 +00001727 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001728 ;; if we landed inside a string, go to the beginning of that
1729 ;; string. this handles triple quoted, multi-line spanning
1730 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001731 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001732 (skip (and delim (make-string 1 delim))))
1733 (when skip
1734 (save-excursion
1735 (py-safe (search-backward skip))
1736 (if (and (eq (char-before) delim)
1737 (eq (char-before (1- (point))) delim))
1738 (setq skip (make-string 3 delim))))
1739 ;; we're looking at a triple-quoted string
1740 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001741 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001742 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001743 (+ (current-indentation)
1744 (if (py-statement-opens-block-p)
1745 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001746 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001747 (- py-indent-offset)
1748 0)))
1749 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001750
1751(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001752 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001753
1754By default, make a buffer-local copy of `py-indent-offset' with the
1755new value, so that other Python buffers are not affected. With
1756\\[universal-argument] (programmatically, optional argument GLOBAL),
1757change the global value of `py-indent-offset'. This affects all
1758Python buffers (that don't have their own buffer-local copy), both
1759those currently existing and those created later in the Emacs session.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001760
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001761Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001762There's no excuse for such foolishness, but sometimes you have to deal
1763with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001764`py-indent-offset' to what it thinks it was when they created the
1765mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001766
1767Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001768looking for a line that opens a block of code. `py-indent-offset' is
1769set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001770statement following it. If the search doesn't succeed going forward,
1771it's tried again going backward."
1772 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001773 (let (new-value
1774 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001775 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001776 (found nil)
1777 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001778 (py-goto-initial-line)
1779 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001780 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1781 (not (py-in-literal restart)))
1782 (setq restart (point))
1783 (py-goto-initial-line)
1784 (if (py-statement-opens-block-p)
1785 (setq found t)
1786 (goto-char restart))))
1787 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001788 (goto-char start)
1789 (py-goto-initial-line)
1790 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001791 (setq found (and
1792 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1793 (or (py-goto-initial-line) t) ; always true -- side effect
1794 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001795 (setq colon-indent (current-indentation)
1796 found (and found (zerop (py-next-statement 1)))
1797 new-value (- (current-indentation) colon-indent))
1798 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001799 (if (not found)
1800 (error "Sorry, couldn't guess a value for py-indent-offset")
1801 (funcall (if global 'kill-local-variable 'make-local-variable)
1802 'py-indent-offset)
1803 (setq py-indent-offset new-value)
1804 (message "%s value of py-indent-offset set to %d"
1805 (if global "Global" "Local")
1806 py-indent-offset))
1807 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001808
Barry Warsaw003932a1998-07-07 15:11:24 +00001809(defun py-comment-indent-function ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00001810 "Python version of `comment-indent-function'."
1811 ;; This is required when filladapt is turned off. Without it, when
1812 ;; filladapt is not used, comments which start in column zero
1813 ;; cascade one character to the right
Barry Warsaw003932a1998-07-07 15:11:24 +00001814 (save-excursion
1815 (beginning-of-line)
1816 (let ((eol (py-point 'eol)))
1817 (and comment-start-skip
1818 (re-search-forward comment-start-skip eol t)
1819 (setq eol (match-beginning 0)))
1820 (goto-char eol)
1821 (skip-chars-backward " \t")
1822 (max comment-column (+ (current-column) (if (bolp) 0 1)))
1823 )))
1824
1825
Barry Warsaw7ae77681994-12-12 20:38:05 +00001826(defun py-shift-region (start end count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001827 "Indent lines from START to END by COUNT spaces."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001828 (save-excursion
Barry Warsaw41a05c71998-08-10 16:33:12 +00001829 (goto-char end)
1830 (beginning-of-line)
1831 (setq end (point))
1832 (goto-char start)
1833 (beginning-of-line)
1834 (setq start (point))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001835 (indent-rigidly start end count)))
1836
1837(defun py-shift-region-left (start end &optional count)
1838 "Shift region of Python code to the left.
1839The lines from the line containing the start of the current region up
1840to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001841shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001842
1843If a prefix argument is given, the region is instead shifted by that
Barry Warsaw41a05c71998-08-10 16:33:12 +00001844many columns. With no active region, dedent only the current line.
1845You cannot dedent the region if any line is already at column zero."
Barry Warsawdea4a291996-07-03 22:59:12 +00001846 (interactive
1847 (let ((p (point))
1848 (m (mark))
1849 (arg current-prefix-arg))
1850 (if m
1851 (list (min p m) (max p m) arg)
1852 (list p (save-excursion (forward-line 1) (point)) arg))))
1853 ;; if any line is at column zero, don't shift the region
1854 (save-excursion
1855 (goto-char start)
1856 (while (< (point) end)
1857 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001858 (if (and (zerop (current-column))
1859 (not (looking-at "\\s *$")))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001860 (error "Region is at left edge"))
Barry Warsawdea4a291996-07-03 22:59:12 +00001861 (forward-line 1)))
1862 (py-shift-region start end (- (prefix-numeric-value
1863 (or count py-indent-offset))))
1864 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001865
1866(defun py-shift-region-right (start end &optional count)
1867 "Shift region of Python code to the right.
1868The lines from the line containing the start of the current region up
1869to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001870shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001871
1872If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001873many columns. With no active region, indent only the current line."
1874 (interactive
1875 (let ((p (point))
1876 (m (mark))
1877 (arg current-prefix-arg))
1878 (if m
1879 (list (min p m) (max p m) arg)
1880 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001881 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001882 (or count py-indent-offset)))
1883 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001884
1885(defun py-indent-region (start end &optional indent-offset)
1886 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001887
Barry Warsaw7ae77681994-12-12 20:38:05 +00001888The lines from the line containing the start of the current region up
1889to (but not including) the line containing the end of the region are
1890reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001891character in the first column, the first line is left alone and the
1892rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001893region is reindented with respect to the (closest code or indenting
1894comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001895
1896This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001897control structures are introduced or removed, or to reformat code
1898using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001899
1900If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001901the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001902used.
1903
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001904Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001905is called! This function does not compute proper indentation from
1906scratch (that's impossible in Python), it merely adjusts the existing
1907indentation to be correct in context.
1908
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001909Warning: This function really has no idea what to do with
1910non-indenting comment lines, and shifts them as if they were indenting
1911comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001912
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001913Special cases: whitespace is deleted from blank lines; continuation
1914lines are shifted by the same amount their initial line was shifted,
1915in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001916initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001917 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001918 (save-excursion
1919 (goto-char end) (beginning-of-line) (setq end (point-marker))
1920 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001921 (let ((py-indent-offset (prefix-numeric-value
1922 (or indent-offset py-indent-offset)))
1923 (indents '(-1)) ; stack of active indent levels
1924 (target-column 0) ; column to which to indent
1925 (base-shifted-by 0) ; amount last base line was shifted
1926 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001927 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001928 0))
1929 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001930 (while (< (point) end)
1931 (setq ci (current-indentation))
1932 ;; figure out appropriate target column
1933 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001934 ((or (eq (following-char) ?#) ; comment in column 1
1935 (looking-at "[ \t]*$")) ; entirely blank
1936 (setq target-column 0))
1937 ((py-continuation-line-p) ; shift relative to base line
1938 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001939 (t ; new base line
1940 (if (> ci (car indents)) ; going deeper; push it
1941 (setq indents (cons ci indents))
1942 ;; else we should have seen this indent before
1943 (setq indents (memq ci indents)) ; pop deeper indents
1944 (if (null indents)
1945 (error "Bad indentation in region, at line %d"
1946 (save-restriction
1947 (widen)
1948 (1+ (count-lines 1 (point)))))))
1949 (setq target-column (+ indent-base
1950 (* py-indent-offset
1951 (- (length indents) 2))))
1952 (setq base-shifted-by (- target-column ci))))
1953 ;; shift as needed
1954 (if (/= ci target-column)
1955 (progn
1956 (delete-horizontal-space)
1957 (indent-to target-column)))
1958 (forward-line 1))))
1959 (set-marker end nil))
1960
Barry Warsawa7891711996-08-01 15:53:09 +00001961(defun py-comment-region (beg end &optional arg)
1962 "Like `comment-region' but uses double hash (`#') comment starter."
1963 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001964 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001965 (comment-region beg end arg)))
1966
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001967
1968;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001969(defun py-previous-statement (count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001970 "Go to the start of the COUNTth preceding Python statement.
1971By default, goes to the previous statement. If there is no such
1972statement, goes to the first statement. Return count of statements
1973left to move. `Statements' do not include blank, comment, or
1974continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001975 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001976 (if (< count 0) (py-next-statement (- count))
1977 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001978 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001979 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001980 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001981 (> count 0)
1982 (zerop (forward-line -1))
1983 (py-goto-statement-at-or-above))
1984 (setq count (1- count)))
1985 (if (> count 0) (goto-char start)))
1986 count))
1987
1988(defun py-next-statement (count)
1989 "Go to the start of next Python statement.
1990If the statement at point is the i'th Python statement, goes to the
1991start of statement i+COUNT. If there is no such statement, goes to the
1992last statement. Returns count of statements left to move. `Statements'
1993do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001994 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001995 (if (< count 0) (py-previous-statement (- count))
1996 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001997 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001998 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001999 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002000 (> count 0)
2001 (py-goto-statement-below))
2002 (setq count (1- count)))
2003 (if (> count 0) (goto-char start)))
2004 count))
2005
2006(defun py-goto-block-up (&optional nomark)
2007 "Move up to start of current block.
2008Go to the statement that starts the smallest enclosing block; roughly
2009speaking, this will be the closest preceding statement that ends with a
2010colon and is indented less than the statement you started on. If
2011successful, also sets the mark to the starting point.
2012
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002013`\\[py-mark-block]' can be used afterward to mark the whole code
2014block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002015
2016If called from a program, the mark will not be set if optional argument
2017NOMARK is not nil."
2018 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002019 (let ((start (point))
2020 (found nil)
2021 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002022 (py-goto-initial-line)
2023 ;; if on blank or non-indenting comment line, use the preceding stmt
2024 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2025 (progn
2026 (py-goto-statement-at-or-above)
2027 (setq found (py-statement-opens-block-p))))
2028 ;; search back for colon line indented less
2029 (setq initial-indent (current-indentation))
2030 (if (zerop initial-indent)
2031 ;; force fast exit
2032 (goto-char (point-min)))
2033 (while (not (or found (bobp)))
2034 (setq found
2035 (and
2036 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2037 (or (py-goto-initial-line) t) ; always true -- side effect
2038 (< (current-indentation) initial-indent)
2039 (py-statement-opens-block-p))))
2040 (if found
2041 (progn
2042 (or nomark (push-mark start))
2043 (back-to-indentation))
2044 (goto-char start)
2045 (error "Enclosing block not found"))))
2046
Barry Warsawab0e86c1998-05-19 15:31:46 +00002047(defun py-beginning-of-def-or-class (&optional class count)
2048 "Move point to start of `def' or `class'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002049
2050Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsawab0e86c1998-05-19 15:31:46 +00002051arg, looks for a `class' instead. The docs below assume the `def'
2052case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002053Programmatically, if CLASS is `either', then moves to either `class'
2054or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002055
Barry Warsawab0e86c1998-05-19 15:31:46 +00002056When second optional argument is given programmatically, move to the
2057COUNTth start of `def'.
2058
2059If point is in a `def' statement already, and after the `d', simply
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002060moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002061
Barry Warsawab0e86c1998-05-19 15:31:46 +00002062Otherwise (i.e. when point is not in a `def' statement, or at or
2063before the `d' of a `def' statement), searches for the closest
2064preceding `def' statement, and leaves point at its start. If no such
2065statement can be found, leaves point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002066
Barry Warsawab0e86c1998-05-19 15:31:46 +00002067Returns t iff a `def' statement is found by these rules.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002068
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002069Note that doing this command repeatedly will take you closer to the
2070start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002071
Barry Warsaw7c29b231998-07-07 17:45:38 +00002072To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002073 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002074 (if (not count)
2075 (setq count 1))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002076 (let ((at-or-before-p (<= (current-column) (current-indentation)))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002077 (start-of-line (goto-char (py-point 'bol)))
2078 (start-of-stmt (goto-char (py-point 'bos)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002079 (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
2080 (class "^[ \t]*class\\>")
2081 (t "^[ \t]*def\\>")))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002082 )
2083 ;; searching backward
2084 (if (and (< 0 count)
2085 (or (/= start-of-stmt start-of-line)
2086 (not at-or-before-p)))
2087 (end-of-line))
2088 ;; search forward
2089 (if (and (> 0 count)
2090 (zerop (current-column))
2091 (looking-at start-re))
2092 (end-of-line))
2093 (re-search-backward start-re nil 'move count)
2094 (goto-char (match-beginning 0))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002095
Barry Warsawab0e86c1998-05-19 15:31:46 +00002096;; Backwards compatibility
2097(defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002098
Barry Warsawab0e86c1998-05-19 15:31:46 +00002099(defun py-end-of-def-or-class (&optional class count)
2100 "Move point beyond end of `def' or `class' body.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002101
Barry Warsawab0e86c1998-05-19 15:31:46 +00002102By default, looks for an appropriate `def'. If you supply a prefix
2103arg, looks for a `class' instead. The docs below assume the `def'
2104case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002105Programmatically, if CLASS is `either', then moves to either `class'
2106or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002107
Barry Warsawab0e86c1998-05-19 15:31:46 +00002108When second optional argument is given programmatically, move to the
2109COUNTth end of `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002110
Barry Warsawab0e86c1998-05-19 15:31:46 +00002111If point is in a `def' statement already, this is the `def' we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002112
Barry Warsawab0e86c1998-05-19 15:31:46 +00002113Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2114contains the statement you started on, that's the `def' we use.
2115
2116Otherwise, we search forward for the closest following `def', and use that.
2117
2118If a `def' can be found by these rules, point is moved to the start of
2119the line immediately following the `def' block, and the position of the
2120start of the `def' is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002121
2122Else point is moved to the end of the buffer, and nil is returned.
2123
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002124Note that doing this command repeatedly will take you closer to the
2125end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002126
Barry Warsaw7c29b231998-07-07 17:45:38 +00002127To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002128 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002129 (if (and count (/= count 1))
2130 (py-beginning-of-def-or-class (- 1 count)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002131 (let ((start (progn (py-goto-initial-line) (point)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002132 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2133 (class "class")
2134 (t "def")))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002135 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002136 ;; move point to start of appropriate def/class
2137 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2138 (setq state 'at-beginning)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002139 ;; else see if py-beginning-of-def-or-class hits container
2140 (if (and (py-beginning-of-def-or-class class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002141 (progn (py-goto-beyond-block)
2142 (> (point) start)))
2143 (setq state 'at-end)
2144 ;; else search forward
2145 (goto-char start)
2146 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2147 (progn (setq state 'at-beginning)
2148 (beginning-of-line)))))
2149 (cond
2150 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2151 ((eq state 'at-end) t)
2152 ((eq state 'not-found) nil)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002153 (t (error "Internal error in `py-end-of-def-or-class'")))))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002154
2155;; Backwards compabitility
Barry Warsaw820273d1998-05-19 15:54:45 +00002156(defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002157
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002158
2159;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002160(defun py-mark-block (&optional extend just-move)
2161 "Mark following block of lines. With prefix arg, mark structure.
2162Easier to use than explain. It sets the region to an `interesting'
2163block of succeeding lines. If point is on a blank line, it goes down to
2164the next non-blank line. That will be the start of the region. The end
2165of the region depends on the kind of line at the start:
2166
2167 - If a comment, the region will include all succeeding comment lines up
2168 to (but not including) the next non-comment line (if any).
2169
2170 - Else if a prefix arg is given, and the line begins one of these
2171 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002172
2173 if elif else try except finally for while def class
2174
Barry Warsaw7ae77681994-12-12 20:38:05 +00002175 the region will be set to the body of the structure, including
2176 following blocks that `belong' to it, but excluding trailing blank
2177 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002178 and all (if any) of the following `except' and `finally' blocks
2179 that belong to the `try' structure will be in the region. Ditto
2180 for if/elif/else, for/else and while/else structures, and (a bit
2181 degenerate, since they're always one-block structures) def and
2182 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002183
2184 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002185 block (see list above), and the block is not a `one-liner' (i.e.,
2186 the statement ends with a colon, not with code), the region will
2187 include all succeeding lines up to (but not including) the next
2188 code statement (if any) that's indented no more than the starting
2189 line, except that trailing blank and comment lines are excluded.
2190 E.g., if the starting line begins a multi-statement `def'
2191 structure, the region will be set to the full function definition,
2192 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002193
2194 - Else the region will include all succeeding lines up to (but not
2195 including) the next blank line, or code or indenting-comment line
2196 indented strictly less than the starting line. Trailing indenting
2197 comment lines are included in this case, but not trailing blank
2198 lines.
2199
2200A msg identifying the location of the mark is displayed in the echo
2201area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2202
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002203If called from a program, optional argument EXTEND plays the role of
2204the prefix arg, and if optional argument JUST-MOVE is not nil, just
2205moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002206 (interactive "P") ; raw prefix arg
2207 (py-goto-initial-line)
2208 ;; skip over blank lines
2209 (while (and
2210 (looking-at "[ \t]*$") ; while blank line
2211 (not (eobp))) ; & somewhere to go
2212 (forward-line 1))
2213 (if (eobp)
2214 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002215 (let ((initial-pos (point))
2216 (initial-indent (current-indentation))
2217 last-pos ; position of last stmt in region
2218 (followers
2219 '((if elif else) (elif elif else) (else)
2220 (try except finally) (except except) (finally)
2221 (for else) (while else)
2222 (def) (class) ) )
2223 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002224
2225 (cond
2226 ;; if comment line, suck up the following comment lines
2227 ((looking-at "[ \t]*#")
2228 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2229 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2230 (setq last-pos (point)))
2231
2232 ;; else if line is a block line and EXTEND given, suck up
2233 ;; the whole structure
2234 ((and extend
2235 (setq first-symbol (py-suck-up-first-keyword) )
2236 (assq first-symbol followers))
2237 (while (and
2238 (or (py-goto-beyond-block) t) ; side effect
2239 (forward-line -1) ; side effect
2240 (setq last-pos (point)) ; side effect
2241 (py-goto-statement-below)
2242 (= (current-indentation) initial-indent)
2243 (setq next-symbol (py-suck-up-first-keyword))
2244 (memq next-symbol (cdr (assq first-symbol followers))))
2245 (setq first-symbol next-symbol)))
2246
2247 ;; else if line *opens* a block, search for next stmt indented <=
2248 ((py-statement-opens-block-p)
2249 (while (and
2250 (setq last-pos (point)) ; always true -- side effect
2251 (py-goto-statement-below)
2252 (> (current-indentation) initial-indent))
2253 nil))
2254
2255 ;; else plain code line; stop at next blank line, or stmt or
2256 ;; indenting comment line indented <
2257 (t
2258 (while (and
2259 (setq last-pos (point)) ; always true -- side effect
2260 (or (py-goto-beyond-final-line) t)
2261 (not (looking-at "[ \t]*$")) ; stop at blank line
2262 (or
2263 (>= (current-indentation) initial-indent)
2264 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2265 nil)))
2266
2267 ;; skip to end of last stmt
2268 (goto-char last-pos)
2269 (py-goto-beyond-final-line)
2270
2271 ;; set mark & display
2272 (if just-move
2273 () ; just return
2274 (push-mark (point) 'no-msg)
2275 (forward-line -1)
2276 (message "Mark set after: %s" (py-suck-up-leading-text))
2277 (goto-char initial-pos))))
2278
Barry Warsaw2518c671997-11-05 00:51:08 +00002279(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002280 "Set region to body of def (or class, with prefix arg) enclosing point.
2281Pushes the current mark, then point, on the mark ring (all language
2282modes do this, but although it's handy it's never documented ...).
2283
2284In most Emacs language modes, this function bears at least a
Barry Warsawab0e86c1998-05-19 15:31:46 +00002285hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2286`\\[py-beginning-of-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002287
2288And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002289Turned out that was more confusing than useful: the `goto start' and
2290`goto end' commands are usually used to search through a file, and
2291people expect them to act a lot like `search backward' and `search
2292forward' string-search commands. But because Python `def' and `class'
2293can nest to arbitrary levels, finding the smallest def containing
2294point cannot be done via a simple backward search: the def containing
2295point may not be the closest preceding def, or even the closest
2296preceding def that's indented less. The fancy algorithm required is
2297appropriate for the usual uses of this `mark' command, but not for the
2298`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002299
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002300So the def marked by this command may not be the one either of the
2301`goto' commands find: If point is on a blank or non-indenting comment
2302line, moves back to start of the closest preceding code statement or
2303indenting comment line. If this is a `def' statement, that's the def
2304we use. Else searches for the smallest enclosing `def' block and uses
2305that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002306
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002307When an enclosing def is found: The mark is left immediately beyond
2308the last line of the def block. Point is left at the start of the
2309def, except that: if the def is preceded by a number of comment lines
2310followed by (at most) one optional blank line, point is left at the
2311start of the comments; else if the def is preceded by a blank line,
2312point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002313
2314The intent is to mark the containing def/class and its associated
2315documentation, to make moving and duplicating functions and classes
2316pleasant."
2317 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002318 (let ((start (point))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002319 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2320 (class "class")
2321 (t "def"))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002322 (push-mark start)
2323 (if (not (py-go-up-tree-to-keyword which))
2324 (progn (goto-char start)
Barry Warsaw7c29b231998-07-07 17:45:38 +00002325 (error "Enclosing %s not found"
2326 (if (eq class 'either)
2327 "def or class"
2328 which)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002329 ;; else enclosing def/class found
2330 (setq start (point))
2331 (py-goto-beyond-block)
2332 (push-mark (point))
2333 (goto-char start)
2334 (if (zerop (forward-line -1)) ; if there is a preceding line
2335 (progn
2336 (if (looking-at "[ \t]*$") ; it's blank
2337 (setq start (point)) ; so reset start point
2338 (goto-char start)) ; else try again
2339 (if (zerop (forward-line -1))
2340 (if (looking-at "[ \t]*#") ; a comment
2341 ;; look back for non-comment line
2342 ;; tricky: note that the regexp matches a blank
2343 ;; line, cuz \n is in the 2nd character class
2344 (and
2345 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2346 (forward-line 1))
2347 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002348 (goto-char start)))))))
2349 (exchange-point-and-mark)
2350 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002351
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002352;; ripped from cc-mode
2353(defun py-forward-into-nomenclature (&optional arg)
2354 "Move forward to end of a nomenclature section or word.
Barry Warsaw41a05c71998-08-10 16:33:12 +00002355With \\[universal-argument] (programmatically, optional argument ARG),
2356do it that many times.
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002357
2358A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2359 (interactive "p")
2360 (let ((case-fold-search nil))
2361 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002362 (re-search-forward
2363 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2364 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002365 (while (and (< arg 0)
2366 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002367 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002368 (point-min) 0))
2369 (forward-char 1)
2370 (setq arg (1+ arg)))))
2371 (py-keep-region-active))
2372
2373(defun py-backward-into-nomenclature (&optional arg)
2374 "Move backward to beginning of a nomenclature section or word.
2375With optional ARG, move that many times. If ARG is negative, move
2376forward.
2377
2378A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2379 (interactive "p")
2380 (py-forward-into-nomenclature (- arg))
2381 (py-keep-region-active))
2382
2383
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002384
2385;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002386
2387;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002388;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2389;; out of the right places, along with the keys they're on & current
2390;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002391(defun py-dump-help-string (str)
2392 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002393 (let ((locals (buffer-local-variables))
2394 funckind funcname func funcdoc
2395 (start 0) mstart end
2396 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002397 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2398 (setq mstart (match-beginning 0) end (match-end 0)
2399 funckind (substring str (match-beginning 1) (match-end 1))
2400 funcname (substring str (match-beginning 2) (match-end 2))
2401 func (intern funcname))
2402 (princ (substitute-command-keys (substring str start mstart)))
2403 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002404 ((equal funckind "c") ; command
2405 (setq funcdoc (documentation func)
2406 keys (concat
2407 "Key(s): "
2408 (mapconcat 'key-description
2409 (where-is-internal func py-mode-map)
2410 ", "))))
2411 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002412 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002413 keys (if (assq func locals)
2414 (concat
2415 "Local/Global values: "
2416 (prin1-to-string (symbol-value func))
2417 " / "
2418 (prin1-to-string (default-value func)))
2419 (concat
2420 "Value: "
2421 (prin1-to-string (symbol-value func))))))
2422 (t ; unexpected
2423 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002424 (princ (format "\n-> %s:\t%s\t%s\n\n"
2425 (if (equal funckind "c") "Command" "Variable")
2426 funcname keys))
2427 (princ funcdoc)
2428 (terpri)
2429 (setq start end))
2430 (princ (substitute-command-keys (substring str start))))
2431 (print-help-return-message)))
2432
2433(defun py-describe-mode ()
2434 "Dump long form of Python-mode docs."
2435 (interactive)
2436 (py-dump-help-string "Major mode for editing Python files.
2437Knows about Python indentation, tokens, comments and continuation lines.
2438Paragraphs are separated by blank lines only.
2439
2440Major sections below begin with the string `@'; specific function and
2441variable docs begin with `->'.
2442
2443@EXECUTING PYTHON CODE
2444
Barry Warsaw820273d1998-05-19 15:54:45 +00002445\\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002446\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2447\\[py-execute-region]\tsends the current region
Barry Warsaw820273d1998-05-19 15:54:45 +00002448\\[py-execute-def-or-class]\tsends the current function or class definition
2449\\[py-execute-string]\tsends an arbitrary string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002450\\[py-shell]\tstarts a Python interpreter window; this will be used by
Barry Warsaw820273d1998-05-19 15:54:45 +00002451\tsubsequent Python execution commands
2452%c:py-execute-import-or-reload
Barry Warsaw7ae77681994-12-12 20:38:05 +00002453%c:py-execute-buffer
2454%c:py-execute-region
Barry Warsaw820273d1998-05-19 15:54:45 +00002455%c:py-execute-def-or-class
2456%c:py-execute-string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002457%c:py-shell
2458
2459@VARIABLES
2460
2461py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002462py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002463
2464py-python-command\tshell command to invoke Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002465py-temp-directory\tdirectory used for temp files (if needed)
2466
2467py-beep-if-tab-change\tring the bell if tab-width is changed
2468%v:py-indent-offset
2469%v:py-block-comment-prefix
2470%v:py-python-command
Barry Warsaw7ae77681994-12-12 20:38:05 +00002471%v:py-temp-directory
2472%v:py-beep-if-tab-change
2473
2474@KINDS OF LINES
2475
2476Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002477preceding line ends with a backslash that's not part of a comment, or
2478the paren/bracket/brace nesting level at the start of the line is
2479non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002480
2481An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002482possibly blanks or tabs), a `comment line' (leftmost non-blank
2483character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002484
2485Comment Lines
2486
2487Although all comment lines are treated alike by Python, Python mode
2488recognizes two kinds that act differently with respect to indentation.
2489
2490An `indenting comment line' is a comment line with a blank, tab or
2491nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002492treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002493indenting comment line will be indented like the comment line. All
2494other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002495following the initial `#') are `non-indenting comment lines', and
2496their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002497
2498Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002499whenever possible. Non-indenting comment lines are useful in cases
2500like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002501
2502\ta = b # a very wordy single-line comment that ends up being
2503\t #... continued onto another line
2504
2505\tif a == b:
2506##\t\tprint 'panic!' # old code we've `commented out'
2507\t\treturn a
2508
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002509Since the `#...' and `##' comment lines have a non-whitespace
2510character following the initial `#', Python mode ignores them when
2511computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002512
2513Continuation Lines and Statements
2514
2515The Python-mode commands generally work on statements instead of on
2516individual lines, where a `statement' is a comment or blank line, or a
2517code line and all of its following continuation lines (if any)
2518considered as a single logical unit. The commands in this mode
2519generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002520statement containing point, even if point happens to be in the middle
2521of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002522
2523
2524@INDENTATION
2525
2526Primarily for entering new code:
2527\t\\[indent-for-tab-command]\t indent line appropriately
2528\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002529\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002530
2531Primarily for reindenting existing code:
2532\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2533\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2534
2535\t\\[py-indent-region]\t reindent region to match its context
2536\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2537\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2538
2539Unlike most programming languages, Python uses indentation, and only
2540indentation, to specify block structure. Hence the indentation supplied
2541automatically by Python-mode is just an educated guess: only you know
2542the block structure you intend, so only you can supply correct
2543indentation.
2544
2545The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2546the indentation of preceding statements. E.g., assuming
2547py-indent-offset is 4, after you enter
2548\tif a > 0: \\[py-newline-and-indent]
2549the cursor will be moved to the position of the `_' (_ is not a
2550character in the file, it's just used here to indicate the location of
2551the cursor):
2552\tif a > 0:
2553\t _
2554If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2555to
2556\tif a > 0:
2557\t c = d
2558\t _
2559Python-mode cannot know whether that's what you intended, or whether
2560\tif a > 0:
2561\t c = d
2562\t_
2563was your intent. In general, Python-mode either reproduces the
2564indentation of the (closest code or indenting-comment) preceding
2565statement, or adds an extra py-indent-offset blanks if the preceding
2566statement has `:' as its last significant (non-whitespace and non-
2567comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002568\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002569
2570Continuation lines are given extra indentation. If you don't like the
2571suggested indentation, change it to something you do like, and Python-
2572mode will strive to indent later lines of the statement in the same way.
2573
2574If a line is a continuation line by virtue of being in an unclosed
2575paren/bracket/brace structure (`list', for short), the suggested
2576indentation depends on whether the current line contains the first item
2577in the list. If it does, it's indented py-indent-offset columns beyond
2578the indentation of the line containing the open bracket. If you don't
2579like that, change it by hand. The remaining items in the list will mimic
2580whatever indentation you give to the first item.
2581
2582If a line is a continuation line because the line preceding it ends with
2583a backslash, the third and following lines of the statement inherit their
2584indentation from the line preceding them. The indentation of the second
2585line in the statement depends on the form of the first (base) line: if
2586the base line is an assignment statement with anything more interesting
2587than the backslash following the leftmost assigning `=', the second line
2588is indented two columns beyond that `='. Else it's indented to two
2589columns beyond the leftmost solid chunk of non-whitespace characters on
2590the base line.
2591
2592Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2593repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2594structure you intend.
2595%c:indent-for-tab-command
2596%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002597%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002598
2599
2600The next function may be handy when editing code you didn't write:
2601%c:py-guess-indent-offset
2602
2603
2604The remaining `indent' functions apply to a region of Python code. They
2605assume the block structure (equals indentation, in Python) of the region
2606is correct, and alter the indentation in various ways while preserving
2607the block structure:
2608%c:py-indent-region
2609%c:py-shift-region-left
2610%c:py-shift-region-right
2611
2612@MARKING & MANIPULATING REGIONS OF CODE
2613
2614\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002615\\[py-mark-def-or-class]\t mark smallest enclosing def
2616\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002617\\[comment-region]\t comment out region of code
2618\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002619%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002620%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002621%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002622
2623@MOVING POINT
2624
2625\\[py-previous-statement]\t move to statement preceding point
2626\\[py-next-statement]\t move to statement following point
2627\\[py-goto-block-up]\t move up to start of current block
Barry Warsawab0e86c1998-05-19 15:31:46 +00002628\\[py-beginning-of-def-or-class]\t move to start of def
2629\\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
2630\\[py-end-of-def-or-class]\t move to end of def
2631\\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002632
2633The first two move to one statement beyond the statement that contains
2634point. A numeric prefix argument tells them to move that many
2635statements instead. Blank lines, comment lines, and continuation lines
2636do not count as `statements' for these commands. So, e.g., you can go
2637to the first code statement in a file by entering
2638\t\\[beginning-of-buffer]\t to move to the top of the file
2639\t\\[py-next-statement]\t to skip over initial comments and blank lines
2640Or do `\\[py-previous-statement]' with a huge prefix argument.
2641%c:py-previous-statement
2642%c:py-next-statement
2643%c:py-goto-block-up
Barry Warsawab0e86c1998-05-19 15:31:46 +00002644%c:py-beginning-of-def-or-class
2645%c:py-end-of-def-or-class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002646
2647@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2648
2649`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2650
2651`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2652overall class and def structure of a module.
2653
2654`\\[back-to-indentation]' moves point to a line's first non-blank character.
2655
2656`\\[indent-relative]' is handy for creating odd indentation.
2657
2658@OTHER EMACS HINTS
2659
2660If you don't like the default value of a variable, change its value to
2661whatever you do like by putting a `setq' line in your .emacs file.
2662E.g., to set the indentation increment to 4, put this line in your
2663.emacs:
2664\t(setq py-indent-offset 4)
2665To see the value of a variable, do `\\[describe-variable]' and enter the variable
2666name at the prompt.
2667
2668When entering a key sequence like `C-c C-n', it is not necessary to
2669release the CONTROL key after doing the `C-c' part -- it suffices to
2670press the CONTROL key, press and release `c' (while still holding down
2671CONTROL), press and release `n' (while still holding down CONTROL), &
2672then release CONTROL.
2673
2674Entering Python mode calls with no arguments the value of the variable
2675`python-mode-hook', if that value exists and is not nil; for backward
2676compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2677the Elisp manual for details.
2678
2679Obscure: When python-mode is first loaded, it looks for all bindings
2680to newline-and-indent in the global keymap, and shadows them with
2681local bindings to py-newline-and-indent."))
2682
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002683
2684;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002685(defvar py-parse-state-re
2686 (concat
2687 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2688 "\\|"
2689 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002690
Barry Warsaw7ae77681994-12-12 20:38:05 +00002691(defun py-parse-state ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002692 "Return the parse state at point (see `parse-partial-sexp' docs)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002693 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002694 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002695 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002696 (while (not done)
2697 ;; back up to the first preceding line (if any; else start of
2698 ;; buffer) that begins with a popular Python keyword, or a
2699 ;; non- whitespace and non-comment character. These are good
2700 ;; places to start parsing to see whether where we started is
2701 ;; at a non-zero nesting level. It may be slow for people who
2702 ;; write huge code blocks or huge lists ... tough beans.
2703 (re-search-backward py-parse-state-re nil 'move)
2704 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002705 ;; In XEmacs, we have a much better way to test for whether
2706 ;; we're in a triple-quoted string or not. Emacs does not
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002707 ;; have this built-in function, which is its loss because
Barry Warsawf64b4051998-02-12 16:52:14 +00002708 ;; without scanning from the beginning of the buffer, there's
2709 ;; no accurate way to determine this otherwise.
2710 (if (not (fboundp 'buffer-syntactic-context))
2711 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002712 (progn
2713 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002714 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002715 (setq done (or (not (nth 3 pps))
2716 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002717 ;; XEmacs
2718 (setq done (or (not (buffer-syntactic-context))
2719 (bobp)))
2720 (when done
2721 (setq pps (parse-partial-sexp (point) here)))
2722 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002723 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002724
Barry Warsaw7ae77681994-12-12 20:38:05 +00002725(defun py-nesting-level ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002726 "Return the buffer position of the last unclosed enclosing list.
2727If nesting level is zero, return nil."
Barry Warsawf64b4051998-02-12 16:52:14 +00002728 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002729 (if (zerop (car status))
2730 nil ; not in a nest
2731 (car (cdr status))))) ; char# of open bracket
2732
Barry Warsaw7ae77681994-12-12 20:38:05 +00002733(defun py-backslash-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002734 "Return t iff preceding line ends with backslash that is not in a comment."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002735 (save-excursion
2736 (beginning-of-line)
2737 (and
2738 ;; use a cheap test first to avoid the regexp if possible
2739 ;; use 'eq' because char-after may return nil
2740 (eq (char-after (- (point) 2)) ?\\ )
2741 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002742 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002743 (looking-at py-continued-re))))
2744
Barry Warsaw7ae77681994-12-12 20:38:05 +00002745(defun py-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002746 "Return t iff current line is a continuation line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002747 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002748 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002749 (or (py-backslash-continuation-line-p)
2750 (py-nesting-level))))
2751
Barry Warsaw7ae77681994-12-12 20:38:05 +00002752(defun py-goto-initial-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002753 "Go to the initial line of the current statement.
2754Usually this is the line we're on, but if we're on the 2nd or
2755following lines of a continuation block, we need to go up to the first
2756line of the block."
2757 ;; Tricky: We want to avoid quadratic-time behavior for long
2758 ;; continued blocks, whether of the backslash or open-bracket
2759 ;; varieties, or a mix of the two. The following manages to do that
2760 ;; in the usual cases.
2761 ;;
2762 ;; Also, if we're sitting inside a triple quoted string, this will
2763 ;; drop us at the line that begins the string.
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002764 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002765 (while (py-continuation-line-p)
2766 (beginning-of-line)
2767 (if (py-backslash-continuation-line-p)
2768 (while (py-backslash-continuation-line-p)
2769 (forward-line -1))
2770 ;; else zip out of nested brackets/braces/parens
2771 (while (setq open-bracket-pos (py-nesting-level))
2772 (goto-char open-bracket-pos)))))
2773 (beginning-of-line))
2774
Barry Warsaw7ae77681994-12-12 20:38:05 +00002775(defun py-goto-beyond-final-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002776 "Go to the point just beyond the fine line of the current statement.
2777Usually this is the start of the next line, but if this is a
2778multi-line statement we need to skip over the continuation lines."
2779 ;; Tricky: Again we need to be clever to avoid quadratic time
2780 ;; behavior.
2781 ;;
2782 ;; XXX: Not quite the right solution, but deals with multi-line doc
2783 ;; strings
Barry Warsaw751f4931998-05-19 16:06:21 +00002784 (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
2785 (goto-char (match-end 0)))
2786 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +00002787 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002788 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002789 (while (and (py-continuation-line-p)
2790 (not (eobp)))
2791 ;; skip over the backslash flavor
2792 (while (and (py-backslash-continuation-line-p)
2793 (not (eobp)))
2794 (forward-line 1))
2795 ;; if in nest, zip to the end of the nest
2796 (setq state (py-parse-state))
2797 (if (and (not (zerop (car state)))
2798 (not (eobp)))
2799 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002800 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002801 (forward-line 1))))))
2802
Barry Warsaw7ae77681994-12-12 20:38:05 +00002803(defun py-statement-opens-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002804 "Return t iff the current statement opens a block.
2805I.e., iff it ends with a colon that is not in a comment. Point should
2806be at the start of a statement."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002807 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002808 (let ((start (point))
2809 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2810 (searching t)
2811 (answer nil)
2812 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002813 (goto-char start)
2814 (while searching
2815 ;; look for a colon with nothing after it except whitespace, and
2816 ;; maybe a comment
2817 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2818 finish t)
2819 (if (eq (point) finish) ; note: no `else' clause; just
2820 ; keep searching if we're not at
2821 ; the end yet
2822 ;; sure looks like it opens a block -- but it might
2823 ;; be in a comment
2824 (progn
2825 (setq searching nil) ; search is done either way
2826 (setq state (parse-partial-sexp start
2827 (match-beginning 0)))
2828 (setq answer (not (nth 4 state)))))
2829 ;; search failed: couldn't find another interesting colon
2830 (setq searching nil)))
2831 answer)))
2832
Barry Warsawf831d811996-07-31 20:42:59 +00002833(defun py-statement-closes-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002834 "Return t iff the current statement closes a block.
2835I.e., if the line starts with `return', `raise', `break', `continue',
2836and `pass'. This doesn't catch embedded statements."
Barry Warsawf831d811996-07-31 20:42:59 +00002837 (let ((here (point)))
2838 (back-to-indentation)
2839 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002840 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002841 (goto-char here))))
2842
Barry Warsaw7ae77681994-12-12 20:38:05 +00002843(defun py-goto-beyond-block ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002844 "Go to point just beyond the final line of block begun by the current line.
2845This is the same as where `py-goto-beyond-final-line' goes unless
2846we're on colon line, in which case we go to the end of the block.
2847Assumes point is at the beginning of the line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002848 (if (py-statement-opens-block-p)
2849 (py-mark-block nil 'just-move)
2850 (py-goto-beyond-final-line)))
2851
Barry Warsaw7ae77681994-12-12 20:38:05 +00002852(defun py-goto-statement-at-or-above ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002853 "Go to the start of the first statement at or preceding point.
2854Return t if there is such a statement, otherwise nil. `Statement'
2855does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002856 (py-goto-initial-line)
2857 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002858 ;; skip back over blank & comment lines
2859 ;; note: will skip a blank or comment line that happens to be
2860 ;; a continuation line too
2861 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2862 (progn (py-goto-initial-line) t)
2863 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002864 t))
2865
Barry Warsaw7ae77681994-12-12 20:38:05 +00002866(defun py-goto-statement-below ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002867 "Go to start of the first statement following the statement containing point.
2868Return t if there is such a statement, otherwise nil. `Statement'
2869does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002870 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002871 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002872 (py-goto-beyond-final-line)
2873 (while (and
2874 (looking-at py-blank-or-comment-re)
2875 (not (eobp)))
2876 (forward-line 1))
2877 (if (eobp)
2878 (progn (goto-char start) nil)
2879 t)))
2880
Barry Warsaw7ae77681994-12-12 20:38:05 +00002881(defun py-go-up-tree-to-keyword (key)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002882 "Go to begining of statement starting with KEY, at or preceding point.
2883
2884KEY is a regular expression describing a Python keyword. Skip blank
2885lines and non-indenting comments. If the statement found starts with
2886KEY, then stop, otherwise go back to first enclosing block starting
2887with KEY. If successful, leave point at the start of the KEY line and
2888return t. Otherwise, leav point at an undefined place and return nil."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002889 ;; skip blanks and non-indenting #
2890 (py-goto-initial-line)
2891 (while (and
2892 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2893 (zerop (forward-line -1))) ; go back
2894 nil)
2895 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002896 (let* ((re (concat "[ \t]*" key "\\b"))
2897 (case-fold-search nil) ; let* so looking-at sees this
2898 (found (looking-at re))
2899 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002900 (while (not (or found dead))
2901 (condition-case nil ; in case no enclosing block
2902 (py-goto-block-up 'no-mark)
2903 (error (setq dead t)))
2904 (or dead (setq found (looking-at re))))
2905 (beginning-of-line)
2906 found))
2907
Barry Warsaw7ae77681994-12-12 20:38:05 +00002908(defun py-suck-up-leading-text ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002909 "Return string in buffer from start of indentation to end of line.
2910Prefix with \"...\" if leading whitespace was skipped."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002911 (save-excursion
2912 (back-to-indentation)
2913 (concat
2914 (if (bolp) "" "...")
2915 (buffer-substring (point) (progn (end-of-line) (point))))))
2916
Barry Warsaw7ae77681994-12-12 20:38:05 +00002917(defun py-suck-up-first-keyword ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002918 "Return first keyword on the line as a Lisp symbol.
2919`Keyword' is defined (essentially) as the regular expression
2920([a-z]+). Returns nil if none was found."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002921 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002922 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2923 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2924 nil)))
2925
Barry Warsawb3e81d51996-09-04 15:12:42 +00002926(defun py-current-defun ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002927 "Python value for `add-log-current-defun-function'.
2928This tells add-log.el how to find the current function/method/variable."
Barry Warsawb3e81d51996-09-04 15:12:42 +00002929 (save-excursion
2930 (if (re-search-backward py-defun-start-re nil t)
2931 (or (match-string 3)
2932 (let ((method (match-string 2)))
2933 (if (and (not (zerop (length (match-string 1))))
2934 (re-search-backward py-class-start-re nil t))
2935 (concat (match-string 1) "." method)
2936 method)))
2937 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002938
2939
Barry Warsawfec75d61995-07-05 23:26:15 +00002940(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002941 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002942
Barry Warsaw850437a1995-03-08 21:50:28 +00002943(defun py-version ()
2944 "Echo the current version of `python-mode' in the minibuffer."
2945 (interactive)
2946 (message "Using `python-mode' version %s" py-version)
2947 (py-keep-region-active))
2948
2949;; only works under Emacs 19
2950;(eval-when-compile
2951; (require 'reporter))
2952
2953(defun py-submit-bug-report (enhancement-p)
2954 "Submit via mail a bug report on `python-mode'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00002955With \\[universal-argument] (programmatically, argument ENHANCEMENT-P
2956non-nil) just submit an enhancement request."
Barry Warsaw850437a1995-03-08 21:50:28 +00002957 (interactive
2958 (list (not (y-or-n-p
Barry Warsaw41a05c71998-08-10 16:33:12 +00002959 "Is this a bug report (hit `n' to send other comments)? "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002960 (let ((reporter-prompt-for-summary-p (if enhancement-p
2961 "(Very) brief summary: "
2962 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002963 (require 'reporter)
2964 (reporter-submit-bug-report
2965 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002966 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002967 ;; varlist
2968 (if enhancement-p nil
2969 '(py-python-command
2970 py-indent-offset
2971 py-block-comment-prefix
Barry Warsaw850437a1995-03-08 21:50:28 +00002972 py-temp-directory
2973 py-beep-if-tab-change))
2974 nil ;pre-hooks
2975 nil ;post-hooks
2976 "Dear Barry,") ;salutation
2977 (if enhancement-p nil
2978 (set-mark (point))
2979 (insert
2980"Please replace this text with a sufficiently large code sample\n\
2981and an exact recipe so that I can reproduce your problem. Failure\n\
2982to do so may mean a greater delay in fixing your bug.\n\n")
2983 (exchange-point-and-mark)
2984 (py-keep-region-active))))
2985
2986
Barry Warsaw47384781997-11-26 05:27:45 +00002987(defun py-kill-emacs-hook ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002988 "Delete files in `py-file-queue'.
2989These are Python temporary files awaiting execution."
Barry Warsaw47384781997-11-26 05:27:45 +00002990 (mapcar #'(lambda (filename)
2991 (py-safe (delete-file filename)))
2992 py-file-queue))
2993
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002994;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002995(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002996
2997
2998
2999(provide 'python-mode)
3000;;; python-mode.el ends here