blob: cbaaec051418e9eff8b2c6fb595e05f6258f2947 [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
24;; subsequently left the net; in 1995, Barry Warsaw inherited the
25;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000026
Barry Warsaw37231521997-12-11 17:23:13 +000027;; COMPATIBILITY:
Barry Warsaw7b0f5681995-03-08 21:33:04 +000028
Barry Warsaw37231521997-12-11 17:23:13 +000029;; This version of python-mode.el is no longer compatible with Emacs
30;; 18. For a gabazillion reasons, I highly recommend upgrading to
31;; X/Emacs 19 or X/Emacs 20. I recommend at least Emacs 19.34 or
32;; XEmacs 19.15. Any of the v20 X/Emacsen should be fine.
Barry Warsaw673d05f1997-12-02 21:51:57 +000033
Barry Warsaw37231521997-12-11 17:23:13 +000034;; NOTE TO FSF EMACS USERS:
35
36;; You may need to acquire the Custom library -- this applies to users
37;; of Emacs 19.34 and NTEmacs based on 19.34, but not to Emacs 20
38;; users. You must also byte-compile this file before use -- this
39;; applies to FSF's Emacs 19.34, 20.x, and NTEmacs based on 19.34.
40;; None of this applies to XEmacs (although byte compilation is still
41;; recommended). You will also need to add the following to your
42;; .emacs file so that the .py files come up in python-mode:
Barry Warsaw7ae77681994-12-12 20:38:05 +000043;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000044;; (autoload 'python-mode "python-mode" "Python editing mode." t)
45;; (setq auto-mode-alist
46;; (cons '("\\.py$" . python-mode) auto-mode-alist))
47;; (setq interpreter-mode-alist
48;; (cons '("python" . python-mode) interpreter-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000049;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000050;; Assuming python-mode.el is on your load-path, it will be invoked
51;; when you visit a .py file, or a file with a first line that looks
52;; like:
53;;
54;; #! /usr/bin/env python
55
Barry Warsaw37231521997-12-11 17:23:13 +000056;; NOTE TO XEMACS USERS:
57
58;; An older version of this file was distributed with XEmacs 19.15,
59;; 19.16 and 20.3. By default, in XEmacs when you visit a .py file,
60;; the buffer is put in Python mode. Likewise for executable scripts
61;; with the word `python' on the first line. You shouldn't need to do
62;; much except make sure this new version is earlier in your
63;; load-path, and byte-compile this file.
64
65;; FOR MORE INFORMATION:
66
Barry Warsaw145ab1c1998-05-19 14:49:49 +000067;; Please see <http://www.python.org/emacs/python-mode/> for the
Barry Warsaw37231521997-12-11 17:23:13 +000068;; latest information and compatibility notes.
69
70;; BUG REPORTING:
Barry Warsaw7ae77681994-12-12 20:38:05 +000071
Barry Warsawaffc0ca1997-11-03 16:59:38 +000072;; To submit bug reports, use C-c C-b. Please include a complete, but
73;; concise code sample and a recipe for reproducing the bug. Send
74;; suggestions and other comments to python-mode@python.org.
75
76;; When in a Python mode buffer, do a C-h m for more help. It's
Barry Warsaw37231521997-12-11 17:23:13 +000077;; doubtful that a texinfo manual would be very useful, but if you
78;; want to contribute one, I'll certainly accept it!
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000079
Barry Warsaw5ea20d51997-12-06 00:00:47 +000080;; If you are using XEmacs, you may also want to check out OO-Browser
81;; that comes bundled with it, including documentation in the info
82;; pages. For GNU Emacs you have to install it yourself. To read
83;; more about OO-Browser, follow these links:
84
85;; http://www.python.org/workshops/1996-06/papers/h.pasanen/oobr_contents.html
86;; http://www.infodock.com/manuals/alt-oobr-cover.html
87
Barry Warsaw37231521997-12-11 17:23:13 +000088;; You may also want to take a look at Harri Pasanen's "Python Library
89;; Reference Hot-Key Help System for XEmacs (or PLRHKHSX for short ;),
90;; version 1.0"
Barry Warsaw7b0f5681995-03-08 21:33:04 +000091;;
Barry Warsaw37231521997-12-11 17:23:13 +000092;; <http://www.iki.fi/hpa/>
93
94;; TO DO LIST:
95
96;; - Better integration with pdb.py and gud-mode for debugging.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000097;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000098;; - possibly force indent-tabs-mode == nil, and add a
99;; write-file-hooks that runs untabify on the whole buffer (to work
100;; around potential tab/space mismatch problems). In practice this
101;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +0000102;; - have py-execute-region on indented code act as if the region is
Barry Warsaw37231521997-12-11 17:23:13 +0000103;; left justified. Avoids syntax errors.
104;; - add a py-goto-block-down, bound to C-c C-d
Barry Warsaw7ae77681994-12-12 20:38:05 +0000105
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000106;;; Code:
107
Barry Warsawc72c11c1997-08-09 06:42:08 +0000108(require 'custom)
Barry Warsaw8529ebb1997-12-01 20:03:12 +0000109(eval-when-compile
Barry Warsaw673d05f1997-12-02 21:51:57 +0000110 (require 'cl)
Barry Warsawb6c1f1f1998-03-19 22:33:06 +0000111 (if (not (and (condition-case nil
112 (require 'custom)
113 (error nil))
114 ;; Stock Emacs 19.34 has a broken/old Custom library
115 ;; that does more harm than good. Fortunately, it is
116 ;; missing defcustom
117 (fboundp 'defcustom)))
Barry Warsaw673d05f1997-12-02 21:51:57 +0000118 (error "STOP! STOP! STOP! STOP!
119
120The Custom library was not found or is out of date. A more current
121version is required. Please download and install the latest version
122of the Custom library from:
123
124 <http://www.dina.kvl.dk/~abraham/custom/>
125
126See the Python Mode home page for details:
127
128 <http://www.python.org/ftp/emacs/>
129")))
130
Barry Warsawc72c11c1997-08-09 06:42:08 +0000131
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000132
133;; user definable variables
134;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000135
Barry Warsawc72c11c1997-08-09 06:42:08 +0000136(defgroup python nil
137 "Support for the Python programming language, <http://www.python.org/>"
138 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000139
Barry Warsawc72c11c1997-08-09 06:42:08 +0000140(defcustom py-python-command "python"
141 "*Shell command used to start Python interpreter."
142 :type 'string
143 :group 'python)
144
Barry Warsawa2398801998-04-09 23:28:20 +0000145(defcustom py-jpython-command "jpython"
146 "*Shell command used to start the JPython interpreter."
147 :type 'string
148 :group 'python)
149
Barry Warsaw8f972b71998-02-05 20:45:49 +0000150(defcustom py-python-command-args '("-i")
151 "*List of string arguments to be used when starting a Python shell."
152 :type '(repeat string)
153 :group 'python)
154
Barry Warsawa2398801998-04-09 23:28:20 +0000155(defcustom py-jpython-command-args '("-i")
156 "*List of string arguments to be used when starting a JPython shell."
157 :type '(repeat string)
158 :group 'python)
159
Barry Warsawc72c11c1997-08-09 06:42:08 +0000160(defcustom py-indent-offset 4
Barry Warsaw41a05c71998-08-10 16:33:12 +0000161 "*Amount of offset per level of indentation.
162`\\[py-guess-indent-offset]' can usually guess a good value when
163you're editing someone else's Python code."
Barry Warsawc72c11c1997-08-09 06:42:08 +0000164 :type 'integer
165 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000166
Barry Warsaw742a5111998-03-13 17:29:15 +0000167(defcustom py-smart-indentation t
168 "*Should `python-mode' try to automagically set some indentation variables?
169When this variable is non-nil, two things happen when a buffer is set
170to `python-mode':
171
172 1. `py-indent-offset' is guess from existing code in the buffer.
Barry Warsaw639eea61998-03-16 18:12:13 +0000173 Only guessed values between 2 and 8 are considered. If a valid
Barry Warsaw742a5111998-03-13 17:29:15 +0000174 guess can't be made (perhaps because you are visiting a new
Barry Warsaw639eea61998-03-16 18:12:13 +0000175 file), then the value in `py-indent-offset' is used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000176
Barry Warsaw639eea61998-03-16 18:12:13 +0000177 2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
178 equal `tab-width' (`indent-tabs-mode' is never turned on by
179 Python mode). This means that for newly written code, tabs are
180 only inserted in indentation if one tab is one indentation
181 level, otherwise only spaces are used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000182
Barry Warsaw8046bef1998-03-13 20:04:52 +0000183Note that both these settings occur *after* `python-mode-hook' is run,
184so if you want to defeat the automagic configuration, you must also
185set `py-smart-indentation' to nil in your `python-mode-hook'."
Barry Warsaw742a5111998-03-13 17:29:15 +0000186 :type 'boolean
187 :group 'python)
188
Barry Warsawc72c11c1997-08-09 06:42:08 +0000189(defcustom py-align-multiline-strings-p t
190 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000191When this flag is non-nil, continuation lines are lined up under the
192preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000193lines are aligned to column zero."
194 :type '(choice (const :tag "Align under preceding line" t)
195 (const :tag "Align to column zero" nil))
196 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000197
Barry Warsawc72c11c1997-08-09 06:42:08 +0000198(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000199 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000200This should follow the convention for non-indenting comment lines so
201that the indentation commands won't get confused (i.e., the string
202should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000203`...' is arbitrary)."
204 :type 'string
205 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000206
Barry Warsawc72c11c1997-08-09 06:42:08 +0000207(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000208 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000209
Barry Warsaw6d627751996-03-06 18:41:38 +0000210When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000211if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000212
213When t, lines that begin with a single `#' are a hint to subsequent
214line indentation. If the previous line is such a comment line (as
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000215opposed to one that starts with `py-block-comment-prefix'), then its
Barry Warsaw6d627751996-03-06 18:41:38 +0000216indentation is used as a hint for this line's indentation. Lines that
217begin with `py-block-comment-prefix' are ignored for indentation
218purposes.
219
220When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000221indentation hints, unless the comment character is in column zero."
222 :type '(choice
223 (const :tag "Skip all comment lines (fast)" nil)
224 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000225 (const :tag "Single # `sets' indentation except at column zero"
226 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000227 )
228 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000229
Barry Warsaw516b6201997-08-09 06:43:20 +0000230(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000231 (let ((ok '(lambda (x)
232 (and x
233 (setq x (expand-file-name x)) ; always true
234 (file-directory-p x)
235 (file-writable-p x)
236 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000237 (or (funcall ok (getenv "TMPDIR"))
238 (funcall ok "/usr/tmp")
239 (funcall ok "/tmp")
240 (funcall ok ".")
241 (error
Barry Warsaw6c6db0a1998-02-25 16:33:56 +0000242 "Couldn't find a usable temp directory -- set `py-temp-directory'")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000243 "*Directory used for temp files created by a *Python* process.
244By default, the first directory from this list that exists and that you
245can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000246/usr/tmp, /tmp, or the current directory."
247 :type 'string
248 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000249
Barry Warsaw516b6201997-08-09 06:43:20 +0000250(defcustom py-beep-if-tab-change t
Barry Warsaw41a05c71998-08-10 16:33:12 +0000251 "*Ring the bell if `tab-width' is changed.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000252If a comment of the form
253
254 \t# vi:set tabsize=<number>:
255
256is found before the first code line when the file is entered, and the
257current value of (the general Emacs variable) `tab-width' does not
258equal <number>, `tab-width' is set to <number>, a message saying so is
259displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000260the Emacs bell is also rung as a warning."
261 :type 'boolean
262 :group 'python)
263
Barry Warsaw9981d221997-12-03 05:25:48 +0000264(defcustom py-jump-on-exception t
265 "*Jump to innermost exception frame in *Python Output* buffer.
Barry Warsaw12c92941998-08-10 21:44:37 +0000266When this variable is non-nil and an exception occurs when running
Barry Warsaw9981d221997-12-03 05:25:48 +0000267Python code synchronously in a subprocess, jump immediately to the
Barry Warsaw12c92941998-08-10 21:44:37 +0000268source code of the innermost traceback frame."
Barry Warsaw3bfed5b1998-05-19 16:25:04 +0000269 :type 'boolean
270 :group 'python)
271
272(defcustom py-ask-about-save t
273 "If not nil, ask about which buffers to save before executing some code.
274Otherwise, all modified buffers are saved without asking."
275 :type 'boolean
276 :group 'python)
Barry Warsaw9981d221997-12-03 05:25:48 +0000277
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000278(defcustom py-backspace-function 'backward-delete-char-untabify
279 "*Function called by `py-electric-backspace' when deleting backwards."
280 :type 'function
281 :group 'python)
282
283(defcustom py-delete-function 'delete-char
284 "*Function called by `py-electric-delete' when deleting forwards."
285 :type 'function
286 :group 'python)
287
Barry Warsawc0ecb531998-01-20 21:43:34 +0000288;; Not customizable
289(defvar py-master-file nil
290 "If non-nil, execute the named file instead of the buffer's file.
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000291The intent is to allow you to set this variable in the file's local
Barry Warsawc0ecb531998-01-20 21:43:34 +0000292variable section, e.g.:
293
294 # Local Variables:
295 # py-master-file: \"master.py\"
296 # End:
297
Barry Warsaw41a05c71998-08-10 16:33:12 +0000298so that typing \\[py-execute-buffer] in that buffer executes the named
299master file instead of the buffer's file. Note that if the file name
300has a relative path, the value of `default-directory' for the buffer
301is prepended to come up with a file name.")
Barry Warsawc0ecb531998-01-20 21:43:34 +0000302(make-variable-buffer-local 'py-master-file)
303
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000304
Barry Warsawc72c11c1997-08-09 06:42:08 +0000305
306;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
307;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
308
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000309(defconst py-emacs-features
310 (let (features)
311 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
312 ;; the same string.
313 (let ((tmp1 (make-temp-name ""))
314 (tmp2 (make-temp-name "")))
315 (if (string-equal tmp1 tmp2)
316 (push 'broken-temp-names features)))
317 ;; return the features
318 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000319 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000320There are many flavors of Emacs out there, with different levels of
321support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000322
Barry Warsawfb07f401997-02-24 03:37:22 +0000323(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000324 (let ((kw1 (mapconcat 'identity
325 '("and" "assert" "break" "class"
326 "continue" "def" "del" "elif"
327 "else" "except" "exec" "for"
328 "from" "global" "if" "import"
329 "in" "is" "lambda" "not"
330 "or" "pass" "print" "raise"
331 "return" "while"
332 )
333 "\\|"))
334 (kw2 (mapconcat 'identity
335 '("else:" "except:" "finally:" "try:")
336 "\\|"))
337 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000338 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000339 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000340 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
341 ;; block introducing keywords with immediately following colons.
342 ;; Yes "except" is in both lists.
343 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000344 ;; classes
345 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
346 1 font-lock-type-face)
347 ;; functions
348 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
349 1 font-lock-function-name-face)
350 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000351 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000352(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
353
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000354
Barry Warsaw81437461996-08-01 19:48:02 +0000355(defvar imenu-example--python-show-method-args-p nil
356 "*Controls echoing of arguments of functions & methods in the imenu buffer.
357When non-nil, arguments are printed.")
358
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000359(make-variable-buffer-local 'py-indent-offset)
360
Barry Warsawe467bfb1997-11-26 05:40:58 +0000361;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000362(defvar py-file-queue nil
363 "Queue of Python temp files awaiting execution.
364Currently-active file is at the head of the list.")
365
Barry Warsawc72c11c1997-08-09 06:42:08 +0000366
367;; Constants
368
Barry Warsawc72c11c1997-08-09 06:42:08 +0000369(defconst py-stringlit-re
370 (concat
Barry Warsaw751f4931998-05-19 16:06:21 +0000371 ;; These fail if backslash-quote ends the string (not worth
372 ;; fixing?). They precede the short versions so that the first two
373 ;; quotes don't look like an empty short string.
374 ;;
375 ;; (maybe raw), long single quoted triple quoted strings (SQTQ),
376 ;; with potential embedded single quotes
377 "[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
378 "\\|"
379 ;; (maybe raw), long double quoted triple quoted strings (DQTQ),
380 ;; with potential embedded double quotes
381 "[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
382 "\\|"
383 "[rR]?'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
Barry Warsawc72c11c1997-08-09 06:42:08 +0000384 "\\|" ; or
Barry Warsaw751f4931998-05-19 16:06:21 +0000385 "[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\"" ; double-quoted
Barry Warsaw41a05c71998-08-10 16:33:12 +0000386 )
387 "Regular expression matching a Python string literal.")
Barry Warsaw751f4931998-05-19 16:06:21 +0000388
Barry Warsawc72c11c1997-08-09 06:42:08 +0000389(defconst py-continued-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000390 ;; This is tricky because a trailing backslash does not mean
391 ;; continuation if it's in a comment
Barry Warsawc72c11c1997-08-09 06:42:08 +0000392 (concat
393 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
Barry Warsaw41a05c71998-08-10 16:33:12 +0000394 "\\\\$")
395 "Regular expression matching Python backslash continuation lines.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000396
Barry Warsaw41a05c71998-08-10 16:33:12 +0000397(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw71c3adb1998-08-10 16:34:33 +0000398 "Regular expression matching a blank or comment line.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000399
Barry Warsawc72c11c1997-08-09 06:42:08 +0000400(defconst py-outdent-re
401 (concat "\\(" (mapconcat 'identity
402 '("else:"
403 "except\\(\\s +.*\\)?:"
404 "finally:"
405 "elif\\s +.*:")
406 "\\|")
Barry Warsaw41a05c71998-08-10 16:33:12 +0000407 "\\)")
408 "Regular expression matching statements to be dedented one level.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000409
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000410(defconst py-block-closing-keywords-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000411 "\\(return\\|raise\\|break\\|continue\\|pass\\)"
412 "Regular expression matching keywords which typically close a block.")
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000413
Barry Warsawc72c11c1997-08-09 06:42:08 +0000414(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000415 (concat
416 "\\("
417 (mapconcat 'identity
418 (list "try:"
419 "except\\(\\s +.*\\)?:"
420 "while\\s +.*:"
421 "for\\s +.*:"
422 "if\\s +.*:"
423 "elif\\s +.*:"
424 (concat py-block-closing-keywords-re "[ \t\n]")
425 )
426 "\\|")
Barry Warsaw41a05c71998-08-10 16:33:12 +0000427 "\\)")
428 "Regular expression matching lines not to dedent after.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000429
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000430(defconst py-defun-start-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000431 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*="
432 ;; If you change this, you probably have to change py-current-defun
433 ;; as well. This is only used by py-current-defun to find the name
434 ;; for add-log.el.
Barry Warsaw71c3adb1998-08-10 16:34:33 +0000435 "Regular expression matching a function, method, or variable assignment.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000436
Barry Warsaw41a05c71998-08-10 16:33:12 +0000437(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)"
438 ;; If you change this, you probably have to change py-current-defun
439 ;; as well. This is only used by py-current-defun to find the name
440 ;; for add-log.el.
441 "Regular expression for finding a class name.")
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000442
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000443(defconst py-traceback-line-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000444 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)"
445 "Regular expression that describes tracebacks.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000446
447
448
449;; Utilities
450
451(defmacro py-safe (&rest body)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000452 "Safely execute BODY, return nil if an error occurred."
Barry Warsawc72c11c1997-08-09 06:42:08 +0000453 (` (condition-case nil
454 (progn (,@ body))
455 (error nil))))
456
457(defsubst py-keep-region-active ()
Barry Warsaw41a05c71998-08-10 16:33:12 +0000458 "Keep the region active in XEmacs."
Barry Warsawc72c11c1997-08-09 06:42:08 +0000459 ;; Ignore byte-compiler warnings you might see. Also note that
460 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
461 ;; to take explicit action.
462 (and (boundp 'zmacs-region-stays)
463 (setq zmacs-region-stays t)))
464
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000465(defsubst py-point (position)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000466 "Returns the value of point at certain commonly referenced POSITIONs.
467POSITION can be one of the following symbols:
468
469 bol -- beginning of line
470 eol -- end of line
471 bod -- beginning of def or class
472 eod -- end of def or class
473 bob -- beginning of buffer
474 eob -- end of buffer
475 boi -- back to indentation
476 bos -- beginning of statement
477
478This function does not modify point or mark."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000479 (let ((here (point)))
480 (cond
481 ((eq position 'bol) (beginning-of-line))
482 ((eq position 'eol) (end-of-line))
Barry Warsawab0e86c1998-05-19 15:31:46 +0000483 ((eq position 'bod) (py-beginning-of-def-or-class))
Barry Warsaw41a05c71998-08-10 16:33:12 +0000484 ((eq position 'eod) (py-end-of-def-or-class))
Barry Warsawab0e86c1998-05-19 15:31:46 +0000485 ;; Kind of funny, I know, but useful for py-up-exception.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000486 ((eq position 'bob) (beginning-of-buffer))
487 ((eq position 'eob) (end-of-buffer))
488 ((eq position 'boi) (back-to-indentation))
Barry Warsawab0e86c1998-05-19 15:31:46 +0000489 ((eq position 'bos) (py-goto-initial-line))
Barry Warsaw41a05c71998-08-10 16:33:12 +0000490 (t (error "Unknown buffer position requested: %s" position))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000491 )
492 (prog1
493 (point)
494 (goto-char here))))
495
496(defsubst py-highlight-line (from to file line)
497 (cond
498 ((fboundp 'make-extent)
499 ;; XEmacs
500 (let ((e (make-extent from to)))
501 (set-extent-property e 'mouse-face 'highlight)
502 (set-extent-property e 'py-exc-info (cons file line))
503 (set-extent-property e 'keymap py-mode-output-map)))
504 (t
505 ;; Emacs -- Please port this!
506 )
507 ))
508
Barry Warsawe908b6b1998-03-19 22:48:02 +0000509(defun py-in-literal (&optional lim)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000510 "Return non-nil if point is in a Python literal (a comment or string).
511Optional argument LIM indicates the beginning of the containing form,
512i.e. the limit on how far back to scan."
513 ;; This is the version used for non-XEmacs, which has a nicer
514 ;; interface.
Barry Warsawe908b6b1998-03-19 22:48:02 +0000515 ;;
516 ;; WARNING: Watch out for infinite recursion.
517 (let* ((lim (or lim (c-point 'bod)))
518 (state (parse-partial-sexp lim (point))))
519 (cond
520 ((nth 3 state) 'string)
521 ((nth 4 state) 'comment)
522 (t nil))))
523
524;; XEmacs has a built-in function that should make this much quicker.
525;; In this case, lim is ignored
526(defun py-fast-in-literal (&optional lim)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000527 "Fast version of `py-in-literal', used only by XEmacs.
528Optional LIM is ignored."
Barry Warsawe908b6b1998-03-19 22:48:02 +0000529 ;; don't have to worry about context == 'block-comment
530 (buffer-syntactic-context))
531
532(if (fboundp 'buffer-syntactic-context)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000533 (defalias 'py-in-literal 'py-fast-in-literal))
Barry Warsawe908b6b1998-03-19 22:48:02 +0000534
535
Barry Warsawc72c11c1997-08-09 06:42:08 +0000536
537;; Major mode boilerplate
538
Barry Warsaw7ae77681994-12-12 20:38:05 +0000539;; define a mode-specific abbrev table for those who use such things
540(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000541 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000542(define-abbrev-table 'python-mode-abbrev-table nil)
543
Barry Warsaw7ae77681994-12-12 20:38:05 +0000544(defvar python-mode-hook nil
545 "*Hook called by `python-mode'.")
546
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000547;; In previous version of python-mode.el, the hook was incorrectly
548;; called py-mode-hook, and was not defvar'd. Deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000549(and (fboundp 'make-obsolete-variable)
550 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
551
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000552(defvar py-mode-map ()
553 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000554(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000555 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000556 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000557 ;; electric keys
558 (define-key py-mode-map ":" 'py-electric-colon)
559 ;; indentation level modifiers
560 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
561 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
562 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
563 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
564 ;; subprocess commands
565 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
Barry Warsaw820273d1998-05-19 15:54:45 +0000566 (define-key py-mode-map "\C-c\C-m" 'py-execute-import-or-reload)
Barry Warsaw1d0364b1998-05-19 16:15:26 +0000567 (define-key py-mode-map "\C-c\C-s" 'py-execute-string)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000568 (define-key py-mode-map "\C-c|" 'py-execute-region)
Barry Warsaw820273d1998-05-19 15:54:45 +0000569 (define-key py-mode-map "\e\C-x" 'py-execute-def-or-class)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000570 (define-key py-mode-map "\C-c!" 'py-shell)
Barry Warsawa2398801998-04-09 23:28:20 +0000571 (define-key py-mode-map "\C-c\C-t" 'py-toggle-shells)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000572 ;; Caution! Enter here at your own risk. We are trying to support
573 ;; several behaviors and it gets disgusting. :-( This logic ripped
574 ;; largely from CC Mode.
575 ;;
576 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
577 ;; backwards deletion behavior to DEL, which both Delete and
578 ;; Backspace get translated to. There's no way to separate this
579 ;; behavior in a clean way, so deal with it! Besides, it's been
580 ;; this way since the dawn of time.
581 (if (not (boundp 'delete-key-deletes-forward))
582 (define-key py-mode-map "\177" 'py-electric-backspace)
583 ;; However, XEmacs 20 actually achieved enlightenment. It is
584 ;; possible to sanely define both backward and forward deletion
585 ;; behavior under X separately (TTYs are forever beyond hope, but
586 ;; who cares? XEmacs 20 does the right thing with these too).
587 (define-key py-mode-map [delete] 'py-electric-delete)
588 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000589 ;; Separate M-BS from C-M-h. The former should remain
590 ;; backward-kill-word.
591 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000592 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000593 ;; Miscellaneous
594 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
595 (define-key py-mode-map "\C-c\t" 'py-indent-region)
596 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
597 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
598 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000599 (define-key py-mode-map "\C-c#" 'py-comment-region)
600 (define-key py-mode-map "\C-c?" 'py-describe-mode)
601 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
Barry Warsawab0e86c1998-05-19 15:31:46 +0000602 (define-key py-mode-map "\e\C-a" 'py-beginning-of-def-or-class)
603 (define-key py-mode-map "\e\C-e" 'py-end-of-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000604 (define-key py-mode-map "\C-c-" 'py-up-exception)
605 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000606 ;; information
607 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
608 (define-key py-mode-map "\C-c\C-v" 'py-version)
609 ;; py-newline-and-indent mappings
Barry Warsaw82aecb91998-01-21 05:14:24 +0000610 (define-key py-mode-map "\n" 'py-newline-and-indent)
611 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000612 ;; shadow global bindings for newline-and-indent w/ the py- version.
613 ;; BAW - this is extremely bad form, but I'm not going to change it
614 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000615 (mapcar #'(lambda (key)
616 (define-key py-mode-map key 'py-newline-and-indent))
617 (where-is-internal 'newline-and-indent))
618 )
619
620(defvar py-mode-output-map nil
Barry Warsaw41a05c71998-08-10 16:33:12 +0000621 "Keymap used in *Python Output* buffers.")
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000622(if py-mode-output-map
623 nil
624 (setq py-mode-output-map (make-sparse-keymap))
625 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
626 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
627 ;; TBD: Disable all self-inserting keys. This is bogus, we should
628 ;; really implement this as *Python Output* buffer being read-only
629 (mapcar #' (lambda (key)
630 (define-key py-mode-output-map key
631 #'(lambda () (interactive) (beep))))
632 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000633 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000634
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000635(defvar py-mode-syntax-table nil
636 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000637(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000638 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000639 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000640 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
641 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
642 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
643 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
644 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
645 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
646 ;; Add operator symbols misassigned in the std table
647 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
648 (modify-syntax-entry ?\% "." py-mode-syntax-table)
649 (modify-syntax-entry ?\& "." py-mode-syntax-table)
650 (modify-syntax-entry ?\* "." py-mode-syntax-table)
651 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
652 (modify-syntax-entry ?\- "." py-mode-syntax-table)
653 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
654 (modify-syntax-entry ?\< "." py-mode-syntax-table)
655 (modify-syntax-entry ?\= "." py-mode-syntax-table)
656 (modify-syntax-entry ?\> "." py-mode-syntax-table)
657 (modify-syntax-entry ?\| "." py-mode-syntax-table)
658 ;; For historical reasons, underscore is word class instead of
659 ;; symbol class. GNU conventions say it should be symbol class, but
660 ;; there's a natural conflict between what major mode authors want
661 ;; and what users expect from `forward-word' and `backward-word'.
662 ;; Guido and I have hashed this out and have decided to keep
663 ;; underscore in word class. If you're tempted to change it, try
664 ;; binding M-f and M-b to py-forward-into-nomenclature and
665 ;; py-backward-into-nomenclature instead.
666 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
667 ;; Both single quote and double quote are string delimiters
668 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
669 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
670 ;; backquote is open and close paren
671 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
672 ;; comment delimiters
673 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
674 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
675 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000676
Barry Warsawb3e81d51996-09-04 15:12:42 +0000677
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000678
Barry Warsaw42f707f1996-07-29 21:05:05 +0000679;; Menu definitions, only relevent if you have the easymenu.el package
680;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000681(defvar py-menu nil
682 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000683This menu will get created automatically if you have the `easymenu'
684package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000685
Barry Warsawc72c11c1997-08-09 06:42:08 +0000686(and (py-safe (require 'easymenu) t)
687 (easy-menu-define
688 py-menu py-mode-map "Python Mode menu"
689 '("Python"
690 ["Comment Out Region" py-comment-region (mark)]
691 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
692 "-"
693 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000694 ["Mark current def" py-mark-def-or-class t]
695 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000696 "-"
697 ["Shift region left" py-shift-region-left (mark)]
698 ["Shift region right" py-shift-region-right (mark)]
699 "-"
Barry Warsaw820273d1998-05-19 15:54:45 +0000700 ["Import/reload file" py-execute-import-or-reload t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000701 ["Execute buffer" py-execute-buffer t]
702 ["Execute region" py-execute-region (mark)]
Barry Warsaw820273d1998-05-19 15:54:45 +0000703 ["Execute def or class" py-execute-def-or-class (mark)]
Barry Warsaw1d0364b1998-05-19 16:15:26 +0000704 ["Execute string" py-execute-string t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000705 ["Start interpreter..." py-shell t]
706 "-"
707 ["Go to start of block" py-goto-block-up t]
Barry Warsawab0e86c1998-05-19 15:31:46 +0000708 ["Go to start of class" (py-beginning-of-def-or-class t) t]
709 ["Move to end of class" (py-end-of-def-or-class t) t]
710 ["Move to start of def" py-beginning-of-def-or-class t]
711 ["Move to end of def" py-end-of-def-or-class t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000712 "-"
713 ["Describe mode" py-describe-mode t]
714 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000715
Barry Warsaw81437461996-08-01 19:48:02 +0000716
717
718;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
719(defvar imenu-example--python-class-regexp
720 (concat ; <<classes>>
721 "\\(" ;
722 "^[ \t]*" ; newline and maybe whitespace
723 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
724 ; possibly multiple superclasses
Barry Warsaw3179fe01998-04-04 21:36:53 +0000725 "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
Barry Warsaw81437461996-08-01 19:48:02 +0000726 "[ \t]*:" ; and the final :
727 "\\)" ; >>classes<<
728 )
729 "Regexp for Python classes for use with the imenu package."
730 )
731
732(defvar imenu-example--python-method-regexp
733 (concat ; <<methods and functions>>
734 "\\(" ;
735 "^[ \t]*" ; new line and maybe whitespace
736 "\\(def[ \t]+" ; function definitions start with def
737 "\\([a-zA-Z0-9_]+\\)" ; name is here
738 ; function arguments...
Barry Warsaw650e8a61998-08-10 21:46:24 +0000739 "[ \t]*(\\([-+/a-zA-Z0-9_=,\* \t\n.()\"'#]*\\))"
Barry Warsaw81437461996-08-01 19:48:02 +0000740 "\\)" ; end of def
741 "[ \t]*:" ; and then the :
742 "\\)" ; >>methods and functions<<
743 )
744 "Regexp for Python methods/functions for use with the imenu package."
745 )
746
747(defvar imenu-example--python-method-no-arg-parens '(2 8)
748 "Indicies into groups of the Python regexp for use with imenu.
749
750Using these values will result in smaller imenu lists, as arguments to
751functions are not listed.
752
753See the variable `imenu-example--python-show-method-args-p' for more
754information.")
755
756(defvar imenu-example--python-method-arg-parens '(2 7)
757 "Indicies into groups of the Python regexp for use with imenu.
758Using these values will result in large imenu lists, as arguments to
759functions are listed.
760
761See the variable `imenu-example--python-show-method-args-p' for more
762information.")
763
764;; Note that in this format, this variable can still be used with the
765;; imenu--generic-function. Otherwise, there is no real reason to have
766;; it.
767(defvar imenu-example--generic-python-expression
768 (cons
769 (concat
770 imenu-example--python-class-regexp
771 "\\|" ; or...
772 imenu-example--python-method-regexp
773 )
774 imenu-example--python-method-no-arg-parens)
775 "Generic Python expression which may be used directly with imenu.
776Used by setting the variable `imenu-generic-expression' to this value.
777Also, see the function \\[imenu-example--create-python-index] for a
778better alternative for finding the index.")
779
780;; These next two variables are used when searching for the python
781;; class/definitions. Just saving some time in accessing the
782;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000783(defvar imenu-example--python-generic-regexp nil)
784(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000785
786
Barry Warsaw81437461996-08-01 19:48:02 +0000787(defun imenu-example--create-python-index ()
788 "Python interface function for imenu package.
789Finds all python classes and functions/methods. Calls function
790\\[imenu-example--create-python-index-engine]. See that function for
791the details of how this works."
792 (setq imenu-example--python-generic-regexp
793 (car imenu-example--generic-python-expression))
794 (setq imenu-example--python-generic-parens
795 (if imenu-example--python-show-method-args-p
796 imenu-example--python-method-arg-parens
797 imenu-example--python-method-no-arg-parens))
798 (goto-char (point-min))
799 (imenu-example--create-python-index-engine nil))
800
801(defun imenu-example--create-python-index-engine (&optional start-indent)
802 "Function for finding imenu definitions in Python.
803
804Finds all definitions (classes, methods, or functions) in a Python
805file for the imenu package.
806
807Returns a possibly nested alist of the form
808
809 (INDEX-NAME . INDEX-POSITION)
810
811The second element of the alist may be an alist, producing a nested
812list as in
813
814 (INDEX-NAME . INDEX-ALIST)
815
816This function should not be called directly, as it calls itself
817recursively and requires some setup. Rather this is the engine for
818the function \\[imenu-example--create-python-index].
819
820It works recursively by looking for all definitions at the current
821indention level. When it finds one, it adds it to the alist. If it
822finds a definition at a greater indentation level, it removes the
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000823previous definition from the alist. In its place it adds all
Barry Warsaw81437461996-08-01 19:48:02 +0000824definitions found at the next indentation level. When it finds a
825definition that is less indented then the current level, it retuns the
826alist it has created thus far.
827
828The optional argument START-INDENT indicates the starting indentation
829at which to continue looking for Python classes, methods, or
830functions. If this is not supplied, the function uses the indentation
831of the first definition found."
832 (let ((index-alist '())
833 (sub-method-alist '())
834 looking-p
835 def-name prev-name
836 cur-indent def-pos
837 (class-paren (first imenu-example--python-generic-parens))
838 (def-paren (second imenu-example--python-generic-parens)))
839 (setq looking-p
840 (re-search-forward imenu-example--python-generic-regexp
841 (point-max) t))
842 (while looking-p
843 (save-excursion
844 ;; used to set def-name to this value but generic-extract-name is
845 ;; new to imenu-1.14. this way it still works with imenu-1.11
846 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
847 (let ((cur-paren (if (match-beginning class-paren)
848 class-paren def-paren)))
849 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000850 (buffer-substring-no-properties (match-beginning cur-paren)
851 (match-end cur-paren))))
Barry Warsaw93c88cc1998-08-18 02:00:44 +0000852 (save-match-data
853 (py-beginning-of-def-or-class))
Barry Warsaw81437461996-08-01 19:48:02 +0000854 (beginning-of-line)
855 (setq cur-indent (current-indentation)))
856
857 ;; HACK: want to go to the next correct definition location. we
858 ;; explicitly list them here. would be better to have them in a
859 ;; list.
860 (setq def-pos
861 (or (match-beginning class-paren)
862 (match-beginning def-paren)))
863
864 ;; if we don't have a starting indent level, take this one
865 (or start-indent
866 (setq start-indent cur-indent))
867
868 ;; if we don't have class name yet, take this one
869 (or prev-name
870 (setq prev-name def-name))
871
872 ;; what level is the next definition on? must be same, deeper
873 ;; or shallower indentation
874 (cond
875 ;; at the same indent level, add it to the list...
876 ((= start-indent cur-indent)
877
878 ;; if we don't have push, use the following...
879 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
880 (push (cons def-name def-pos) index-alist))
881
882 ;; deeper indented expression, recur...
883 ((< start-indent cur-indent)
884
885 ;; the point is currently on the expression we're supposed to
886 ;; start on, so go back to the last expression. The recursive
887 ;; call will find this place again and add it to the correct
888 ;; list
889 (re-search-backward imenu-example--python-generic-regexp
890 (point-min) 'move)
891 (setq sub-method-alist (imenu-example--create-python-index-engine
892 cur-indent))
893
894 (if sub-method-alist
895 ;; we put the last element on the index-alist on the start
896 ;; of the submethod alist so the user can still get to it.
897 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000898 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000899 (cons save-elmt sub-method-alist))
900 index-alist))))
901
902 ;; found less indented expression, we're done.
903 (t
904 (setq looking-p nil)
905 (re-search-backward imenu-example--python-generic-regexp
906 (point-min) t)))
907 (setq prev-name def-name)
908 (and looking-p
909 (setq looking-p
910 (re-search-forward imenu-example--python-generic-regexp
911 (point-max) 'move))))
912 (nreverse index-alist)))
913
Barry Warsaw42f707f1996-07-29 21:05:05 +0000914
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000915;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000916(defun python-mode ()
917 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000918To submit a problem report, enter `\\[py-submit-bug-report]' from a
919`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
920documentation. To see what version of `python-mode' you are running,
921enter `\\[py-version]'.
922
923This mode knows about Python indentation, tokens, comments and
924continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000925
926COMMANDS
927\\{py-mode-map}
928VARIABLES
929
Barry Warsaw42f707f1996-07-29 21:05:05 +0000930py-indent-offset\t\tindentation increment
Barry Warsaw41a05c71998-08-10 16:33:12 +0000931py-block-comment-prefix\t\tcomment string used by `comment-region'
Barry Warsaw42f707f1996-07-29 21:05:05 +0000932py-python-command\t\tshell command to invoke Python interpreter
Barry Warsaw42f707f1996-07-29 21:05:05 +0000933py-temp-directory\t\tdirectory used for temp files (if needed)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000934py-beep-if-tab-change\t\tring the bell if `tab-width' is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000935 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000936 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000937 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000938 (make-local-variable 'font-lock-defaults)
939 (make-local-variable 'paragraph-separate)
940 (make-local-variable 'paragraph-start)
941 (make-local-variable 'require-final-newline)
942 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000943 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000944 (make-local-variable 'comment-start-skip)
945 (make-local-variable 'comment-column)
Barry Warsaw003932a1998-07-07 15:11:24 +0000946 (make-local-variable 'comment-indent-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000947 (make-local-variable 'indent-region-function)
948 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000949 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000950 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000951 (set-syntax-table py-mode-syntax-table)
Barry Warsaw003932a1998-07-07 15:11:24 +0000952 (setq major-mode 'python-mode
953 mode-name "Python"
954 local-abbrev-table python-mode-abbrev-table
955 font-lock-defaults '(python-font-lock-keywords)
956 paragraph-separate "^[ \t]*$"
957 paragraph-start "^[ \t]*$"
958 require-final-newline t
959 comment-start "# "
960 comment-end ""
961 comment-start-skip "# *"
962 comment-column 40
963 comment-indent-function 'py-comment-indent-function
964 indent-region-function 'py-indent-region
965 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000966 ;; tell add-log.el how to find the current function/method/variable
967 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000968 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000969 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000970 ;; add the menu
971 (if py-menu
972 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000973 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000974 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000975 (setq comment-multi-line nil))
Barry Warsaw742a5111998-03-13 17:29:15 +0000976 ;; Install Imenu, only works for Emacs.
977 (when (py-safe (require 'imenu))
978 (make-variable-buffer-local 'imenu-create-index-function)
979 (setq imenu-create-index-function
980 (function imenu-example--create-python-index))
981 (setq imenu-generic-expression
982 imenu-example--generic-python-expression)
983 (if (fboundp 'imenu-add-to-menubar)
984 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
985 )
986 ;; Run the mode hook. Note that py-mode-hook is deprecated.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000987 (if python-mode-hook
988 (run-hooks 'python-mode-hook)
Barry Warsaw742a5111998-03-13 17:29:15 +0000989 (run-hooks 'py-mode-hook))
990 ;; Now do the automagical guessing
991 (if py-smart-indentation
992 (let ((offset py-indent-offset))
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000993 ;; It's okay if this fails to guess a good value
Barry Warsaw742a5111998-03-13 17:29:15 +0000994 (if (and (py-safe (py-guess-indent-offset))
995 (<= py-indent-offset 8)
996 (>= py-indent-offset 2))
997 (setq offset py-indent-offset))
998 (setq py-indent-offset offset)
Barry Warsaw639eea61998-03-16 18:12:13 +0000999 ;; Only turn indent-tabs-mode off if tab-width !=
1000 ;; py-indent-offset. Never turn it on, because the user must
1001 ;; have explicitly turned it off.
1002 (if (/= tab-width py-indent-offset)
1003 (setq indent-tabs-mode nil))
Barry Warsaw742a5111998-03-13 17:29:15 +00001004 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001005
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001006
Barry Warsawb91b7431995-03-14 15:55:20 +00001007;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001008(defun py-outdent-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00001009 "Returns non-nil if the current line should dedent one level."
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001010 (save-excursion
1011 (and (progn (back-to-indentation)
1012 (looking-at py-outdent-re))
Barry Warsawf06777d1998-01-21 05:36:18 +00001013 (progn (forward-line -1)
1014 (py-goto-initial-line)
1015 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001016 (while (or (looking-at py-blank-or-comment-re)
1017 (bobp))
1018 (backward-to-indentation 1))
1019 (not (looking-at py-no-outdent-re)))
1020 )))
1021
Barry Warsawb91b7431995-03-14 15:55:20 +00001022(defun py-electric-colon (arg)
1023 "Insert a colon.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001024In certain cases the line is dedented appropriately. If a numeric
1025argument ARG is provided, that many colons are inserted
1026non-electrically. Electric behavior is inhibited inside a string or
1027comment."
Barry Warsawb91b7431995-03-14 15:55:20 +00001028 (interactive "P")
1029 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001030 ;; are we in a string or comment?
1031 (if (save-excursion
1032 (let ((pps (parse-partial-sexp (save-excursion
Barry Warsawab0e86c1998-05-19 15:31:46 +00001033 (py-beginning-of-def-or-class)
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001034 (point))
1035 (point))))
1036 (not (or (nth 3 pps) (nth 4 pps)))))
1037 (save-excursion
1038 (let ((here (point))
1039 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001040 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001041 (if (and (not arg)
1042 (py-outdent-p)
1043 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +00001044 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001045 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001046 )
1047 (setq outdent py-indent-offset))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001048 ;; Don't indent, only dedent. This assumes that any lines
1049 ;; that are already dedented relative to
1050 ;; py-compute-indentation were put there on purpose. It's
1051 ;; highly annoying to have `:' indent for you. Use TAB, C-c
1052 ;; C-l or C-c C-r to adjust. TBD: Is there a better way to
1053 ;; determine this???
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001054 (if (< (current-indentation) indent) nil
1055 (goto-char here)
1056 (beginning-of-line)
1057 (delete-horizontal-space)
1058 (indent-to (- indent outdent))
1059 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001060
1061
Barry Warsawa97a3f31997-11-04 18:47:06 +00001062;; Python subprocess utilities and filters
1063(defun py-execute-file (proc filename)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001064 "Send to Python interpreter process PROC \"execfile('FILENAME')\".
1065Make that process's buffer visible and force display. Also make
1066comint believe the user typed this string so that
1067`kill-output-from-shell' does The Right Thing."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001068 (let ((curbuf (current-buffer))
1069 (procbuf (process-buffer proc))
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001070; (comint-scroll-to-bottom-on-output t)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001071 (msg (format "## working on region in file %s...\n" filename))
1072 (cmd (format "execfile('%s')\n" filename)))
1073 (unwind-protect
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001074 (save-excursion
Barry Warsawa97a3f31997-11-04 18:47:06 +00001075 (set-buffer procbuf)
1076 (goto-char (point-max))
1077 (move-marker (process-mark proc) (point))
1078 (funcall (process-filter proc) proc msg))
1079 (set-buffer curbuf))
1080 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001081
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001082(defun py-comint-output-filter-function (string)
1083 "Watch output for Python prompt and exec next file waiting in queue.
1084This function is appropriate for `comint-output-filter-functions'."
1085 (when (and (string-equal ">>> " string)
1086 py-file-queue)
1087 (py-safe (delete-file (car py-file-queue)))
1088 (setq py-file-queue (cdr py-file-queue))
1089 (if py-file-queue
1090 (let ((pyproc (get-buffer-process (current-buffer))))
1091 (py-execute-file pyproc (car py-file-queue))))
1092 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001093
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001094(defun py-postprocess-output-buffer (buf)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001095 "Highlight exceptions found in BUF.
1096If an exception occurred return t, otherwise return nil. BUF must exist."
Barry Warsawf9b99f41998-03-26 16:08:59 +00001097 (let (line file bol err-p)
Barry Warsaw9981d221997-12-03 05:25:48 +00001098 (save-excursion
1099 (set-buffer buf)
1100 (beginning-of-buffer)
1101 (while (re-search-forward py-traceback-line-re nil t)
1102 (setq file (match-string 1)
1103 line (string-to-int (match-string 2))
1104 bol (py-point 'bol))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001105 (py-highlight-line bol (py-point 'eol) file line)))
1106 (when (and py-jump-on-exception line)
1107 (beep)
1108 (py-jump-to-exception file line)
1109 (setq err-p t))
1110 err-p))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001111
Barry Warsaw9981d221997-12-03 05:25:48 +00001112
Barry Warsawa97a3f31997-11-04 18:47:06 +00001113
1114;;; Subprocess commands
1115
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001116;; only used when (memq 'broken-temp-names py-emacs-features)
1117(defvar py-serial-number 0)
1118(defvar py-exception-buffer nil)
1119(defconst py-output-buffer "*Python Output*")
Barry Warsawa2398801998-04-09 23:28:20 +00001120(make-variable-buffer-local 'py-output-buffer)
1121
1122;; for toggling between CPython and JPython
1123(defvar py-which-shell py-python-command)
1124(defvar py-which-args py-python-command-args)
1125(defvar py-which-bufname "Python")
1126(make-variable-buffer-local 'py-which-shell)
1127(make-variable-buffer-local 'py-which-args)
1128(make-variable-buffer-local 'py-which-bufname)
1129
1130(defun py-toggle-shells (arg)
1131 "Toggles between the CPython and JPython shells.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001132With positive argument ARG (interactively \\[universal-argument]),
1133uses the CPython shell, with negative ARG uses the JPython shell, and
1134with a zero argument, toggles the shell."
Barry Warsawa2398801998-04-09 23:28:20 +00001135 (interactive "P")
1136 ;; default is to toggle
1137 (if (null arg)
1138 (setq arg 0))
1139 ;; toggle if zero
1140 (if (= arg 0)
1141 (if (string-equal py-which-bufname "Python")
1142 (setq arg -1)
1143 (setq arg 1)))
1144 (let (msg)
1145 (cond
1146 ((< 0 arg)
1147 ;; set to CPython
1148 (setq py-which-shell py-python-command
1149 py-which-args py-python-command-args
1150 py-which-bufname "Python"
1151 msg "CPython"
1152 mode-name "Python"))
1153 ((> 0 arg)
1154 (setq py-which-shell py-jpython-command
1155 py-which-args py-jpython-command-args
1156 py-which-bufname "JPython"
1157 msg "JPython"
1158 mode-name "JPython"))
1159 )
Barry Warsawea609c11998-04-10 16:08:26 +00001160 (message "Using the %s shell" msg)
Barry Warsawa2398801998-04-09 23:28:20 +00001161 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001162
Barry Warsawa97a3f31997-11-04 18:47:06 +00001163;;;###autoload
1164(defun py-shell ()
1165 "Start an interactive Python interpreter in another window.
1166This is like Shell mode, except that Python is running in the window
1167instead of a shell. See the `Interactive Shell' and `Shell Mode'
1168sections of the Emacs manual for details, especially for the key
1169bindings active in the `*Python*' buffer.
1170
Barry Warsawa2398801998-04-09 23:28:20 +00001171Note: You can toggle between using the CPython interpreter and the
1172JPython interpreter by hitting \\[py-toggle-shells]. This toggles
1173buffer local variables which control whether all your subshell
1174interactions happen to the `*JPython*' or `*Python*' buffers (the
1175latter is the name used for the CPython buffer).
1176
Barry Warsawa97a3f31997-11-04 18:47:06 +00001177Warning: Don't use an interactive Python if you change sys.ps1 or
1178sys.ps2 from their default values, or if you're running code that
1179prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1180distinguish your output from Python's output, and assumes that `>>> '
1181at the start of a line is a prompt from Python. Similarly, the Emacs
1182Shell mode code assumes that both `>>> ' and `... ' at the start of a
1183line are Python prompts. Bad things can happen if you fool either
1184mode.
1185
1186Warning: If you do any editing *in* the process buffer *while* the
1187buffer is accepting output from Python, do NOT attempt to `undo' the
1188changes. Some of the output (nowhere near the parts you changed!) may
1189be lost if you do. This appears to be an Emacs bug, an unfortunate
1190interaction between undo and process filters; the same problem exists in
1191non-Python process buffers using the default (Emacs-supplied) process
1192filter."
1193 ;; BAW - should undo be disabled in the python process buffer, if
1194 ;; this bug still exists?
1195 (interactive)
1196 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001197 (switch-to-buffer-other-window
Barry Warsawa2398801998-04-09 23:28:20 +00001198 (apply 'make-comint py-which-bufname py-which-shell nil py-which-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001199 (make-local-variable 'comint-prompt-regexp)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001200 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001201 (make-local-variable 'comint-output-filter-functions)
1202 (add-hook 'comint-output-filter-functions 'py-comint-output-filter-function)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001203 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001204 ;; set up keybindings for this subshell
1205 (local-set-key [tab] 'self-insert-command)
1206 (local-set-key "\C-c-" 'py-up-exception)
1207 (local-set-key "\C-c=" 'py-down-exception)
1208 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001209
Barry Warsawa97a3f31997-11-04 18:47:06 +00001210(defun py-clear-queue ()
1211 "Clear the queue of temporary files waiting to execute."
1212 (interactive)
1213 (let ((n (length py-file-queue)))
1214 (mapcar 'delete-file py-file-queue)
1215 (setq py-file-queue nil)
1216 (message "%d pending files de-queued." n)))
1217
Barry Warsaw820273d1998-05-19 15:54:45 +00001218
Barry Warsawa97a3f31997-11-04 18:47:06 +00001219(defun py-execute-region (start end &optional async)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001220 "Execute the region in a Python interpreter.
1221
Barry Warsawa97a3f31997-11-04 18:47:06 +00001222The region is first copied into a temporary file (in the directory
1223`py-temp-directory'). If there is no Python interpreter shell
1224running, this file is executed synchronously using
Barry Warsaw41a05c71998-08-10 16:33:12 +00001225`shell-command-on-region'. If the program is long running, use
1226\\[universal-argument] to run the command asynchronously in its own
1227buffer.
1228
1229When this function is used programmatically, arguments START and END
1230specify the region to execute, and optional third argument ASYNC, if
1231non-nil, specifies to run the command asynchronously in its own
1232buffer.
Barry Warsawa97a3f31997-11-04 18:47:06 +00001233
1234If the Python interpreter shell is running, the region is execfile()'d
1235in that shell. If you try to execute regions too quickly,
1236`python-mode' will queue them up and execute them one at a time when
1237it sees a `>>> ' prompt from Python. Each time this happens, the
1238process buffer is popped into a window (if it's not already in some
1239window) so you can see it, and a comment of the form
1240
1241 \t## working on region in file <name>...
1242
1243is inserted at the end. See also the command `py-clear-queue'."
1244 (interactive "r\nP")
1245 (or (< start end)
1246 (error "Region is empty"))
1247 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001248 (temp (if (memq 'broken-temp-names py-emacs-features)
Barry Warsaw1b344241998-08-07 22:24:16 +00001249 (let
1250 ((sn py-serial-number)
1251 (pid (and (fboundp 'emacs-pid) (emacs-pid))))
1252 (setq py-serial-number (1+ py-serial-number))
1253 (if pid
1254 (format "python-%d-%d" sn pid)
1255 (format "python-%d" sn)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001256 (make-temp-name "python-")))
1257 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001258 (write-region start end file nil 'nomsg)
1259 (cond
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001260 ;; always run the code in its own asynchronous subprocess
Barry Warsawa97a3f31997-11-04 18:47:06 +00001261 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001262 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001263 (start-process "Python" buf py-python-command "-u" file)
1264 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001265 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001266 ))
1267 ;; if the Python interpreter shell is running, queue it up for
1268 ;; execution there.
1269 (proc
1270 ;; use the existing python shell
1271 (if (not py-file-queue)
1272 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001273 (message "File %s queued for execution" file))
Barry Warsaw3c96f6f1998-08-20 19:44:51 +00001274 (setq py-file-queue (append py-file-queue (list file)))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001275 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001276 (t
1277 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001278 (shell-command-on-region start end py-python-command py-output-buffer)
Barry Warsaw512af041998-03-25 23:27:17 +00001279 ;; shell-command-on-region kills the output buffer if it never
1280 ;; existed and there's no output from the command
1281 (if (not (get-buffer py-output-buffer))
1282 (message "No output.")
1283 (setq py-exception-buffer (current-buffer))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001284 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1285 (pop-to-buffer py-output-buffer)
1286 (if err-p
1287 (pop-to-buffer py-exception-buffer)))
Barry Warsaw512af041998-03-25 23:27:17 +00001288 ))
1289 )))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001290
Barry Warsaw820273d1998-05-19 15:54:45 +00001291
1292;; Code execution commands
Barry Warsawa97a3f31997-11-04 18:47:06 +00001293(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001294 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001295If the file local variable `py-master-file' is non-nil, execute the
1296named file instead of the buffer's file.
1297
Barry Warsaw7ae77681994-12-12 20:38:05 +00001298If there is a *Python* process buffer it is used. If a clipping
1299restriction is in effect, only the accessible portion of the buffer is
1300sent. A trailing newline will be supplied if needed.
1301
Barry Warsaw41a05c71998-08-10 16:33:12 +00001302See the `\\[py-execute-region]' docs for an account of some
1303subtleties, including the use of the optional ASYNC argument."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001304 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001305 (if py-master-file
1306 (let* ((filename (expand-file-name py-master-file))
1307 (buffer (or (get-file-buffer filename)
1308 (find-file-noselect filename))))
1309 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001310 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001311
Barry Warsaw820273d1998-05-19 15:54:45 +00001312(defun py-execute-import-or-reload (&optional async)
1313 "Import the current buffer's file in a Python interpreter.
1314
1315If the file has already been imported, then do reload instead to get
Barry Warsaw7c29b231998-07-07 17:45:38 +00001316the latest version.
1317
1318If the file's name does not end in \".py\", then do execfile instead.
1319
1320If the current buffer is not visiting a file, do `py-execute-buffer'
1321instead.
1322
1323If the file local variable `py-master-file' is non-nil, import or
1324reload the named file instead of the buffer's file. The file may be
1325saved based on the value of `py-execute-import-or-reload-save-p'.
Barry Warsaw820273d1998-05-19 15:54:45 +00001326
Barry Warsaw41a05c71998-08-10 16:33:12 +00001327See the `\\[py-execute-region]' docs for an account of some
1328subtleties, including the use of the optional ASYNC argument.
Barry Warsaw820273d1998-05-19 15:54:45 +00001329
Barry Warsaw7c29b231998-07-07 17:45:38 +00001330This may be preferable to `\\[py-execute-buffer]' because:
Barry Warsaw820273d1998-05-19 15:54:45 +00001331
1332 - Definitions stay in their module rather than appearing at top
1333 level, where they would clutter the global namespace and not affect
1334 uses of qualified names (MODULE.NAME).
1335
1336 - The Python debugger gets line number information about the functions."
1337 (interactive "P")
1338 ;; Check file local variable py-master-file
1339 (if py-master-file
1340 (let* ((filename (expand-file-name py-master-file))
1341 (buffer (or (get-file-buffer filename)
1342 (find-file-noselect filename))))
1343 (set-buffer buffer)))
1344 (let ((file (buffer-file-name (current-buffer))))
1345 (if file
1346 (progn
Barry Warsaw3bfed5b1998-05-19 16:25:04 +00001347 ;; Maybe save some buffers
1348 (save-some-buffers (not py-ask-about-save) nil)
Barry Warsaw820273d1998-05-19 15:54:45 +00001349 (py-execute-string
1350 (if (string-match "\\.py$" file)
1351 (let ((f (file-name-sans-extension
1352 (file-name-nondirectory file))))
1353 (format "if globals().has_key('%s'):\n reload(%s)\nelse:\n import %s\n"
1354 f f f))
1355 (format "execfile('%s')\n" file))
1356 async))
1357 ;; else
1358 (py-execute-buffer async))))
1359
1360
1361(defun py-execute-def-or-class (&optional async)
1362 "Send the current function or class definition to a Python interpreter.
1363
1364If there is a *Python* process buffer it is used.
1365
Barry Warsaw41a05c71998-08-10 16:33:12 +00001366See the `\\[py-execute-region]' docs for an account of some
1367subtleties, including the use of the optional ASYNC argument."
Barry Warsaw820273d1998-05-19 15:54:45 +00001368 (interactive "P")
1369 (save-excursion
1370 (py-mark-def-or-class)
1371 ;; mark is before point
1372 (py-execute-region (mark) (point) async)))
1373
1374
1375(defun py-execute-string (string &optional async)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001376 "Send the argument STRING to a Python interpreter.
Barry Warsaw820273d1998-05-19 15:54:45 +00001377
1378If there is a *Python* process buffer it is used.
1379
Barry Warsaw41a05c71998-08-10 16:33:12 +00001380See the `\\[py-execute-region]' docs for an account of some
1381subtleties, including the use of the optional ASYNC argument."
Barry Warsaw820273d1998-05-19 15:54:45 +00001382 (interactive "sExecute Python command: ")
1383 (save-excursion
1384 (set-buffer (get-buffer-create
1385 (generate-new-buffer-name " *Python Command*")))
1386 (insert string)
1387 (py-execute-region (point-min) (point-max) async)))
1388
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001389
1390
1391(defun py-jump-to-exception (file line)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001392 "Jump to the Python code in FILE at LINE."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001393 (let ((buffer (cond ((string-equal file "<stdin>")
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001394 (if (consp py-exception-buffer)
1395 (cdr py-exception-buffer)
1396 py-exception-buffer))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001397 ((and (consp py-exception-buffer)
1398 (string-equal file (car py-exception-buffer)))
1399 (cdr py-exception-buffer))
1400 ((py-safe (find-file-noselect file)))
1401 ;; could not figure out what file the exception
1402 ;; is pointing to, so prompt for it
1403 (t (find-file (read-file-name "Exception file: "
1404 nil
1405 file t))))))
1406 (pop-to-buffer buffer)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001407 ;; Force Python mode
Barry Warsaw820273d1998-05-19 15:54:45 +00001408 (if (not (eq major-mode 'python-mode))
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001409 (python-mode))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001410 (goto-line line)
1411 (message "Jumping to exception in file %s on line %d" file line)))
1412
1413(defun py-mouseto-exception (event)
Barry Warsaw12c92941998-08-10 21:44:37 +00001414 "Jump to the code which caused the Python exception at EVENT.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001415EVENT is usually a mouse click."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001416 (interactive "e")
1417 (cond
1418 ((fboundp 'event-point)
1419 ;; XEmacs
1420 (let* ((point (event-point event))
1421 (buffer (event-buffer event))
1422 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1423 (info (and e (extent-property e 'py-exc-info))))
1424 (message "Event point: %d, info: %s" point info)
1425 (and info
1426 (py-jump-to-exception (car info) (cdr info)))
1427 ))
1428 ;; Emacs -- Please port this!
1429 ))
1430
1431(defun py-goto-exception ()
1432 "Go to the line indicated by the traceback."
1433 (interactive)
1434 (let (file line)
1435 (save-excursion
1436 (beginning-of-line)
1437 (if (looking-at py-traceback-line-re)
1438 (setq file (match-string 1)
1439 line (string-to-int (match-string 2)))))
1440 (if (not file)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001441 (error "Not on a traceback line"))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001442 (py-jump-to-exception file line)))
1443
1444(defun py-find-next-exception (start buffer searchdir errwhere)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001445 "Find the next Python exception and jump to the code that caused it.
1446START is the buffer position in BUFFER from which to begin searching
1447for an exception. SEARCHDIR is a function, either
1448`re-search-backward' or `re-search-forward' indicating the direction
1449to search. ERRWHERE is used in an error message if the limit (top or
1450bottom) of the trackback stack is encountered."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001451 (let (file line)
1452 (save-excursion
1453 (set-buffer buffer)
1454 (goto-char (py-point start))
1455 (if (funcall searchdir py-traceback-line-re nil t)
1456 (setq file (match-string 1)
1457 line (string-to-int (match-string 2)))))
1458 (if (and file line)
1459 (py-jump-to-exception file line)
1460 (error "%s of traceback" errwhere))))
1461
1462(defun py-down-exception (&optional bottom)
1463 "Go to the next line down in the traceback.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001464With \\[univeral-argument] (programmatically, optional argument
1465BOTTOM), jump to the bottom (innermost) exception in the exception
1466stack."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001467 (interactive "P")
1468 (let* ((proc (get-process "Python"))
1469 (buffer (if proc "*Python*" py-output-buffer)))
1470 (if bottom
1471 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1472 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1473
1474(defun py-up-exception (&optional top)
1475 "Go to the previous line up in the traceback.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001476With \\[universal-argument] (programmatically, optional argument TOP)
1477jump to the top (outermost) exception in the exception stack."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001478 (interactive "P")
1479 (let* ((proc (get-process "Python"))
1480 (buffer (if proc "*Python*" py-output-buffer)))
1481 (if top
1482 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001483 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001484
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001485
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001486;; Electric deletion
1487(defun py-electric-backspace (arg)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001488 "Delete preceding character or levels of indentation.
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001489Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001490with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001491
Barry Warsaw41a05c71998-08-10 16:33:12 +00001492If point is at the leftmost column, delete the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001493
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001494Otherwise, if point is at the leftmost non-whitespace character of a
1495line that is neither a continuation line nor a non-indenting comment
1496line, or if point is at the end of a blank line, this command reduces
1497the indentation to match that of the line that opened the current
1498block of code. The line that opened the block is displayed in the
Barry Warsaw41a05c71998-08-10 16:33:12 +00001499echo area to help you keep track of where you are. With
1500\\[universal-argument] dedents that many blocks (but not past column
1501zero).
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001502
1503Otherwise the preceding character is deleted, converting a tab to
1504spaces if needed so that only a single column position is deleted.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001505\\[universal-argument] specifies how many characters to delete
1506(default is 1).
1507
1508When used programmatically, argument ARG specifies the number of
1509blocks to dedent, or the number of characters to delete, as indicated
1510above."
Barry Warsaw03970731996-07-03 23:12:52 +00001511 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001512 (if (or (/= (current-indentation) (current-column))
1513 (bolp)
1514 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001515 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001516 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001517 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001518 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001519 ;; force non-blank so py-goto-block-up doesn't ignore it
1520 (insert-char ?* 1)
1521 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001522 (let ((base-indent 0) ; indentation of base line
1523 (base-text "") ; and text of base line
1524 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001525 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001526 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001527 (condition-case nil ; in case no enclosing block
1528 (progn
1529 (py-goto-block-up 'no-mark)
1530 (setq base-indent (current-indentation)
1531 base-text (py-suck-up-leading-text)
1532 base-found-p t))
1533 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001534 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001535 (delete-char 1) ; toss the dummy character
1536 (delete-horizontal-space)
1537 (indent-to base-indent)
1538 (if base-found-p
1539 (message "Closes block: %s" base-text)))))
1540
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001541
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001542(defun py-electric-delete (arg)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001543 "Delete preceding or following character or levels of whitespace.
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001544
1545The behavior of this function depends on the variable
1546`delete-key-deletes-forward'. If this variable is nil (or does not
Barry Warsaw41a05c71998-08-10 16:33:12 +00001547exist, as in older Emacsen and non-XEmacs versions), then this
1548function behaves identically to \\[c-electric-backspace].
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001549
1550If `delete-key-deletes-forward' is non-nil and is supported in your
1551Emacs, then deletion occurs in the forward direction, by calling the
Barry Warsaw41a05c71998-08-10 16:33:12 +00001552function in `py-delete-function'.
1553
1554\\[universal-argument] (programmatically, argument ARG) specifies the
1555number of characters to delete (default is 1)."
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001556 (interactive "*p")
1557 (if (and (boundp 'delete-key-deletes-forward)
1558 delete-key-deletes-forward)
1559 (funcall py-delete-function arg)
1560 ;; else
1561 (py-electric-backspace arg)))
1562
1563;; required for pending-del and delsel modes
1564(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1565(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1566(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1567(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1568
1569
1570
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001571(defun py-indent-line (&optional arg)
1572 "Fix the indentation of the current line according to Python rules.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001573With \\[universal-argument] (programmatically, the optional argument
1574ARG non-nil), ignore dedenting rules for block closing statements
1575(e.g. return, raise, break, continue, pass)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001576
1577This function is normally bound to `indent-line-function' so
1578\\[indent-for-tab-command] will call it."
1579 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001580 (let* ((ci (current-indentation))
1581 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001582 (need (py-compute-indentation (not arg))))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001583 ;; see if we need to dedent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001584 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001585 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001586 (if (/= ci need)
1587 (save-excursion
1588 (beginning-of-line)
1589 (delete-horizontal-space)
1590 (indent-to need)))
1591 (if move-to-indentation-p (back-to-indentation))))
1592
1593(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001594 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001595This is just `strives to' because correct indentation can't be computed
1596from scratch for Python code. In general, deletes the whitespace before
1597point, inserts a newline, and takes an educated guess as to how you want
1598the new line indented."
1599 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001600 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001601 (if (< ci (current-column)) ; if point beyond indentation
1602 (newline-and-indent)
1603 ;; else try to act like newline-and-indent "normally" acts
1604 (beginning-of-line)
1605 (insert-char ?\n 1)
1606 (move-to-column ci))))
1607
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001608(defun py-compute-indentation (honor-block-close-p)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001609 "Compute Python indentation.
1610When HONOR-BLOCK-CLOSE-P is non-nil, statements such as `return',
1611`raise', `break', `continue', and `pass' force one level of
1612dedenting."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001613 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001614 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001615 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001616 (pps (parse-partial-sexp bod (point)))
1617 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001618 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001619 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001620 ((or (and (nth 3 pps) (nth 3 boipps))
1621 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001622 (save-excursion
1623 (if (not py-align-multiline-strings-p) 0
1624 ;; skip back over blank & non-indenting comment lines
1625 ;; note: will skip a blank or non-indenting comment line
1626 ;; that happens to be a continuation line too
1627 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1628 (back-to-indentation)
1629 (current-column))))
1630 ;; are we on a continuation line?
1631 ((py-continuation-line-p)
1632 (let ((startpos (point))
1633 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001634 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001635 (if open-bracket-pos
1636 (progn
1637 ;; align with first item in list; else a normal
1638 ;; indent beyond the line with the open bracket
1639 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1640 ;; is the first list item on the same line?
1641 (skip-chars-forward " \t")
1642 (if (null (memq (following-char) '(?\n ?# ?\\)))
1643 ; yes, so line up with it
1644 (current-column)
1645 ;; first list item on another line, or doesn't exist yet
1646 (forward-line 1)
1647 (while (and (< (point) startpos)
1648 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1649 (forward-line 1))
Barry Warsaw92166d91998-04-01 21:59:41 +00001650 (if (and (< (point) startpos)
1651 (/= startpos
1652 (save-excursion
1653 (goto-char (1+ open-bracket-pos))
Barry Warsaw77d1fce1998-04-16 20:04:59 +00001654 (forward-comment (point-max))
Barry Warsaw92166d91998-04-01 21:59:41 +00001655 (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001656 ;; again mimic the first list item
1657 (current-indentation)
1658 ;; else they're about to enter the first item
1659 (goto-char open-bracket-pos)
1660 (+ (current-indentation) py-indent-offset))))
1661
1662 ;; else on backslash continuation line
1663 (forward-line -1)
1664 (if (py-continuation-line-p) ; on at least 3rd line in block
1665 (current-indentation) ; so just continue the pattern
1666 ;; else started on 2nd line in block, so indent more.
1667 ;; if base line is an assignment with a start on a RHS,
1668 ;; indent to 2 beyond the leftmost "="; else skip first
1669 ;; chunk of non-whitespace characters on base line, + 1 more
1670 ;; column
1671 (end-of-line)
1672 (setq endpos (point) searching t)
1673 (back-to-indentation)
1674 (setq startpos (point))
1675 ;; look at all "=" from left to right, stopping at first
1676 ;; one not nested in a list or string
1677 (while searching
1678 (skip-chars-forward "^=" endpos)
1679 (if (= (point) endpos)
1680 (setq searching nil)
1681 (forward-char 1)
1682 (setq state (parse-partial-sexp startpos (point)))
1683 (if (and (zerop (car state)) ; not in a bracket
1684 (null (nth 3 state))) ; & not in a string
1685 (progn
1686 (setq searching nil) ; done searching in any case
1687 (setq found
1688 (not (or
1689 (eq (following-char) ?=)
1690 (memq (char-after (- (point) 2))
1691 '(?< ?> ?!)))))))))
1692 (if (or (not found) ; not an assignment
1693 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1694 (progn
1695 (goto-char startpos)
1696 (skip-chars-forward "^ \t\n")))
1697 (1+ (current-column))))))
1698
1699 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001700 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001701
Barry Warsawa7891711996-08-01 15:53:09 +00001702 ;; Dfn: "Indenting comment line". A line containing only a
1703 ;; comment, but which is treated like a statement for
1704 ;; indentation calculation purposes. Such lines are only
1705 ;; treated specially by the mode; they are not treated
1706 ;; specially by the Python interpreter.
1707
1708 ;; The rules for indenting comment lines are a line where:
1709 ;; - the first non-whitespace character is `#', and
1710 ;; - the character following the `#' is whitespace, and
Barry Warsaw41a05c71998-08-10 16:33:12 +00001711 ;; - the line is dedented with respect to (i.e. to the left
Barry Warsawa7891711996-08-01 15:53:09 +00001712 ;; of) the indentation of the preceding non-blank line.
1713
1714 ;; The first non-blank line following an indenting comment
1715 ;; line is given the same amount of indentation as the
1716 ;; indenting comment line.
1717
1718 ;; All other comment-only lines are ignored for indentation
1719 ;; purposes.
1720
1721 ;; Are we looking at a comment-only line which is *not* an
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001722 ;; indenting comment line? If so, we assume that it's been
Barry Warsawa7891711996-08-01 15:53:09 +00001723 ;; placed at the desired indentation, so leave it alone.
1724 ;; Indenting comment lines are aligned as statements down
1725 ;; below.
1726 ((and (looking-at "[ \t]*#[^ \t\n]")
1727 ;; NOTE: this test will not be performed in older Emacsen
1728 (fboundp 'forward-comment)
1729 (<= (current-indentation)
1730 (save-excursion
1731 (forward-comment (- (point-max)))
1732 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001733 (current-indentation))
1734
1735 ;; else indentation based on that of the statement that
1736 ;; precedes us; use the first line of that statement to
1737 ;; establish the base, in case the user forced a non-std
1738 ;; indentation for the continuation lines (if any)
1739 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001740 ;; skip back over blank & non-indenting comment lines note:
1741 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001742 ;; happens to be a continuation line too. use fast Emacs 19
1743 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001744 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001745 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001746 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001747 (let (done)
1748 (while (not done)
Barry Warsaw12c92941998-08-10 21:44:37 +00001749 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#\\)" nil 'move)
1750 (setq done (or (bobp)
1751 (and (eq py-honor-comment-indentation t)
1752 (save-excursion
1753 (back-to-indentation)
1754 (not (looking-at py-block-comment-prefix))
1755 ))
1756 (and (not (eq py-honor-comment-indentation t))
1757 (save-excursion
1758 (back-to-indentation)
1759 (not (zerop (current-column)))))
1760 ))
Barry Warsaw6d627751996-03-06 18:41:38 +00001761 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001762 ;; if we landed inside a string, go to the beginning of that
1763 ;; string. this handles triple quoted, multi-line spanning
1764 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001765 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001766 (skip (and delim (make-string 1 delim))))
1767 (when skip
1768 (save-excursion
1769 (py-safe (search-backward skip))
1770 (if (and (eq (char-before) delim)
1771 (eq (char-before (1- (point))) delim))
1772 (setq skip (make-string 3 delim))))
1773 ;; we're looking at a triple-quoted string
1774 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001775 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001776 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001777 (+ (current-indentation)
1778 (if (py-statement-opens-block-p)
1779 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001780 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001781 (- py-indent-offset)
1782 0)))
1783 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001784
1785(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001786 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001787
1788By default, make a buffer-local copy of `py-indent-offset' with the
1789new value, so that other Python buffers are not affected. With
1790\\[universal-argument] (programmatically, optional argument GLOBAL),
1791change the global value of `py-indent-offset'. This affects all
1792Python buffers (that don't have their own buffer-local copy), both
1793those currently existing and those created later in the Emacs session.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001794
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001795Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001796There's no excuse for such foolishness, but sometimes you have to deal
1797with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001798`py-indent-offset' to what it thinks it was when they created the
1799mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001800
1801Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001802looking for a line that opens a block of code. `py-indent-offset' is
1803set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001804statement following it. If the search doesn't succeed going forward,
1805it's tried again going backward."
1806 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001807 (let (new-value
1808 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001809 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001810 (found nil)
1811 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001812 (py-goto-initial-line)
1813 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001814 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1815 (not (py-in-literal restart)))
1816 (setq restart (point))
1817 (py-goto-initial-line)
1818 (if (py-statement-opens-block-p)
1819 (setq found t)
1820 (goto-char restart))))
1821 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001822 (goto-char start)
1823 (py-goto-initial-line)
1824 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001825 (setq found (and
1826 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1827 (or (py-goto-initial-line) t) ; always true -- side effect
1828 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001829 (setq colon-indent (current-indentation)
1830 found (and found (zerop (py-next-statement 1)))
1831 new-value (- (current-indentation) colon-indent))
1832 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001833 (if (not found)
1834 (error "Sorry, couldn't guess a value for py-indent-offset")
1835 (funcall (if global 'kill-local-variable 'make-local-variable)
1836 'py-indent-offset)
1837 (setq py-indent-offset new-value)
1838 (message "%s value of py-indent-offset set to %d"
1839 (if global "Global" "Local")
1840 py-indent-offset))
1841 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001842
Barry Warsaw003932a1998-07-07 15:11:24 +00001843(defun py-comment-indent-function ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00001844 "Python version of `comment-indent-function'."
1845 ;; This is required when filladapt is turned off. Without it, when
1846 ;; filladapt is not used, comments which start in column zero
1847 ;; cascade one character to the right
Barry Warsaw003932a1998-07-07 15:11:24 +00001848 (save-excursion
1849 (beginning-of-line)
1850 (let ((eol (py-point 'eol)))
1851 (and comment-start-skip
1852 (re-search-forward comment-start-skip eol t)
1853 (setq eol (match-beginning 0)))
1854 (goto-char eol)
1855 (skip-chars-backward " \t")
1856 (max comment-column (+ (current-column) (if (bolp) 0 1)))
1857 )))
1858
1859
Barry Warsaw7ae77681994-12-12 20:38:05 +00001860(defun py-shift-region (start end count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001861 "Indent lines from START to END by COUNT spaces."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001862 (save-excursion
Barry Warsaw41a05c71998-08-10 16:33:12 +00001863 (goto-char end)
1864 (beginning-of-line)
1865 (setq end (point))
1866 (goto-char start)
1867 (beginning-of-line)
1868 (setq start (point))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001869 (indent-rigidly start end count)))
1870
1871(defun py-shift-region-left (start end &optional count)
1872 "Shift region of Python code to the left.
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 left, 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 Warsaw41a05c71998-08-10 16:33:12 +00001878many columns. With no active region, dedent only the current line.
1879You cannot dedent the region if any line is already at column zero."
Barry Warsawdea4a291996-07-03 22:59:12 +00001880 (interactive
1881 (let ((p (point))
1882 (m (mark))
1883 (arg current-prefix-arg))
1884 (if m
1885 (list (min p m) (max p m) arg)
1886 (list p (save-excursion (forward-line 1) (point)) arg))))
1887 ;; if any line is at column zero, don't shift the region
1888 (save-excursion
1889 (goto-char start)
1890 (while (< (point) end)
1891 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001892 (if (and (zerop (current-column))
1893 (not (looking-at "\\s *$")))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001894 (error "Region is at left edge"))
Barry Warsawdea4a291996-07-03 22:59:12 +00001895 (forward-line 1)))
1896 (py-shift-region start end (- (prefix-numeric-value
1897 (or count py-indent-offset))))
1898 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001899
1900(defun py-shift-region-right (start end &optional count)
1901 "Shift region of Python code to the right.
1902The lines from the line containing the start of the current region up
1903to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001904shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001905
1906If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001907many columns. With no active region, indent only the current line."
1908 (interactive
1909 (let ((p (point))
1910 (m (mark))
1911 (arg current-prefix-arg))
1912 (if m
1913 (list (min p m) (max p m) arg)
1914 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001915 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001916 (or count py-indent-offset)))
1917 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001918
1919(defun py-indent-region (start end &optional indent-offset)
1920 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001921
Barry Warsaw7ae77681994-12-12 20:38:05 +00001922The lines from the line containing the start of the current region up
1923to (but not including) the line containing the end of the region are
1924reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001925character in the first column, the first line is left alone and the
1926rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001927region is reindented with respect to the (closest code or indenting
1928comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001929
1930This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001931control structures are introduced or removed, or to reformat code
1932using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001933
1934If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001935the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001936used.
1937
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001938Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001939is called! This function does not compute proper indentation from
1940scratch (that's impossible in Python), it merely adjusts the existing
1941indentation to be correct in context.
1942
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001943Warning: This function really has no idea what to do with
1944non-indenting comment lines, and shifts them as if they were indenting
1945comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001946
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001947Special cases: whitespace is deleted from blank lines; continuation
1948lines are shifted by the same amount their initial line was shifted,
1949in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001950initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001951 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001952 (save-excursion
1953 (goto-char end) (beginning-of-line) (setq end (point-marker))
1954 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001955 (let ((py-indent-offset (prefix-numeric-value
1956 (or indent-offset py-indent-offset)))
1957 (indents '(-1)) ; stack of active indent levels
1958 (target-column 0) ; column to which to indent
1959 (base-shifted-by 0) ; amount last base line was shifted
1960 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001961 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001962 0))
1963 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001964 (while (< (point) end)
1965 (setq ci (current-indentation))
1966 ;; figure out appropriate target column
1967 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001968 ((or (eq (following-char) ?#) ; comment in column 1
1969 (looking-at "[ \t]*$")) ; entirely blank
1970 (setq target-column 0))
1971 ((py-continuation-line-p) ; shift relative to base line
1972 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001973 (t ; new base line
1974 (if (> ci (car indents)) ; going deeper; push it
1975 (setq indents (cons ci indents))
1976 ;; else we should have seen this indent before
1977 (setq indents (memq ci indents)) ; pop deeper indents
1978 (if (null indents)
1979 (error "Bad indentation in region, at line %d"
1980 (save-restriction
1981 (widen)
1982 (1+ (count-lines 1 (point)))))))
1983 (setq target-column (+ indent-base
1984 (* py-indent-offset
1985 (- (length indents) 2))))
1986 (setq base-shifted-by (- target-column ci))))
1987 ;; shift as needed
1988 (if (/= ci target-column)
1989 (progn
1990 (delete-horizontal-space)
1991 (indent-to target-column)))
1992 (forward-line 1))))
1993 (set-marker end nil))
1994
Barry Warsawa7891711996-08-01 15:53:09 +00001995(defun py-comment-region (beg end &optional arg)
1996 "Like `comment-region' but uses double hash (`#') comment starter."
1997 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001998 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001999 (comment-region beg end arg)))
2000
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002001
2002;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00002003(defun py-previous-statement (count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002004 "Go to the start of the COUNTth preceding Python statement.
2005By default, goes to the previous statement. If there is no such
2006statement, goes to the first statement. Return count of statements
2007left to move. `Statements' do not include blank, comment, or
2008continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002009 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002010 (if (< count 0) (py-next-statement (- count))
2011 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002012 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002013 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002014 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002015 (> count 0)
2016 (zerop (forward-line -1))
2017 (py-goto-statement-at-or-above))
2018 (setq count (1- count)))
2019 (if (> count 0) (goto-char start)))
2020 count))
2021
2022(defun py-next-statement (count)
2023 "Go to the start of next Python statement.
2024If the statement at point is the i'th Python statement, goes to the
2025start of statement i+COUNT. If there is no such statement, goes to the
2026last statement. Returns count of statements left to move. `Statements'
2027do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002028 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002029 (if (< count 0) (py-previous-statement (- count))
2030 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002031 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002032 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002033 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002034 (> count 0)
2035 (py-goto-statement-below))
2036 (setq count (1- count)))
2037 (if (> count 0) (goto-char start)))
2038 count))
2039
2040(defun py-goto-block-up (&optional nomark)
2041 "Move up to start of current block.
2042Go to the statement that starts the smallest enclosing block; roughly
2043speaking, this will be the closest preceding statement that ends with a
2044colon and is indented less than the statement you started on. If
2045successful, also sets the mark to the starting point.
2046
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002047`\\[py-mark-block]' can be used afterward to mark the whole code
2048block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002049
2050If called from a program, the mark will not be set if optional argument
2051NOMARK is not nil."
2052 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002053 (let ((start (point))
2054 (found nil)
2055 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002056 (py-goto-initial-line)
2057 ;; if on blank or non-indenting comment line, use the preceding stmt
2058 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2059 (progn
2060 (py-goto-statement-at-or-above)
2061 (setq found (py-statement-opens-block-p))))
2062 ;; search back for colon line indented less
2063 (setq initial-indent (current-indentation))
2064 (if (zerop initial-indent)
2065 ;; force fast exit
2066 (goto-char (point-min)))
2067 (while (not (or found (bobp)))
2068 (setq found
2069 (and
2070 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2071 (or (py-goto-initial-line) t) ; always true -- side effect
2072 (< (current-indentation) initial-indent)
2073 (py-statement-opens-block-p))))
2074 (if found
2075 (progn
2076 (or nomark (push-mark start))
2077 (back-to-indentation))
2078 (goto-char start)
2079 (error "Enclosing block not found"))))
2080
Barry Warsawab0e86c1998-05-19 15:31:46 +00002081(defun py-beginning-of-def-or-class (&optional class count)
2082 "Move point to start of `def' or `class'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002083
2084Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsawab0e86c1998-05-19 15:31:46 +00002085arg, looks for a `class' instead. The docs below assume the `def'
2086case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002087Programmatically, if CLASS is `either', then moves to either `class'
2088or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002089
Barry Warsawab0e86c1998-05-19 15:31:46 +00002090When second optional argument is given programmatically, move to the
2091COUNTth start of `def'.
2092
2093If point is in a `def' statement already, and after the `d', simply
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002094moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002095
Barry Warsawab0e86c1998-05-19 15:31:46 +00002096Otherwise (i.e. when point is not in a `def' statement, or at or
2097before the `d' of a `def' statement), searches for the closest
2098preceding `def' statement, and leaves point at its start. If no such
2099statement can be found, leaves point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002100
Barry Warsawab0e86c1998-05-19 15:31:46 +00002101Returns t iff a `def' statement is found by these rules.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002102
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002103Note that doing this command repeatedly will take you closer to the
2104start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002105
Barry Warsaw7c29b231998-07-07 17:45:38 +00002106To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002107 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002108 (if (not count)
2109 (setq count 1))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002110 (let ((at-or-before-p (<= (current-column) (current-indentation)))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002111 (start-of-line (goto-char (py-point 'bol)))
2112 (start-of-stmt (goto-char (py-point 'bos)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002113 (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
2114 (class "^[ \t]*class\\>")
2115 (t "^[ \t]*def\\>")))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002116 )
2117 ;; searching backward
2118 (if (and (< 0 count)
2119 (or (/= start-of-stmt start-of-line)
2120 (not at-or-before-p)))
2121 (end-of-line))
2122 ;; search forward
2123 (if (and (> 0 count)
2124 (zerop (current-column))
2125 (looking-at start-re))
2126 (end-of-line))
2127 (re-search-backward start-re nil 'move count)
2128 (goto-char (match-beginning 0))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002129
Barry Warsawab0e86c1998-05-19 15:31:46 +00002130;; Backwards compatibility
2131(defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002132
Barry Warsawab0e86c1998-05-19 15:31:46 +00002133(defun py-end-of-def-or-class (&optional class count)
2134 "Move point beyond end of `def' or `class' body.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002135
Barry Warsawab0e86c1998-05-19 15:31:46 +00002136By default, looks for an appropriate `def'. If you supply a prefix
2137arg, looks for a `class' instead. The docs below assume the `def'
2138case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002139Programmatically, if CLASS is `either', then moves to either `class'
2140or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002141
Barry Warsawab0e86c1998-05-19 15:31:46 +00002142When second optional argument is given programmatically, move to the
2143COUNTth end of `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002144
Barry Warsawab0e86c1998-05-19 15:31:46 +00002145If point is in a `def' statement already, this is the `def' we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002146
Barry Warsawab0e86c1998-05-19 15:31:46 +00002147Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2148contains the statement you started on, that's the `def' we use.
2149
2150Otherwise, we search forward for the closest following `def', and use that.
2151
2152If a `def' can be found by these rules, point is moved to the start of
2153the line immediately following the `def' block, and the position of the
2154start of the `def' is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002155
2156Else point is moved to the end of the buffer, and nil is returned.
2157
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002158Note that doing this command repeatedly will take you closer to the
2159end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002160
Barry Warsaw7c29b231998-07-07 17:45:38 +00002161To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002162 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002163 (if (and count (/= count 1))
2164 (py-beginning-of-def-or-class (- 1 count)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002165 (let ((start (progn (py-goto-initial-line) (point)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002166 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2167 (class "class")
2168 (t "def")))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002169 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002170 ;; move point to start of appropriate def/class
2171 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2172 (setq state 'at-beginning)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002173 ;; else see if py-beginning-of-def-or-class hits container
2174 (if (and (py-beginning-of-def-or-class class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002175 (progn (py-goto-beyond-block)
2176 (> (point) start)))
2177 (setq state 'at-end)
2178 ;; else search forward
2179 (goto-char start)
2180 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2181 (progn (setq state 'at-beginning)
2182 (beginning-of-line)))))
2183 (cond
2184 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2185 ((eq state 'at-end) t)
2186 ((eq state 'not-found) nil)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002187 (t (error "Internal error in `py-end-of-def-or-class'")))))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002188
2189;; Backwards compabitility
Barry Warsaw820273d1998-05-19 15:54:45 +00002190(defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002191
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002192
2193;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002194(defun py-mark-block (&optional extend just-move)
2195 "Mark following block of lines. With prefix arg, mark structure.
2196Easier to use than explain. It sets the region to an `interesting'
2197block of succeeding lines. If point is on a blank line, it goes down to
2198the next non-blank line. That will be the start of the region. The end
2199of the region depends on the kind of line at the start:
2200
2201 - If a comment, the region will include all succeeding comment lines up
2202 to (but not including) the next non-comment line (if any).
2203
2204 - Else if a prefix arg is given, and the line begins one of these
2205 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002206
2207 if elif else try except finally for while def class
2208
Barry Warsaw7ae77681994-12-12 20:38:05 +00002209 the region will be set to the body of the structure, including
2210 following blocks that `belong' to it, but excluding trailing blank
2211 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002212 and all (if any) of the following `except' and `finally' blocks
2213 that belong to the `try' structure will be in the region. Ditto
2214 for if/elif/else, for/else and while/else structures, and (a bit
2215 degenerate, since they're always one-block structures) def and
2216 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002217
2218 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002219 block (see list above), and the block is not a `one-liner' (i.e.,
2220 the statement ends with a colon, not with code), the region will
2221 include all succeeding lines up to (but not including) the next
2222 code statement (if any) that's indented no more than the starting
2223 line, except that trailing blank and comment lines are excluded.
2224 E.g., if the starting line begins a multi-statement `def'
2225 structure, the region will be set to the full function definition,
2226 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002227
2228 - Else the region will include all succeeding lines up to (but not
2229 including) the next blank line, or code or indenting-comment line
2230 indented strictly less than the starting line. Trailing indenting
2231 comment lines are included in this case, but not trailing blank
2232 lines.
2233
2234A msg identifying the location of the mark is displayed in the echo
2235area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2236
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002237If called from a program, optional argument EXTEND plays the role of
2238the prefix arg, and if optional argument JUST-MOVE is not nil, just
2239moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002240 (interactive "P") ; raw prefix arg
2241 (py-goto-initial-line)
2242 ;; skip over blank lines
2243 (while (and
2244 (looking-at "[ \t]*$") ; while blank line
2245 (not (eobp))) ; & somewhere to go
2246 (forward-line 1))
2247 (if (eobp)
2248 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002249 (let ((initial-pos (point))
2250 (initial-indent (current-indentation))
2251 last-pos ; position of last stmt in region
2252 (followers
2253 '((if elif else) (elif elif else) (else)
2254 (try except finally) (except except) (finally)
2255 (for else) (while else)
2256 (def) (class) ) )
2257 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002258
2259 (cond
2260 ;; if comment line, suck up the following comment lines
2261 ((looking-at "[ \t]*#")
2262 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2263 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2264 (setq last-pos (point)))
2265
2266 ;; else if line is a block line and EXTEND given, suck up
2267 ;; the whole structure
2268 ((and extend
2269 (setq first-symbol (py-suck-up-first-keyword) )
2270 (assq first-symbol followers))
2271 (while (and
2272 (or (py-goto-beyond-block) t) ; side effect
2273 (forward-line -1) ; side effect
2274 (setq last-pos (point)) ; side effect
2275 (py-goto-statement-below)
2276 (= (current-indentation) initial-indent)
2277 (setq next-symbol (py-suck-up-first-keyword))
2278 (memq next-symbol (cdr (assq first-symbol followers))))
2279 (setq first-symbol next-symbol)))
2280
2281 ;; else if line *opens* a block, search for next stmt indented <=
2282 ((py-statement-opens-block-p)
2283 (while (and
2284 (setq last-pos (point)) ; always true -- side effect
2285 (py-goto-statement-below)
2286 (> (current-indentation) initial-indent))
2287 nil))
2288
2289 ;; else plain code line; stop at next blank line, or stmt or
2290 ;; indenting comment line indented <
2291 (t
2292 (while (and
2293 (setq last-pos (point)) ; always true -- side effect
2294 (or (py-goto-beyond-final-line) t)
2295 (not (looking-at "[ \t]*$")) ; stop at blank line
2296 (or
2297 (>= (current-indentation) initial-indent)
2298 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2299 nil)))
2300
2301 ;; skip to end of last stmt
2302 (goto-char last-pos)
2303 (py-goto-beyond-final-line)
2304
2305 ;; set mark & display
2306 (if just-move
2307 () ; just return
2308 (push-mark (point) 'no-msg)
2309 (forward-line -1)
2310 (message "Mark set after: %s" (py-suck-up-leading-text))
2311 (goto-char initial-pos))))
2312
Barry Warsaw2518c671997-11-05 00:51:08 +00002313(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002314 "Set region to body of def (or class, with prefix arg) enclosing point.
2315Pushes the current mark, then point, on the mark ring (all language
2316modes do this, but although it's handy it's never documented ...).
2317
2318In most Emacs language modes, this function bears at least a
Barry Warsawab0e86c1998-05-19 15:31:46 +00002319hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2320`\\[py-beginning-of-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002321
2322And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002323Turned out that was more confusing than useful: the `goto start' and
2324`goto end' commands are usually used to search through a file, and
2325people expect them to act a lot like `search backward' and `search
2326forward' string-search commands. But because Python `def' and `class'
2327can nest to arbitrary levels, finding the smallest def containing
2328point cannot be done via a simple backward search: the def containing
2329point may not be the closest preceding def, or even the closest
2330preceding def that's indented less. The fancy algorithm required is
2331appropriate for the usual uses of this `mark' command, but not for the
2332`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002333
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002334So the def marked by this command may not be the one either of the
2335`goto' commands find: If point is on a blank or non-indenting comment
2336line, moves back to start of the closest preceding code statement or
2337indenting comment line. If this is a `def' statement, that's the def
2338we use. Else searches for the smallest enclosing `def' block and uses
2339that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002340
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002341When an enclosing def is found: The mark is left immediately beyond
2342the last line of the def block. Point is left at the start of the
2343def, except that: if the def is preceded by a number of comment lines
2344followed by (at most) one optional blank line, point is left at the
2345start of the comments; else if the def is preceded by a blank line,
2346point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002347
2348The intent is to mark the containing def/class and its associated
2349documentation, to make moving and duplicating functions and classes
2350pleasant."
2351 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002352 (let ((start (point))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002353 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2354 (class "class")
2355 (t "def"))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002356 (push-mark start)
2357 (if (not (py-go-up-tree-to-keyword which))
2358 (progn (goto-char start)
Barry Warsaw7c29b231998-07-07 17:45:38 +00002359 (error "Enclosing %s not found"
2360 (if (eq class 'either)
2361 "def or class"
2362 which)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002363 ;; else enclosing def/class found
2364 (setq start (point))
2365 (py-goto-beyond-block)
2366 (push-mark (point))
2367 (goto-char start)
2368 (if (zerop (forward-line -1)) ; if there is a preceding line
2369 (progn
2370 (if (looking-at "[ \t]*$") ; it's blank
2371 (setq start (point)) ; so reset start point
2372 (goto-char start)) ; else try again
2373 (if (zerop (forward-line -1))
2374 (if (looking-at "[ \t]*#") ; a comment
2375 ;; look back for non-comment line
2376 ;; tricky: note that the regexp matches a blank
2377 ;; line, cuz \n is in the 2nd character class
2378 (and
2379 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2380 (forward-line 1))
2381 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002382 (goto-char start)))))))
2383 (exchange-point-and-mark)
2384 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002385
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002386;; ripped from cc-mode
2387(defun py-forward-into-nomenclature (&optional arg)
2388 "Move forward to end of a nomenclature section or word.
Barry Warsaw41a05c71998-08-10 16:33:12 +00002389With \\[universal-argument] (programmatically, optional argument ARG),
2390do it that many times.
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002391
2392A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2393 (interactive "p")
2394 (let ((case-fold-search nil))
2395 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002396 (re-search-forward
2397 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2398 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002399 (while (and (< arg 0)
2400 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002401 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002402 (point-min) 0))
2403 (forward-char 1)
2404 (setq arg (1+ arg)))))
2405 (py-keep-region-active))
2406
2407(defun py-backward-into-nomenclature (&optional arg)
2408 "Move backward to beginning of a nomenclature section or word.
2409With optional ARG, move that many times. If ARG is negative, move
2410forward.
2411
2412A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2413 (interactive "p")
2414 (py-forward-into-nomenclature (- arg))
2415 (py-keep-region-active))
2416
2417
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002418
2419;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002420
2421;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002422;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2423;; out of the right places, along with the keys they're on & current
2424;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002425(defun py-dump-help-string (str)
2426 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002427 (let ((locals (buffer-local-variables))
2428 funckind funcname func funcdoc
2429 (start 0) mstart end
2430 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002431 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2432 (setq mstart (match-beginning 0) end (match-end 0)
2433 funckind (substring str (match-beginning 1) (match-end 1))
2434 funcname (substring str (match-beginning 2) (match-end 2))
2435 func (intern funcname))
2436 (princ (substitute-command-keys (substring str start mstart)))
2437 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002438 ((equal funckind "c") ; command
2439 (setq funcdoc (documentation func)
2440 keys (concat
2441 "Key(s): "
2442 (mapconcat 'key-description
2443 (where-is-internal func py-mode-map)
2444 ", "))))
2445 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002446 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002447 keys (if (assq func locals)
2448 (concat
2449 "Local/Global values: "
2450 (prin1-to-string (symbol-value func))
2451 " / "
2452 (prin1-to-string (default-value func)))
2453 (concat
2454 "Value: "
2455 (prin1-to-string (symbol-value func))))))
2456 (t ; unexpected
2457 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002458 (princ (format "\n-> %s:\t%s\t%s\n\n"
2459 (if (equal funckind "c") "Command" "Variable")
2460 funcname keys))
2461 (princ funcdoc)
2462 (terpri)
2463 (setq start end))
2464 (princ (substitute-command-keys (substring str start))))
2465 (print-help-return-message)))
2466
2467(defun py-describe-mode ()
2468 "Dump long form of Python-mode docs."
2469 (interactive)
2470 (py-dump-help-string "Major mode for editing Python files.
2471Knows about Python indentation, tokens, comments and continuation lines.
2472Paragraphs are separated by blank lines only.
2473
2474Major sections below begin with the string `@'; specific function and
2475variable docs begin with `->'.
2476
2477@EXECUTING PYTHON CODE
2478
Barry Warsaw820273d1998-05-19 15:54:45 +00002479\\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002480\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2481\\[py-execute-region]\tsends the current region
Barry Warsaw820273d1998-05-19 15:54:45 +00002482\\[py-execute-def-or-class]\tsends the current function or class definition
2483\\[py-execute-string]\tsends an arbitrary string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002484\\[py-shell]\tstarts a Python interpreter window; this will be used by
Barry Warsaw820273d1998-05-19 15:54:45 +00002485\tsubsequent Python execution commands
2486%c:py-execute-import-or-reload
Barry Warsaw7ae77681994-12-12 20:38:05 +00002487%c:py-execute-buffer
2488%c:py-execute-region
Barry Warsaw820273d1998-05-19 15:54:45 +00002489%c:py-execute-def-or-class
2490%c:py-execute-string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002491%c:py-shell
2492
2493@VARIABLES
2494
2495py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002496py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002497
2498py-python-command\tshell command to invoke Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002499py-temp-directory\tdirectory used for temp files (if needed)
2500
2501py-beep-if-tab-change\tring the bell if tab-width is changed
2502%v:py-indent-offset
2503%v:py-block-comment-prefix
2504%v:py-python-command
Barry Warsaw7ae77681994-12-12 20:38:05 +00002505%v:py-temp-directory
2506%v:py-beep-if-tab-change
2507
2508@KINDS OF LINES
2509
2510Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002511preceding line ends with a backslash that's not part of a comment, or
2512the paren/bracket/brace nesting level at the start of the line is
2513non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002514
2515An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002516possibly blanks or tabs), a `comment line' (leftmost non-blank
2517character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002518
2519Comment Lines
2520
2521Although all comment lines are treated alike by Python, Python mode
2522recognizes two kinds that act differently with respect to indentation.
2523
2524An `indenting comment line' is a comment line with a blank, tab or
2525nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002526treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002527indenting comment line will be indented like the comment line. All
2528other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002529following the initial `#') are `non-indenting comment lines', and
2530their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002531
2532Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002533whenever possible. Non-indenting comment lines are useful in cases
2534like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002535
2536\ta = b # a very wordy single-line comment that ends up being
2537\t #... continued onto another line
2538
2539\tif a == b:
2540##\t\tprint 'panic!' # old code we've `commented out'
2541\t\treturn a
2542
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002543Since the `#...' and `##' comment lines have a non-whitespace
2544character following the initial `#', Python mode ignores them when
2545computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002546
2547Continuation Lines and Statements
2548
2549The Python-mode commands generally work on statements instead of on
2550individual lines, where a `statement' is a comment or blank line, or a
2551code line and all of its following continuation lines (if any)
2552considered as a single logical unit. The commands in this mode
2553generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002554statement containing point, even if point happens to be in the middle
2555of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002556
2557
2558@INDENTATION
2559
2560Primarily for entering new code:
2561\t\\[indent-for-tab-command]\t indent line appropriately
2562\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002563\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002564
2565Primarily for reindenting existing code:
2566\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2567\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2568
2569\t\\[py-indent-region]\t reindent region to match its context
2570\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2571\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2572
2573Unlike most programming languages, Python uses indentation, and only
2574indentation, to specify block structure. Hence the indentation supplied
2575automatically by Python-mode is just an educated guess: only you know
2576the block structure you intend, so only you can supply correct
2577indentation.
2578
2579The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2580the indentation of preceding statements. E.g., assuming
2581py-indent-offset is 4, after you enter
2582\tif a > 0: \\[py-newline-and-indent]
2583the cursor will be moved to the position of the `_' (_ is not a
2584character in the file, it's just used here to indicate the location of
2585the cursor):
2586\tif a > 0:
2587\t _
2588If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2589to
2590\tif a > 0:
2591\t c = d
2592\t _
2593Python-mode cannot know whether that's what you intended, or whether
2594\tif a > 0:
2595\t c = d
2596\t_
2597was your intent. In general, Python-mode either reproduces the
2598indentation of the (closest code or indenting-comment) preceding
2599statement, or adds an extra py-indent-offset blanks if the preceding
2600statement has `:' as its last significant (non-whitespace and non-
2601comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002602\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002603
2604Continuation lines are given extra indentation. If you don't like the
2605suggested indentation, change it to something you do like, and Python-
2606mode will strive to indent later lines of the statement in the same way.
2607
2608If a line is a continuation line by virtue of being in an unclosed
2609paren/bracket/brace structure (`list', for short), the suggested
2610indentation depends on whether the current line contains the first item
2611in the list. If it does, it's indented py-indent-offset columns beyond
2612the indentation of the line containing the open bracket. If you don't
2613like that, change it by hand. The remaining items in the list will mimic
2614whatever indentation you give to the first item.
2615
2616If a line is a continuation line because the line preceding it ends with
2617a backslash, the third and following lines of the statement inherit their
2618indentation from the line preceding them. The indentation of the second
2619line in the statement depends on the form of the first (base) line: if
2620the base line is an assignment statement with anything more interesting
2621than the backslash following the leftmost assigning `=', the second line
2622is indented two columns beyond that `='. Else it's indented to two
2623columns beyond the leftmost solid chunk of non-whitespace characters on
2624the base line.
2625
2626Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2627repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2628structure you intend.
2629%c:indent-for-tab-command
2630%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002631%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002632
2633
2634The next function may be handy when editing code you didn't write:
2635%c:py-guess-indent-offset
2636
2637
2638The remaining `indent' functions apply to a region of Python code. They
2639assume the block structure (equals indentation, in Python) of the region
2640is correct, and alter the indentation in various ways while preserving
2641the block structure:
2642%c:py-indent-region
2643%c:py-shift-region-left
2644%c:py-shift-region-right
2645
2646@MARKING & MANIPULATING REGIONS OF CODE
2647
2648\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002649\\[py-mark-def-or-class]\t mark smallest enclosing def
2650\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002651\\[comment-region]\t comment out region of code
2652\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002653%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002654%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002655%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002656
2657@MOVING POINT
2658
2659\\[py-previous-statement]\t move to statement preceding point
2660\\[py-next-statement]\t move to statement following point
2661\\[py-goto-block-up]\t move up to start of current block
Barry Warsawab0e86c1998-05-19 15:31:46 +00002662\\[py-beginning-of-def-or-class]\t move to start of def
2663\\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
2664\\[py-end-of-def-or-class]\t move to end of def
2665\\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002666
2667The first two move to one statement beyond the statement that contains
2668point. A numeric prefix argument tells them to move that many
2669statements instead. Blank lines, comment lines, and continuation lines
2670do not count as `statements' for these commands. So, e.g., you can go
2671to the first code statement in a file by entering
2672\t\\[beginning-of-buffer]\t to move to the top of the file
2673\t\\[py-next-statement]\t to skip over initial comments and blank lines
2674Or do `\\[py-previous-statement]' with a huge prefix argument.
2675%c:py-previous-statement
2676%c:py-next-statement
2677%c:py-goto-block-up
Barry Warsawab0e86c1998-05-19 15:31:46 +00002678%c:py-beginning-of-def-or-class
2679%c:py-end-of-def-or-class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002680
2681@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2682
2683`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2684
2685`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2686overall class and def structure of a module.
2687
2688`\\[back-to-indentation]' moves point to a line's first non-blank character.
2689
2690`\\[indent-relative]' is handy for creating odd indentation.
2691
2692@OTHER EMACS HINTS
2693
2694If you don't like the default value of a variable, change its value to
2695whatever you do like by putting a `setq' line in your .emacs file.
2696E.g., to set the indentation increment to 4, put this line in your
2697.emacs:
2698\t(setq py-indent-offset 4)
2699To see the value of a variable, do `\\[describe-variable]' and enter the variable
2700name at the prompt.
2701
2702When entering a key sequence like `C-c C-n', it is not necessary to
2703release the CONTROL key after doing the `C-c' part -- it suffices to
2704press the CONTROL key, press and release `c' (while still holding down
2705CONTROL), press and release `n' (while still holding down CONTROL), &
2706then release CONTROL.
2707
2708Entering Python mode calls with no arguments the value of the variable
2709`python-mode-hook', if that value exists and is not nil; for backward
2710compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2711the Elisp manual for details.
2712
2713Obscure: When python-mode is first loaded, it looks for all bindings
2714to newline-and-indent in the global keymap, and shadows them with
2715local bindings to py-newline-and-indent."))
2716
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002717
2718;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002719(defvar py-parse-state-re
2720 (concat
2721 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2722 "\\|"
2723 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002724
Barry Warsaw7ae77681994-12-12 20:38:05 +00002725(defun py-parse-state ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002726 "Return the parse state at point (see `parse-partial-sexp' docs)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002727 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002728 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002729 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002730 (while (not done)
2731 ;; back up to the first preceding line (if any; else start of
2732 ;; buffer) that begins with a popular Python keyword, or a
2733 ;; non- whitespace and non-comment character. These are good
2734 ;; places to start parsing to see whether where we started is
2735 ;; at a non-zero nesting level. It may be slow for people who
2736 ;; write huge code blocks or huge lists ... tough beans.
2737 (re-search-backward py-parse-state-re nil 'move)
2738 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002739 ;; In XEmacs, we have a much better way to test for whether
2740 ;; we're in a triple-quoted string or not. Emacs does not
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002741 ;; have this built-in function, which is its loss because
Barry Warsawf64b4051998-02-12 16:52:14 +00002742 ;; without scanning from the beginning of the buffer, there's
2743 ;; no accurate way to determine this otherwise.
2744 (if (not (fboundp 'buffer-syntactic-context))
2745 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002746 (progn
2747 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002748 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002749 (setq done (or (not (nth 3 pps))
2750 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002751 ;; XEmacs
2752 (setq done (or (not (buffer-syntactic-context))
2753 (bobp)))
2754 (when done
2755 (setq pps (parse-partial-sexp (point) here)))
2756 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002757 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002758
Barry Warsaw7ae77681994-12-12 20:38:05 +00002759(defun py-nesting-level ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002760 "Return the buffer position of the last unclosed enclosing list.
2761If nesting level is zero, return nil."
Barry Warsawf64b4051998-02-12 16:52:14 +00002762 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002763 (if (zerop (car status))
2764 nil ; not in a nest
2765 (car (cdr status))))) ; char# of open bracket
2766
Barry Warsaw7ae77681994-12-12 20:38:05 +00002767(defun py-backslash-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002768 "Return t iff preceding line ends with backslash that is not in a comment."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002769 (save-excursion
2770 (beginning-of-line)
2771 (and
2772 ;; use a cheap test first to avoid the regexp if possible
2773 ;; use 'eq' because char-after may return nil
2774 (eq (char-after (- (point) 2)) ?\\ )
2775 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002776 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002777 (looking-at py-continued-re))))
2778
Barry Warsaw7ae77681994-12-12 20:38:05 +00002779(defun py-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002780 "Return t iff current line is a continuation line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002781 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002782 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002783 (or (py-backslash-continuation-line-p)
2784 (py-nesting-level))))
2785
Barry Warsaw7ae77681994-12-12 20:38:05 +00002786(defun py-goto-initial-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002787 "Go to the initial line of the current statement.
2788Usually this is the line we're on, but if we're on the 2nd or
2789following lines of a continuation block, we need to go up to the first
2790line of the block."
2791 ;; Tricky: We want to avoid quadratic-time behavior for long
2792 ;; continued blocks, whether of the backslash or open-bracket
2793 ;; varieties, or a mix of the two. The following manages to do that
2794 ;; in the usual cases.
2795 ;;
2796 ;; Also, if we're sitting inside a triple quoted string, this will
2797 ;; drop us at the line that begins the string.
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002798 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002799 (while (py-continuation-line-p)
2800 (beginning-of-line)
2801 (if (py-backslash-continuation-line-p)
2802 (while (py-backslash-continuation-line-p)
2803 (forward-line -1))
2804 ;; else zip out of nested brackets/braces/parens
2805 (while (setq open-bracket-pos (py-nesting-level))
2806 (goto-char open-bracket-pos)))))
2807 (beginning-of-line))
2808
Barry Warsaw7ae77681994-12-12 20:38:05 +00002809(defun py-goto-beyond-final-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002810 "Go to the point just beyond the fine line of the current statement.
2811Usually this is the start of the next line, but if this is a
2812multi-line statement we need to skip over the continuation lines."
2813 ;; Tricky: Again we need to be clever to avoid quadratic time
2814 ;; behavior.
2815 ;;
2816 ;; XXX: Not quite the right solution, but deals with multi-line doc
2817 ;; strings
Barry Warsaw751f4931998-05-19 16:06:21 +00002818 (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
2819 (goto-char (match-end 0)))
2820 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +00002821 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002822 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002823 (while (and (py-continuation-line-p)
2824 (not (eobp)))
2825 ;; skip over the backslash flavor
2826 (while (and (py-backslash-continuation-line-p)
2827 (not (eobp)))
2828 (forward-line 1))
2829 ;; if in nest, zip to the end of the nest
2830 (setq state (py-parse-state))
2831 (if (and (not (zerop (car state)))
2832 (not (eobp)))
2833 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002834 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002835 (forward-line 1))))))
2836
Barry Warsaw7ae77681994-12-12 20:38:05 +00002837(defun py-statement-opens-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002838 "Return t iff the current statement opens a block.
2839I.e., iff it ends with a colon that is not in a comment. Point should
2840be at the start of a statement."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002841 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002842 (let ((start (point))
2843 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2844 (searching t)
2845 (answer nil)
2846 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002847 (goto-char start)
2848 (while searching
2849 ;; look for a colon with nothing after it except whitespace, and
2850 ;; maybe a comment
2851 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2852 finish t)
2853 (if (eq (point) finish) ; note: no `else' clause; just
2854 ; keep searching if we're not at
2855 ; the end yet
2856 ;; sure looks like it opens a block -- but it might
2857 ;; be in a comment
2858 (progn
2859 (setq searching nil) ; search is done either way
2860 (setq state (parse-partial-sexp start
2861 (match-beginning 0)))
2862 (setq answer (not (nth 4 state)))))
2863 ;; search failed: couldn't find another interesting colon
2864 (setq searching nil)))
2865 answer)))
2866
Barry Warsawf831d811996-07-31 20:42:59 +00002867(defun py-statement-closes-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002868 "Return t iff the current statement closes a block.
2869I.e., if the line starts with `return', `raise', `break', `continue',
2870and `pass'. This doesn't catch embedded statements."
Barry Warsawf831d811996-07-31 20:42:59 +00002871 (let ((here (point)))
2872 (back-to-indentation)
2873 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002874 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002875 (goto-char here))))
2876
Barry Warsaw7ae77681994-12-12 20:38:05 +00002877(defun py-goto-beyond-block ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002878 "Go to point just beyond the final line of block begun by the current line.
2879This is the same as where `py-goto-beyond-final-line' goes unless
2880we're on colon line, in which case we go to the end of the block.
2881Assumes point is at the beginning of the line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002882 (if (py-statement-opens-block-p)
2883 (py-mark-block nil 'just-move)
2884 (py-goto-beyond-final-line)))
2885
Barry Warsaw7ae77681994-12-12 20:38:05 +00002886(defun py-goto-statement-at-or-above ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002887 "Go to the start of the first statement at or preceding point.
2888Return t if there is such a statement, otherwise nil. `Statement'
2889does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002890 (py-goto-initial-line)
2891 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002892 ;; skip back over blank & comment lines
2893 ;; note: will skip a blank or comment line that happens to be
2894 ;; a continuation line too
2895 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2896 (progn (py-goto-initial-line) t)
2897 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002898 t))
2899
Barry Warsaw7ae77681994-12-12 20:38:05 +00002900(defun py-goto-statement-below ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002901 "Go to start of the first statement following the statement containing point.
2902Return t if there is such a statement, otherwise nil. `Statement'
2903does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002904 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002905 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002906 (py-goto-beyond-final-line)
2907 (while (and
2908 (looking-at py-blank-or-comment-re)
2909 (not (eobp)))
2910 (forward-line 1))
2911 (if (eobp)
2912 (progn (goto-char start) nil)
2913 t)))
2914
Barry Warsaw7ae77681994-12-12 20:38:05 +00002915(defun py-go-up-tree-to-keyword (key)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002916 "Go to begining of statement starting with KEY, at or preceding point.
2917
2918KEY is a regular expression describing a Python keyword. Skip blank
2919lines and non-indenting comments. If the statement found starts with
2920KEY, then stop, otherwise go back to first enclosing block starting
2921with KEY. If successful, leave point at the start of the KEY line and
2922return t. Otherwise, leav point at an undefined place and return nil."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002923 ;; skip blanks and non-indenting #
2924 (py-goto-initial-line)
2925 (while (and
2926 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2927 (zerop (forward-line -1))) ; go back
2928 nil)
2929 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002930 (let* ((re (concat "[ \t]*" key "\\b"))
2931 (case-fold-search nil) ; let* so looking-at sees this
2932 (found (looking-at re))
2933 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002934 (while (not (or found dead))
2935 (condition-case nil ; in case no enclosing block
2936 (py-goto-block-up 'no-mark)
2937 (error (setq dead t)))
2938 (or dead (setq found (looking-at re))))
2939 (beginning-of-line)
2940 found))
2941
Barry Warsaw7ae77681994-12-12 20:38:05 +00002942(defun py-suck-up-leading-text ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002943 "Return string in buffer from start of indentation to end of line.
2944Prefix with \"...\" if leading whitespace was skipped."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002945 (save-excursion
2946 (back-to-indentation)
2947 (concat
2948 (if (bolp) "" "...")
2949 (buffer-substring (point) (progn (end-of-line) (point))))))
2950
Barry Warsaw7ae77681994-12-12 20:38:05 +00002951(defun py-suck-up-first-keyword ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002952 "Return first keyword on the line as a Lisp symbol.
2953`Keyword' is defined (essentially) as the regular expression
2954([a-z]+). Returns nil if none was found."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002955 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002956 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2957 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2958 nil)))
2959
Barry Warsawb3e81d51996-09-04 15:12:42 +00002960(defun py-current-defun ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002961 "Python value for `add-log-current-defun-function'.
2962This tells add-log.el how to find the current function/method/variable."
Barry Warsawb3e81d51996-09-04 15:12:42 +00002963 (save-excursion
2964 (if (re-search-backward py-defun-start-re nil t)
2965 (or (match-string 3)
2966 (let ((method (match-string 2)))
2967 (if (and (not (zerop (length (match-string 1))))
2968 (re-search-backward py-class-start-re nil t))
2969 (concat (match-string 1) "." method)
2970 method)))
2971 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002972
2973
Barry Warsawfec75d61995-07-05 23:26:15 +00002974(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002975 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002976
Barry Warsaw850437a1995-03-08 21:50:28 +00002977(defun py-version ()
2978 "Echo the current version of `python-mode' in the minibuffer."
2979 (interactive)
2980 (message "Using `python-mode' version %s" py-version)
2981 (py-keep-region-active))
2982
2983;; only works under Emacs 19
2984;(eval-when-compile
2985; (require 'reporter))
2986
2987(defun py-submit-bug-report (enhancement-p)
2988 "Submit via mail a bug report on `python-mode'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00002989With \\[universal-argument] (programmatically, argument ENHANCEMENT-P
2990non-nil) just submit an enhancement request."
Barry Warsaw850437a1995-03-08 21:50:28 +00002991 (interactive
2992 (list (not (y-or-n-p
Barry Warsaw41a05c71998-08-10 16:33:12 +00002993 "Is this a bug report (hit `n' to send other comments)? "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002994 (let ((reporter-prompt-for-summary-p (if enhancement-p
2995 "(Very) brief summary: "
2996 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002997 (require 'reporter)
2998 (reporter-submit-bug-report
2999 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00003000 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00003001 ;; varlist
3002 (if enhancement-p nil
3003 '(py-python-command
3004 py-indent-offset
3005 py-block-comment-prefix
Barry Warsaw850437a1995-03-08 21:50:28 +00003006 py-temp-directory
3007 py-beep-if-tab-change))
3008 nil ;pre-hooks
3009 nil ;post-hooks
3010 "Dear Barry,") ;salutation
3011 (if enhancement-p nil
3012 (set-mark (point))
3013 (insert
3014"Please replace this text with a sufficiently large code sample\n\
3015and an exact recipe so that I can reproduce your problem. Failure\n\
3016to do so may mean a greater delay in fixing your bug.\n\n")
3017 (exchange-point-and-mark)
3018 (py-keep-region-active))))
3019
3020
Barry Warsaw47384781997-11-26 05:27:45 +00003021(defun py-kill-emacs-hook ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003022 "Delete files in `py-file-queue'.
3023These are Python temporary files awaiting execution."
Barry Warsaw47384781997-11-26 05:27:45 +00003024 (mapcar #'(lambda (filename)
3025 (py-safe (delete-file filename)))
3026 py-file-queue))
3027
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003028;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00003029(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003030
3031
3032
3033(provide 'python-mode)
3034;;; python-mode.el ends here