blob: 61ae46518b5096a7b70efc77703b3148f38d0fd7 [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 Warsaw218eb751998-09-22 19:51:47 +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 Warsaw218eb751998-09-22 19:51:47 +0000164`...' is arbitrary). However, this string should not end in whitespace."
Barry Warsawc72c11c1997-08-09 06:42:08 +0000165 :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))
Barry Warsaw02e5f691998-09-24 23:48:40 +00001043 (cmd (format "execfile(r'%s')\n" filename)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001044 (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))
Barry Warsaw02e5f691998-09-24 23:48:40 +00001321 (format "execfile(r'%s')\n" file))
Barry Warsaw820273d1998-05-19 15:54:45 +00001322 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 Warsaw218eb751998-09-22 19:51:47 +00001713 (let ((prefix-re (concat py-block-comment-prefix "[ \t]*"))
1714 done)
Barry Warsaw6d627751996-03-06 18:41:38 +00001715 (while (not done)
Barry Warsaw12c92941998-08-10 21:44:37 +00001716 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#\\)" nil 'move)
1717 (setq done (or (bobp)
1718 (and (eq py-honor-comment-indentation t)
1719 (save-excursion
1720 (back-to-indentation)
Barry Warsaw218eb751998-09-22 19:51:47 +00001721 (not (looking-at prefix-re))
Barry Warsaw12c92941998-08-10 21:44:37 +00001722 ))
1723 (and (not (eq py-honor-comment-indentation t))
1724 (save-excursion
1725 (back-to-indentation)
1726 (not (zerop (current-column)))))
1727 ))
Barry Warsaw6d627751996-03-06 18:41:38 +00001728 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001729 ;; if we landed inside a string, go to the beginning of that
1730 ;; string. this handles triple quoted, multi-line spanning
1731 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001732 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001733 (skip (and delim (make-string 1 delim))))
1734 (when skip
1735 (save-excursion
1736 (py-safe (search-backward skip))
1737 (if (and (eq (char-before) delim)
1738 (eq (char-before (1- (point))) delim))
1739 (setq skip (make-string 3 delim))))
1740 ;; we're looking at a triple-quoted string
1741 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001742 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001743 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001744 (+ (current-indentation)
1745 (if (py-statement-opens-block-p)
1746 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001747 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001748 (- py-indent-offset)
1749 0)))
1750 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001751
1752(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001753 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001754
1755By default, make a buffer-local copy of `py-indent-offset' with the
1756new value, so that other Python buffers are not affected. With
1757\\[universal-argument] (programmatically, optional argument GLOBAL),
1758change the global value of `py-indent-offset'. This affects all
1759Python buffers (that don't have their own buffer-local copy), both
1760those currently existing and those created later in the Emacs session.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001761
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001762Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001763There's no excuse for such foolishness, but sometimes you have to deal
1764with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001765`py-indent-offset' to what it thinks it was when they created the
1766mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001767
1768Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001769looking for a line that opens a block of code. `py-indent-offset' is
1770set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001771statement following it. If the search doesn't succeed going forward,
1772it's tried again going backward."
1773 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001774 (let (new-value
1775 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001776 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001777 (found nil)
1778 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001779 (py-goto-initial-line)
1780 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001781 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1782 (not (py-in-literal restart)))
1783 (setq restart (point))
1784 (py-goto-initial-line)
1785 (if (py-statement-opens-block-p)
1786 (setq found t)
1787 (goto-char restart))))
1788 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001789 (goto-char start)
1790 (py-goto-initial-line)
1791 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001792 (setq found (and
1793 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1794 (or (py-goto-initial-line) t) ; always true -- side effect
1795 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001796 (setq colon-indent (current-indentation)
1797 found (and found (zerop (py-next-statement 1)))
1798 new-value (- (current-indentation) colon-indent))
1799 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001800 (if (not found)
1801 (error "Sorry, couldn't guess a value for py-indent-offset")
1802 (funcall (if global 'kill-local-variable 'make-local-variable)
1803 'py-indent-offset)
1804 (setq py-indent-offset new-value)
1805 (message "%s value of py-indent-offset set to %d"
1806 (if global "Global" "Local")
1807 py-indent-offset))
1808 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001809
Barry Warsaw003932a1998-07-07 15:11:24 +00001810(defun py-comment-indent-function ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00001811 "Python version of `comment-indent-function'."
1812 ;; This is required when filladapt is turned off. Without it, when
1813 ;; filladapt is not used, comments which start in column zero
1814 ;; cascade one character to the right
Barry Warsaw003932a1998-07-07 15:11:24 +00001815 (save-excursion
1816 (beginning-of-line)
1817 (let ((eol (py-point 'eol)))
1818 (and comment-start-skip
1819 (re-search-forward comment-start-skip eol t)
1820 (setq eol (match-beginning 0)))
1821 (goto-char eol)
1822 (skip-chars-backward " \t")
1823 (max comment-column (+ (current-column) (if (bolp) 0 1)))
1824 )))
1825
1826
Barry Warsaw7ae77681994-12-12 20:38:05 +00001827(defun py-shift-region (start end count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001828 "Indent lines from START to END by COUNT spaces."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001829 (save-excursion
Barry Warsaw41a05c71998-08-10 16:33:12 +00001830 (goto-char end)
1831 (beginning-of-line)
1832 (setq end (point))
1833 (goto-char start)
1834 (beginning-of-line)
1835 (setq start (point))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001836 (indent-rigidly start end count)))
1837
1838(defun py-shift-region-left (start end &optional count)
1839 "Shift region of Python code to the left.
1840The lines from the line containing the start of the current region up
1841to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001842shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001843
1844If a prefix argument is given, the region is instead shifted by that
Barry Warsaw41a05c71998-08-10 16:33:12 +00001845many columns. With no active region, dedent only the current line.
1846You cannot dedent the region if any line is already at column zero."
Barry Warsawdea4a291996-07-03 22:59:12 +00001847 (interactive
1848 (let ((p (point))
1849 (m (mark))
1850 (arg current-prefix-arg))
1851 (if m
1852 (list (min p m) (max p m) arg)
1853 (list p (save-excursion (forward-line 1) (point)) arg))))
1854 ;; if any line is at column zero, don't shift the region
1855 (save-excursion
1856 (goto-char start)
1857 (while (< (point) end)
1858 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001859 (if (and (zerop (current-column))
1860 (not (looking-at "\\s *$")))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001861 (error "Region is at left edge"))
Barry Warsawdea4a291996-07-03 22:59:12 +00001862 (forward-line 1)))
1863 (py-shift-region start end (- (prefix-numeric-value
1864 (or count py-indent-offset))))
1865 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001866
1867(defun py-shift-region-right (start end &optional count)
1868 "Shift region of Python code to the right.
1869The lines from the line containing the start of the current region up
1870to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001871shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001872
1873If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001874many columns. With no active region, indent only the current line."
1875 (interactive
1876 (let ((p (point))
1877 (m (mark))
1878 (arg current-prefix-arg))
1879 (if m
1880 (list (min p m) (max p m) arg)
1881 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001882 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001883 (or count py-indent-offset)))
1884 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001885
1886(defun py-indent-region (start end &optional indent-offset)
1887 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001888
Barry Warsaw7ae77681994-12-12 20:38:05 +00001889The lines from the line containing the start of the current region up
1890to (but not including) the line containing the end of the region are
1891reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001892character in the first column, the first line is left alone and the
1893rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001894region is reindented with respect to the (closest code or indenting
1895comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001896
1897This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001898control structures are introduced or removed, or to reformat code
1899using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001900
1901If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001902the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001903used.
1904
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001905Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001906is called! This function does not compute proper indentation from
1907scratch (that's impossible in Python), it merely adjusts the existing
1908indentation to be correct in context.
1909
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001910Warning: This function really has no idea what to do with
1911non-indenting comment lines, and shifts them as if they were indenting
1912comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001913
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001914Special cases: whitespace is deleted from blank lines; continuation
1915lines are shifted by the same amount their initial line was shifted,
1916in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001917initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001918 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001919 (save-excursion
1920 (goto-char end) (beginning-of-line) (setq end (point-marker))
1921 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001922 (let ((py-indent-offset (prefix-numeric-value
1923 (or indent-offset py-indent-offset)))
1924 (indents '(-1)) ; stack of active indent levels
1925 (target-column 0) ; column to which to indent
1926 (base-shifted-by 0) ; amount last base line was shifted
1927 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001928 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001929 0))
1930 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001931 (while (< (point) end)
1932 (setq ci (current-indentation))
1933 ;; figure out appropriate target column
1934 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001935 ((or (eq (following-char) ?#) ; comment in column 1
1936 (looking-at "[ \t]*$")) ; entirely blank
1937 (setq target-column 0))
1938 ((py-continuation-line-p) ; shift relative to base line
1939 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001940 (t ; new base line
1941 (if (> ci (car indents)) ; going deeper; push it
1942 (setq indents (cons ci indents))
1943 ;; else we should have seen this indent before
1944 (setq indents (memq ci indents)) ; pop deeper indents
1945 (if (null indents)
1946 (error "Bad indentation in region, at line %d"
1947 (save-restriction
1948 (widen)
1949 (1+ (count-lines 1 (point)))))))
1950 (setq target-column (+ indent-base
1951 (* py-indent-offset
1952 (- (length indents) 2))))
1953 (setq base-shifted-by (- target-column ci))))
1954 ;; shift as needed
1955 (if (/= ci target-column)
1956 (progn
1957 (delete-horizontal-space)
1958 (indent-to target-column)))
1959 (forward-line 1))))
1960 (set-marker end nil))
1961
Barry Warsawa7891711996-08-01 15:53:09 +00001962(defun py-comment-region (beg end &optional arg)
1963 "Like `comment-region' but uses double hash (`#') comment starter."
1964 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001965 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001966 (comment-region beg end arg)))
1967
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001968
1969;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001970(defun py-previous-statement (count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001971 "Go to the start of the COUNTth preceding Python statement.
1972By default, goes to the previous statement. If there is no such
1973statement, goes to the first statement. Return count of statements
1974left to move. `Statements' do not include blank, comment, or
1975continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001976 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001977 (if (< count 0) (py-next-statement (- count))
1978 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001979 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001980 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001981 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001982 (> count 0)
1983 (zerop (forward-line -1))
1984 (py-goto-statement-at-or-above))
1985 (setq count (1- count)))
1986 (if (> count 0) (goto-char start)))
1987 count))
1988
1989(defun py-next-statement (count)
1990 "Go to the start of next Python statement.
1991If the statement at point is the i'th Python statement, goes to the
1992start of statement i+COUNT. If there is no such statement, goes to the
1993last statement. Returns count of statements left to move. `Statements'
1994do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001995 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001996 (if (< count 0) (py-previous-statement (- count))
1997 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001998 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001999 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002000 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002001 (> count 0)
2002 (py-goto-statement-below))
2003 (setq count (1- count)))
2004 (if (> count 0) (goto-char start)))
2005 count))
2006
2007(defun py-goto-block-up (&optional nomark)
2008 "Move up to start of current block.
2009Go to the statement that starts the smallest enclosing block; roughly
2010speaking, this will be the closest preceding statement that ends with a
2011colon and is indented less than the statement you started on. If
2012successful, also sets the mark to the starting point.
2013
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002014`\\[py-mark-block]' can be used afterward to mark the whole code
2015block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002016
2017If called from a program, the mark will not be set if optional argument
2018NOMARK is not nil."
2019 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002020 (let ((start (point))
2021 (found nil)
2022 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002023 (py-goto-initial-line)
2024 ;; if on blank or non-indenting comment line, use the preceding stmt
2025 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2026 (progn
2027 (py-goto-statement-at-or-above)
2028 (setq found (py-statement-opens-block-p))))
2029 ;; search back for colon line indented less
2030 (setq initial-indent (current-indentation))
2031 (if (zerop initial-indent)
2032 ;; force fast exit
2033 (goto-char (point-min)))
2034 (while (not (or found (bobp)))
2035 (setq found
2036 (and
2037 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2038 (or (py-goto-initial-line) t) ; always true -- side effect
2039 (< (current-indentation) initial-indent)
2040 (py-statement-opens-block-p))))
2041 (if found
2042 (progn
2043 (or nomark (push-mark start))
2044 (back-to-indentation))
2045 (goto-char start)
2046 (error "Enclosing block not found"))))
2047
Barry Warsawab0e86c1998-05-19 15:31:46 +00002048(defun py-beginning-of-def-or-class (&optional class count)
2049 "Move point to start of `def' or `class'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002050
2051Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsawab0e86c1998-05-19 15:31:46 +00002052arg, looks for a `class' instead. The docs below assume the `def'
2053case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002054Programmatically, if CLASS is `either', then moves to either `class'
2055or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002056
Barry Warsawab0e86c1998-05-19 15:31:46 +00002057When second optional argument is given programmatically, move to the
2058COUNTth start of `def'.
2059
2060If point is in a `def' statement already, and after the `d', simply
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002061moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002062
Barry Warsawab0e86c1998-05-19 15:31:46 +00002063Otherwise (i.e. when point is not in a `def' statement, or at or
2064before the `d' of a `def' statement), searches for the closest
2065preceding `def' statement, and leaves point at its start. If no such
2066statement can be found, leaves point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002067
Barry Warsawab0e86c1998-05-19 15:31:46 +00002068Returns t iff a `def' statement is found by these rules.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002069
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002070Note that doing this command repeatedly will take you closer to the
2071start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002072
Barry Warsaw7c29b231998-07-07 17:45:38 +00002073To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002074 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002075 (if (not count)
2076 (setq count 1))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002077 (let ((at-or-before-p (<= (current-column) (current-indentation)))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002078 (start-of-line (goto-char (py-point 'bol)))
2079 (start-of-stmt (goto-char (py-point 'bos)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002080 (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
2081 (class "^[ \t]*class\\>")
2082 (t "^[ \t]*def\\>")))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002083 )
2084 ;; searching backward
2085 (if (and (< 0 count)
2086 (or (/= start-of-stmt start-of-line)
2087 (not at-or-before-p)))
2088 (end-of-line))
2089 ;; search forward
2090 (if (and (> 0 count)
2091 (zerop (current-column))
2092 (looking-at start-re))
2093 (end-of-line))
2094 (re-search-backward start-re nil 'move count)
2095 (goto-char (match-beginning 0))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002096
Barry Warsawab0e86c1998-05-19 15:31:46 +00002097;; Backwards compatibility
2098(defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002099
Barry Warsawab0e86c1998-05-19 15:31:46 +00002100(defun py-end-of-def-or-class (&optional class count)
2101 "Move point beyond end of `def' or `class' body.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002102
Barry Warsawab0e86c1998-05-19 15:31:46 +00002103By default, looks for an appropriate `def'. If you supply a prefix
2104arg, looks for a `class' instead. The docs below assume the `def'
2105case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002106Programmatically, if CLASS is `either', then moves to either `class'
2107or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002108
Barry Warsawab0e86c1998-05-19 15:31:46 +00002109When second optional argument is given programmatically, move to the
2110COUNTth end of `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002111
Barry Warsawab0e86c1998-05-19 15:31:46 +00002112If point is in a `def' statement already, this is the `def' we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002113
Barry Warsawab0e86c1998-05-19 15:31:46 +00002114Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2115contains the statement you started on, that's the `def' we use.
2116
2117Otherwise, we search forward for the closest following `def', and use that.
2118
2119If a `def' can be found by these rules, point is moved to the start of
2120the line immediately following the `def' block, and the position of the
2121start of the `def' is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002122
2123Else point is moved to the end of the buffer, and nil is returned.
2124
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002125Note that doing this command repeatedly will take you closer to the
2126end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002127
Barry Warsaw7c29b231998-07-07 17:45:38 +00002128To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002129 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002130 (if (and count (/= count 1))
2131 (py-beginning-of-def-or-class (- 1 count)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002132 (let ((start (progn (py-goto-initial-line) (point)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002133 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2134 (class "class")
2135 (t "def")))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002136 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002137 ;; move point to start of appropriate def/class
2138 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2139 (setq state 'at-beginning)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002140 ;; else see if py-beginning-of-def-or-class hits container
2141 (if (and (py-beginning-of-def-or-class class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002142 (progn (py-goto-beyond-block)
2143 (> (point) start)))
2144 (setq state 'at-end)
2145 ;; else search forward
2146 (goto-char start)
2147 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2148 (progn (setq state 'at-beginning)
2149 (beginning-of-line)))))
2150 (cond
2151 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2152 ((eq state 'at-end) t)
2153 ((eq state 'not-found) nil)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002154 (t (error "Internal error in `py-end-of-def-or-class'")))))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002155
2156;; Backwards compabitility
Barry Warsaw820273d1998-05-19 15:54:45 +00002157(defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002158
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002159
2160;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002161(defun py-mark-block (&optional extend just-move)
2162 "Mark following block of lines. With prefix arg, mark structure.
2163Easier to use than explain. It sets the region to an `interesting'
2164block of succeeding lines. If point is on a blank line, it goes down to
2165the next non-blank line. That will be the start of the region. The end
2166of the region depends on the kind of line at the start:
2167
2168 - If a comment, the region will include all succeeding comment lines up
2169 to (but not including) the next non-comment line (if any).
2170
2171 - Else if a prefix arg is given, and the line begins one of these
2172 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002173
2174 if elif else try except finally for while def class
2175
Barry Warsaw7ae77681994-12-12 20:38:05 +00002176 the region will be set to the body of the structure, including
2177 following blocks that `belong' to it, but excluding trailing blank
2178 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002179 and all (if any) of the following `except' and `finally' blocks
2180 that belong to the `try' structure will be in the region. Ditto
2181 for if/elif/else, for/else and while/else structures, and (a bit
2182 degenerate, since they're always one-block structures) def and
2183 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002184
2185 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002186 block (see list above), and the block is not a `one-liner' (i.e.,
2187 the statement ends with a colon, not with code), the region will
2188 include all succeeding lines up to (but not including) the next
2189 code statement (if any) that's indented no more than the starting
2190 line, except that trailing blank and comment lines are excluded.
2191 E.g., if the starting line begins a multi-statement `def'
2192 structure, the region will be set to the full function definition,
2193 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002194
2195 - Else the region will include all succeeding lines up to (but not
2196 including) the next blank line, or code or indenting-comment line
2197 indented strictly less than the starting line. Trailing indenting
2198 comment lines are included in this case, but not trailing blank
2199 lines.
2200
2201A msg identifying the location of the mark is displayed in the echo
2202area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2203
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002204If called from a program, optional argument EXTEND plays the role of
2205the prefix arg, and if optional argument JUST-MOVE is not nil, just
2206moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002207 (interactive "P") ; raw prefix arg
2208 (py-goto-initial-line)
2209 ;; skip over blank lines
2210 (while (and
2211 (looking-at "[ \t]*$") ; while blank line
2212 (not (eobp))) ; & somewhere to go
2213 (forward-line 1))
2214 (if (eobp)
2215 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002216 (let ((initial-pos (point))
2217 (initial-indent (current-indentation))
2218 last-pos ; position of last stmt in region
2219 (followers
2220 '((if elif else) (elif elif else) (else)
2221 (try except finally) (except except) (finally)
2222 (for else) (while else)
2223 (def) (class) ) )
2224 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002225
2226 (cond
2227 ;; if comment line, suck up the following comment lines
2228 ((looking-at "[ \t]*#")
2229 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2230 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2231 (setq last-pos (point)))
2232
2233 ;; else if line is a block line and EXTEND given, suck up
2234 ;; the whole structure
2235 ((and extend
2236 (setq first-symbol (py-suck-up-first-keyword) )
2237 (assq first-symbol followers))
2238 (while (and
2239 (or (py-goto-beyond-block) t) ; side effect
2240 (forward-line -1) ; side effect
2241 (setq last-pos (point)) ; side effect
2242 (py-goto-statement-below)
2243 (= (current-indentation) initial-indent)
2244 (setq next-symbol (py-suck-up-first-keyword))
2245 (memq next-symbol (cdr (assq first-symbol followers))))
2246 (setq first-symbol next-symbol)))
2247
2248 ;; else if line *opens* a block, search for next stmt indented <=
2249 ((py-statement-opens-block-p)
2250 (while (and
2251 (setq last-pos (point)) ; always true -- side effect
2252 (py-goto-statement-below)
2253 (> (current-indentation) initial-indent))
2254 nil))
2255
2256 ;; else plain code line; stop at next blank line, or stmt or
2257 ;; indenting comment line indented <
2258 (t
2259 (while (and
2260 (setq last-pos (point)) ; always true -- side effect
2261 (or (py-goto-beyond-final-line) t)
2262 (not (looking-at "[ \t]*$")) ; stop at blank line
2263 (or
2264 (>= (current-indentation) initial-indent)
2265 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2266 nil)))
2267
2268 ;; skip to end of last stmt
2269 (goto-char last-pos)
2270 (py-goto-beyond-final-line)
2271
2272 ;; set mark & display
2273 (if just-move
2274 () ; just return
2275 (push-mark (point) 'no-msg)
2276 (forward-line -1)
2277 (message "Mark set after: %s" (py-suck-up-leading-text))
2278 (goto-char initial-pos))))
2279
Barry Warsaw2518c671997-11-05 00:51:08 +00002280(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002281 "Set region to body of def (or class, with prefix arg) enclosing point.
2282Pushes the current mark, then point, on the mark ring (all language
2283modes do this, but although it's handy it's never documented ...).
2284
2285In most Emacs language modes, this function bears at least a
Barry Warsawab0e86c1998-05-19 15:31:46 +00002286hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2287`\\[py-beginning-of-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002288
2289And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002290Turned out that was more confusing than useful: the `goto start' and
2291`goto end' commands are usually used to search through a file, and
2292people expect them to act a lot like `search backward' and `search
2293forward' string-search commands. But because Python `def' and `class'
2294can nest to arbitrary levels, finding the smallest def containing
2295point cannot be done via a simple backward search: the def containing
2296point may not be the closest preceding def, or even the closest
2297preceding def that's indented less. The fancy algorithm required is
2298appropriate for the usual uses of this `mark' command, but not for the
2299`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002300
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002301So the def marked by this command may not be the one either of the
2302`goto' commands find: If point is on a blank or non-indenting comment
2303line, moves back to start of the closest preceding code statement or
2304indenting comment line. If this is a `def' statement, that's the def
2305we use. Else searches for the smallest enclosing `def' block and uses
2306that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002307
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002308When an enclosing def is found: The mark is left immediately beyond
2309the last line of the def block. Point is left at the start of the
2310def, except that: if the def is preceded by a number of comment lines
2311followed by (at most) one optional blank line, point is left at the
2312start of the comments; else if the def is preceded by a blank line,
2313point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002314
2315The intent is to mark the containing def/class and its associated
2316documentation, to make moving and duplicating functions and classes
2317pleasant."
2318 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002319 (let ((start (point))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002320 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2321 (class "class")
2322 (t "def"))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002323 (push-mark start)
2324 (if (not (py-go-up-tree-to-keyword which))
2325 (progn (goto-char start)
Barry Warsaw7c29b231998-07-07 17:45:38 +00002326 (error "Enclosing %s not found"
2327 (if (eq class 'either)
2328 "def or class"
2329 which)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002330 ;; else enclosing def/class found
2331 (setq start (point))
2332 (py-goto-beyond-block)
2333 (push-mark (point))
2334 (goto-char start)
2335 (if (zerop (forward-line -1)) ; if there is a preceding line
2336 (progn
2337 (if (looking-at "[ \t]*$") ; it's blank
2338 (setq start (point)) ; so reset start point
2339 (goto-char start)) ; else try again
2340 (if (zerop (forward-line -1))
2341 (if (looking-at "[ \t]*#") ; a comment
2342 ;; look back for non-comment line
2343 ;; tricky: note that the regexp matches a blank
2344 ;; line, cuz \n is in the 2nd character class
2345 (and
2346 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2347 (forward-line 1))
2348 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002349 (goto-char start)))))))
2350 (exchange-point-and-mark)
2351 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002352
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002353;; ripped from cc-mode
2354(defun py-forward-into-nomenclature (&optional arg)
2355 "Move forward to end of a nomenclature section or word.
Barry Warsaw41a05c71998-08-10 16:33:12 +00002356With \\[universal-argument] (programmatically, optional argument ARG),
2357do it that many times.
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002358
2359A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2360 (interactive "p")
2361 (let ((case-fold-search nil))
2362 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002363 (re-search-forward
2364 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2365 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002366 (while (and (< arg 0)
2367 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002368 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002369 (point-min) 0))
2370 (forward-char 1)
2371 (setq arg (1+ arg)))))
2372 (py-keep-region-active))
2373
2374(defun py-backward-into-nomenclature (&optional arg)
2375 "Move backward to beginning of a nomenclature section or word.
2376With optional ARG, move that many times. If ARG is negative, move
2377forward.
2378
2379A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2380 (interactive "p")
2381 (py-forward-into-nomenclature (- arg))
2382 (py-keep-region-active))
2383
2384
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002385
2386;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002387
2388;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002389;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2390;; out of the right places, along with the keys they're on & current
2391;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002392(defun py-dump-help-string (str)
2393 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002394 (let ((locals (buffer-local-variables))
2395 funckind funcname func funcdoc
2396 (start 0) mstart end
2397 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002398 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2399 (setq mstart (match-beginning 0) end (match-end 0)
2400 funckind (substring str (match-beginning 1) (match-end 1))
2401 funcname (substring str (match-beginning 2) (match-end 2))
2402 func (intern funcname))
2403 (princ (substitute-command-keys (substring str start mstart)))
2404 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002405 ((equal funckind "c") ; command
2406 (setq funcdoc (documentation func)
2407 keys (concat
2408 "Key(s): "
2409 (mapconcat 'key-description
2410 (where-is-internal func py-mode-map)
2411 ", "))))
2412 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002413 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002414 keys (if (assq func locals)
2415 (concat
2416 "Local/Global values: "
2417 (prin1-to-string (symbol-value func))
2418 " / "
2419 (prin1-to-string (default-value func)))
2420 (concat
2421 "Value: "
2422 (prin1-to-string (symbol-value func))))))
2423 (t ; unexpected
2424 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002425 (princ (format "\n-> %s:\t%s\t%s\n\n"
2426 (if (equal funckind "c") "Command" "Variable")
2427 funcname keys))
2428 (princ funcdoc)
2429 (terpri)
2430 (setq start end))
2431 (princ (substitute-command-keys (substring str start))))
2432 (print-help-return-message)))
2433
2434(defun py-describe-mode ()
2435 "Dump long form of Python-mode docs."
2436 (interactive)
2437 (py-dump-help-string "Major mode for editing Python files.
2438Knows about Python indentation, tokens, comments and continuation lines.
2439Paragraphs are separated by blank lines only.
2440
2441Major sections below begin with the string `@'; specific function and
2442variable docs begin with `->'.
2443
2444@EXECUTING PYTHON CODE
2445
Barry Warsaw820273d1998-05-19 15:54:45 +00002446\\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002447\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2448\\[py-execute-region]\tsends the current region
Barry Warsaw820273d1998-05-19 15:54:45 +00002449\\[py-execute-def-or-class]\tsends the current function or class definition
2450\\[py-execute-string]\tsends an arbitrary string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002451\\[py-shell]\tstarts a Python interpreter window; this will be used by
Barry Warsaw820273d1998-05-19 15:54:45 +00002452\tsubsequent Python execution commands
2453%c:py-execute-import-or-reload
Barry Warsaw7ae77681994-12-12 20:38:05 +00002454%c:py-execute-buffer
2455%c:py-execute-region
Barry Warsaw820273d1998-05-19 15:54:45 +00002456%c:py-execute-def-or-class
2457%c:py-execute-string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002458%c:py-shell
2459
2460@VARIABLES
2461
2462py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002463py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002464
2465py-python-command\tshell command to invoke Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002466py-temp-directory\tdirectory used for temp files (if needed)
2467
2468py-beep-if-tab-change\tring the bell if tab-width is changed
2469%v:py-indent-offset
2470%v:py-block-comment-prefix
2471%v:py-python-command
Barry Warsaw7ae77681994-12-12 20:38:05 +00002472%v:py-temp-directory
2473%v:py-beep-if-tab-change
2474
2475@KINDS OF LINES
2476
2477Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002478preceding line ends with a backslash that's not part of a comment, or
2479the paren/bracket/brace nesting level at the start of the line is
2480non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002481
2482An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002483possibly blanks or tabs), a `comment line' (leftmost non-blank
2484character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002485
2486Comment Lines
2487
2488Although all comment lines are treated alike by Python, Python mode
2489recognizes two kinds that act differently with respect to indentation.
2490
2491An `indenting comment line' is a comment line with a blank, tab or
2492nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002493treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002494indenting comment line will be indented like the comment line. All
2495other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002496following the initial `#') are `non-indenting comment lines', and
2497their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002498
2499Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002500whenever possible. Non-indenting comment lines are useful in cases
2501like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002502
2503\ta = b # a very wordy single-line comment that ends up being
2504\t #... continued onto another line
2505
2506\tif a == b:
2507##\t\tprint 'panic!' # old code we've `commented out'
2508\t\treturn a
2509
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002510Since the `#...' and `##' comment lines have a non-whitespace
2511character following the initial `#', Python mode ignores them when
2512computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002513
2514Continuation Lines and Statements
2515
2516The Python-mode commands generally work on statements instead of on
2517individual lines, where a `statement' is a comment or blank line, or a
2518code line and all of its following continuation lines (if any)
2519considered as a single logical unit. The commands in this mode
2520generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002521statement containing point, even if point happens to be in the middle
2522of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002523
2524
2525@INDENTATION
2526
2527Primarily for entering new code:
2528\t\\[indent-for-tab-command]\t indent line appropriately
2529\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002530\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002531
2532Primarily for reindenting existing code:
2533\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2534\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2535
2536\t\\[py-indent-region]\t reindent region to match its context
2537\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2538\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2539
2540Unlike most programming languages, Python uses indentation, and only
2541indentation, to specify block structure. Hence the indentation supplied
2542automatically by Python-mode is just an educated guess: only you know
2543the block structure you intend, so only you can supply correct
2544indentation.
2545
2546The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2547the indentation of preceding statements. E.g., assuming
2548py-indent-offset is 4, after you enter
2549\tif a > 0: \\[py-newline-and-indent]
2550the cursor will be moved to the position of the `_' (_ is not a
2551character in the file, it's just used here to indicate the location of
2552the cursor):
2553\tif a > 0:
2554\t _
2555If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2556to
2557\tif a > 0:
2558\t c = d
2559\t _
2560Python-mode cannot know whether that's what you intended, or whether
2561\tif a > 0:
2562\t c = d
2563\t_
2564was your intent. In general, Python-mode either reproduces the
2565indentation of the (closest code or indenting-comment) preceding
2566statement, or adds an extra py-indent-offset blanks if the preceding
2567statement has `:' as its last significant (non-whitespace and non-
2568comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002569\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002570
2571Continuation lines are given extra indentation. If you don't like the
2572suggested indentation, change it to something you do like, and Python-
2573mode will strive to indent later lines of the statement in the same way.
2574
2575If a line is a continuation line by virtue of being in an unclosed
2576paren/bracket/brace structure (`list', for short), the suggested
2577indentation depends on whether the current line contains the first item
2578in the list. If it does, it's indented py-indent-offset columns beyond
2579the indentation of the line containing the open bracket. If you don't
2580like that, change it by hand. The remaining items in the list will mimic
2581whatever indentation you give to the first item.
2582
2583If a line is a continuation line because the line preceding it ends with
2584a backslash, the third and following lines of the statement inherit their
2585indentation from the line preceding them. The indentation of the second
2586line in the statement depends on the form of the first (base) line: if
2587the base line is an assignment statement with anything more interesting
2588than the backslash following the leftmost assigning `=', the second line
2589is indented two columns beyond that `='. Else it's indented to two
2590columns beyond the leftmost solid chunk of non-whitespace characters on
2591the base line.
2592
2593Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2594repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2595structure you intend.
2596%c:indent-for-tab-command
2597%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002598%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002599
2600
2601The next function may be handy when editing code you didn't write:
2602%c:py-guess-indent-offset
2603
2604
2605The remaining `indent' functions apply to a region of Python code. They
2606assume the block structure (equals indentation, in Python) of the region
2607is correct, and alter the indentation in various ways while preserving
2608the block structure:
2609%c:py-indent-region
2610%c:py-shift-region-left
2611%c:py-shift-region-right
2612
2613@MARKING & MANIPULATING REGIONS OF CODE
2614
2615\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002616\\[py-mark-def-or-class]\t mark smallest enclosing def
2617\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002618\\[comment-region]\t comment out region of code
2619\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002620%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002621%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002622%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002623
2624@MOVING POINT
2625
2626\\[py-previous-statement]\t move to statement preceding point
2627\\[py-next-statement]\t move to statement following point
2628\\[py-goto-block-up]\t move up to start of current block
Barry Warsawab0e86c1998-05-19 15:31:46 +00002629\\[py-beginning-of-def-or-class]\t move to start of def
2630\\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
2631\\[py-end-of-def-or-class]\t move to end of def
2632\\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002633
2634The first two move to one statement beyond the statement that contains
2635point. A numeric prefix argument tells them to move that many
2636statements instead. Blank lines, comment lines, and continuation lines
2637do not count as `statements' for these commands. So, e.g., you can go
2638to the first code statement in a file by entering
2639\t\\[beginning-of-buffer]\t to move to the top of the file
2640\t\\[py-next-statement]\t to skip over initial comments and blank lines
2641Or do `\\[py-previous-statement]' with a huge prefix argument.
2642%c:py-previous-statement
2643%c:py-next-statement
2644%c:py-goto-block-up
Barry Warsawab0e86c1998-05-19 15:31:46 +00002645%c:py-beginning-of-def-or-class
2646%c:py-end-of-def-or-class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002647
2648@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2649
2650`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2651
2652`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2653overall class and def structure of a module.
2654
2655`\\[back-to-indentation]' moves point to a line's first non-blank character.
2656
2657`\\[indent-relative]' is handy for creating odd indentation.
2658
2659@OTHER EMACS HINTS
2660
2661If you don't like the default value of a variable, change its value to
2662whatever you do like by putting a `setq' line in your .emacs file.
2663E.g., to set the indentation increment to 4, put this line in your
2664.emacs:
2665\t(setq py-indent-offset 4)
2666To see the value of a variable, do `\\[describe-variable]' and enter the variable
2667name at the prompt.
2668
2669When entering a key sequence like `C-c C-n', it is not necessary to
2670release the CONTROL key after doing the `C-c' part -- it suffices to
2671press the CONTROL key, press and release `c' (while still holding down
2672CONTROL), press and release `n' (while still holding down CONTROL), &
2673then release CONTROL.
2674
2675Entering Python mode calls with no arguments the value of the variable
2676`python-mode-hook', if that value exists and is not nil; for backward
2677compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2678the Elisp manual for details.
2679
2680Obscure: When python-mode is first loaded, it looks for all bindings
2681to newline-and-indent in the global keymap, and shadows them with
2682local bindings to py-newline-and-indent."))
2683
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002684
2685;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002686(defvar py-parse-state-re
2687 (concat
2688 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2689 "\\|"
2690 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002691
Barry Warsaw7ae77681994-12-12 20:38:05 +00002692(defun py-parse-state ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002693 "Return the parse state at point (see `parse-partial-sexp' docs)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002694 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002695 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002696 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002697 (while (not done)
2698 ;; back up to the first preceding line (if any; else start of
2699 ;; buffer) that begins with a popular Python keyword, or a
2700 ;; non- whitespace and non-comment character. These are good
2701 ;; places to start parsing to see whether where we started is
2702 ;; at a non-zero nesting level. It may be slow for people who
2703 ;; write huge code blocks or huge lists ... tough beans.
2704 (re-search-backward py-parse-state-re nil 'move)
2705 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002706 ;; In XEmacs, we have a much better way to test for whether
2707 ;; we're in a triple-quoted string or not. Emacs does not
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002708 ;; have this built-in function, which is its loss because
Barry Warsawf64b4051998-02-12 16:52:14 +00002709 ;; without scanning from the beginning of the buffer, there's
2710 ;; no accurate way to determine this otherwise.
2711 (if (not (fboundp 'buffer-syntactic-context))
2712 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002713 (progn
2714 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002715 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002716 (setq done (or (not (nth 3 pps))
2717 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002718 ;; XEmacs
2719 (setq done (or (not (buffer-syntactic-context))
2720 (bobp)))
2721 (when done
2722 (setq pps (parse-partial-sexp (point) here)))
2723 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002724 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002725
Barry Warsaw7ae77681994-12-12 20:38:05 +00002726(defun py-nesting-level ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002727 "Return the buffer position of the last unclosed enclosing list.
2728If nesting level is zero, return nil."
Barry Warsawf64b4051998-02-12 16:52:14 +00002729 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002730 (if (zerop (car status))
2731 nil ; not in a nest
2732 (car (cdr status))))) ; char# of open bracket
2733
Barry Warsaw7ae77681994-12-12 20:38:05 +00002734(defun py-backslash-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002735 "Return t iff preceding line ends with backslash that is not in a comment."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002736 (save-excursion
2737 (beginning-of-line)
2738 (and
2739 ;; use a cheap test first to avoid the regexp if possible
2740 ;; use 'eq' because char-after may return nil
2741 (eq (char-after (- (point) 2)) ?\\ )
2742 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002743 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002744 (looking-at py-continued-re))))
2745
Barry Warsaw7ae77681994-12-12 20:38:05 +00002746(defun py-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002747 "Return t iff current line is a continuation line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002748 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002749 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002750 (or (py-backslash-continuation-line-p)
2751 (py-nesting-level))))
2752
Barry Warsaw7ae77681994-12-12 20:38:05 +00002753(defun py-goto-initial-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002754 "Go to the initial line of the current statement.
2755Usually this is the line we're on, but if we're on the 2nd or
2756following lines of a continuation block, we need to go up to the first
2757line of the block."
2758 ;; Tricky: We want to avoid quadratic-time behavior for long
2759 ;; continued blocks, whether of the backslash or open-bracket
2760 ;; varieties, or a mix of the two. The following manages to do that
2761 ;; in the usual cases.
2762 ;;
2763 ;; Also, if we're sitting inside a triple quoted string, this will
2764 ;; drop us at the line that begins the string.
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002765 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002766 (while (py-continuation-line-p)
2767 (beginning-of-line)
2768 (if (py-backslash-continuation-line-p)
2769 (while (py-backslash-continuation-line-p)
2770 (forward-line -1))
2771 ;; else zip out of nested brackets/braces/parens
2772 (while (setq open-bracket-pos (py-nesting-level))
2773 (goto-char open-bracket-pos)))))
2774 (beginning-of-line))
2775
Barry Warsaw7ae77681994-12-12 20:38:05 +00002776(defun py-goto-beyond-final-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002777 "Go to the point just beyond the fine line of the current statement.
2778Usually this is the start of the next line, but if this is a
2779multi-line statement we need to skip over the continuation lines."
2780 ;; Tricky: Again we need to be clever to avoid quadratic time
2781 ;; behavior.
2782 ;;
2783 ;; XXX: Not quite the right solution, but deals with multi-line doc
2784 ;; strings
Barry Warsaw751f4931998-05-19 16:06:21 +00002785 (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
2786 (goto-char (match-end 0)))
2787 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +00002788 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002789 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002790 (while (and (py-continuation-line-p)
2791 (not (eobp)))
2792 ;; skip over the backslash flavor
2793 (while (and (py-backslash-continuation-line-p)
2794 (not (eobp)))
2795 (forward-line 1))
2796 ;; if in nest, zip to the end of the nest
2797 (setq state (py-parse-state))
2798 (if (and (not (zerop (car state)))
2799 (not (eobp)))
2800 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002801 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002802 (forward-line 1))))))
2803
Barry Warsaw7ae77681994-12-12 20:38:05 +00002804(defun py-statement-opens-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002805 "Return t iff the current statement opens a block.
2806I.e., iff it ends with a colon that is not in a comment. Point should
2807be at the start of a statement."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002808 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002809 (let ((start (point))
2810 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2811 (searching t)
2812 (answer nil)
2813 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002814 (goto-char start)
2815 (while searching
2816 ;; look for a colon with nothing after it except whitespace, and
2817 ;; maybe a comment
2818 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2819 finish t)
2820 (if (eq (point) finish) ; note: no `else' clause; just
2821 ; keep searching if we're not at
2822 ; the end yet
2823 ;; sure looks like it opens a block -- but it might
2824 ;; be in a comment
2825 (progn
2826 (setq searching nil) ; search is done either way
2827 (setq state (parse-partial-sexp start
2828 (match-beginning 0)))
2829 (setq answer (not (nth 4 state)))))
2830 ;; search failed: couldn't find another interesting colon
2831 (setq searching nil)))
2832 answer)))
2833
Barry Warsawf831d811996-07-31 20:42:59 +00002834(defun py-statement-closes-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002835 "Return t iff the current statement closes a block.
2836I.e., if the line starts with `return', `raise', `break', `continue',
2837and `pass'. This doesn't catch embedded statements."
Barry Warsawf831d811996-07-31 20:42:59 +00002838 (let ((here (point)))
2839 (back-to-indentation)
2840 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002841 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002842 (goto-char here))))
2843
Barry Warsaw7ae77681994-12-12 20:38:05 +00002844(defun py-goto-beyond-block ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002845 "Go to point just beyond the final line of block begun by the current line.
2846This is the same as where `py-goto-beyond-final-line' goes unless
2847we're on colon line, in which case we go to the end of the block.
2848Assumes point is at the beginning of the line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002849 (if (py-statement-opens-block-p)
2850 (py-mark-block nil 'just-move)
2851 (py-goto-beyond-final-line)))
2852
Barry Warsaw7ae77681994-12-12 20:38:05 +00002853(defun py-goto-statement-at-or-above ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002854 "Go to the start of the first statement at or preceding point.
2855Return t if there is such a statement, otherwise nil. `Statement'
2856does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002857 (py-goto-initial-line)
2858 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002859 ;; skip back over blank & comment lines
2860 ;; note: will skip a blank or comment line that happens to be
2861 ;; a continuation line too
2862 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2863 (progn (py-goto-initial-line) t)
2864 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002865 t))
2866
Barry Warsaw7ae77681994-12-12 20:38:05 +00002867(defun py-goto-statement-below ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002868 "Go to start of the first statement following the statement containing point.
2869Return t if there is such a statement, otherwise nil. `Statement'
2870does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002871 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002872 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002873 (py-goto-beyond-final-line)
2874 (while (and
2875 (looking-at py-blank-or-comment-re)
2876 (not (eobp)))
2877 (forward-line 1))
2878 (if (eobp)
2879 (progn (goto-char start) nil)
2880 t)))
2881
Barry Warsaw7ae77681994-12-12 20:38:05 +00002882(defun py-go-up-tree-to-keyword (key)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002883 "Go to begining of statement starting with KEY, at or preceding point.
2884
2885KEY is a regular expression describing a Python keyword. Skip blank
2886lines and non-indenting comments. If the statement found starts with
2887KEY, then stop, otherwise go back to first enclosing block starting
2888with KEY. If successful, leave point at the start of the KEY line and
2889return t. Otherwise, leav point at an undefined place and return nil."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002890 ;; skip blanks and non-indenting #
2891 (py-goto-initial-line)
2892 (while (and
2893 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2894 (zerop (forward-line -1))) ; go back
2895 nil)
2896 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002897 (let* ((re (concat "[ \t]*" key "\\b"))
2898 (case-fold-search nil) ; let* so looking-at sees this
2899 (found (looking-at re))
2900 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002901 (while (not (or found dead))
2902 (condition-case nil ; in case no enclosing block
2903 (py-goto-block-up 'no-mark)
2904 (error (setq dead t)))
2905 (or dead (setq found (looking-at re))))
2906 (beginning-of-line)
2907 found))
2908
Barry Warsaw7ae77681994-12-12 20:38:05 +00002909(defun py-suck-up-leading-text ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002910 "Return string in buffer from start of indentation to end of line.
2911Prefix with \"...\" if leading whitespace was skipped."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002912 (save-excursion
2913 (back-to-indentation)
2914 (concat
2915 (if (bolp) "" "...")
2916 (buffer-substring (point) (progn (end-of-line) (point))))))
2917
Barry Warsaw7ae77681994-12-12 20:38:05 +00002918(defun py-suck-up-first-keyword ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002919 "Return first keyword on the line as a Lisp symbol.
2920`Keyword' is defined (essentially) as the regular expression
2921([a-z]+). Returns nil if none was found."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002922 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002923 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2924 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2925 nil)))
2926
Barry Warsawb3e81d51996-09-04 15:12:42 +00002927(defun py-current-defun ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002928 "Python value for `add-log-current-defun-function'.
2929This tells add-log.el how to find the current function/method/variable."
Barry Warsawb3e81d51996-09-04 15:12:42 +00002930 (save-excursion
2931 (if (re-search-backward py-defun-start-re nil t)
2932 (or (match-string 3)
2933 (let ((method (match-string 2)))
2934 (if (and (not (zerop (length (match-string 1))))
2935 (re-search-backward py-class-start-re nil t))
2936 (concat (match-string 1) "." method)
2937 method)))
2938 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002939
2940
Barry Warsawfec75d61995-07-05 23:26:15 +00002941(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002942 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002943
Barry Warsaw850437a1995-03-08 21:50:28 +00002944(defun py-version ()
2945 "Echo the current version of `python-mode' in the minibuffer."
2946 (interactive)
2947 (message "Using `python-mode' version %s" py-version)
2948 (py-keep-region-active))
2949
2950;; only works under Emacs 19
2951;(eval-when-compile
2952; (require 'reporter))
2953
2954(defun py-submit-bug-report (enhancement-p)
2955 "Submit via mail a bug report on `python-mode'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00002956With \\[universal-argument] (programmatically, argument ENHANCEMENT-P
2957non-nil) just submit an enhancement request."
Barry Warsaw850437a1995-03-08 21:50:28 +00002958 (interactive
2959 (list (not (y-or-n-p
Barry Warsaw41a05c71998-08-10 16:33:12 +00002960 "Is this a bug report (hit `n' to send other comments)? "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002961 (let ((reporter-prompt-for-summary-p (if enhancement-p
2962 "(Very) brief summary: "
2963 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002964 (require 'reporter)
2965 (reporter-submit-bug-report
2966 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002967 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002968 ;; varlist
2969 (if enhancement-p nil
2970 '(py-python-command
2971 py-indent-offset
2972 py-block-comment-prefix
Barry Warsaw850437a1995-03-08 21:50:28 +00002973 py-temp-directory
2974 py-beep-if-tab-change))
2975 nil ;pre-hooks
2976 nil ;post-hooks
2977 "Dear Barry,") ;salutation
2978 (if enhancement-p nil
2979 (set-mark (point))
2980 (insert
2981"Please replace this text with a sufficiently large code sample\n\
2982and an exact recipe so that I can reproduce your problem. Failure\n\
2983to do so may mean a greater delay in fixing your bug.\n\n")
2984 (exchange-point-and-mark)
2985 (py-keep-region-active))))
2986
2987
Barry Warsaw47384781997-11-26 05:27:45 +00002988(defun py-kill-emacs-hook ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002989 "Delete files in `py-file-queue'.
2990These are Python temporary files awaiting execution."
Barry Warsaw47384781997-11-26 05:27:45 +00002991 (mapcar #'(lambda (filename)
2992 (py-safe (delete-file filename)))
2993 py-file-queue))
2994
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002995;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002996(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002997
2998
2999
3000(provide 'python-mode)
3001;;; python-mode.el ends here