blob: e96e671641c9dbba5977f35891f629578c258b02 [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'."
Barry Warsaw4f94c731998-09-25 19:40:10 +00001056 (when (and (or (string-equal string ">>> ")
1057 ;; NT XEmacs 21.0 kludge
1058 (and (>= (length string) 5)
1059 (string-equal (substring string -5) "\n>>> ")))
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001060 py-file-queue)
1061 (py-safe (delete-file (car py-file-queue)))
1062 (setq py-file-queue (cdr py-file-queue))
1063 (if py-file-queue
1064 (let ((pyproc (get-buffer-process (current-buffer))))
1065 (py-execute-file pyproc (car py-file-queue))))
1066 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001067
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001068(defun py-postprocess-output-buffer (buf)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001069 "Highlight exceptions found in BUF.
1070If an exception occurred return t, otherwise return nil. BUF must exist."
Barry Warsawf9b99f41998-03-26 16:08:59 +00001071 (let (line file bol err-p)
Barry Warsaw9981d221997-12-03 05:25:48 +00001072 (save-excursion
1073 (set-buffer buf)
1074 (beginning-of-buffer)
1075 (while (re-search-forward py-traceback-line-re nil t)
1076 (setq file (match-string 1)
1077 line (string-to-int (match-string 2))
1078 bol (py-point 'bol))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001079 (py-highlight-line bol (py-point 'eol) file line)))
1080 (when (and py-jump-on-exception line)
1081 (beep)
1082 (py-jump-to-exception file line)
1083 (setq err-p t))
1084 err-p))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001085
Barry Warsaw9981d221997-12-03 05:25:48 +00001086
Barry Warsawa97a3f31997-11-04 18:47:06 +00001087
1088;;; Subprocess commands
1089
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001090;; only used when (memq 'broken-temp-names py-emacs-features)
1091(defvar py-serial-number 0)
1092(defvar py-exception-buffer nil)
1093(defconst py-output-buffer "*Python Output*")
Barry Warsawa2398801998-04-09 23:28:20 +00001094(make-variable-buffer-local 'py-output-buffer)
1095
1096;; for toggling between CPython and JPython
1097(defvar py-which-shell py-python-command)
1098(defvar py-which-args py-python-command-args)
1099(defvar py-which-bufname "Python")
1100(make-variable-buffer-local 'py-which-shell)
1101(make-variable-buffer-local 'py-which-args)
1102(make-variable-buffer-local 'py-which-bufname)
1103
1104(defun py-toggle-shells (arg)
1105 "Toggles between the CPython and JPython shells.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001106With positive argument ARG (interactively \\[universal-argument]),
1107uses the CPython shell, with negative ARG uses the JPython shell, and
1108with a zero argument, toggles the shell."
Barry Warsawa2398801998-04-09 23:28:20 +00001109 (interactive "P")
1110 ;; default is to toggle
1111 (if (null arg)
1112 (setq arg 0))
1113 ;; toggle if zero
1114 (if (= arg 0)
1115 (if (string-equal py-which-bufname "Python")
1116 (setq arg -1)
1117 (setq arg 1)))
1118 (let (msg)
1119 (cond
1120 ((< 0 arg)
1121 ;; set to CPython
1122 (setq py-which-shell py-python-command
1123 py-which-args py-python-command-args
1124 py-which-bufname "Python"
1125 msg "CPython"
1126 mode-name "Python"))
1127 ((> 0 arg)
1128 (setq py-which-shell py-jpython-command
1129 py-which-args py-jpython-command-args
1130 py-which-bufname "JPython"
1131 msg "JPython"
1132 mode-name "JPython"))
1133 )
Barry Warsawea609c11998-04-10 16:08:26 +00001134 (message "Using the %s shell" msg)
Barry Warsawa2398801998-04-09 23:28:20 +00001135 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001136
Barry Warsawa97a3f31997-11-04 18:47:06 +00001137;;;###autoload
1138(defun py-shell ()
1139 "Start an interactive Python interpreter in another window.
1140This is like Shell mode, except that Python is running in the window
1141instead of a shell. See the `Interactive Shell' and `Shell Mode'
1142sections of the Emacs manual for details, especially for the key
1143bindings active in the `*Python*' buffer.
1144
Barry Warsawa2398801998-04-09 23:28:20 +00001145Note: You can toggle between using the CPython interpreter and the
1146JPython interpreter by hitting \\[py-toggle-shells]. This toggles
1147buffer local variables which control whether all your subshell
1148interactions happen to the `*JPython*' or `*Python*' buffers (the
1149latter is the name used for the CPython buffer).
1150
Barry Warsawa97a3f31997-11-04 18:47:06 +00001151Warning: Don't use an interactive Python if you change sys.ps1 or
1152sys.ps2 from their default values, or if you're running code that
1153prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1154distinguish your output from Python's output, and assumes that `>>> '
1155at the start of a line is a prompt from Python. Similarly, the Emacs
1156Shell mode code assumes that both `>>> ' and `... ' at the start of a
1157line are Python prompts. Bad things can happen if you fool either
1158mode.
1159
1160Warning: If you do any editing *in* the process buffer *while* the
1161buffer is accepting output from Python, do NOT attempt to `undo' the
1162changes. Some of the output (nowhere near the parts you changed!) may
1163be lost if you do. This appears to be an Emacs bug, an unfortunate
1164interaction between undo and process filters; the same problem exists in
1165non-Python process buffers using the default (Emacs-supplied) process
1166filter."
1167 ;; BAW - should undo be disabled in the python process buffer, if
1168 ;; this bug still exists?
1169 (interactive)
Barry Warsaw2518c671997-11-05 00:51:08 +00001170 (switch-to-buffer-other-window
Barry Warsawa2398801998-04-09 23:28:20 +00001171 (apply 'make-comint py-which-bufname py-which-shell nil py-which-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001172 (make-local-variable 'comint-prompt-regexp)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001173 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001174 (add-hook 'comint-output-filter-functions 'py-comint-output-filter-function)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001175 (set-syntax-table py-mode-syntax-table)
Barry Warsaw6dfbe5d1998-08-20 21:51:27 +00001176 (use-local-map py-shell-map)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001177 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001178
Barry Warsawa97a3f31997-11-04 18:47:06 +00001179(defun py-clear-queue ()
1180 "Clear the queue of temporary files waiting to execute."
1181 (interactive)
1182 (let ((n (length py-file-queue)))
1183 (mapcar 'delete-file py-file-queue)
1184 (setq py-file-queue nil)
1185 (message "%d pending files de-queued." n)))
1186
Barry Warsaw820273d1998-05-19 15:54:45 +00001187
Barry Warsawa97a3f31997-11-04 18:47:06 +00001188(defun py-execute-region (start end &optional async)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001189 "Execute the region in a Python interpreter.
1190
Barry Warsawa97a3f31997-11-04 18:47:06 +00001191The region is first copied into a temporary file (in the directory
1192`py-temp-directory'). If there is no Python interpreter shell
1193running, this file is executed synchronously using
Barry Warsaw41a05c71998-08-10 16:33:12 +00001194`shell-command-on-region'. If the program is long running, use
1195\\[universal-argument] to run the command asynchronously in its own
1196buffer.
1197
1198When this function is used programmatically, arguments START and END
1199specify the region to execute, and optional third argument ASYNC, if
1200non-nil, specifies to run the command asynchronously in its own
1201buffer.
Barry Warsawa97a3f31997-11-04 18:47:06 +00001202
1203If the Python interpreter shell is running, the region is execfile()'d
1204in that shell. If you try to execute regions too quickly,
1205`python-mode' will queue them up and execute them one at a time when
1206it sees a `>>> ' prompt from Python. Each time this happens, the
1207process buffer is popped into a window (if it's not already in some
1208window) so you can see it, and a comment of the form
1209
1210 \t## working on region in file <name>...
1211
1212is inserted at the end. See also the command `py-clear-queue'."
1213 (interactive "r\nP")
1214 (or (< start end)
1215 (error "Region is empty"))
1216 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001217 (temp (if (memq 'broken-temp-names py-emacs-features)
Barry Warsaw1b344241998-08-07 22:24:16 +00001218 (let
1219 ((sn py-serial-number)
1220 (pid (and (fboundp 'emacs-pid) (emacs-pid))))
1221 (setq py-serial-number (1+ py-serial-number))
1222 (if pid
1223 (format "python-%d-%d" sn pid)
1224 (format "python-%d" sn)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001225 (make-temp-name "python-")))
1226 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001227 (write-region start end file nil 'nomsg)
1228 (cond
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001229 ;; always run the code in its own asynchronous subprocess
Barry Warsawa97a3f31997-11-04 18:47:06 +00001230 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001231 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001232 (start-process "Python" buf py-python-command "-u" file)
1233 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001234 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001235 ))
1236 ;; if the Python interpreter shell is running, queue it up for
1237 ;; execution there.
1238 (proc
1239 ;; use the existing python shell
1240 (if (not py-file-queue)
1241 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001242 (message "File %s queued for execution" file))
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001243 (setq py-file-queue (append py-file-queue (list file)))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001244 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001245 (t
1246 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001247 (shell-command-on-region start end py-python-command py-output-buffer)
Barry Warsaw512af041998-03-25 23:27:17 +00001248 ;; shell-command-on-region kills the output buffer if it never
1249 ;; existed and there's no output from the command
1250 (if (not (get-buffer py-output-buffer))
1251 (message "No output.")
1252 (setq py-exception-buffer (current-buffer))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001253 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1254 (pop-to-buffer py-output-buffer)
1255 (if err-p
1256 (pop-to-buffer py-exception-buffer)))
Barry Warsaw512af041998-03-25 23:27:17 +00001257 ))
1258 )))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001259
Barry Warsaw820273d1998-05-19 15:54:45 +00001260
1261;; Code execution commands
Barry Warsawa97a3f31997-11-04 18:47:06 +00001262(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001263 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001264If the file local variable `py-master-file' is non-nil, execute the
1265named file instead of the buffer's file.
1266
Barry Warsaw7ae77681994-12-12 20:38:05 +00001267If there is a *Python* process buffer it is used. If a clipping
1268restriction is in effect, only the accessible portion of the buffer is
1269sent. A trailing newline will be supplied if needed.
1270
Barry Warsaw41a05c71998-08-10 16:33:12 +00001271See the `\\[py-execute-region]' docs for an account of some
1272subtleties, including the use of the optional ASYNC argument."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001273 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001274 (if py-master-file
1275 (let* ((filename (expand-file-name py-master-file))
1276 (buffer (or (get-file-buffer filename)
1277 (find-file-noselect filename))))
1278 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001279 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001280
Barry Warsaw820273d1998-05-19 15:54:45 +00001281(defun py-execute-import-or-reload (&optional async)
1282 "Import the current buffer's file in a Python interpreter.
1283
1284If the file has already been imported, then do reload instead to get
Barry Warsaw7c29b231998-07-07 17:45:38 +00001285the latest version.
1286
1287If the file's name does not end in \".py\", then do execfile instead.
1288
1289If the current buffer is not visiting a file, do `py-execute-buffer'
1290instead.
1291
1292If the file local variable `py-master-file' is non-nil, import or
1293reload the named file instead of the buffer's file. The file may be
1294saved based on the value of `py-execute-import-or-reload-save-p'.
Barry Warsaw820273d1998-05-19 15:54:45 +00001295
Barry Warsaw41a05c71998-08-10 16:33:12 +00001296See the `\\[py-execute-region]' docs for an account of some
1297subtleties, including the use of the optional ASYNC argument.
Barry Warsaw820273d1998-05-19 15:54:45 +00001298
Barry Warsaw7c29b231998-07-07 17:45:38 +00001299This may be preferable to `\\[py-execute-buffer]' because:
Barry Warsaw820273d1998-05-19 15:54:45 +00001300
1301 - Definitions stay in their module rather than appearing at top
1302 level, where they would clutter the global namespace and not affect
1303 uses of qualified names (MODULE.NAME).
1304
1305 - The Python debugger gets line number information about the functions."
1306 (interactive "P")
1307 ;; Check file local variable py-master-file
1308 (if py-master-file
1309 (let* ((filename (expand-file-name py-master-file))
1310 (buffer (or (get-file-buffer filename)
1311 (find-file-noselect filename))))
1312 (set-buffer buffer)))
1313 (let ((file (buffer-file-name (current-buffer))))
1314 (if file
1315 (progn
Barry Warsaw3bfed5b1998-05-19 16:25:04 +00001316 ;; Maybe save some buffers
1317 (save-some-buffers (not py-ask-about-save) nil)
Barry Warsaw820273d1998-05-19 15:54:45 +00001318 (py-execute-string
1319 (if (string-match "\\.py$" file)
1320 (let ((f (file-name-sans-extension
1321 (file-name-nondirectory file))))
1322 (format "if globals().has_key('%s'):\n reload(%s)\nelse:\n import %s\n"
1323 f f f))
Barry Warsaw02e5f691998-09-24 23:48:40 +00001324 (format "execfile(r'%s')\n" file))
Barry Warsaw820273d1998-05-19 15:54:45 +00001325 async))
1326 ;; else
1327 (py-execute-buffer async))))
1328
1329
1330(defun py-execute-def-or-class (&optional async)
1331 "Send the current function or class definition to a Python interpreter.
1332
1333If there is a *Python* process buffer it is used.
1334
Barry Warsaw41a05c71998-08-10 16:33:12 +00001335See the `\\[py-execute-region]' docs for an account of some
1336subtleties, including the use of the optional ASYNC argument."
Barry Warsaw820273d1998-05-19 15:54:45 +00001337 (interactive "P")
1338 (save-excursion
1339 (py-mark-def-or-class)
1340 ;; mark is before point
1341 (py-execute-region (mark) (point) async)))
1342
1343
1344(defun py-execute-string (string &optional async)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001345 "Send the argument STRING to a Python interpreter.
Barry Warsaw820273d1998-05-19 15:54:45 +00001346
1347If there is a *Python* process buffer it is used.
1348
Barry Warsaw41a05c71998-08-10 16:33:12 +00001349See the `\\[py-execute-region]' docs for an account of some
1350subtleties, including the use of the optional ASYNC argument."
Barry Warsaw820273d1998-05-19 15:54:45 +00001351 (interactive "sExecute Python command: ")
1352 (save-excursion
1353 (set-buffer (get-buffer-create
1354 (generate-new-buffer-name " *Python Command*")))
1355 (insert string)
1356 (py-execute-region (point-min) (point-max) async)))
1357
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001358
1359
1360(defun py-jump-to-exception (file line)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001361 "Jump to the Python code in FILE at LINE."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001362 (let ((buffer (cond ((string-equal file "<stdin>")
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001363 (if (consp py-exception-buffer)
1364 (cdr py-exception-buffer)
1365 py-exception-buffer))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001366 ((and (consp py-exception-buffer)
1367 (string-equal file (car py-exception-buffer)))
1368 (cdr py-exception-buffer))
1369 ((py-safe (find-file-noselect file)))
1370 ;; could not figure out what file the exception
1371 ;; is pointing to, so prompt for it
1372 (t (find-file (read-file-name "Exception file: "
1373 nil
1374 file t))))))
1375 (pop-to-buffer buffer)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001376 ;; Force Python mode
Barry Warsaw820273d1998-05-19 15:54:45 +00001377 (if (not (eq major-mode 'python-mode))
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001378 (python-mode))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001379 (goto-line line)
1380 (message "Jumping to exception in file %s on line %d" file line)))
1381
1382(defun py-mouseto-exception (event)
Barry Warsaw12c92941998-08-10 21:44:37 +00001383 "Jump to the code which caused the Python exception at EVENT.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001384EVENT is usually a mouse click."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001385 (interactive "e")
1386 (cond
1387 ((fboundp 'event-point)
1388 ;; XEmacs
1389 (let* ((point (event-point event))
1390 (buffer (event-buffer event))
1391 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1392 (info (and e (extent-property e 'py-exc-info))))
1393 (message "Event point: %d, info: %s" point info)
1394 (and info
1395 (py-jump-to-exception (car info) (cdr info)))
1396 ))
1397 ;; Emacs -- Please port this!
1398 ))
1399
1400(defun py-goto-exception ()
1401 "Go to the line indicated by the traceback."
1402 (interactive)
1403 (let (file line)
1404 (save-excursion
1405 (beginning-of-line)
1406 (if (looking-at py-traceback-line-re)
1407 (setq file (match-string 1)
1408 line (string-to-int (match-string 2)))))
1409 (if (not file)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001410 (error "Not on a traceback line"))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001411 (py-jump-to-exception file line)))
1412
1413(defun py-find-next-exception (start buffer searchdir errwhere)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001414 "Find the next Python exception and jump to the code that caused it.
1415START is the buffer position in BUFFER from which to begin searching
1416for an exception. SEARCHDIR is a function, either
1417`re-search-backward' or `re-search-forward' indicating the direction
1418to search. ERRWHERE is used in an error message if the limit (top or
1419bottom) of the trackback stack is encountered."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001420 (let (file line)
1421 (save-excursion
1422 (set-buffer buffer)
1423 (goto-char (py-point start))
1424 (if (funcall searchdir py-traceback-line-re nil t)
1425 (setq file (match-string 1)
1426 line (string-to-int (match-string 2)))))
1427 (if (and file line)
1428 (py-jump-to-exception file line)
1429 (error "%s of traceback" errwhere))))
1430
1431(defun py-down-exception (&optional bottom)
1432 "Go to the next line down in the traceback.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001433With \\[univeral-argument] (programmatically, optional argument
1434BOTTOM), jump to the bottom (innermost) exception in the exception
1435stack."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001436 (interactive "P")
1437 (let* ((proc (get-process "Python"))
1438 (buffer (if proc "*Python*" py-output-buffer)))
1439 (if bottom
1440 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1441 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1442
1443(defun py-up-exception (&optional top)
1444 "Go to the previous line up in the traceback.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001445With \\[universal-argument] (programmatically, optional argument TOP)
1446jump to the top (outermost) exception in the exception stack."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001447 (interactive "P")
1448 (let* ((proc (get-process "Python"))
1449 (buffer (if proc "*Python*" py-output-buffer)))
1450 (if top
1451 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001452 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001453
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001454
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001455;; Electric deletion
1456(defun py-electric-backspace (arg)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001457 "Delete preceding character or levels of indentation.
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001458Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001459with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001460
Barry Warsaw41a05c71998-08-10 16:33:12 +00001461If point is at the leftmost column, delete the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001462
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001463Otherwise, if point is at the leftmost non-whitespace character of a
1464line that is neither a continuation line nor a non-indenting comment
1465line, or if point is at the end of a blank line, this command reduces
1466the indentation to match that of the line that opened the current
1467block of code. The line that opened the block is displayed in the
Barry Warsaw41a05c71998-08-10 16:33:12 +00001468echo area to help you keep track of where you are. With
1469\\[universal-argument] dedents that many blocks (but not past column
1470zero).
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001471
1472Otherwise the preceding character is deleted, converting a tab to
1473spaces if needed so that only a single column position is deleted.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001474\\[universal-argument] specifies how many characters to delete
1475(default is 1).
1476
1477When used programmatically, argument ARG specifies the number of
1478blocks to dedent, or the number of characters to delete, as indicated
1479above."
Barry Warsaw03970731996-07-03 23:12:52 +00001480 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001481 (if (or (/= (current-indentation) (current-column))
1482 (bolp)
1483 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001484 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001485 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001486 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001487 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001488 ;; force non-blank so py-goto-block-up doesn't ignore it
1489 (insert-char ?* 1)
1490 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001491 (let ((base-indent 0) ; indentation of base line
1492 (base-text "") ; and text of base line
1493 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001494 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001495 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001496 (condition-case nil ; in case no enclosing block
1497 (progn
1498 (py-goto-block-up 'no-mark)
1499 (setq base-indent (current-indentation)
1500 base-text (py-suck-up-leading-text)
1501 base-found-p t))
1502 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001503 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001504 (delete-char 1) ; toss the dummy character
1505 (delete-horizontal-space)
1506 (indent-to base-indent)
1507 (if base-found-p
1508 (message "Closes block: %s" base-text)))))
1509
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001510
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001511(defun py-electric-delete (arg)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001512 "Delete preceding or following character or levels of whitespace.
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001513
1514The behavior of this function depends on the variable
1515`delete-key-deletes-forward'. If this variable is nil (or does not
Barry Warsaw41a05c71998-08-10 16:33:12 +00001516exist, as in older Emacsen and non-XEmacs versions), then this
1517function behaves identically to \\[c-electric-backspace].
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001518
1519If `delete-key-deletes-forward' is non-nil and is supported in your
1520Emacs, then deletion occurs in the forward direction, by calling the
Barry Warsaw41a05c71998-08-10 16:33:12 +00001521function in `py-delete-function'.
1522
1523\\[universal-argument] (programmatically, argument ARG) specifies the
1524number of characters to delete (default is 1)."
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001525 (interactive "*p")
1526 (if (and (boundp 'delete-key-deletes-forward)
1527 delete-key-deletes-forward)
1528 (funcall py-delete-function arg)
1529 ;; else
1530 (py-electric-backspace arg)))
1531
1532;; required for pending-del and delsel modes
1533(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1534(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1535(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1536(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1537
1538
1539
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001540(defun py-indent-line (&optional arg)
1541 "Fix the indentation of the current line according to Python rules.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001542With \\[universal-argument] (programmatically, the optional argument
1543ARG non-nil), ignore dedenting rules for block closing statements
1544(e.g. return, raise, break, continue, pass)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001545
1546This function is normally bound to `indent-line-function' so
1547\\[indent-for-tab-command] will call it."
1548 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001549 (let* ((ci (current-indentation))
1550 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001551 (need (py-compute-indentation (not arg))))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001552 ;; see if we need to dedent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001553 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001554 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001555 (if (/= ci need)
1556 (save-excursion
1557 (beginning-of-line)
1558 (delete-horizontal-space)
1559 (indent-to need)))
1560 (if move-to-indentation-p (back-to-indentation))))
1561
1562(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001563 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001564This is just `strives to' because correct indentation can't be computed
1565from scratch for Python code. In general, deletes the whitespace before
1566point, inserts a newline, and takes an educated guess as to how you want
1567the new line indented."
1568 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001569 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001570 (if (< ci (current-column)) ; if point beyond indentation
1571 (newline-and-indent)
1572 ;; else try to act like newline-and-indent "normally" acts
1573 (beginning-of-line)
1574 (insert-char ?\n 1)
1575 (move-to-column ci))))
1576
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001577(defun py-compute-indentation (honor-block-close-p)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001578 "Compute Python indentation.
1579When HONOR-BLOCK-CLOSE-P is non-nil, statements such as `return',
1580`raise', `break', `continue', and `pass' force one level of
1581dedenting."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001582 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001583 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001584 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001585 (pps (parse-partial-sexp bod (point)))
1586 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001587 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001588 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001589 ((or (and (nth 3 pps) (nth 3 boipps))
1590 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001591 (save-excursion
1592 (if (not py-align-multiline-strings-p) 0
1593 ;; skip back over blank & non-indenting comment lines
1594 ;; note: will skip a blank or non-indenting comment line
1595 ;; that happens to be a continuation line too
1596 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1597 (back-to-indentation)
1598 (current-column))))
1599 ;; are we on a continuation line?
1600 ((py-continuation-line-p)
1601 (let ((startpos (point))
1602 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001603 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001604 (if open-bracket-pos
1605 (progn
1606 ;; align with first item in list; else a normal
1607 ;; indent beyond the line with the open bracket
1608 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1609 ;; is the first list item on the same line?
1610 (skip-chars-forward " \t")
1611 (if (null (memq (following-char) '(?\n ?# ?\\)))
1612 ; yes, so line up with it
1613 (current-column)
1614 ;; first list item on another line, or doesn't exist yet
1615 (forward-line 1)
1616 (while (and (< (point) startpos)
1617 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1618 (forward-line 1))
Barry Warsaw92166d91998-04-01 21:59:41 +00001619 (if (and (< (point) startpos)
1620 (/= startpos
1621 (save-excursion
1622 (goto-char (1+ open-bracket-pos))
Barry Warsaw77d1fce1998-04-16 20:04:59 +00001623 (forward-comment (point-max))
Barry Warsaw92166d91998-04-01 21:59:41 +00001624 (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001625 ;; again mimic the first list item
1626 (current-indentation)
1627 ;; else they're about to enter the first item
1628 (goto-char open-bracket-pos)
1629 (+ (current-indentation) py-indent-offset))))
1630
1631 ;; else on backslash continuation line
1632 (forward-line -1)
1633 (if (py-continuation-line-p) ; on at least 3rd line in block
1634 (current-indentation) ; so just continue the pattern
1635 ;; else started on 2nd line in block, so indent more.
1636 ;; if base line is an assignment with a start on a RHS,
1637 ;; indent to 2 beyond the leftmost "="; else skip first
1638 ;; chunk of non-whitespace characters on base line, + 1 more
1639 ;; column
1640 (end-of-line)
1641 (setq endpos (point) searching t)
1642 (back-to-indentation)
1643 (setq startpos (point))
1644 ;; look at all "=" from left to right, stopping at first
1645 ;; one not nested in a list or string
1646 (while searching
1647 (skip-chars-forward "^=" endpos)
1648 (if (= (point) endpos)
1649 (setq searching nil)
1650 (forward-char 1)
1651 (setq state (parse-partial-sexp startpos (point)))
1652 (if (and (zerop (car state)) ; not in a bracket
1653 (null (nth 3 state))) ; & not in a string
1654 (progn
1655 (setq searching nil) ; done searching in any case
1656 (setq found
1657 (not (or
1658 (eq (following-char) ?=)
1659 (memq (char-after (- (point) 2))
1660 '(?< ?> ?!)))))))))
1661 (if (or (not found) ; not an assignment
1662 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1663 (progn
1664 (goto-char startpos)
1665 (skip-chars-forward "^ \t\n")))
1666 (1+ (current-column))))))
1667
1668 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001669 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001670
Barry Warsawa7891711996-08-01 15:53:09 +00001671 ;; Dfn: "Indenting comment line". A line containing only a
1672 ;; comment, but which is treated like a statement for
1673 ;; indentation calculation purposes. Such lines are only
1674 ;; treated specially by the mode; they are not treated
1675 ;; specially by the Python interpreter.
1676
1677 ;; The rules for indenting comment lines are a line where:
1678 ;; - the first non-whitespace character is `#', and
1679 ;; - the character following the `#' is whitespace, and
Barry Warsaw41a05c71998-08-10 16:33:12 +00001680 ;; - the line is dedented with respect to (i.e. to the left
Barry Warsawa7891711996-08-01 15:53:09 +00001681 ;; of) the indentation of the preceding non-blank line.
1682
1683 ;; The first non-blank line following an indenting comment
1684 ;; line is given the same amount of indentation as the
1685 ;; indenting comment line.
1686
1687 ;; All other comment-only lines are ignored for indentation
1688 ;; purposes.
1689
1690 ;; Are we looking at a comment-only line which is *not* an
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001691 ;; indenting comment line? If so, we assume that it's been
Barry Warsawa7891711996-08-01 15:53:09 +00001692 ;; placed at the desired indentation, so leave it alone.
1693 ;; Indenting comment lines are aligned as statements down
1694 ;; below.
1695 ((and (looking-at "[ \t]*#[^ \t\n]")
1696 ;; NOTE: this test will not be performed in older Emacsen
1697 (fboundp 'forward-comment)
1698 (<= (current-indentation)
1699 (save-excursion
1700 (forward-comment (- (point-max)))
1701 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001702 (current-indentation))
1703
1704 ;; else indentation based on that of the statement that
1705 ;; precedes us; use the first line of that statement to
1706 ;; establish the base, in case the user forced a non-std
1707 ;; indentation for the continuation lines (if any)
1708 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001709 ;; skip back over blank & non-indenting comment lines note:
1710 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001711 ;; happens to be a continuation line too. use fast Emacs 19
1712 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001713 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001714 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001715 (forward-comment (- (point-max)))
Barry Warsaw218eb751998-09-22 19:51:47 +00001716 (let ((prefix-re (concat py-block-comment-prefix "[ \t]*"))
1717 done)
Barry Warsaw6d627751996-03-06 18:41:38 +00001718 (while (not done)
Barry Warsaw12c92941998-08-10 21:44:37 +00001719 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#\\)" nil 'move)
1720 (setq done (or (bobp)
1721 (and (eq py-honor-comment-indentation t)
1722 (save-excursion
1723 (back-to-indentation)
Barry Warsaw218eb751998-09-22 19:51:47 +00001724 (not (looking-at prefix-re))
Barry Warsaw12c92941998-08-10 21:44:37 +00001725 ))
1726 (and (not (eq py-honor-comment-indentation t))
1727 (save-excursion
1728 (back-to-indentation)
1729 (not (zerop (current-column)))))
1730 ))
Barry Warsaw6d627751996-03-06 18:41:38 +00001731 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001732 ;; if we landed inside a string, go to the beginning of that
1733 ;; string. this handles triple quoted, multi-line spanning
1734 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001735 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001736 (skip (and delim (make-string 1 delim))))
1737 (when skip
1738 (save-excursion
1739 (py-safe (search-backward skip))
1740 (if (and (eq (char-before) delim)
1741 (eq (char-before (1- (point))) delim))
1742 (setq skip (make-string 3 delim))))
1743 ;; we're looking at a triple-quoted string
1744 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001745 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001746 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001747 (+ (current-indentation)
1748 (if (py-statement-opens-block-p)
1749 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001750 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001751 (- py-indent-offset)
1752 0)))
1753 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001754
1755(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001756 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001757
1758By default, make a buffer-local copy of `py-indent-offset' with the
1759new value, so that other Python buffers are not affected. With
1760\\[universal-argument] (programmatically, optional argument GLOBAL),
1761change the global value of `py-indent-offset'. This affects all
1762Python buffers (that don't have their own buffer-local copy), both
1763those currently existing and those created later in the Emacs session.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001764
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001765Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001766There's no excuse for such foolishness, but sometimes you have to deal
1767with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001768`py-indent-offset' to what it thinks it was when they created the
1769mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001770
1771Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001772looking for a line that opens a block of code. `py-indent-offset' is
1773set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001774statement following it. If the search doesn't succeed going forward,
1775it's tried again going backward."
1776 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001777 (let (new-value
1778 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001779 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001780 (found nil)
1781 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001782 (py-goto-initial-line)
1783 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001784 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1785 (not (py-in-literal restart)))
1786 (setq restart (point))
1787 (py-goto-initial-line)
1788 (if (py-statement-opens-block-p)
1789 (setq found t)
1790 (goto-char restart))))
1791 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001792 (goto-char start)
1793 (py-goto-initial-line)
1794 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001795 (setq found (and
1796 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1797 (or (py-goto-initial-line) t) ; always true -- side effect
1798 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001799 (setq colon-indent (current-indentation)
1800 found (and found (zerop (py-next-statement 1)))
1801 new-value (- (current-indentation) colon-indent))
1802 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001803 (if (not found)
1804 (error "Sorry, couldn't guess a value for py-indent-offset")
1805 (funcall (if global 'kill-local-variable 'make-local-variable)
1806 'py-indent-offset)
1807 (setq py-indent-offset new-value)
Barry Warsawd35c2551998-09-25 00:08:38 +00001808 (or noninteractive
1809 (message "%s value of py-indent-offset set to %d"
1810 (if global "Global" "Local")
1811 py-indent-offset)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001812 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001813
Barry Warsaw003932a1998-07-07 15:11:24 +00001814(defun py-comment-indent-function ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00001815 "Python version of `comment-indent-function'."
1816 ;; This is required when filladapt is turned off. Without it, when
1817 ;; filladapt is not used, comments which start in column zero
1818 ;; cascade one character to the right
Barry Warsaw003932a1998-07-07 15:11:24 +00001819 (save-excursion
1820 (beginning-of-line)
1821 (let ((eol (py-point 'eol)))
1822 (and comment-start-skip
1823 (re-search-forward comment-start-skip eol t)
1824 (setq eol (match-beginning 0)))
1825 (goto-char eol)
1826 (skip-chars-backward " \t")
1827 (max comment-column (+ (current-column) (if (bolp) 0 1)))
1828 )))
1829
1830
Barry Warsaw7ae77681994-12-12 20:38:05 +00001831(defun py-shift-region (start end count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001832 "Indent lines from START to END by COUNT spaces."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001833 (save-excursion
Barry Warsaw41a05c71998-08-10 16:33:12 +00001834 (goto-char end)
1835 (beginning-of-line)
1836 (setq end (point))
1837 (goto-char start)
1838 (beginning-of-line)
1839 (setq start (point))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001840 (indent-rigidly start end count)))
1841
1842(defun py-shift-region-left (start end &optional count)
1843 "Shift region of Python code to the left.
1844The lines from the line containing the start of the current region up
1845to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001846shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001847
1848If a prefix argument is given, the region is instead shifted by that
Barry Warsaw41a05c71998-08-10 16:33:12 +00001849many columns. With no active region, dedent only the current line.
1850You cannot dedent the region if any line is already at column zero."
Barry Warsawdea4a291996-07-03 22:59:12 +00001851 (interactive
1852 (let ((p (point))
1853 (m (mark))
1854 (arg current-prefix-arg))
1855 (if m
1856 (list (min p m) (max p m) arg)
1857 (list p (save-excursion (forward-line 1) (point)) arg))))
1858 ;; if any line is at column zero, don't shift the region
1859 (save-excursion
1860 (goto-char start)
1861 (while (< (point) end)
1862 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001863 (if (and (zerop (current-column))
1864 (not (looking-at "\\s *$")))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001865 (error "Region is at left edge"))
Barry Warsawdea4a291996-07-03 22:59:12 +00001866 (forward-line 1)))
1867 (py-shift-region start end (- (prefix-numeric-value
1868 (or count py-indent-offset))))
1869 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001870
1871(defun py-shift-region-right (start end &optional count)
1872 "Shift region of Python code to the right.
1873The lines from the line containing the start of the current region up
1874to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001875shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001876
1877If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001878many columns. With no active region, indent only the current line."
1879 (interactive
1880 (let ((p (point))
1881 (m (mark))
1882 (arg current-prefix-arg))
1883 (if m
1884 (list (min p m) (max p m) arg)
1885 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001886 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001887 (or count py-indent-offset)))
1888 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001889
1890(defun py-indent-region (start end &optional indent-offset)
1891 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001892
Barry Warsaw7ae77681994-12-12 20:38:05 +00001893The lines from the line containing the start of the current region up
1894to (but not including) the line containing the end of the region are
1895reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001896character in the first column, the first line is left alone and the
1897rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001898region is reindented with respect to the (closest code or indenting
1899comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001900
1901This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001902control structures are introduced or removed, or to reformat code
1903using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001904
1905If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001906the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001907used.
1908
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001909Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001910is called! This function does not compute proper indentation from
1911scratch (that's impossible in Python), it merely adjusts the existing
1912indentation to be correct in context.
1913
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001914Warning: This function really has no idea what to do with
1915non-indenting comment lines, and shifts them as if they were indenting
1916comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001917
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001918Special cases: whitespace is deleted from blank lines; continuation
1919lines are shifted by the same amount their initial line was shifted,
1920in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001921initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001922 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001923 (save-excursion
1924 (goto-char end) (beginning-of-line) (setq end (point-marker))
1925 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001926 (let ((py-indent-offset (prefix-numeric-value
1927 (or indent-offset py-indent-offset)))
1928 (indents '(-1)) ; stack of active indent levels
1929 (target-column 0) ; column to which to indent
1930 (base-shifted-by 0) ; amount last base line was shifted
1931 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001932 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001933 0))
1934 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001935 (while (< (point) end)
1936 (setq ci (current-indentation))
1937 ;; figure out appropriate target column
1938 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001939 ((or (eq (following-char) ?#) ; comment in column 1
1940 (looking-at "[ \t]*$")) ; entirely blank
1941 (setq target-column 0))
1942 ((py-continuation-line-p) ; shift relative to base line
1943 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001944 (t ; new base line
1945 (if (> ci (car indents)) ; going deeper; push it
1946 (setq indents (cons ci indents))
1947 ;; else we should have seen this indent before
1948 (setq indents (memq ci indents)) ; pop deeper indents
1949 (if (null indents)
1950 (error "Bad indentation in region, at line %d"
1951 (save-restriction
1952 (widen)
1953 (1+ (count-lines 1 (point)))))))
1954 (setq target-column (+ indent-base
1955 (* py-indent-offset
1956 (- (length indents) 2))))
1957 (setq base-shifted-by (- target-column ci))))
1958 ;; shift as needed
1959 (if (/= ci target-column)
1960 (progn
1961 (delete-horizontal-space)
1962 (indent-to target-column)))
1963 (forward-line 1))))
1964 (set-marker end nil))
1965
Barry Warsawa7891711996-08-01 15:53:09 +00001966(defun py-comment-region (beg end &optional arg)
1967 "Like `comment-region' but uses double hash (`#') comment starter."
1968 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001969 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001970 (comment-region beg end arg)))
1971
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001972
1973;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001974(defun py-previous-statement (count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001975 "Go to the start of the COUNTth preceding Python statement.
1976By default, goes to the previous statement. If there is no such
1977statement, goes to the first statement. Return count of statements
1978left to move. `Statements' do not include blank, comment, or
1979continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001980 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001981 (if (< count 0) (py-next-statement (- count))
1982 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001983 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001984 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001985 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001986 (> count 0)
1987 (zerop (forward-line -1))
1988 (py-goto-statement-at-or-above))
1989 (setq count (1- count)))
1990 (if (> count 0) (goto-char start)))
1991 count))
1992
1993(defun py-next-statement (count)
1994 "Go to the start of next Python statement.
1995If the statement at point is the i'th Python statement, goes to the
1996start of statement i+COUNT. If there is no such statement, goes to the
1997last statement. Returns count of statements left to move. `Statements'
1998do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001999 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002000 (if (< count 0) (py-previous-statement (- count))
2001 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002002 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002003 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002004 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002005 (> count 0)
2006 (py-goto-statement-below))
2007 (setq count (1- count)))
2008 (if (> count 0) (goto-char start)))
2009 count))
2010
2011(defun py-goto-block-up (&optional nomark)
2012 "Move up to start of current block.
2013Go to the statement that starts the smallest enclosing block; roughly
2014speaking, this will be the closest preceding statement that ends with a
2015colon and is indented less than the statement you started on. If
2016successful, also sets the mark to the starting point.
2017
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002018`\\[py-mark-block]' can be used afterward to mark the whole code
2019block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002020
2021If called from a program, the mark will not be set if optional argument
2022NOMARK is not nil."
2023 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002024 (let ((start (point))
2025 (found nil)
2026 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002027 (py-goto-initial-line)
2028 ;; if on blank or non-indenting comment line, use the preceding stmt
2029 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2030 (progn
2031 (py-goto-statement-at-or-above)
2032 (setq found (py-statement-opens-block-p))))
2033 ;; search back for colon line indented less
2034 (setq initial-indent (current-indentation))
2035 (if (zerop initial-indent)
2036 ;; force fast exit
2037 (goto-char (point-min)))
2038 (while (not (or found (bobp)))
2039 (setq found
2040 (and
2041 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2042 (or (py-goto-initial-line) t) ; always true -- side effect
2043 (< (current-indentation) initial-indent)
2044 (py-statement-opens-block-p))))
2045 (if found
2046 (progn
2047 (or nomark (push-mark start))
2048 (back-to-indentation))
2049 (goto-char start)
2050 (error "Enclosing block not found"))))
2051
Barry Warsawab0e86c1998-05-19 15:31:46 +00002052(defun py-beginning-of-def-or-class (&optional class count)
2053 "Move point to start of `def' or `class'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002054
2055Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsawab0e86c1998-05-19 15:31:46 +00002056arg, looks for a `class' instead. The docs below assume the `def'
2057case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002058Programmatically, if CLASS is `either', then moves to either `class'
2059or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002060
Barry Warsawab0e86c1998-05-19 15:31:46 +00002061When second optional argument is given programmatically, move to the
2062COUNTth start of `def'.
2063
2064If point is in a `def' statement already, and after the `d', simply
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002065moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002066
Barry Warsawab0e86c1998-05-19 15:31:46 +00002067Otherwise (i.e. when point is not in a `def' statement, or at or
2068before the `d' of a `def' statement), searches for the closest
2069preceding `def' statement, and leaves point at its start. If no such
2070statement can be found, leaves point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002071
Barry Warsawab0e86c1998-05-19 15:31:46 +00002072Returns t iff a `def' statement is found by these rules.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002073
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002074Note that doing this command repeatedly will take you closer to the
2075start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002076
Barry Warsaw7c29b231998-07-07 17:45:38 +00002077To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002078 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002079 (if (not count)
2080 (setq count 1))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002081 (let ((at-or-before-p (<= (current-column) (current-indentation)))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002082 (start-of-line (goto-char (py-point 'bol)))
2083 (start-of-stmt (goto-char (py-point 'bos)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002084 (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
2085 (class "^[ \t]*class\\>")
2086 (t "^[ \t]*def\\>")))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002087 )
2088 ;; searching backward
2089 (if (and (< 0 count)
2090 (or (/= start-of-stmt start-of-line)
2091 (not at-or-before-p)))
2092 (end-of-line))
2093 ;; search forward
2094 (if (and (> 0 count)
2095 (zerop (current-column))
2096 (looking-at start-re))
2097 (end-of-line))
2098 (re-search-backward start-re nil 'move count)
2099 (goto-char (match-beginning 0))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002100
Barry Warsawab0e86c1998-05-19 15:31:46 +00002101;; Backwards compatibility
2102(defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002103
Barry Warsawab0e86c1998-05-19 15:31:46 +00002104(defun py-end-of-def-or-class (&optional class count)
2105 "Move point beyond end of `def' or `class' body.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002106
Barry Warsawab0e86c1998-05-19 15:31:46 +00002107By default, looks for an appropriate `def'. If you supply a prefix
2108arg, looks for a `class' instead. The docs below assume the `def'
2109case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002110Programmatically, if CLASS is `either', then moves to either `class'
2111or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002112
Barry Warsawab0e86c1998-05-19 15:31:46 +00002113When second optional argument is given programmatically, move to the
2114COUNTth end of `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002115
Barry Warsawab0e86c1998-05-19 15:31:46 +00002116If point is in a `def' statement already, this is the `def' we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002117
Barry Warsawab0e86c1998-05-19 15:31:46 +00002118Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2119contains the statement you started on, that's the `def' we use.
2120
2121Otherwise, we search forward for the closest following `def', and use that.
2122
2123If a `def' can be found by these rules, point is moved to the start of
2124the line immediately following the `def' block, and the position of the
2125start of the `def' is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002126
2127Else point is moved to the end of the buffer, and nil is returned.
2128
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002129Note that doing this command repeatedly will take you closer to the
2130end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002131
Barry Warsaw7c29b231998-07-07 17:45:38 +00002132To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002133 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002134 (if (and count (/= count 1))
2135 (py-beginning-of-def-or-class (- 1 count)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002136 (let ((start (progn (py-goto-initial-line) (point)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002137 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2138 (class "class")
2139 (t "def")))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002140 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002141 ;; move point to start of appropriate def/class
2142 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2143 (setq state 'at-beginning)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002144 ;; else see if py-beginning-of-def-or-class hits container
2145 (if (and (py-beginning-of-def-or-class class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002146 (progn (py-goto-beyond-block)
2147 (> (point) start)))
2148 (setq state 'at-end)
2149 ;; else search forward
2150 (goto-char start)
2151 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2152 (progn (setq state 'at-beginning)
2153 (beginning-of-line)))))
2154 (cond
2155 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2156 ((eq state 'at-end) t)
2157 ((eq state 'not-found) nil)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002158 (t (error "Internal error in `py-end-of-def-or-class'")))))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002159
2160;; Backwards compabitility
Barry Warsaw820273d1998-05-19 15:54:45 +00002161(defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002162
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002163
2164;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002165(defun py-mark-block (&optional extend just-move)
2166 "Mark following block of lines. With prefix arg, mark structure.
2167Easier to use than explain. It sets the region to an `interesting'
2168block of succeeding lines. If point is on a blank line, it goes down to
2169the next non-blank line. That will be the start of the region. The end
2170of the region depends on the kind of line at the start:
2171
2172 - If a comment, the region will include all succeeding comment lines up
2173 to (but not including) the next non-comment line (if any).
2174
2175 - Else if a prefix arg is given, and the line begins one of these
2176 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002177
2178 if elif else try except finally for while def class
2179
Barry Warsaw7ae77681994-12-12 20:38:05 +00002180 the region will be set to the body of the structure, including
2181 following blocks that `belong' to it, but excluding trailing blank
2182 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002183 and all (if any) of the following `except' and `finally' blocks
2184 that belong to the `try' structure will be in the region. Ditto
2185 for if/elif/else, for/else and while/else structures, and (a bit
2186 degenerate, since they're always one-block structures) def and
2187 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002188
2189 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002190 block (see list above), and the block is not a `one-liner' (i.e.,
2191 the statement ends with a colon, not with code), the region will
2192 include all succeeding lines up to (but not including) the next
2193 code statement (if any) that's indented no more than the starting
2194 line, except that trailing blank and comment lines are excluded.
2195 E.g., if the starting line begins a multi-statement `def'
2196 structure, the region will be set to the full function definition,
2197 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002198
2199 - Else the region will include all succeeding lines up to (but not
2200 including) the next blank line, or code or indenting-comment line
2201 indented strictly less than the starting line. Trailing indenting
2202 comment lines are included in this case, but not trailing blank
2203 lines.
2204
2205A msg identifying the location of the mark is displayed in the echo
2206area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2207
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002208If called from a program, optional argument EXTEND plays the role of
2209the prefix arg, and if optional argument JUST-MOVE is not nil, just
2210moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002211 (interactive "P") ; raw prefix arg
2212 (py-goto-initial-line)
2213 ;; skip over blank lines
2214 (while (and
2215 (looking-at "[ \t]*$") ; while blank line
2216 (not (eobp))) ; & somewhere to go
2217 (forward-line 1))
2218 (if (eobp)
2219 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002220 (let ((initial-pos (point))
2221 (initial-indent (current-indentation))
2222 last-pos ; position of last stmt in region
2223 (followers
2224 '((if elif else) (elif elif else) (else)
2225 (try except finally) (except except) (finally)
2226 (for else) (while else)
2227 (def) (class) ) )
2228 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002229
2230 (cond
2231 ;; if comment line, suck up the following comment lines
2232 ((looking-at "[ \t]*#")
2233 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2234 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2235 (setq last-pos (point)))
2236
2237 ;; else if line is a block line and EXTEND given, suck up
2238 ;; the whole structure
2239 ((and extend
2240 (setq first-symbol (py-suck-up-first-keyword) )
2241 (assq first-symbol followers))
2242 (while (and
2243 (or (py-goto-beyond-block) t) ; side effect
2244 (forward-line -1) ; side effect
2245 (setq last-pos (point)) ; side effect
2246 (py-goto-statement-below)
2247 (= (current-indentation) initial-indent)
2248 (setq next-symbol (py-suck-up-first-keyword))
2249 (memq next-symbol (cdr (assq first-symbol followers))))
2250 (setq first-symbol next-symbol)))
2251
2252 ;; else if line *opens* a block, search for next stmt indented <=
2253 ((py-statement-opens-block-p)
2254 (while (and
2255 (setq last-pos (point)) ; always true -- side effect
2256 (py-goto-statement-below)
2257 (> (current-indentation) initial-indent))
2258 nil))
2259
2260 ;; else plain code line; stop at next blank line, or stmt or
2261 ;; indenting comment line indented <
2262 (t
2263 (while (and
2264 (setq last-pos (point)) ; always true -- side effect
2265 (or (py-goto-beyond-final-line) t)
2266 (not (looking-at "[ \t]*$")) ; stop at blank line
2267 (or
2268 (>= (current-indentation) initial-indent)
2269 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2270 nil)))
2271
2272 ;; skip to end of last stmt
2273 (goto-char last-pos)
2274 (py-goto-beyond-final-line)
2275
2276 ;; set mark & display
2277 (if just-move
2278 () ; just return
2279 (push-mark (point) 'no-msg)
2280 (forward-line -1)
2281 (message "Mark set after: %s" (py-suck-up-leading-text))
2282 (goto-char initial-pos))))
2283
Barry Warsaw2518c671997-11-05 00:51:08 +00002284(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002285 "Set region to body of def (or class, with prefix arg) enclosing point.
2286Pushes the current mark, then point, on the mark ring (all language
2287modes do this, but although it's handy it's never documented ...).
2288
2289In most Emacs language modes, this function bears at least a
Barry Warsawab0e86c1998-05-19 15:31:46 +00002290hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2291`\\[py-beginning-of-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002292
2293And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002294Turned out that was more confusing than useful: the `goto start' and
2295`goto end' commands are usually used to search through a file, and
2296people expect them to act a lot like `search backward' and `search
2297forward' string-search commands. But because Python `def' and `class'
2298can nest to arbitrary levels, finding the smallest def containing
2299point cannot be done via a simple backward search: the def containing
2300point may not be the closest preceding def, or even the closest
2301preceding def that's indented less. The fancy algorithm required is
2302appropriate for the usual uses of this `mark' command, but not for the
2303`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002304
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002305So the def marked by this command may not be the one either of the
2306`goto' commands find: If point is on a blank or non-indenting comment
2307line, moves back to start of the closest preceding code statement or
2308indenting comment line. If this is a `def' statement, that's the def
2309we use. Else searches for the smallest enclosing `def' block and uses
2310that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002311
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002312When an enclosing def is found: The mark is left immediately beyond
2313the last line of the def block. Point is left at the start of the
2314def, except that: if the def is preceded by a number of comment lines
2315followed by (at most) one optional blank line, point is left at the
2316start of the comments; else if the def is preceded by a blank line,
2317point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002318
2319The intent is to mark the containing def/class and its associated
2320documentation, to make moving and duplicating functions and classes
2321pleasant."
2322 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002323 (let ((start (point))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002324 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2325 (class "class")
2326 (t "def"))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002327 (push-mark start)
2328 (if (not (py-go-up-tree-to-keyword which))
2329 (progn (goto-char start)
Barry Warsaw7c29b231998-07-07 17:45:38 +00002330 (error "Enclosing %s not found"
2331 (if (eq class 'either)
2332 "def or class"
2333 which)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002334 ;; else enclosing def/class found
2335 (setq start (point))
2336 (py-goto-beyond-block)
2337 (push-mark (point))
2338 (goto-char start)
2339 (if (zerop (forward-line -1)) ; if there is a preceding line
2340 (progn
2341 (if (looking-at "[ \t]*$") ; it's blank
2342 (setq start (point)) ; so reset start point
2343 (goto-char start)) ; else try again
2344 (if (zerop (forward-line -1))
2345 (if (looking-at "[ \t]*#") ; a comment
2346 ;; look back for non-comment line
2347 ;; tricky: note that the regexp matches a blank
2348 ;; line, cuz \n is in the 2nd character class
2349 (and
2350 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2351 (forward-line 1))
2352 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002353 (goto-char start)))))))
2354 (exchange-point-and-mark)
2355 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002356
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002357;; ripped from cc-mode
2358(defun py-forward-into-nomenclature (&optional arg)
2359 "Move forward to end of a nomenclature section or word.
Barry Warsaw41a05c71998-08-10 16:33:12 +00002360With \\[universal-argument] (programmatically, optional argument ARG),
2361do it that many times.
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002362
2363A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2364 (interactive "p")
2365 (let ((case-fold-search nil))
2366 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002367 (re-search-forward
2368 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2369 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002370 (while (and (< arg 0)
2371 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002372 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002373 (point-min) 0))
2374 (forward-char 1)
2375 (setq arg (1+ arg)))))
2376 (py-keep-region-active))
2377
2378(defun py-backward-into-nomenclature (&optional arg)
2379 "Move backward to beginning of a nomenclature section or word.
2380With optional ARG, move that many times. If ARG is negative, move
2381forward.
2382
2383A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2384 (interactive "p")
2385 (py-forward-into-nomenclature (- arg))
2386 (py-keep-region-active))
2387
2388
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002389
2390;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002391
2392;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002393;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2394;; out of the right places, along with the keys they're on & current
2395;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002396(defun py-dump-help-string (str)
2397 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002398 (let ((locals (buffer-local-variables))
2399 funckind funcname func funcdoc
2400 (start 0) mstart end
2401 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002402 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2403 (setq mstart (match-beginning 0) end (match-end 0)
2404 funckind (substring str (match-beginning 1) (match-end 1))
2405 funcname (substring str (match-beginning 2) (match-end 2))
2406 func (intern funcname))
2407 (princ (substitute-command-keys (substring str start mstart)))
2408 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002409 ((equal funckind "c") ; command
2410 (setq funcdoc (documentation func)
2411 keys (concat
2412 "Key(s): "
2413 (mapconcat 'key-description
2414 (where-is-internal func py-mode-map)
2415 ", "))))
2416 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002417 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002418 keys (if (assq func locals)
2419 (concat
2420 "Local/Global values: "
2421 (prin1-to-string (symbol-value func))
2422 " / "
2423 (prin1-to-string (default-value func)))
2424 (concat
2425 "Value: "
2426 (prin1-to-string (symbol-value func))))))
2427 (t ; unexpected
2428 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002429 (princ (format "\n-> %s:\t%s\t%s\n\n"
2430 (if (equal funckind "c") "Command" "Variable")
2431 funcname keys))
2432 (princ funcdoc)
2433 (terpri)
2434 (setq start end))
2435 (princ (substitute-command-keys (substring str start))))
2436 (print-help-return-message)))
2437
2438(defun py-describe-mode ()
2439 "Dump long form of Python-mode docs."
2440 (interactive)
2441 (py-dump-help-string "Major mode for editing Python files.
2442Knows about Python indentation, tokens, comments and continuation lines.
2443Paragraphs are separated by blank lines only.
2444
2445Major sections below begin with the string `@'; specific function and
2446variable docs begin with `->'.
2447
2448@EXECUTING PYTHON CODE
2449
Barry Warsaw820273d1998-05-19 15:54:45 +00002450\\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002451\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2452\\[py-execute-region]\tsends the current region
Barry Warsaw820273d1998-05-19 15:54:45 +00002453\\[py-execute-def-or-class]\tsends the current function or class definition
2454\\[py-execute-string]\tsends an arbitrary string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002455\\[py-shell]\tstarts a Python interpreter window; this will be used by
Barry Warsaw820273d1998-05-19 15:54:45 +00002456\tsubsequent Python execution commands
2457%c:py-execute-import-or-reload
Barry Warsaw7ae77681994-12-12 20:38:05 +00002458%c:py-execute-buffer
2459%c:py-execute-region
Barry Warsaw820273d1998-05-19 15:54:45 +00002460%c:py-execute-def-or-class
2461%c:py-execute-string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002462%c:py-shell
2463
2464@VARIABLES
2465
2466py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002467py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002468
2469py-python-command\tshell command to invoke Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002470py-temp-directory\tdirectory used for temp files (if needed)
2471
2472py-beep-if-tab-change\tring the bell if tab-width is changed
2473%v:py-indent-offset
2474%v:py-block-comment-prefix
2475%v:py-python-command
Barry Warsaw7ae77681994-12-12 20:38:05 +00002476%v:py-temp-directory
2477%v:py-beep-if-tab-change
2478
2479@KINDS OF LINES
2480
2481Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002482preceding line ends with a backslash that's not part of a comment, or
2483the paren/bracket/brace nesting level at the start of the line is
2484non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002485
2486An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002487possibly blanks or tabs), a `comment line' (leftmost non-blank
2488character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002489
2490Comment Lines
2491
2492Although all comment lines are treated alike by Python, Python mode
2493recognizes two kinds that act differently with respect to indentation.
2494
2495An `indenting comment line' is a comment line with a blank, tab or
2496nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002497treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002498indenting comment line will be indented like the comment line. All
2499other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002500following the initial `#') are `non-indenting comment lines', and
2501their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002502
2503Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002504whenever possible. Non-indenting comment lines are useful in cases
2505like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002506
2507\ta = b # a very wordy single-line comment that ends up being
2508\t #... continued onto another line
2509
2510\tif a == b:
2511##\t\tprint 'panic!' # old code we've `commented out'
2512\t\treturn a
2513
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002514Since the `#...' and `##' comment lines have a non-whitespace
2515character following the initial `#', Python mode ignores them when
2516computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002517
2518Continuation Lines and Statements
2519
2520The Python-mode commands generally work on statements instead of on
2521individual lines, where a `statement' is a comment or blank line, or a
2522code line and all of its following continuation lines (if any)
2523considered as a single logical unit. The commands in this mode
2524generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002525statement containing point, even if point happens to be in the middle
2526of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002527
2528
2529@INDENTATION
2530
2531Primarily for entering new code:
2532\t\\[indent-for-tab-command]\t indent line appropriately
2533\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002534\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002535
2536Primarily for reindenting existing code:
2537\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2538\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2539
2540\t\\[py-indent-region]\t reindent region to match its context
2541\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2542\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2543
2544Unlike most programming languages, Python uses indentation, and only
2545indentation, to specify block structure. Hence the indentation supplied
2546automatically by Python-mode is just an educated guess: only you know
2547the block structure you intend, so only you can supply correct
2548indentation.
2549
2550The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2551the indentation of preceding statements. E.g., assuming
2552py-indent-offset is 4, after you enter
2553\tif a > 0: \\[py-newline-and-indent]
2554the cursor will be moved to the position of the `_' (_ is not a
2555character in the file, it's just used here to indicate the location of
2556the cursor):
2557\tif a > 0:
2558\t _
2559If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2560to
2561\tif a > 0:
2562\t c = d
2563\t _
2564Python-mode cannot know whether that's what you intended, or whether
2565\tif a > 0:
2566\t c = d
2567\t_
2568was your intent. In general, Python-mode either reproduces the
2569indentation of the (closest code or indenting-comment) preceding
2570statement, or adds an extra py-indent-offset blanks if the preceding
2571statement has `:' as its last significant (non-whitespace and non-
2572comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002573\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002574
2575Continuation lines are given extra indentation. If you don't like the
2576suggested indentation, change it to something you do like, and Python-
2577mode will strive to indent later lines of the statement in the same way.
2578
2579If a line is a continuation line by virtue of being in an unclosed
2580paren/bracket/brace structure (`list', for short), the suggested
2581indentation depends on whether the current line contains the first item
2582in the list. If it does, it's indented py-indent-offset columns beyond
2583the indentation of the line containing the open bracket. If you don't
2584like that, change it by hand. The remaining items in the list will mimic
2585whatever indentation you give to the first item.
2586
2587If a line is a continuation line because the line preceding it ends with
2588a backslash, the third and following lines of the statement inherit their
2589indentation from the line preceding them. The indentation of the second
2590line in the statement depends on the form of the first (base) line: if
2591the base line is an assignment statement with anything more interesting
2592than the backslash following the leftmost assigning `=', the second line
2593is indented two columns beyond that `='. Else it's indented to two
2594columns beyond the leftmost solid chunk of non-whitespace characters on
2595the base line.
2596
2597Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2598repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2599structure you intend.
2600%c:indent-for-tab-command
2601%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002602%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002603
2604
2605The next function may be handy when editing code you didn't write:
2606%c:py-guess-indent-offset
2607
2608
2609The remaining `indent' functions apply to a region of Python code. They
2610assume the block structure (equals indentation, in Python) of the region
2611is correct, and alter the indentation in various ways while preserving
2612the block structure:
2613%c:py-indent-region
2614%c:py-shift-region-left
2615%c:py-shift-region-right
2616
2617@MARKING & MANIPULATING REGIONS OF CODE
2618
2619\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002620\\[py-mark-def-or-class]\t mark smallest enclosing def
2621\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002622\\[comment-region]\t comment out region of code
2623\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002624%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002625%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002626%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002627
2628@MOVING POINT
2629
2630\\[py-previous-statement]\t move to statement preceding point
2631\\[py-next-statement]\t move to statement following point
2632\\[py-goto-block-up]\t move up to start of current block
Barry Warsawab0e86c1998-05-19 15:31:46 +00002633\\[py-beginning-of-def-or-class]\t move to start of def
2634\\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
2635\\[py-end-of-def-or-class]\t move to end of def
2636\\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002637
2638The first two move to one statement beyond the statement that contains
2639point. A numeric prefix argument tells them to move that many
2640statements instead. Blank lines, comment lines, and continuation lines
2641do not count as `statements' for these commands. So, e.g., you can go
2642to the first code statement in a file by entering
2643\t\\[beginning-of-buffer]\t to move to the top of the file
2644\t\\[py-next-statement]\t to skip over initial comments and blank lines
2645Or do `\\[py-previous-statement]' with a huge prefix argument.
2646%c:py-previous-statement
2647%c:py-next-statement
2648%c:py-goto-block-up
Barry Warsawab0e86c1998-05-19 15:31:46 +00002649%c:py-beginning-of-def-or-class
2650%c:py-end-of-def-or-class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002651
2652@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2653
2654`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2655
2656`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2657overall class and def structure of a module.
2658
2659`\\[back-to-indentation]' moves point to a line's first non-blank character.
2660
2661`\\[indent-relative]' is handy for creating odd indentation.
2662
2663@OTHER EMACS HINTS
2664
2665If you don't like the default value of a variable, change its value to
2666whatever you do like by putting a `setq' line in your .emacs file.
2667E.g., to set the indentation increment to 4, put this line in your
2668.emacs:
2669\t(setq py-indent-offset 4)
2670To see the value of a variable, do `\\[describe-variable]' and enter the variable
2671name at the prompt.
2672
2673When entering a key sequence like `C-c C-n', it is not necessary to
2674release the CONTROL key after doing the `C-c' part -- it suffices to
2675press the CONTROL key, press and release `c' (while still holding down
2676CONTROL), press and release `n' (while still holding down CONTROL), &
2677then release CONTROL.
2678
2679Entering Python mode calls with no arguments the value of the variable
2680`python-mode-hook', if that value exists and is not nil; for backward
2681compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2682the Elisp manual for details.
2683
2684Obscure: When python-mode is first loaded, it looks for all bindings
2685to newline-and-indent in the global keymap, and shadows them with
2686local bindings to py-newline-and-indent."))
2687
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002688
2689;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002690(defvar py-parse-state-re
2691 (concat
2692 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2693 "\\|"
2694 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002695
Barry Warsaw7ae77681994-12-12 20:38:05 +00002696(defun py-parse-state ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002697 "Return the parse state at point (see `parse-partial-sexp' docs)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002698 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002699 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002700 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002701 (while (not done)
2702 ;; back up to the first preceding line (if any; else start of
2703 ;; buffer) that begins with a popular Python keyword, or a
2704 ;; non- whitespace and non-comment character. These are good
2705 ;; places to start parsing to see whether where we started is
2706 ;; at a non-zero nesting level. It may be slow for people who
2707 ;; write huge code blocks or huge lists ... tough beans.
2708 (re-search-backward py-parse-state-re nil 'move)
2709 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002710 ;; In XEmacs, we have a much better way to test for whether
2711 ;; we're in a triple-quoted string or not. Emacs does not
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002712 ;; have this built-in function, which is its loss because
Barry Warsawf64b4051998-02-12 16:52:14 +00002713 ;; without scanning from the beginning of the buffer, there's
2714 ;; no accurate way to determine this otherwise.
2715 (if (not (fboundp 'buffer-syntactic-context))
2716 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002717 (progn
2718 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002719 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002720 (setq done (or (not (nth 3 pps))
2721 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002722 ;; XEmacs
2723 (setq done (or (not (buffer-syntactic-context))
2724 (bobp)))
2725 (when done
2726 (setq pps (parse-partial-sexp (point) here)))
2727 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002728 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002729
Barry Warsaw7ae77681994-12-12 20:38:05 +00002730(defun py-nesting-level ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002731 "Return the buffer position of the last unclosed enclosing list.
2732If nesting level is zero, return nil."
Barry Warsawf64b4051998-02-12 16:52:14 +00002733 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002734 (if (zerop (car status))
2735 nil ; not in a nest
2736 (car (cdr status))))) ; char# of open bracket
2737
Barry Warsaw7ae77681994-12-12 20:38:05 +00002738(defun py-backslash-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002739 "Return t iff preceding line ends with backslash that is not in a comment."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002740 (save-excursion
2741 (beginning-of-line)
2742 (and
2743 ;; use a cheap test first to avoid the regexp if possible
2744 ;; use 'eq' because char-after may return nil
2745 (eq (char-after (- (point) 2)) ?\\ )
2746 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002747 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002748 (looking-at py-continued-re))))
2749
Barry Warsaw7ae77681994-12-12 20:38:05 +00002750(defun py-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002751 "Return t iff current line is a continuation line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002752 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002753 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002754 (or (py-backslash-continuation-line-p)
2755 (py-nesting-level))))
2756
Barry Warsaw7ae77681994-12-12 20:38:05 +00002757(defun py-goto-initial-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002758 "Go to the initial line of the current statement.
2759Usually this is the line we're on, but if we're on the 2nd or
2760following lines of a continuation block, we need to go up to the first
2761line of the block."
2762 ;; Tricky: We want to avoid quadratic-time behavior for long
2763 ;; continued blocks, whether of the backslash or open-bracket
2764 ;; varieties, or a mix of the two. The following manages to do that
2765 ;; in the usual cases.
2766 ;;
2767 ;; Also, if we're sitting inside a triple quoted string, this will
2768 ;; drop us at the line that begins the string.
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002769 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002770 (while (py-continuation-line-p)
2771 (beginning-of-line)
2772 (if (py-backslash-continuation-line-p)
2773 (while (py-backslash-continuation-line-p)
2774 (forward-line -1))
2775 ;; else zip out of nested brackets/braces/parens
2776 (while (setq open-bracket-pos (py-nesting-level))
2777 (goto-char open-bracket-pos)))))
2778 (beginning-of-line))
2779
Barry Warsaw7ae77681994-12-12 20:38:05 +00002780(defun py-goto-beyond-final-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002781 "Go to the point just beyond the fine line of the current statement.
2782Usually this is the start of the next line, but if this is a
2783multi-line statement we need to skip over the continuation lines."
2784 ;; Tricky: Again we need to be clever to avoid quadratic time
2785 ;; behavior.
2786 ;;
2787 ;; XXX: Not quite the right solution, but deals with multi-line doc
2788 ;; strings
Barry Warsaw751f4931998-05-19 16:06:21 +00002789 (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
2790 (goto-char (match-end 0)))
2791 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +00002792 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002793 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002794 (while (and (py-continuation-line-p)
2795 (not (eobp)))
2796 ;; skip over the backslash flavor
2797 (while (and (py-backslash-continuation-line-p)
2798 (not (eobp)))
2799 (forward-line 1))
2800 ;; if in nest, zip to the end of the nest
2801 (setq state (py-parse-state))
2802 (if (and (not (zerop (car state)))
2803 (not (eobp)))
2804 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002805 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002806 (forward-line 1))))))
2807
Barry Warsaw7ae77681994-12-12 20:38:05 +00002808(defun py-statement-opens-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002809 "Return t iff the current statement opens a block.
2810I.e., iff it ends with a colon that is not in a comment. Point should
2811be at the start of a statement."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002812 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002813 (let ((start (point))
2814 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2815 (searching t)
2816 (answer nil)
2817 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002818 (goto-char start)
2819 (while searching
2820 ;; look for a colon with nothing after it except whitespace, and
2821 ;; maybe a comment
2822 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2823 finish t)
2824 (if (eq (point) finish) ; note: no `else' clause; just
2825 ; keep searching if we're not at
2826 ; the end yet
2827 ;; sure looks like it opens a block -- but it might
2828 ;; be in a comment
2829 (progn
2830 (setq searching nil) ; search is done either way
2831 (setq state (parse-partial-sexp start
2832 (match-beginning 0)))
2833 (setq answer (not (nth 4 state)))))
2834 ;; search failed: couldn't find another interesting colon
2835 (setq searching nil)))
2836 answer)))
2837
Barry Warsawf831d811996-07-31 20:42:59 +00002838(defun py-statement-closes-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002839 "Return t iff the current statement closes a block.
2840I.e., if the line starts with `return', `raise', `break', `continue',
2841and `pass'. This doesn't catch embedded statements."
Barry Warsawf831d811996-07-31 20:42:59 +00002842 (let ((here (point)))
2843 (back-to-indentation)
2844 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002845 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002846 (goto-char here))))
2847
Barry Warsaw7ae77681994-12-12 20:38:05 +00002848(defun py-goto-beyond-block ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002849 "Go to point just beyond the final line of block begun by the current line.
2850This is the same as where `py-goto-beyond-final-line' goes unless
2851we're on colon line, in which case we go to the end of the block.
2852Assumes point is at the beginning of the line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002853 (if (py-statement-opens-block-p)
2854 (py-mark-block nil 'just-move)
2855 (py-goto-beyond-final-line)))
2856
Barry Warsaw7ae77681994-12-12 20:38:05 +00002857(defun py-goto-statement-at-or-above ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002858 "Go to the start of the first statement at or preceding point.
2859Return t if there is such a statement, otherwise nil. `Statement'
2860does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002861 (py-goto-initial-line)
2862 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002863 ;; skip back over blank & comment lines
2864 ;; note: will skip a blank or comment line that happens to be
2865 ;; a continuation line too
2866 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2867 (progn (py-goto-initial-line) t)
2868 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002869 t))
2870
Barry Warsaw7ae77681994-12-12 20:38:05 +00002871(defun py-goto-statement-below ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002872 "Go to start of the first statement following the statement containing point.
2873Return t if there is such a statement, otherwise nil. `Statement'
2874does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002875 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002876 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002877 (py-goto-beyond-final-line)
2878 (while (and
2879 (looking-at py-blank-or-comment-re)
2880 (not (eobp)))
2881 (forward-line 1))
2882 (if (eobp)
2883 (progn (goto-char start) nil)
2884 t)))
2885
Barry Warsaw7ae77681994-12-12 20:38:05 +00002886(defun py-go-up-tree-to-keyword (key)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002887 "Go to begining of statement starting with KEY, at or preceding point.
2888
2889KEY is a regular expression describing a Python keyword. Skip blank
2890lines and non-indenting comments. If the statement found starts with
2891KEY, then stop, otherwise go back to first enclosing block starting
2892with KEY. If successful, leave point at the start of the KEY line and
2893return t. Otherwise, leav point at an undefined place and return nil."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002894 ;; skip blanks and non-indenting #
2895 (py-goto-initial-line)
2896 (while (and
2897 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2898 (zerop (forward-line -1))) ; go back
2899 nil)
2900 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002901 (let* ((re (concat "[ \t]*" key "\\b"))
2902 (case-fold-search nil) ; let* so looking-at sees this
2903 (found (looking-at re))
2904 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002905 (while (not (or found dead))
2906 (condition-case nil ; in case no enclosing block
2907 (py-goto-block-up 'no-mark)
2908 (error (setq dead t)))
2909 (or dead (setq found (looking-at re))))
2910 (beginning-of-line)
2911 found))
2912
Barry Warsaw7ae77681994-12-12 20:38:05 +00002913(defun py-suck-up-leading-text ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002914 "Return string in buffer from start of indentation to end of line.
2915Prefix with \"...\" if leading whitespace was skipped."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002916 (save-excursion
2917 (back-to-indentation)
2918 (concat
2919 (if (bolp) "" "...")
2920 (buffer-substring (point) (progn (end-of-line) (point))))))
2921
Barry Warsaw7ae77681994-12-12 20:38:05 +00002922(defun py-suck-up-first-keyword ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002923 "Return first keyword on the line as a Lisp symbol.
2924`Keyword' is defined (essentially) as the regular expression
2925([a-z]+). Returns nil if none was found."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002926 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002927 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2928 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2929 nil)))
2930
Barry Warsawb3e81d51996-09-04 15:12:42 +00002931(defun py-current-defun ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002932 "Python value for `add-log-current-defun-function'.
2933This tells add-log.el how to find the current function/method/variable."
Barry Warsawb3e81d51996-09-04 15:12:42 +00002934 (save-excursion
2935 (if (re-search-backward py-defun-start-re nil t)
2936 (or (match-string 3)
2937 (let ((method (match-string 2)))
2938 (if (and (not (zerop (length (match-string 1))))
2939 (re-search-backward py-class-start-re nil t))
2940 (concat (match-string 1) "." method)
2941 method)))
2942 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002943
2944
Barry Warsawfec75d61995-07-05 23:26:15 +00002945(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002946 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002947
Barry Warsaw850437a1995-03-08 21:50:28 +00002948(defun py-version ()
2949 "Echo the current version of `python-mode' in the minibuffer."
2950 (interactive)
2951 (message "Using `python-mode' version %s" py-version)
2952 (py-keep-region-active))
2953
2954;; only works under Emacs 19
2955;(eval-when-compile
2956; (require 'reporter))
2957
2958(defun py-submit-bug-report (enhancement-p)
2959 "Submit via mail a bug report on `python-mode'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00002960With \\[universal-argument] (programmatically, argument ENHANCEMENT-P
2961non-nil) just submit an enhancement request."
Barry Warsaw850437a1995-03-08 21:50:28 +00002962 (interactive
2963 (list (not (y-or-n-p
Barry Warsaw41a05c71998-08-10 16:33:12 +00002964 "Is this a bug report (hit `n' to send other comments)? "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002965 (let ((reporter-prompt-for-summary-p (if enhancement-p
2966 "(Very) brief summary: "
2967 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002968 (require 'reporter)
2969 (reporter-submit-bug-report
2970 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002971 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002972 ;; varlist
2973 (if enhancement-p nil
2974 '(py-python-command
2975 py-indent-offset
2976 py-block-comment-prefix
Barry Warsaw850437a1995-03-08 21:50:28 +00002977 py-temp-directory
2978 py-beep-if-tab-change))
2979 nil ;pre-hooks
2980 nil ;post-hooks
2981 "Dear Barry,") ;salutation
2982 (if enhancement-p nil
2983 (set-mark (point))
2984 (insert
2985"Please replace this text with a sufficiently large code sample\n\
2986and an exact recipe so that I can reproduce your problem. Failure\n\
2987to do so may mean a greater delay in fixing your bug.\n\n")
2988 (exchange-point-and-mark)
2989 (py-keep-region-active))))
2990
2991
Barry Warsaw47384781997-11-26 05:27:45 +00002992(defun py-kill-emacs-hook ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002993 "Delete files in `py-file-queue'.
2994These are Python temporary files awaiting execution."
Barry Warsaw47384781997-11-26 05:27:45 +00002995 (mapcar #'(lambda (filename)
2996 (py-safe (delete-file filename)))
2997 py-file-queue))
2998
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002999;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00003000(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003001
3002
3003
3004(provide 'python-mode)
3005;;; python-mode.el ends here