blob: 558d7667e5ebdf59e39a15a175fe5f00ba348992 [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
67;; Please see <http://www.python.org/ftp/emacs/pmdetails.html> for the
68;; 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
161 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000162Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +0000163when you're editing someone else's Python code."
164 :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
215opposed to one that starts with `py-block-comment-prefix'), then it's
216indentation 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 Warsaw8ee4a601998-02-06 16:01:52 +0000230(defcustom py-scroll-process-buffer nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000231 "*Scroll Python process buffer as output arrives.
232If nil, the Python process buffer acts, with respect to scrolling, like
233Shell-mode buffers normally act. This is surprisingly complicated and
234so won't be explained here; in fact, you can't get the whole story
235without studying the Emacs C code.
236
237If non-nil, the behavior is different in two respects (which are
238slightly inaccurate in the interest of brevity):
239
240 - If the buffer is in a window, and you left point at its end, the
241 window will scroll as new output arrives, and point will move to the
242 buffer's end, even if the window is not the selected window (that
243 being the one the cursor is in). The usual behavior for shell-mode
244 windows is not to scroll, and to leave point where it was, if the
245 buffer is in a window other than the selected window.
246
247 - If the buffer is not visible in any window, and you left point at
248 its end, the buffer will be popped into a window as soon as more
249 output arrives. This is handy if you have a long-running
250 computation and don't want to tie up screen area waiting for the
251 output. The usual behavior for a shell-mode buffer is to stay
252 invisible until you explicitly visit it.
253
254Note the `and if you left point at its end' clauses in both of the
255above: you can `turn off' the special behaviors while output is in
256progress, by visiting the Python buffer and moving point to anywhere
257besides the end. Then the buffer won't scroll, point will remain where
258you leave it, and if you hide the buffer it will stay hidden until you
259visit it again. You can enable and disable the special behaviors as
260often as you like, while output is in progress, by (respectively) moving
261point to, or away from, the end of the buffer.
262
263Warning: If you expect a large amount of output, you'll probably be
264happier setting this option to nil.
265
266Obscure: `End of buffer' above should really say `at or beyond the
267process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000268told <grin>."
269 :type 'boolean
270 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000271
Barry Warsaw516b6201997-08-09 06:43:20 +0000272(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000273 (let ((ok '(lambda (x)
274 (and x
275 (setq x (expand-file-name x)) ; always true
276 (file-directory-p x)
277 (file-writable-p x)
278 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000279 (or (funcall ok (getenv "TMPDIR"))
280 (funcall ok "/usr/tmp")
281 (funcall ok "/tmp")
282 (funcall ok ".")
283 (error
Barry Warsaw6c6db0a1998-02-25 16:33:56 +0000284 "Couldn't find a usable temp directory -- set `py-temp-directory'")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000285 "*Directory used for temp files created by a *Python* process.
286By default, the first directory from this list that exists and that you
287can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000288/usr/tmp, /tmp, or the current directory."
289 :type 'string
290 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000291
Barry Warsaw516b6201997-08-09 06:43:20 +0000292(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000293 "*Ring the bell if tab-width is changed.
294If a comment of the form
295
296 \t# vi:set tabsize=<number>:
297
298is found before the first code line when the file is entered, and the
299current value of (the general Emacs variable) `tab-width' does not
300equal <number>, `tab-width' is set to <number>, a message saying so is
301displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000302the Emacs bell is also rung as a warning."
303 :type 'boolean
304 :group 'python)
305
Barry Warsaw9981d221997-12-03 05:25:48 +0000306(defcustom py-jump-on-exception t
307 "*Jump to innermost exception frame in *Python Output* buffer.
308When this variable is non-nil and ane exception occurs when running
309Python code synchronously in a subprocess, jump immediately to the
310source code of the innermost frame.")
311
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000312(defcustom py-backspace-function 'backward-delete-char-untabify
313 "*Function called by `py-electric-backspace' when deleting backwards."
314 :type 'function
315 :group 'python)
316
317(defcustom py-delete-function 'delete-char
318 "*Function called by `py-electric-delete' when deleting forwards."
319 :type 'function
320 :group 'python)
321
Barry Warsawc0ecb531998-01-20 21:43:34 +0000322;; Not customizable
323(defvar py-master-file nil
324 "If non-nil, execute the named file instead of the buffer's file.
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000325The intent is to allow you to set this variable in the file's local
Barry Warsawc0ecb531998-01-20 21:43:34 +0000326variable section, e.g.:
327
328 # Local Variables:
329 # py-master-file: \"master.py\"
330 # End:
331
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000332so that typing \\[py-execute-buffer] in that buffer executes the
Barry Warsawc0ecb531998-01-20 21:43:34 +0000333named master file instead of the buffer's file. Note that if the file
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000334name has a relative path, the `default-directory' for the buffer is
335prepended to come up with a file name.")
Barry Warsawc0ecb531998-01-20 21:43:34 +0000336(make-variable-buffer-local 'py-master-file)
337
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000338
Barry Warsawc72c11c1997-08-09 06:42:08 +0000339
340;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
341;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
342
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000343(defconst py-emacs-features
344 (let (features)
345 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
346 ;; the same string.
347 (let ((tmp1 (make-temp-name ""))
348 (tmp2 (make-temp-name "")))
349 (if (string-equal tmp1 tmp2)
350 (push 'broken-temp-names features)))
351 ;; return the features
352 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000353 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000354There are many flavors of Emacs out there, with different levels of
355support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000356
Barry Warsawfb07f401997-02-24 03:37:22 +0000357(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000358 (let ((kw1 (mapconcat 'identity
359 '("and" "assert" "break" "class"
360 "continue" "def" "del" "elif"
361 "else" "except" "exec" "for"
362 "from" "global" "if" "import"
363 "in" "is" "lambda" "not"
364 "or" "pass" "print" "raise"
365 "return" "while"
366 )
367 "\\|"))
368 (kw2 (mapconcat 'identity
369 '("else:" "except:" "finally:" "try:")
370 "\\|"))
371 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000372 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000373 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000374 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
375 ;; block introducing keywords with immediately following colons.
376 ;; Yes "except" is in both lists.
377 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000378 ;; classes
379 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
380 1 font-lock-type-face)
381 ;; functions
382 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
383 1 font-lock-function-name-face)
384 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000385 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000386(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
387
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000388
Barry Warsaw81437461996-08-01 19:48:02 +0000389(defvar imenu-example--python-show-method-args-p nil
390 "*Controls echoing of arguments of functions & methods in the imenu buffer.
391When non-nil, arguments are printed.")
392
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000393(make-variable-buffer-local 'py-indent-offset)
394
Barry Warsawe467bfb1997-11-26 05:40:58 +0000395;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000396(defvar py-file-queue nil
397 "Queue of Python temp files awaiting execution.
398Currently-active file is at the head of the list.")
399
Barry Warsawc72c11c1997-08-09 06:42:08 +0000400
401;; Constants
402
403;; Regexp matching a Python string literal
404(defconst py-stringlit-re
405 (concat
406 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
407 "\\|" ; or
408 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
409
410;; Regexp matching Python lines that are continued via backslash.
411;; This is tricky because a trailing backslash does not mean
412;; continuation if it's in a comment
413(defconst py-continued-re
414 (concat
415 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
416 "\\\\$"))
417
418;; Regexp matching blank or comment lines.
419(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
420
421;; Regexp matching clauses to be outdented one level.
422(defconst py-outdent-re
423 (concat "\\(" (mapconcat 'identity
424 '("else:"
425 "except\\(\\s +.*\\)?:"
426 "finally:"
427 "elif\\s +.*:")
428 "\\|")
429 "\\)"))
430
431
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000432;; Regexp matching keywords which typically close a block
433(defconst py-block-closing-keywords-re
434 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
435
Barry Warsawc72c11c1997-08-09 06:42:08 +0000436;; Regexp matching lines to not outdent after.
437(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000438 (concat
439 "\\("
440 (mapconcat 'identity
441 (list "try:"
442 "except\\(\\s +.*\\)?:"
443 "while\\s +.*:"
444 "for\\s +.*:"
445 "if\\s +.*:"
446 "elif\\s +.*:"
447 (concat py-block-closing-keywords-re "[ \t\n]")
448 )
449 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000450 "\\)"))
451
452;; Regexp matching a function, method or variable assignment. If you
453;; change this, you probably have to change `py-current-defun' as
454;; well. This is only used by `py-current-defun' to find the name for
455;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000456(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000457 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
458
459;; Regexp for finding a class name. If you change this, you probably
460;; have to change `py-current-defun' as well. This is only used by
461;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000462(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
463
464;; Regexp that describes tracebacks
465(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000466 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000467
468
469
470;; Utilities
471
472(defmacro py-safe (&rest body)
473 ;; safely execute BODY, return nil if an error occurred
474 (` (condition-case nil
475 (progn (,@ body))
476 (error nil))))
477
478(defsubst py-keep-region-active ()
479 ;; Do whatever is necessary to keep the region active in XEmacs.
480 ;; Ignore byte-compiler warnings you might see. Also note that
481 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
482 ;; to take explicit action.
483 (and (boundp 'zmacs-region-stays)
484 (setq zmacs-region-stays t)))
485
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000486(defsubst py-point (position)
487 ;; Returns the value of point at certain commonly referenced POSITIONs.
488 ;; POSITION can be one of the following symbols:
489 ;;
490 ;; bol -- beginning of line
491 ;; eol -- end of line
492 ;; bod -- beginning of defun
493 ;; boi -- back to indentation
494 ;;
495 ;; This function does not modify point or mark.
496 (let ((here (point)))
497 (cond
498 ((eq position 'bol) (beginning-of-line))
499 ((eq position 'eol) (end-of-line))
500 ((eq position 'bod) (beginning-of-python-def-or-class))
501 ((eq position 'bob) (beginning-of-buffer))
502 ((eq position 'eob) (end-of-buffer))
503 ((eq position 'boi) (back-to-indentation))
504 (t (error "unknown buffer position requested: %s" position))
505 )
506 (prog1
507 (point)
508 (goto-char here))))
509
510(defsubst py-highlight-line (from to file line)
511 (cond
512 ((fboundp 'make-extent)
513 ;; XEmacs
514 (let ((e (make-extent from to)))
515 (set-extent-property e 'mouse-face 'highlight)
516 (set-extent-property e 'py-exc-info (cons file line))
517 (set-extent-property e 'keymap py-mode-output-map)))
518 (t
519 ;; Emacs -- Please port this!
520 )
521 ))
522
Barry Warsawe908b6b1998-03-19 22:48:02 +0000523(defun py-in-literal (&optional lim)
524 ;; Determine if point is in a Python literal, defined as a comment
525 ;; or string. This is the version used for non-XEmacs, which has a
526 ;; nicer interface.
527 ;;
528 ;; WARNING: Watch out for infinite recursion.
529 (let* ((lim (or lim (c-point 'bod)))
530 (state (parse-partial-sexp lim (point))))
531 (cond
532 ((nth 3 state) 'string)
533 ((nth 4 state) 'comment)
534 (t nil))))
535
536;; XEmacs has a built-in function that should make this much quicker.
537;; In this case, lim is ignored
538(defun py-fast-in-literal (&optional lim)
539 ;; don't have to worry about context == 'block-comment
540 (buffer-syntactic-context))
541
542(if (fboundp 'buffer-syntactic-context)
543 (defalias 'c-in-literal 'c-fast-in-literal))
544
545
Barry Warsawc72c11c1997-08-09 06:42:08 +0000546
547;; Major mode boilerplate
548
Barry Warsaw7ae77681994-12-12 20:38:05 +0000549;; define a mode-specific abbrev table for those who use such things
550(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000551 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000552(define-abbrev-table 'python-mode-abbrev-table nil)
553
Barry Warsaw7ae77681994-12-12 20:38:05 +0000554(defvar python-mode-hook nil
555 "*Hook called by `python-mode'.")
556
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000557;; in previous version of python-mode.el, the hook was incorrectly
558;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000559(and (fboundp 'make-obsolete-variable)
560 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
561
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000562(defvar py-mode-map ()
563 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000564(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000565 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000566 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000567 ;; electric keys
568 (define-key py-mode-map ":" 'py-electric-colon)
569 ;; indentation level modifiers
570 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
571 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
572 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
573 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
574 ;; subprocess commands
575 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
576 (define-key py-mode-map "\C-c|" 'py-execute-region)
577 (define-key py-mode-map "\C-c!" 'py-shell)
Barry Warsawa2398801998-04-09 23:28:20 +0000578 (define-key py-mode-map "\C-c\C-t" 'py-toggle-shells)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000579 ;; Caution! Enter here at your own risk. We are trying to support
580 ;; several behaviors and it gets disgusting. :-( This logic ripped
581 ;; largely from CC Mode.
582 ;;
583 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
584 ;; backwards deletion behavior to DEL, which both Delete and
585 ;; Backspace get translated to. There's no way to separate this
586 ;; behavior in a clean way, so deal with it! Besides, it's been
587 ;; this way since the dawn of time.
588 (if (not (boundp 'delete-key-deletes-forward))
589 (define-key py-mode-map "\177" 'py-electric-backspace)
590 ;; However, XEmacs 20 actually achieved enlightenment. It is
591 ;; possible to sanely define both backward and forward deletion
592 ;; behavior under X separately (TTYs are forever beyond hope, but
593 ;; who cares? XEmacs 20 does the right thing with these too).
594 (define-key py-mode-map [delete] 'py-electric-delete)
595 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000596 ;; Separate M-BS from C-M-h. The former should remain
597 ;; backward-kill-word.
598 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000599 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000600 ;; Miscellaneous
601 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
602 (define-key py-mode-map "\C-c\t" 'py-indent-region)
603 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
604 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
605 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000606 (define-key py-mode-map "\C-c#" 'py-comment-region)
607 (define-key py-mode-map "\C-c?" 'py-describe-mode)
608 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
609 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
610 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000611 (define-key py-mode-map "\C-c-" 'py-up-exception)
612 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000613 ;; information
614 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
615 (define-key py-mode-map "\C-c\C-v" 'py-version)
616 ;; py-newline-and-indent mappings
Barry Warsaw82aecb91998-01-21 05:14:24 +0000617 (define-key py-mode-map "\n" 'py-newline-and-indent)
618 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000619 ;; shadow global bindings for newline-and-indent w/ the py- version.
620 ;; BAW - this is extremely bad form, but I'm not going to change it
621 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000622 (mapcar #'(lambda (key)
623 (define-key py-mode-map key 'py-newline-and-indent))
624 (where-is-internal 'newline-and-indent))
625 )
626
627(defvar py-mode-output-map nil
628 "Keymap used in *Python Output* buffers*")
629(if py-mode-output-map
630 nil
631 (setq py-mode-output-map (make-sparse-keymap))
632 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
633 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
634 ;; TBD: Disable all self-inserting keys. This is bogus, we should
635 ;; really implement this as *Python Output* buffer being read-only
636 (mapcar #' (lambda (key)
637 (define-key py-mode-output-map key
638 #'(lambda () (interactive) (beep))))
639 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000640 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000641
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000642(defvar py-mode-syntax-table nil
643 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000644(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000645 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000646 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000647 (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 ;; Add operator symbols misassigned in the std 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 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
659 (modify-syntax-entry ?\- "." py-mode-syntax-table)
660 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
661 (modify-syntax-entry ?\< "." py-mode-syntax-table)
662 (modify-syntax-entry ?\= "." py-mode-syntax-table)
663 (modify-syntax-entry ?\> "." py-mode-syntax-table)
664 (modify-syntax-entry ?\| "." py-mode-syntax-table)
665 ;; For historical reasons, underscore is word class instead of
666 ;; symbol class. GNU conventions say it should be symbol class, but
667 ;; there's a natural conflict between what major mode authors want
668 ;; and what users expect from `forward-word' and `backward-word'.
669 ;; Guido and I have hashed this out and have decided to keep
670 ;; underscore in word class. If you're tempted to change it, try
671 ;; binding M-f and M-b to py-forward-into-nomenclature and
672 ;; py-backward-into-nomenclature instead.
673 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
674 ;; Both single quote and double quote are string delimiters
675 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
676 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
677 ;; backquote is open and close paren
678 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
679 ;; comment delimiters
680 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
681 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
682 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000683
Barry Warsawb3e81d51996-09-04 15:12:42 +0000684
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000685
Barry Warsaw42f707f1996-07-29 21:05:05 +0000686;; Menu definitions, only relevent if you have the easymenu.el package
687;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000688(defvar py-menu nil
689 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000690This menu will get created automatically if you have the `easymenu'
691package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000692
Barry Warsawc72c11c1997-08-09 06:42:08 +0000693(and (py-safe (require 'easymenu) t)
694 (easy-menu-define
695 py-menu py-mode-map "Python Mode menu"
696 '("Python"
697 ["Comment Out Region" py-comment-region (mark)]
698 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
699 "-"
700 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000701 ["Mark current def" py-mark-def-or-class t]
702 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000703 "-"
704 ["Shift region left" py-shift-region-left (mark)]
705 ["Shift region right" py-shift-region-right (mark)]
706 "-"
707 ["Execute buffer" py-execute-buffer t]
708 ["Execute region" py-execute-region (mark)]
709 ["Start interpreter..." py-shell t]
710 "-"
711 ["Go to start of block" py-goto-block-up t]
712 ["Go to start of class" (beginning-of-python-def-or-class t) t]
713 ["Move to end of class" (end-of-python-def-or-class t) t]
714 ["Move to start of def" beginning-of-python-def-or-class t]
715 ["Move to end of def" end-of-python-def-or-class t]
716 "-"
717 ["Describe mode" py-describe-mode t]
718 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000719
Barry Warsaw81437461996-08-01 19:48:02 +0000720
721
722;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
723(defvar imenu-example--python-class-regexp
724 (concat ; <<classes>>
725 "\\(" ;
726 "^[ \t]*" ; newline and maybe whitespace
727 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
728 ; possibly multiple superclasses
Barry Warsaw3179fe01998-04-04 21:36:53 +0000729 "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
Barry Warsaw81437461996-08-01 19:48:02 +0000730 "[ \t]*:" ; and the final :
731 "\\)" ; >>classes<<
732 )
733 "Regexp for Python classes for use with the imenu package."
734 )
735
736(defvar imenu-example--python-method-regexp
737 (concat ; <<methods and functions>>
738 "\\(" ;
739 "^[ \t]*" ; new line and maybe whitespace
740 "\\(def[ \t]+" ; function definitions start with def
741 "\\([a-zA-Z0-9_]+\\)" ; name is here
742 ; function arguments...
743 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
744 "\\)" ; end of def
745 "[ \t]*:" ; and then the :
746 "\\)" ; >>methods and functions<<
747 )
748 "Regexp for Python methods/functions for use with the imenu package."
749 )
750
751(defvar imenu-example--python-method-no-arg-parens '(2 8)
752 "Indicies into groups of the Python regexp for use with imenu.
753
754Using these values will result in smaller imenu lists, as arguments to
755functions are not listed.
756
757See the variable `imenu-example--python-show-method-args-p' for more
758information.")
759
760(defvar imenu-example--python-method-arg-parens '(2 7)
761 "Indicies into groups of the Python regexp for use with imenu.
762Using these values will result in large imenu lists, as arguments to
763functions are listed.
764
765See the variable `imenu-example--python-show-method-args-p' for more
766information.")
767
768;; Note that in this format, this variable can still be used with the
769;; imenu--generic-function. Otherwise, there is no real reason to have
770;; it.
771(defvar imenu-example--generic-python-expression
772 (cons
773 (concat
774 imenu-example--python-class-regexp
775 "\\|" ; or...
776 imenu-example--python-method-regexp
777 )
778 imenu-example--python-method-no-arg-parens)
779 "Generic Python expression which may be used directly with imenu.
780Used by setting the variable `imenu-generic-expression' to this value.
781Also, see the function \\[imenu-example--create-python-index] for a
782better alternative for finding the index.")
783
784;; These next two variables are used when searching for the python
785;; class/definitions. Just saving some time in accessing the
786;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000787(defvar imenu-example--python-generic-regexp nil)
788(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000789
790
Barry Warsaw81437461996-08-01 19:48:02 +0000791(defun imenu-example--create-python-index ()
792 "Python interface function for imenu package.
793Finds all python classes and functions/methods. Calls function
794\\[imenu-example--create-python-index-engine]. See that function for
795the details of how this works."
796 (setq imenu-example--python-generic-regexp
797 (car imenu-example--generic-python-expression))
798 (setq imenu-example--python-generic-parens
799 (if imenu-example--python-show-method-args-p
800 imenu-example--python-method-arg-parens
801 imenu-example--python-method-no-arg-parens))
802 (goto-char (point-min))
803 (imenu-example--create-python-index-engine nil))
804
805(defun imenu-example--create-python-index-engine (&optional start-indent)
806 "Function for finding imenu definitions in Python.
807
808Finds all definitions (classes, methods, or functions) in a Python
809file for the imenu package.
810
811Returns a possibly nested alist of the form
812
813 (INDEX-NAME . INDEX-POSITION)
814
815The second element of the alist may be an alist, producing a nested
816list as in
817
818 (INDEX-NAME . INDEX-ALIST)
819
820This function should not be called directly, as it calls itself
821recursively and requires some setup. Rather this is the engine for
822the function \\[imenu-example--create-python-index].
823
824It works recursively by looking for all definitions at the current
825indention level. When it finds one, it adds it to the alist. If it
826finds a definition at a greater indentation level, it removes the
827previous definition from the alist. In it's place it adds all
828definitions found at the next indentation level. When it finds a
829definition that is less indented then the current level, it retuns the
830alist it has created thus far.
831
832The optional argument START-INDENT indicates the starting indentation
833at which to continue looking for Python classes, methods, or
834functions. If this is not supplied, the function uses the indentation
835of the first definition found."
836 (let ((index-alist '())
837 (sub-method-alist '())
838 looking-p
839 def-name prev-name
840 cur-indent def-pos
841 (class-paren (first imenu-example--python-generic-parens))
842 (def-paren (second imenu-example--python-generic-parens)))
843 (setq looking-p
844 (re-search-forward imenu-example--python-generic-regexp
845 (point-max) t))
846 (while looking-p
847 (save-excursion
848 ;; used to set def-name to this value but generic-extract-name is
849 ;; new to imenu-1.14. this way it still works with imenu-1.11
850 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
851 (let ((cur-paren (if (match-beginning class-paren)
852 class-paren def-paren)))
853 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000854 (buffer-substring-no-properties (match-beginning cur-paren)
855 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000856 (beginning-of-line)
857 (setq cur-indent (current-indentation)))
858
859 ;; HACK: want to go to the next correct definition location. we
860 ;; explicitly list them here. would be better to have them in a
861 ;; list.
862 (setq def-pos
863 (or (match-beginning class-paren)
864 (match-beginning def-paren)))
865
866 ;; if we don't have a starting indent level, take this one
867 (or start-indent
868 (setq start-indent cur-indent))
869
870 ;; if we don't have class name yet, take this one
871 (or prev-name
872 (setq prev-name def-name))
873
874 ;; what level is the next definition on? must be same, deeper
875 ;; or shallower indentation
876 (cond
877 ;; at the same indent level, add it to the list...
878 ((= start-indent cur-indent)
879
880 ;; if we don't have push, use the following...
881 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
882 (push (cons def-name def-pos) index-alist))
883
884 ;; deeper indented expression, recur...
885 ((< start-indent cur-indent)
886
887 ;; the point is currently on the expression we're supposed to
888 ;; start on, so go back to the last expression. The recursive
889 ;; call will find this place again and add it to the correct
890 ;; list
891 (re-search-backward imenu-example--python-generic-regexp
892 (point-min) 'move)
893 (setq sub-method-alist (imenu-example--create-python-index-engine
894 cur-indent))
895
896 (if sub-method-alist
897 ;; we put the last element on the index-alist on the start
898 ;; of the submethod alist so the user can still get to it.
899 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000900 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000901 (cons save-elmt sub-method-alist))
902 index-alist))))
903
904 ;; found less indented expression, we're done.
905 (t
906 (setq looking-p nil)
907 (re-search-backward imenu-example--python-generic-regexp
908 (point-min) t)))
909 (setq prev-name def-name)
910 (and looking-p
911 (setq looking-p
912 (re-search-forward imenu-example--python-generic-regexp
913 (point-max) 'move))))
914 (nreverse index-alist)))
915
Barry Warsaw42f707f1996-07-29 21:05:05 +0000916
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000917;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000918(defun python-mode ()
919 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000920To submit a problem report, enter `\\[py-submit-bug-report]' from a
921`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
922documentation. To see what version of `python-mode' you are running,
923enter `\\[py-version]'.
924
925This mode knows about Python indentation, tokens, comments and
926continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000927
928COMMANDS
929\\{py-mode-map}
930VARIABLES
931
Barry Warsaw42f707f1996-07-29 21:05:05 +0000932py-indent-offset\t\tindentation increment
933py-block-comment-prefix\t\tcomment string used by comment-region
934py-python-command\t\tshell command to invoke Python interpreter
935py-scroll-process-buffer\t\talways scroll Python process buffer
936py-temp-directory\t\tdirectory used for temp files (if needed)
937py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000938 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000939 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000940 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000941 (make-local-variable 'font-lock-defaults)
942 (make-local-variable 'paragraph-separate)
943 (make-local-variable 'paragraph-start)
944 (make-local-variable 'require-final-newline)
945 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000946 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000947 (make-local-variable 'comment-start-skip)
948 (make-local-variable 'comment-column)
949 (make-local-variable 'indent-region-function)
950 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000951 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000952 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000953 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000954 (setq major-mode 'python-mode
955 mode-name "Python"
956 local-abbrev-table python-mode-abbrev-table
Barry Warsaw5c38bf61997-12-02 22:01:04 +0000957 font-lock-defaults '(python-font-lock-keywords)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000958 paragraph-separate "^[ \t]*$"
959 paragraph-start "^[ \t]*$"
960 require-final-newline t
961 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000962 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000963 comment-start-skip "# *"
964 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000965 indent-region-function 'py-indent-region
966 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000967 ;; tell add-log.el how to find the current function/method/variable
968 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000969 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000970 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000971 ;; add the menu
972 (if py-menu
973 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000974 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000975 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000976 (setq comment-multi-line nil))
Barry Warsaw742a5111998-03-13 17:29:15 +0000977 ;; Install Imenu, only works for Emacs.
978 (when (py-safe (require 'imenu))
979 (make-variable-buffer-local 'imenu-create-index-function)
980 (setq imenu-create-index-function
981 (function imenu-example--create-python-index))
982 (setq imenu-generic-expression
983 imenu-example--generic-python-expression)
984 (if (fboundp 'imenu-add-to-menubar)
985 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
986 )
987 ;; Run the mode hook. Note that py-mode-hook is deprecated.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000988 (if python-mode-hook
989 (run-hooks 'python-mode-hook)
Barry Warsaw742a5111998-03-13 17:29:15 +0000990 (run-hooks 'py-mode-hook))
991 ;; Now do the automagical guessing
992 (if py-smart-indentation
993 (let ((offset py-indent-offset))
994 ;; Its okay if this fails to guess a good value
995 (if (and (py-safe (py-guess-indent-offset))
996 (<= py-indent-offset 8)
997 (>= py-indent-offset 2))
998 (setq offset py-indent-offset))
999 (setq py-indent-offset offset)
Barry Warsaw639eea61998-03-16 18:12:13 +00001000 ;; Only turn indent-tabs-mode off if tab-width !=
1001 ;; py-indent-offset. Never turn it on, because the user must
1002 ;; have explicitly turned it off.
1003 (if (/= tab-width py-indent-offset)
1004 (setq indent-tabs-mode nil))
Barry Warsaw742a5111998-03-13 17:29:15 +00001005 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001006
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001007
Barry Warsawb91b7431995-03-14 15:55:20 +00001008;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001009(defun py-outdent-p ()
1010 ;; returns non-nil if the current line should outdent one level
1011 (save-excursion
1012 (and (progn (back-to-indentation)
1013 (looking-at py-outdent-re))
Barry Warsawf06777d1998-01-21 05:36:18 +00001014 (progn (forward-line -1)
1015 (py-goto-initial-line)
1016 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001017 (while (or (looking-at py-blank-or-comment-re)
1018 (bobp))
1019 (backward-to-indentation 1))
1020 (not (looking-at py-no-outdent-re)))
1021 )))
1022
Barry Warsawb91b7431995-03-14 15:55:20 +00001023(defun py-electric-colon (arg)
1024 "Insert a colon.
1025In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001026argument is provided, that many colons are inserted non-electrically.
1027Electric behavior is inhibited inside a string or comment."
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
1033 (beginning-of-python-def-or-class)
1034 (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))
1048 ;; Don't indent, only outdent. This assumes that any lines that
1049 ;; are already outdented relative to py-compute-indentation were
1050 ;; put there on purpose. Its highly annoying to have `:' indent
1051 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
1052 ;; there a better way to determine this???
1053 (if (< (current-indentation) indent) nil
1054 (goto-char here)
1055 (beginning-of-line)
1056 (delete-horizontal-space)
1057 (indent-to (- indent outdent))
1058 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001059
1060
Barry Warsawa97a3f31997-11-04 18:47:06 +00001061;; Python subprocess utilities and filters
1062(defun py-execute-file (proc filename)
1063 ;; Send a properly formatted execfile('FILENAME') to the underlying
1064 ;; Python interpreter process FILENAME. Make that process's buffer
1065 ;; visible and force display. Also make comint believe the user
1066 ;; typed this string so that kill-output-from-shell does The Right
1067 ;; Thing.
1068 (let ((curbuf (current-buffer))
1069 (procbuf (process-buffer proc))
1070 (comint-scroll-to-bottom-on-output t)
1071 (msg (format "## working on region in file %s...\n" filename))
1072 (cmd (format "execfile('%s')\n" filename)))
1073 (unwind-protect
1074 (progn
1075 (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
1082(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001083 (let ((curbuf (current-buffer))
1084 (pbuf (process-buffer pyproc))
1085 (pmark (process-mark pyproc))
1086 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001087 ;; make sure we switch to a different buffer at least once. if we
1088 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001089 ;; window, and point is before the end, and lots of output is
1090 ;; coming at a fast pace, then (a) simple cursor-movement commands
1091 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
1092 ;; to have a visible effect (the window just doesn't get updated,
1093 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
1094 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001095 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001096 ;; #b makes no sense to me at all. #a almost makes sense: unless
1097 ;; we actually change buffers, set_buffer_internal in buffer.c
1098 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1099 ;; seems to make the Emacs command loop reluctant to update the
1100 ;; display. Perhaps the default process filter in process.c's
1101 ;; read_process_output has update_mode_lines++ for a similar
1102 ;; reason? beats me ...
1103
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001104 (unwind-protect
1105 ;; make sure current buffer is restored
1106 ;; BAW - we want to check to see if this still applies
1107 (progn
1108 ;; mysterious ugly hack
1109 (if (eq curbuf pbuf)
1110 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001111
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001112 (set-buffer pbuf)
1113 (let* ((start (point))
1114 (goback (< start pmark))
1115 (goend (and (not goback) (= start (point-max))))
1116 (buffer-read-only nil))
1117 (goto-char pmark)
1118 (insert string)
1119 (move-marker pmark (point))
1120 (setq file-finished
1121 (and py-file-queue
1122 (equal ">>> "
1123 (buffer-substring
1124 (prog2 (beginning-of-line) (point)
1125 (goto-char pmark))
1126 (point)))))
1127 (if goback (goto-char start)
1128 ;; else
1129 (if py-scroll-process-buffer
1130 (let* ((pop-up-windows t)
1131 (pwin (display-buffer pbuf)))
1132 (set-window-point pwin (point)))))
1133 (set-buffer curbuf)
1134 (if file-finished
1135 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001136 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001137 (setq py-file-queue (cdr py-file-queue))
1138 (if py-file-queue
1139 (py-execute-file pyproc (car py-file-queue)))))
1140 (and goend
1141 (progn (set-buffer pbuf)
1142 (goto-char (point-max))))
1143 ))
1144 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001145
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001146(defun py-postprocess-output-buffer (buf)
Barry Warsawf9b99f41998-03-26 16:08:59 +00001147 ;; Highlight exceptions found in BUF. If an exception occurred
1148 ;; return t, otherwise return nil. BUF must exist.
1149 (let (line file bol err-p)
Barry Warsaw9981d221997-12-03 05:25:48 +00001150 (save-excursion
1151 (set-buffer buf)
1152 (beginning-of-buffer)
1153 (while (re-search-forward py-traceback-line-re nil t)
1154 (setq file (match-string 1)
1155 line (string-to-int (match-string 2))
1156 bol (py-point 'bol))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001157 (py-highlight-line bol (py-point 'eol) file line)))
1158 (when (and py-jump-on-exception line)
1159 (beep)
1160 (py-jump-to-exception file line)
1161 (setq err-p t))
1162 err-p))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001163
Barry Warsaw9981d221997-12-03 05:25:48 +00001164
Barry Warsawa97a3f31997-11-04 18:47:06 +00001165
1166;;; Subprocess commands
1167
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001168;; only used when (memq 'broken-temp-names py-emacs-features)
1169(defvar py-serial-number 0)
1170(defvar py-exception-buffer nil)
1171(defconst py-output-buffer "*Python Output*")
Barry Warsawa2398801998-04-09 23:28:20 +00001172(make-variable-buffer-local 'py-output-buffer)
1173
1174;; for toggling between CPython and JPython
1175(defvar py-which-shell py-python-command)
1176(defvar py-which-args py-python-command-args)
1177(defvar py-which-bufname "Python")
1178(make-variable-buffer-local 'py-which-shell)
1179(make-variable-buffer-local 'py-which-args)
1180(make-variable-buffer-local 'py-which-bufname)
1181
1182(defun py-toggle-shells (arg)
1183 "Toggles between the CPython and JPython shells.
1184With positive \\[universal-argument], uses the CPython shell, with
1185negative \\[universal-argument] uses the JPython shell, and with a
1186zero argument, toggles the shell."
1187 (interactive "P")
1188 ;; default is to toggle
1189 (if (null arg)
1190 (setq arg 0))
1191 ;; toggle if zero
1192 (if (= arg 0)
1193 (if (string-equal py-which-bufname "Python")
1194 (setq arg -1)
1195 (setq arg 1)))
1196 (let (msg)
1197 (cond
1198 ((< 0 arg)
1199 ;; set to CPython
1200 (setq py-which-shell py-python-command
1201 py-which-args py-python-command-args
1202 py-which-bufname "Python"
1203 msg "CPython"
1204 mode-name "Python"))
1205 ((> 0 arg)
1206 (setq py-which-shell py-jpython-command
1207 py-which-args py-jpython-command-args
1208 py-which-bufname "JPython"
1209 msg "JPython"
1210 mode-name "JPython"))
1211 )
1212 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001213
Barry Warsawa97a3f31997-11-04 18:47:06 +00001214;;;###autoload
1215(defun py-shell ()
1216 "Start an interactive Python interpreter in another window.
1217This is like Shell mode, except that Python is running in the window
1218instead of a shell. See the `Interactive Shell' and `Shell Mode'
1219sections of the Emacs manual for details, especially for the key
1220bindings active in the `*Python*' buffer.
1221
1222See the docs for variable `py-scroll-buffer' for info on scrolling
1223behavior in the process window.
1224
Barry Warsawa2398801998-04-09 23:28:20 +00001225Note: You can toggle between using the CPython interpreter and the
1226JPython interpreter by hitting \\[py-toggle-shells]. This toggles
1227buffer local variables which control whether all your subshell
1228interactions happen to the `*JPython*' or `*Python*' buffers (the
1229latter is the name used for the CPython buffer).
1230
Barry Warsawa97a3f31997-11-04 18:47:06 +00001231Warning: Don't use an interactive Python if you change sys.ps1 or
1232sys.ps2 from their default values, or if you're running code that
1233prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1234distinguish your output from Python's output, and assumes that `>>> '
1235at the start of a line is a prompt from Python. Similarly, the Emacs
1236Shell mode code assumes that both `>>> ' and `... ' at the start of a
1237line are Python prompts. Bad things can happen if you fool either
1238mode.
1239
1240Warning: If you do any editing *in* the process buffer *while* the
1241buffer is accepting output from Python, do NOT attempt to `undo' the
1242changes. Some of the output (nowhere near the parts you changed!) may
1243be lost if you do. This appears to be an Emacs bug, an unfortunate
1244interaction between undo and process filters; the same problem exists in
1245non-Python process buffers using the default (Emacs-supplied) process
1246filter."
1247 ;; BAW - should undo be disabled in the python process buffer, if
1248 ;; this bug still exists?
1249 (interactive)
1250 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001251 (switch-to-buffer-other-window
Barry Warsawa2398801998-04-09 23:28:20 +00001252 (apply 'make-comint py-which-bufname py-which-shell nil py-which-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001253 (make-local-variable 'comint-prompt-regexp)
1254 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1255 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1256 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001257 ;; set up keybindings for this subshell
1258 (local-set-key [tab] 'self-insert-command)
1259 (local-set-key "\C-c-" 'py-up-exception)
1260 (local-set-key "\C-c=" 'py-down-exception)
1261 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001262
Barry Warsawa97a3f31997-11-04 18:47:06 +00001263(defun py-clear-queue ()
1264 "Clear the queue of temporary files waiting to execute."
1265 (interactive)
1266 (let ((n (length py-file-queue)))
1267 (mapcar 'delete-file py-file-queue)
1268 (setq py-file-queue nil)
1269 (message "%d pending files de-queued." n)))
1270
1271(defun py-execute-region (start end &optional async)
1272 "Execute the the region in a Python interpreter.
1273The region is first copied into a temporary file (in the directory
1274`py-temp-directory'). If there is no Python interpreter shell
1275running, this file is executed synchronously using
1276`shell-command-on-region'. If the program is long running, use an
1277optional \\[universal-argument] to run the command asynchronously in
1278its own buffer.
1279
1280If the Python interpreter shell is running, the region is execfile()'d
1281in that shell. If you try to execute regions too quickly,
1282`python-mode' will queue them up and execute them one at a time when
1283it sees a `>>> ' prompt from Python. Each time this happens, the
1284process buffer is popped into a window (if it's not already in some
1285window) so you can see it, and a comment of the form
1286
1287 \t## working on region in file <name>...
1288
1289is inserted at the end. See also the command `py-clear-queue'."
1290 (interactive "r\nP")
1291 (or (< start end)
1292 (error "Region is empty"))
1293 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001294 (temp (if (memq 'broken-temp-names py-emacs-features)
1295 (prog1
1296 (format "python-%d" py-serial-number)
1297 (setq py-serial-number (1+ py-serial-number)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001298 (make-temp-name "python-")))
1299 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001300 (write-region start end file nil 'nomsg)
1301 (cond
1302 ;; always run the code in it's own asynchronous subprocess
1303 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001304 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001305 (start-process "Python" buf py-python-command "-u" file)
1306 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001307 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001308 ))
1309 ;; if the Python interpreter shell is running, queue it up for
1310 ;; execution there.
1311 (proc
1312 ;; use the existing python shell
1313 (if (not py-file-queue)
1314 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001315 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001316 (push file py-file-queue)
1317 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001318 (t
1319 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001320 (shell-command-on-region start end py-python-command py-output-buffer)
Barry Warsaw512af041998-03-25 23:27:17 +00001321 ;; shell-command-on-region kills the output buffer if it never
1322 ;; existed and there's no output from the command
1323 (if (not (get-buffer py-output-buffer))
1324 (message "No output.")
1325 (setq py-exception-buffer (current-buffer))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001326 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1327 (pop-to-buffer py-output-buffer)
1328 (if err-p
1329 (pop-to-buffer py-exception-buffer)))
Barry Warsaw512af041998-03-25 23:27:17 +00001330 ))
1331 )))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001332
1333;; Code execution command
1334(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001335 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001336If the file local variable `py-master-file' is non-nil, execute the
1337named file instead of the buffer's file.
1338
Barry Warsaw7ae77681994-12-12 20:38:05 +00001339If there is a *Python* process buffer it is used. If a clipping
1340restriction is in effect, only the accessible portion of the buffer is
1341sent. A trailing newline will be supplied if needed.
1342
1343See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001344 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001345 (if py-master-file
1346 (let* ((filename (expand-file-name py-master-file))
1347 (buffer (or (get-file-buffer filename)
1348 (find-file-noselect filename))))
1349 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001350 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001351
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001352
1353
1354(defun py-jump-to-exception (file line)
1355 (let ((buffer (cond ((string-equal file "<stdin>")
1356 py-exception-buffer)
1357 ((and (consp py-exception-buffer)
1358 (string-equal file (car py-exception-buffer)))
1359 (cdr py-exception-buffer))
1360 ((py-safe (find-file-noselect file)))
1361 ;; could not figure out what file the exception
1362 ;; is pointing to, so prompt for it
1363 (t (find-file (read-file-name "Exception file: "
1364 nil
1365 file t))))))
1366 (pop-to-buffer buffer)
1367 (goto-line line)
1368 (message "Jumping to exception in file %s on line %d" file line)))
1369
1370(defun py-mouseto-exception (event)
1371 (interactive "e")
1372 (cond
1373 ((fboundp 'event-point)
1374 ;; XEmacs
1375 (let* ((point (event-point event))
1376 (buffer (event-buffer event))
1377 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1378 (info (and e (extent-property e 'py-exc-info))))
1379 (message "Event point: %d, info: %s" point info)
1380 (and info
1381 (py-jump-to-exception (car info) (cdr info)))
1382 ))
1383 ;; Emacs -- Please port this!
1384 ))
1385
1386(defun py-goto-exception ()
1387 "Go to the line indicated by the traceback."
1388 (interactive)
1389 (let (file line)
1390 (save-excursion
1391 (beginning-of-line)
1392 (if (looking-at py-traceback-line-re)
1393 (setq file (match-string 1)
1394 line (string-to-int (match-string 2)))))
1395 (if (not file)
1396 (error "Not on a traceback line."))
1397 (py-jump-to-exception file line)))
1398
1399(defun py-find-next-exception (start buffer searchdir errwhere)
1400 ;; Go to start position in buffer, search in the specified
1401 ;; direction, and jump to the exception found. If at the end of the
1402 ;; exception, print error message
1403 (let (file line)
1404 (save-excursion
1405 (set-buffer buffer)
1406 (goto-char (py-point start))
1407 (if (funcall searchdir py-traceback-line-re nil t)
1408 (setq file (match-string 1)
1409 line (string-to-int (match-string 2)))))
1410 (if (and file line)
1411 (py-jump-to-exception file line)
1412 (error "%s of traceback" errwhere))))
1413
1414(defun py-down-exception (&optional bottom)
1415 "Go to the next line down in the traceback.
1416With optional \\[universal-argument], jump to the bottom (innermost)
1417exception in the exception stack."
1418 (interactive "P")
1419 (let* ((proc (get-process "Python"))
1420 (buffer (if proc "*Python*" py-output-buffer)))
1421 (if bottom
1422 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1423 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1424
1425(defun py-up-exception (&optional top)
1426 "Go to the previous line up in the traceback.
1427With optional \\[universal-argument], jump to the top (outermost)
1428exception in the exception stack."
1429 (interactive "P")
1430 (let* ((proc (get-process "Python"))
1431 (buffer (if proc "*Python*" py-output-buffer)))
1432 (if top
1433 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001434 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001435
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001436
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001437;; Electric deletion
1438(defun py-electric-backspace (arg)
1439 "Deletes preceding character or levels of indentation.
1440Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001441with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001442
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001443If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001444
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001445Otherwise, if point is at the leftmost non-whitespace character of a
1446line that is neither a continuation line nor a non-indenting comment
1447line, or if point is at the end of a blank line, this command reduces
1448the indentation to match that of the line that opened the current
1449block of code. The line that opened the block is displayed in the
1450echo area to help you keep track of where you are. With numeric arg,
1451outdents that many blocks (but not past column zero).
1452
1453Otherwise the preceding character is deleted, converting a tab to
1454spaces if needed so that only a single column position is deleted.
1455Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001456 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001457 (if (or (/= (current-indentation) (current-column))
1458 (bolp)
1459 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001460 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001461 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001462 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001463 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001464 ;; force non-blank so py-goto-block-up doesn't ignore it
1465 (insert-char ?* 1)
1466 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001467 (let ((base-indent 0) ; indentation of base line
1468 (base-text "") ; and text of base line
1469 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001470 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001471 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001472 (condition-case nil ; in case no enclosing block
1473 (progn
1474 (py-goto-block-up 'no-mark)
1475 (setq base-indent (current-indentation)
1476 base-text (py-suck-up-leading-text)
1477 base-found-p t))
1478 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001479 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001480 (delete-char 1) ; toss the dummy character
1481 (delete-horizontal-space)
1482 (indent-to base-indent)
1483 (if base-found-p
1484 (message "Closes block: %s" base-text)))))
1485
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001486
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001487(defun py-electric-delete (arg)
1488 "Deletes preceding or following character or levels of whitespace.
1489
1490The behavior of this function depends on the variable
1491`delete-key-deletes-forward'. If this variable is nil (or does not
1492exist, as in older Emacsen), then this function behaves identical to
1493\\[c-electric-backspace].
1494
1495If `delete-key-deletes-forward' is non-nil and is supported in your
1496Emacs, then deletion occurs in the forward direction, by calling the
1497function in `py-delete-function'."
1498 (interactive "*p")
1499 (if (and (boundp 'delete-key-deletes-forward)
1500 delete-key-deletes-forward)
1501 (funcall py-delete-function arg)
1502 ;; else
1503 (py-electric-backspace arg)))
1504
1505;; required for pending-del and delsel modes
1506(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1507(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1508(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1509(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1510
1511
1512
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001513(defun py-indent-line (&optional arg)
1514 "Fix the indentation of the current line according to Python rules.
1515With \\[universal-argument], ignore outdenting rules for block
1516closing statements (e.g. return, raise, break, continue, pass)
1517
1518This function is normally bound to `indent-line-function' so
1519\\[indent-for-tab-command] will call it."
1520 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001521 (let* ((ci (current-indentation))
1522 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001523 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001524 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001525 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001526 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001527 (if (/= ci need)
1528 (save-excursion
1529 (beginning-of-line)
1530 (delete-horizontal-space)
1531 (indent-to need)))
1532 (if move-to-indentation-p (back-to-indentation))))
1533
1534(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001535 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001536This is just `strives to' because correct indentation can't be computed
1537from scratch for Python code. In general, deletes the whitespace before
1538point, inserts a newline, and takes an educated guess as to how you want
1539the new line indented."
1540 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001541 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001542 (if (< ci (current-column)) ; if point beyond indentation
1543 (newline-and-indent)
1544 ;; else try to act like newline-and-indent "normally" acts
1545 (beginning-of-line)
1546 (insert-char ?\n 1)
1547 (move-to-column ci))))
1548
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001549(defun py-compute-indentation (honor-block-close-p)
1550 ;; implements all the rules for indentation computation. when
1551 ;; honor-block-close-p is non-nil, statements such as return, raise,
1552 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001553 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001554 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001555 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001556 (pps (parse-partial-sexp bod (point)))
1557 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001558 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001559 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001560 ((or (and (nth 3 pps) (nth 3 boipps))
1561 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001562 (save-excursion
1563 (if (not py-align-multiline-strings-p) 0
1564 ;; skip back over blank & non-indenting comment lines
1565 ;; note: will skip a blank or non-indenting comment line
1566 ;; that happens to be a continuation line too
1567 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1568 (back-to-indentation)
1569 (current-column))))
1570 ;; are we on a continuation line?
1571 ((py-continuation-line-p)
1572 (let ((startpos (point))
1573 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001574 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001575 (if open-bracket-pos
1576 (progn
1577 ;; align with first item in list; else a normal
1578 ;; indent beyond the line with the open bracket
1579 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1580 ;; is the first list item on the same line?
1581 (skip-chars-forward " \t")
1582 (if (null (memq (following-char) '(?\n ?# ?\\)))
1583 ; yes, so line up with it
1584 (current-column)
1585 ;; first list item on another line, or doesn't exist yet
1586 (forward-line 1)
1587 (while (and (< (point) startpos)
1588 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1589 (forward-line 1))
Barry Warsaw92166d91998-04-01 21:59:41 +00001590 (if (and (< (point) startpos)
1591 (/= startpos
1592 (save-excursion
1593 (goto-char (1+ open-bracket-pos))
1594 (skip-chars-forward " \t\n")
1595 (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001596 ;; again mimic the first list item
1597 (current-indentation)
1598 ;; else they're about to enter the first item
1599 (goto-char open-bracket-pos)
1600 (+ (current-indentation) py-indent-offset))))
1601
1602 ;; else on backslash continuation line
1603 (forward-line -1)
1604 (if (py-continuation-line-p) ; on at least 3rd line in block
1605 (current-indentation) ; so just continue the pattern
1606 ;; else started on 2nd line in block, so indent more.
1607 ;; if base line is an assignment with a start on a RHS,
1608 ;; indent to 2 beyond the leftmost "="; else skip first
1609 ;; chunk of non-whitespace characters on base line, + 1 more
1610 ;; column
1611 (end-of-line)
1612 (setq endpos (point) searching t)
1613 (back-to-indentation)
1614 (setq startpos (point))
1615 ;; look at all "=" from left to right, stopping at first
1616 ;; one not nested in a list or string
1617 (while searching
1618 (skip-chars-forward "^=" endpos)
1619 (if (= (point) endpos)
1620 (setq searching nil)
1621 (forward-char 1)
1622 (setq state (parse-partial-sexp startpos (point)))
1623 (if (and (zerop (car state)) ; not in a bracket
1624 (null (nth 3 state))) ; & not in a string
1625 (progn
1626 (setq searching nil) ; done searching in any case
1627 (setq found
1628 (not (or
1629 (eq (following-char) ?=)
1630 (memq (char-after (- (point) 2))
1631 '(?< ?> ?!)))))))))
1632 (if (or (not found) ; not an assignment
1633 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1634 (progn
1635 (goto-char startpos)
1636 (skip-chars-forward "^ \t\n")))
1637 (1+ (current-column))))))
1638
1639 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001640 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001641
Barry Warsawa7891711996-08-01 15:53:09 +00001642 ;; Dfn: "Indenting comment line". A line containing only a
1643 ;; comment, but which is treated like a statement for
1644 ;; indentation calculation purposes. Such lines are only
1645 ;; treated specially by the mode; they are not treated
1646 ;; specially by the Python interpreter.
1647
1648 ;; The rules for indenting comment lines are a line where:
1649 ;; - the first non-whitespace character is `#', and
1650 ;; - the character following the `#' is whitespace, and
1651 ;; - the line is outdented with respect to (i.e. to the left
1652 ;; of) the indentation of the preceding non-blank line.
1653
1654 ;; The first non-blank line following an indenting comment
1655 ;; line is given the same amount of indentation as the
1656 ;; indenting comment line.
1657
1658 ;; All other comment-only lines are ignored for indentation
1659 ;; purposes.
1660
1661 ;; Are we looking at a comment-only line which is *not* an
1662 ;; indenting comment line? If so, we assume that its been
1663 ;; placed at the desired indentation, so leave it alone.
1664 ;; Indenting comment lines are aligned as statements down
1665 ;; below.
1666 ((and (looking-at "[ \t]*#[^ \t\n]")
1667 ;; NOTE: this test will not be performed in older Emacsen
1668 (fboundp 'forward-comment)
1669 (<= (current-indentation)
1670 (save-excursion
1671 (forward-comment (- (point-max)))
1672 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001673 (current-indentation))
1674
1675 ;; else indentation based on that of the statement that
1676 ;; precedes us; use the first line of that statement to
1677 ;; establish the base, in case the user forced a non-std
1678 ;; indentation for the continuation lines (if any)
1679 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001680 ;; skip back over blank & non-indenting comment lines note:
1681 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001682 ;; happens to be a continuation line too. use fast Emacs 19
1683 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001684 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001685 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001686 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001687 (let (done)
1688 (while (not done)
1689 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1690 nil 'move)
1691 (setq done (or (eq py-honor-comment-indentation t)
1692 (bobp)
1693 (/= (following-char) ?#)
1694 (not (zerop (current-column)))))
1695 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001696 ;; if we landed inside a string, go to the beginning of that
1697 ;; string. this handles triple quoted, multi-line spanning
1698 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001699 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001700 (skip (and delim (make-string 1 delim))))
1701 (when skip
1702 (save-excursion
1703 (py-safe (search-backward skip))
1704 (if (and (eq (char-before) delim)
1705 (eq (char-before (1- (point))) delim))
1706 (setq skip (make-string 3 delim))))
1707 ;; we're looking at a triple-quoted string
1708 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001709 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001710 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001711 (+ (current-indentation)
1712 (if (py-statement-opens-block-p)
1713 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001714 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001715 (- py-indent-offset)
1716 0)))
1717 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001718
1719(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001720 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001721By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001722`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001723Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001724`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001725their own buffer-local copy), both those currently existing and those
1726created later in the Emacs session.
1727
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001728Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001729There's no excuse for such foolishness, but sometimes you have to deal
1730with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001731`py-indent-offset' to what it thinks it was when they created the
1732mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001733
1734Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001735looking for a line that opens a block of code. `py-indent-offset' is
1736set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001737statement following it. If the search doesn't succeed going forward,
1738it's tried again going backward."
1739 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001740 (let (new-value
1741 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001742 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001743 (found nil)
1744 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001745 (py-goto-initial-line)
1746 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001747 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1748 (not (py-in-literal restart)))
1749 (setq restart (point))
1750 (py-goto-initial-line)
1751 (if (py-statement-opens-block-p)
1752 (setq found t)
1753 (goto-char restart))))
1754 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001755 (goto-char start)
1756 (py-goto-initial-line)
1757 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001758 (setq found (and
1759 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1760 (or (py-goto-initial-line) t) ; always true -- side effect
1761 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001762 (setq colon-indent (current-indentation)
1763 found (and found (zerop (py-next-statement 1)))
1764 new-value (- (current-indentation) colon-indent))
1765 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001766 (if (not found)
1767 (error "Sorry, couldn't guess a value for py-indent-offset")
1768 (funcall (if global 'kill-local-variable 'make-local-variable)
1769 'py-indent-offset)
1770 (setq py-indent-offset new-value)
1771 (message "%s value of py-indent-offset set to %d"
1772 (if global "Global" "Local")
1773 py-indent-offset))
1774 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001775
1776(defun py-shift-region (start end count)
1777 (save-excursion
1778 (goto-char end) (beginning-of-line) (setq end (point))
1779 (goto-char start) (beginning-of-line) (setq start (point))
1780 (indent-rigidly start end count)))
1781
1782(defun py-shift-region-left (start end &optional count)
1783 "Shift region of Python code to the left.
1784The lines from the line containing the start of the current region up
1785to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001786shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001787
1788If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001789many columns. With no active region, outdent only the current line.
1790You cannot outdent the region if any line is already at column zero."
1791 (interactive
1792 (let ((p (point))
1793 (m (mark))
1794 (arg current-prefix-arg))
1795 (if m
1796 (list (min p m) (max p m) arg)
1797 (list p (save-excursion (forward-line 1) (point)) arg))))
1798 ;; if any line is at column zero, don't shift the region
1799 (save-excursion
1800 (goto-char start)
1801 (while (< (point) end)
1802 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001803 (if (and (zerop (current-column))
1804 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001805 (error "Region is at left edge."))
1806 (forward-line 1)))
1807 (py-shift-region start end (- (prefix-numeric-value
1808 (or count py-indent-offset))))
1809 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001810
1811(defun py-shift-region-right (start end &optional count)
1812 "Shift region of Python code to the right.
1813The lines from the line containing the start of the current region up
1814to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001815shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001816
1817If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001818many columns. With no active region, indent only the current line."
1819 (interactive
1820 (let ((p (point))
1821 (m (mark))
1822 (arg current-prefix-arg))
1823 (if m
1824 (list (min p m) (max p m) arg)
1825 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001826 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001827 (or count py-indent-offset)))
1828 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001829
1830(defun py-indent-region (start end &optional indent-offset)
1831 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001832
Barry Warsaw7ae77681994-12-12 20:38:05 +00001833The lines from the line containing the start of the current region up
1834to (but not including) the line containing the end of the region are
1835reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001836character in the first column, the first line is left alone and the
1837rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001838region is reindented with respect to the (closest code or indenting
1839comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001840
1841This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001842control structures are introduced or removed, or to reformat code
1843using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001844
1845If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001846the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001847used.
1848
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001849Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001850is called! This function does not compute proper indentation from
1851scratch (that's impossible in Python), it merely adjusts the existing
1852indentation to be correct in context.
1853
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001854Warning: This function really has no idea what to do with
1855non-indenting comment lines, and shifts them as if they were indenting
1856comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001857
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001858Special cases: whitespace is deleted from blank lines; continuation
1859lines are shifted by the same amount their initial line was shifted,
1860in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001861initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001862 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001863 (save-excursion
1864 (goto-char end) (beginning-of-line) (setq end (point-marker))
1865 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001866 (let ((py-indent-offset (prefix-numeric-value
1867 (or indent-offset py-indent-offset)))
1868 (indents '(-1)) ; stack of active indent levels
1869 (target-column 0) ; column to which to indent
1870 (base-shifted-by 0) ; amount last base line was shifted
1871 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001872 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001873 0))
1874 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001875 (while (< (point) end)
1876 (setq ci (current-indentation))
1877 ;; figure out appropriate target column
1878 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001879 ((or (eq (following-char) ?#) ; comment in column 1
1880 (looking-at "[ \t]*$")) ; entirely blank
1881 (setq target-column 0))
1882 ((py-continuation-line-p) ; shift relative to base line
1883 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001884 (t ; new base line
1885 (if (> ci (car indents)) ; going deeper; push it
1886 (setq indents (cons ci indents))
1887 ;; else we should have seen this indent before
1888 (setq indents (memq ci indents)) ; pop deeper indents
1889 (if (null indents)
1890 (error "Bad indentation in region, at line %d"
1891 (save-restriction
1892 (widen)
1893 (1+ (count-lines 1 (point)))))))
1894 (setq target-column (+ indent-base
1895 (* py-indent-offset
1896 (- (length indents) 2))))
1897 (setq base-shifted-by (- target-column ci))))
1898 ;; shift as needed
1899 (if (/= ci target-column)
1900 (progn
1901 (delete-horizontal-space)
1902 (indent-to target-column)))
1903 (forward-line 1))))
1904 (set-marker end nil))
1905
Barry Warsawa7891711996-08-01 15:53:09 +00001906(defun py-comment-region (beg end &optional arg)
1907 "Like `comment-region' but uses double hash (`#') comment starter."
1908 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001909 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001910 (comment-region beg end arg)))
1911
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001912
1913;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001914(defun py-previous-statement (count)
1915 "Go to the start of previous Python statement.
1916If the statement at point is the i'th Python statement, goes to the
1917start of statement i-COUNT. If there is no such statement, goes to the
1918first statement. Returns count of statements left to move.
1919`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001920 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001921 (if (< count 0) (py-next-statement (- count))
1922 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001923 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001924 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001925 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001926 (> count 0)
1927 (zerop (forward-line -1))
1928 (py-goto-statement-at-or-above))
1929 (setq count (1- count)))
1930 (if (> count 0) (goto-char start)))
1931 count))
1932
1933(defun py-next-statement (count)
1934 "Go to the start of next Python statement.
1935If the statement at point is the i'th Python statement, goes to the
1936start of statement i+COUNT. If there is no such statement, goes to the
1937last statement. Returns count of statements left to move. `Statements'
1938do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001939 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001940 (if (< count 0) (py-previous-statement (- count))
1941 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001942 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001943 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001944 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001945 (> count 0)
1946 (py-goto-statement-below))
1947 (setq count (1- count)))
1948 (if (> count 0) (goto-char start)))
1949 count))
1950
1951(defun py-goto-block-up (&optional nomark)
1952 "Move up to start of current block.
1953Go to the statement that starts the smallest enclosing block; roughly
1954speaking, this will be the closest preceding statement that ends with a
1955colon and is indented less than the statement you started on. If
1956successful, also sets the mark to the starting point.
1957
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001958`\\[py-mark-block]' can be used afterward to mark the whole code
1959block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001960
1961If called from a program, the mark will not be set if optional argument
1962NOMARK is not nil."
1963 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001964 (let ((start (point))
1965 (found nil)
1966 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001967 (py-goto-initial-line)
1968 ;; if on blank or non-indenting comment line, use the preceding stmt
1969 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1970 (progn
1971 (py-goto-statement-at-or-above)
1972 (setq found (py-statement-opens-block-p))))
1973 ;; search back for colon line indented less
1974 (setq initial-indent (current-indentation))
1975 (if (zerop initial-indent)
1976 ;; force fast exit
1977 (goto-char (point-min)))
1978 (while (not (or found (bobp)))
1979 (setq found
1980 (and
1981 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1982 (or (py-goto-initial-line) t) ; always true -- side effect
1983 (< (current-indentation) initial-indent)
1984 (py-statement-opens-block-p))))
1985 (if found
1986 (progn
1987 (or nomark (push-mark start))
1988 (back-to-indentation))
1989 (goto-char start)
1990 (error "Enclosing block not found"))))
1991
1992(defun beginning-of-python-def-or-class (&optional class)
1993 "Move point to start of def (or class, with prefix arg).
1994
1995Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001996arg, looks for a `class' instead. The docs assume the `def' case;
1997just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001998
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001999If point is in a def statement already, and after the `d', simply
2000moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002001
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002002Else (point is not in a def statement, or at or before the `d' of a
2003def statement), searches for the closest preceding def statement, and
2004leaves point at its start. If no such statement can be found, leaves
2005point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002006
2007Returns t iff a def statement is found by these rules.
2008
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002009Note that doing this command repeatedly will take you closer to the
2010start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002011
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002012If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00002013`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002014 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002015 (let ((at-or-before-p (<= (current-column) (current-indentation)))
2016 (start-of-line (progn (beginning-of-line) (point)))
2017 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002018 (if (or (/= start-of-stmt start-of-line)
2019 (not at-or-before-p))
2020 (end-of-line)) ; OK to match on this line
2021 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002022 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002023
2024(defun end-of-python-def-or-class (&optional class)
2025 "Move point beyond end of def (or class, with prefix arg) body.
2026
2027By default, looks for an appropriate `def'. If you supply a prefix arg,
2028looks for a `class' instead. The docs assume the `def' case; just
2029substitute `class' for `def' for the other case.
2030
2031If point is in a def statement already, this is the def we use.
2032
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002033Else if the def found by `\\[beginning-of-python-def-or-class]'
2034contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002035
2036Else we search forward for the closest following def, and use that.
2037
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002038If a def can be found by these rules, point is moved to the start of
2039the line immediately following the def block, and the position of the
2040start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002041
2042Else point is moved to the end of the buffer, and nil is returned.
2043
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002044Note that doing this command repeatedly will take you closer to the
2045end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002046
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002047If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00002048`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002049 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002050 (let ((start (progn (py-goto-initial-line) (point)))
2051 (which (if class "class" "def"))
2052 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002053 ;; move point to start of appropriate def/class
2054 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2055 (setq state 'at-beginning)
2056 ;; else see if beginning-of-python-def-or-class hits container
2057 (if (and (beginning-of-python-def-or-class class)
2058 (progn (py-goto-beyond-block)
2059 (> (point) start)))
2060 (setq state 'at-end)
2061 ;; else search forward
2062 (goto-char start)
2063 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2064 (progn (setq state 'at-beginning)
2065 (beginning-of-line)))))
2066 (cond
2067 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2068 ((eq state 'at-end) t)
2069 ((eq state 'not-found) nil)
2070 (t (error "internal error in end-of-python-def-or-class")))))
2071
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002072
2073;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002074(defun py-mark-block (&optional extend just-move)
2075 "Mark following block of lines. With prefix arg, mark structure.
2076Easier to use than explain. It sets the region to an `interesting'
2077block of succeeding lines. If point is on a blank line, it goes down to
2078the next non-blank line. That will be the start of the region. The end
2079of the region depends on the kind of line at the start:
2080
2081 - If a comment, the region will include all succeeding comment lines up
2082 to (but not including) the next non-comment line (if any).
2083
2084 - Else if a prefix arg is given, and the line begins one of these
2085 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002086
2087 if elif else try except finally for while def class
2088
Barry Warsaw7ae77681994-12-12 20:38:05 +00002089 the region will be set to the body of the structure, including
2090 following blocks that `belong' to it, but excluding trailing blank
2091 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002092 and all (if any) of the following `except' and `finally' blocks
2093 that belong to the `try' structure will be in the region. Ditto
2094 for if/elif/else, for/else and while/else structures, and (a bit
2095 degenerate, since they're always one-block structures) def and
2096 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002097
2098 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002099 block (see list above), and the block is not a `one-liner' (i.e.,
2100 the statement ends with a colon, not with code), the region will
2101 include all succeeding lines up to (but not including) the next
2102 code statement (if any) that's indented no more than the starting
2103 line, except that trailing blank and comment lines are excluded.
2104 E.g., if the starting line begins a multi-statement `def'
2105 structure, the region will be set to the full function definition,
2106 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002107
2108 - Else the region will include all succeeding lines up to (but not
2109 including) the next blank line, or code or indenting-comment line
2110 indented strictly less than the starting line. Trailing indenting
2111 comment lines are included in this case, but not trailing blank
2112 lines.
2113
2114A msg identifying the location of the mark is displayed in the echo
2115area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2116
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002117If called from a program, optional argument EXTEND plays the role of
2118the prefix arg, and if optional argument JUST-MOVE is not nil, just
2119moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002120 (interactive "P") ; raw prefix arg
2121 (py-goto-initial-line)
2122 ;; skip over blank lines
2123 (while (and
2124 (looking-at "[ \t]*$") ; while blank line
2125 (not (eobp))) ; & somewhere to go
2126 (forward-line 1))
2127 (if (eobp)
2128 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002129 (let ((initial-pos (point))
2130 (initial-indent (current-indentation))
2131 last-pos ; position of last stmt in region
2132 (followers
2133 '((if elif else) (elif elif else) (else)
2134 (try except finally) (except except) (finally)
2135 (for else) (while else)
2136 (def) (class) ) )
2137 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002138
2139 (cond
2140 ;; if comment line, suck up the following comment lines
2141 ((looking-at "[ \t]*#")
2142 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2143 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2144 (setq last-pos (point)))
2145
2146 ;; else if line is a block line and EXTEND given, suck up
2147 ;; the whole structure
2148 ((and extend
2149 (setq first-symbol (py-suck-up-first-keyword) )
2150 (assq first-symbol followers))
2151 (while (and
2152 (or (py-goto-beyond-block) t) ; side effect
2153 (forward-line -1) ; side effect
2154 (setq last-pos (point)) ; side effect
2155 (py-goto-statement-below)
2156 (= (current-indentation) initial-indent)
2157 (setq next-symbol (py-suck-up-first-keyword))
2158 (memq next-symbol (cdr (assq first-symbol followers))))
2159 (setq first-symbol next-symbol)))
2160
2161 ;; else if line *opens* a block, search for next stmt indented <=
2162 ((py-statement-opens-block-p)
2163 (while (and
2164 (setq last-pos (point)) ; always true -- side effect
2165 (py-goto-statement-below)
2166 (> (current-indentation) initial-indent))
2167 nil))
2168
2169 ;; else plain code line; stop at next blank line, or stmt or
2170 ;; indenting comment line indented <
2171 (t
2172 (while (and
2173 (setq last-pos (point)) ; always true -- side effect
2174 (or (py-goto-beyond-final-line) t)
2175 (not (looking-at "[ \t]*$")) ; stop at blank line
2176 (or
2177 (>= (current-indentation) initial-indent)
2178 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2179 nil)))
2180
2181 ;; skip to end of last stmt
2182 (goto-char last-pos)
2183 (py-goto-beyond-final-line)
2184
2185 ;; set mark & display
2186 (if just-move
2187 () ; just return
2188 (push-mark (point) 'no-msg)
2189 (forward-line -1)
2190 (message "Mark set after: %s" (py-suck-up-leading-text))
2191 (goto-char initial-pos))))
2192
Barry Warsaw2518c671997-11-05 00:51:08 +00002193(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002194 "Set region to body of def (or class, with prefix arg) enclosing point.
2195Pushes the current mark, then point, on the mark ring (all language
2196modes do this, but although it's handy it's never documented ...).
2197
2198In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002199hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
2200`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002201
2202And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002203Turned out that was more confusing than useful: the `goto start' and
2204`goto end' commands are usually used to search through a file, and
2205people expect them to act a lot like `search backward' and `search
2206forward' string-search commands. But because Python `def' and `class'
2207can nest to arbitrary levels, finding the smallest def containing
2208point cannot be done via a simple backward search: the def containing
2209point may not be the closest preceding def, or even the closest
2210preceding def that's indented less. The fancy algorithm required is
2211appropriate for the usual uses of this `mark' command, but not for the
2212`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002213
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002214So the def marked by this command may not be the one either of the
2215`goto' commands find: If point is on a blank or non-indenting comment
2216line, moves back to start of the closest preceding code statement or
2217indenting comment line. If this is a `def' statement, that's the def
2218we use. Else searches for the smallest enclosing `def' block and uses
2219that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002220
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002221When an enclosing def is found: The mark is left immediately beyond
2222the last line of the def block. Point is left at the start of the
2223def, except that: if the def is preceded by a number of comment lines
2224followed by (at most) one optional blank line, point is left at the
2225start of the comments; else if the def is preceded by a blank line,
2226point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002227
2228The intent is to mark the containing def/class and its associated
2229documentation, to make moving and duplicating functions and classes
2230pleasant."
2231 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002232 (let ((start (point))
2233 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002234 (push-mark start)
2235 (if (not (py-go-up-tree-to-keyword which))
2236 (progn (goto-char start)
2237 (error "Enclosing %s not found" which))
2238 ;; else enclosing def/class found
2239 (setq start (point))
2240 (py-goto-beyond-block)
2241 (push-mark (point))
2242 (goto-char start)
2243 (if (zerop (forward-line -1)) ; if there is a preceding line
2244 (progn
2245 (if (looking-at "[ \t]*$") ; it's blank
2246 (setq start (point)) ; so reset start point
2247 (goto-char start)) ; else try again
2248 (if (zerop (forward-line -1))
2249 (if (looking-at "[ \t]*#") ; a comment
2250 ;; look back for non-comment line
2251 ;; tricky: note that the regexp matches a blank
2252 ;; line, cuz \n is in the 2nd character class
2253 (and
2254 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2255 (forward-line 1))
2256 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002257 (goto-char start)))))))
2258 (exchange-point-and-mark)
2259 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002260
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002261;; ripped from cc-mode
2262(defun py-forward-into-nomenclature (&optional arg)
2263 "Move forward to end of a nomenclature section or word.
2264With arg, to it arg times.
2265
2266A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2267 (interactive "p")
2268 (let ((case-fold-search nil))
2269 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002270 (re-search-forward
2271 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2272 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002273 (while (and (< arg 0)
2274 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002275 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002276 (point-min) 0))
2277 (forward-char 1)
2278 (setq arg (1+ arg)))))
2279 (py-keep-region-active))
2280
2281(defun py-backward-into-nomenclature (&optional arg)
2282 "Move backward to beginning of a nomenclature section or word.
2283With optional ARG, move that many times. If ARG is negative, move
2284forward.
2285
2286A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2287 (interactive "p")
2288 (py-forward-into-nomenclature (- arg))
2289 (py-keep-region-active))
2290
2291
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002292
2293;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002294
2295;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002296;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2297;; out of the right places, along with the keys they're on & current
2298;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002299(defun py-dump-help-string (str)
2300 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002301 (let ((locals (buffer-local-variables))
2302 funckind funcname func funcdoc
2303 (start 0) mstart end
2304 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002305 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2306 (setq mstart (match-beginning 0) end (match-end 0)
2307 funckind (substring str (match-beginning 1) (match-end 1))
2308 funcname (substring str (match-beginning 2) (match-end 2))
2309 func (intern funcname))
2310 (princ (substitute-command-keys (substring str start mstart)))
2311 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002312 ((equal funckind "c") ; command
2313 (setq funcdoc (documentation func)
2314 keys (concat
2315 "Key(s): "
2316 (mapconcat 'key-description
2317 (where-is-internal func py-mode-map)
2318 ", "))))
2319 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002320 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002321 keys (if (assq func locals)
2322 (concat
2323 "Local/Global values: "
2324 (prin1-to-string (symbol-value func))
2325 " / "
2326 (prin1-to-string (default-value func)))
2327 (concat
2328 "Value: "
2329 (prin1-to-string (symbol-value func))))))
2330 (t ; unexpected
2331 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002332 (princ (format "\n-> %s:\t%s\t%s\n\n"
2333 (if (equal funckind "c") "Command" "Variable")
2334 funcname keys))
2335 (princ funcdoc)
2336 (terpri)
2337 (setq start end))
2338 (princ (substitute-command-keys (substring str start))))
2339 (print-help-return-message)))
2340
2341(defun py-describe-mode ()
2342 "Dump long form of Python-mode docs."
2343 (interactive)
2344 (py-dump-help-string "Major mode for editing Python files.
2345Knows about Python indentation, tokens, comments and continuation lines.
2346Paragraphs are separated by blank lines only.
2347
2348Major sections below begin with the string `@'; specific function and
2349variable docs begin with `->'.
2350
2351@EXECUTING PYTHON CODE
2352
2353\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2354\\[py-execute-region]\tsends the current region
2355\\[py-shell]\tstarts a Python interpreter window; this will be used by
2356\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2357%c:py-execute-buffer
2358%c:py-execute-region
2359%c:py-shell
2360
2361@VARIABLES
2362
2363py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002364py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002365
2366py-python-command\tshell command to invoke Python interpreter
2367py-scroll-process-buffer\talways scroll Python process buffer
2368py-temp-directory\tdirectory used for temp files (if needed)
2369
2370py-beep-if-tab-change\tring the bell if tab-width is changed
2371%v:py-indent-offset
2372%v:py-block-comment-prefix
2373%v:py-python-command
2374%v:py-scroll-process-buffer
2375%v:py-temp-directory
2376%v:py-beep-if-tab-change
2377
2378@KINDS OF LINES
2379
2380Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002381preceding line ends with a backslash that's not part of a comment, or
2382the paren/bracket/brace nesting level at the start of the line is
2383non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002384
2385An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002386possibly blanks or tabs), a `comment line' (leftmost non-blank
2387character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002388
2389Comment Lines
2390
2391Although all comment lines are treated alike by Python, Python mode
2392recognizes two kinds that act differently with respect to indentation.
2393
2394An `indenting comment line' is a comment line with a blank, tab or
2395nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002396treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002397indenting comment line will be indented like the comment line. All
2398other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002399following the initial `#') are `non-indenting comment lines', and
2400their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002401
2402Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002403whenever possible. Non-indenting comment lines are useful in cases
2404like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002405
2406\ta = b # a very wordy single-line comment that ends up being
2407\t #... continued onto another line
2408
2409\tif a == b:
2410##\t\tprint 'panic!' # old code we've `commented out'
2411\t\treturn a
2412
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002413Since the `#...' and `##' comment lines have a non-whitespace
2414character following the initial `#', Python mode ignores them when
2415computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002416
2417Continuation Lines and Statements
2418
2419The Python-mode commands generally work on statements instead of on
2420individual lines, where a `statement' is a comment or blank line, or a
2421code line and all of its following continuation lines (if any)
2422considered as a single logical unit. The commands in this mode
2423generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002424statement containing point, even if point happens to be in the middle
2425of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002426
2427
2428@INDENTATION
2429
2430Primarily for entering new code:
2431\t\\[indent-for-tab-command]\t indent line appropriately
2432\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002433\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002434
2435Primarily for reindenting existing code:
2436\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2437\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2438
2439\t\\[py-indent-region]\t reindent region to match its context
2440\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2441\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2442
2443Unlike most programming languages, Python uses indentation, and only
2444indentation, to specify block structure. Hence the indentation supplied
2445automatically by Python-mode is just an educated guess: only you know
2446the block structure you intend, so only you can supply correct
2447indentation.
2448
2449The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2450the indentation of preceding statements. E.g., assuming
2451py-indent-offset is 4, after you enter
2452\tif a > 0: \\[py-newline-and-indent]
2453the cursor will be moved to the position of the `_' (_ is not a
2454character in the file, it's just used here to indicate the location of
2455the cursor):
2456\tif a > 0:
2457\t _
2458If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2459to
2460\tif a > 0:
2461\t c = d
2462\t _
2463Python-mode cannot know whether that's what you intended, or whether
2464\tif a > 0:
2465\t c = d
2466\t_
2467was your intent. In general, Python-mode either reproduces the
2468indentation of the (closest code or indenting-comment) preceding
2469statement, or adds an extra py-indent-offset blanks if the preceding
2470statement has `:' as its last significant (non-whitespace and non-
2471comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002472\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002473
2474Continuation lines are given extra indentation. If you don't like the
2475suggested indentation, change it to something you do like, and Python-
2476mode will strive to indent later lines of the statement in the same way.
2477
2478If a line is a continuation line by virtue of being in an unclosed
2479paren/bracket/brace structure (`list', for short), the suggested
2480indentation depends on whether the current line contains the first item
2481in the list. If it does, it's indented py-indent-offset columns beyond
2482the indentation of the line containing the open bracket. If you don't
2483like that, change it by hand. The remaining items in the list will mimic
2484whatever indentation you give to the first item.
2485
2486If a line is a continuation line because the line preceding it ends with
2487a backslash, the third and following lines of the statement inherit their
2488indentation from the line preceding them. The indentation of the second
2489line in the statement depends on the form of the first (base) line: if
2490the base line is an assignment statement with anything more interesting
2491than the backslash following the leftmost assigning `=', the second line
2492is indented two columns beyond that `='. Else it's indented to two
2493columns beyond the leftmost solid chunk of non-whitespace characters on
2494the base line.
2495
2496Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2497repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2498structure you intend.
2499%c:indent-for-tab-command
2500%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002501%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002502
2503
2504The next function may be handy when editing code you didn't write:
2505%c:py-guess-indent-offset
2506
2507
2508The remaining `indent' functions apply to a region of Python code. They
2509assume the block structure (equals indentation, in Python) of the region
2510is correct, and alter the indentation in various ways while preserving
2511the block structure:
2512%c:py-indent-region
2513%c:py-shift-region-left
2514%c:py-shift-region-right
2515
2516@MARKING & MANIPULATING REGIONS OF CODE
2517
2518\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002519\\[py-mark-def-or-class]\t mark smallest enclosing def
2520\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002521\\[comment-region]\t comment out region of code
2522\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002523%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002524%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002525%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002526
2527@MOVING POINT
2528
2529\\[py-previous-statement]\t move to statement preceding point
2530\\[py-next-statement]\t move to statement following point
2531\\[py-goto-block-up]\t move up to start of current block
2532\\[beginning-of-python-def-or-class]\t move to start of def
2533\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2534\\[end-of-python-def-or-class]\t move to end of def
2535\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2536
2537The first two move to one statement beyond the statement that contains
2538point. A numeric prefix argument tells them to move that many
2539statements instead. Blank lines, comment lines, and continuation lines
2540do not count as `statements' for these commands. So, e.g., you can go
2541to the first code statement in a file by entering
2542\t\\[beginning-of-buffer]\t to move to the top of the file
2543\t\\[py-next-statement]\t to skip over initial comments and blank lines
2544Or do `\\[py-previous-statement]' with a huge prefix argument.
2545%c:py-previous-statement
2546%c:py-next-statement
2547%c:py-goto-block-up
2548%c:beginning-of-python-def-or-class
2549%c:end-of-python-def-or-class
2550
2551@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2552
2553`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2554
2555`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2556overall class and def structure of a module.
2557
2558`\\[back-to-indentation]' moves point to a line's first non-blank character.
2559
2560`\\[indent-relative]' is handy for creating odd indentation.
2561
2562@OTHER EMACS HINTS
2563
2564If you don't like the default value of a variable, change its value to
2565whatever you do like by putting a `setq' line in your .emacs file.
2566E.g., to set the indentation increment to 4, put this line in your
2567.emacs:
2568\t(setq py-indent-offset 4)
2569To see the value of a variable, do `\\[describe-variable]' and enter the variable
2570name at the prompt.
2571
2572When entering a key sequence like `C-c C-n', it is not necessary to
2573release the CONTROL key after doing the `C-c' part -- it suffices to
2574press the CONTROL key, press and release `c' (while still holding down
2575CONTROL), press and release `n' (while still holding down CONTROL), &
2576then release CONTROL.
2577
2578Entering Python mode calls with no arguments the value of the variable
2579`python-mode-hook', if that value exists and is not nil; for backward
2580compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2581the Elisp manual for details.
2582
2583Obscure: When python-mode is first loaded, it looks for all bindings
2584to newline-and-indent in the global keymap, and shadows them with
2585local bindings to py-newline-and-indent."))
2586
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002587
2588;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002589(defvar py-parse-state-re
2590 (concat
2591 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2592 "\\|"
2593 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002594
Barry Warsaw7ae77681994-12-12 20:38:05 +00002595;; returns the parse state at point (see parse-partial-sexp docs)
2596(defun py-parse-state ()
2597 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002598 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002599 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002600 (while (not done)
2601 ;; back up to the first preceding line (if any; else start of
2602 ;; buffer) that begins with a popular Python keyword, or a
2603 ;; non- whitespace and non-comment character. These are good
2604 ;; places to start parsing to see whether where we started is
2605 ;; at a non-zero nesting level. It may be slow for people who
2606 ;; write huge code blocks or huge lists ... tough beans.
2607 (re-search-backward py-parse-state-re nil 'move)
2608 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002609 ;; In XEmacs, we have a much better way to test for whether
2610 ;; we're in a triple-quoted string or not. Emacs does not
2611 ;; have this built-in function, which is it's loss because
2612 ;; without scanning from the beginning of the buffer, there's
2613 ;; no accurate way to determine this otherwise.
2614 (if (not (fboundp 'buffer-syntactic-context))
2615 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002616 (progn
2617 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002618 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002619 (setq done (or (not (nth 3 pps))
2620 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002621 ;; XEmacs
2622 (setq done (or (not (buffer-syntactic-context))
2623 (bobp)))
2624 (when done
2625 (setq pps (parse-partial-sexp (point) here)))
2626 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002627 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002628
2629;; if point is at a non-zero nesting level, returns the number of the
2630;; character that opens the smallest enclosing unclosed list; else
2631;; returns nil.
2632(defun py-nesting-level ()
Barry Warsawf64b4051998-02-12 16:52:14 +00002633 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002634 (if (zerop (car status))
2635 nil ; not in a nest
2636 (car (cdr status))))) ; char# of open bracket
2637
2638;; t iff preceding line ends with backslash that's not in a comment
2639(defun py-backslash-continuation-line-p ()
2640 (save-excursion
2641 (beginning-of-line)
2642 (and
2643 ;; use a cheap test first to avoid the regexp if possible
2644 ;; use 'eq' because char-after may return nil
2645 (eq (char-after (- (point) 2)) ?\\ )
2646 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002647 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002648 (looking-at py-continued-re))))
2649
2650;; t iff current line is a continuation line
2651(defun py-continuation-line-p ()
2652 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002653 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002654 (or (py-backslash-continuation-line-p)
2655 (py-nesting-level))))
2656
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002657;; go to initial line of current statement; usually this is the line
2658;; we're on, but if we're on the 2nd or following lines of a
2659;; continuation block, we need to go up to the first line of the
2660;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002661;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002662;; Tricky: We want to avoid quadratic-time behavior for long continued
2663;; blocks, whether of the backslash or open-bracket varieties, or a
2664;; mix of the two. The following manages to do that in the usual
2665;; cases.
Barry Warsawc210e691998-01-20 22:52:56 +00002666;;
2667;; Also, if we're sitting inside a triple quoted string, this will
2668;; drop us at the line that begins the string.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002669(defun py-goto-initial-line ()
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002670 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002671 (while (py-continuation-line-p)
2672 (beginning-of-line)
2673 (if (py-backslash-continuation-line-p)
2674 (while (py-backslash-continuation-line-p)
2675 (forward-line -1))
2676 ;; else zip out of nested brackets/braces/parens
2677 (while (setq open-bracket-pos (py-nesting-level))
2678 (goto-char open-bracket-pos)))))
2679 (beginning-of-line))
2680
2681;; go to point right beyond final line of current statement; usually
2682;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002683;; statement we need to skip over the continuation lines. Tricky:
2684;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002685(defun py-goto-beyond-final-line ()
2686 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002687 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002688 (while (and (py-continuation-line-p)
2689 (not (eobp)))
2690 ;; skip over the backslash flavor
2691 (while (and (py-backslash-continuation-line-p)
2692 (not (eobp)))
2693 (forward-line 1))
2694 ;; if in nest, zip to the end of the nest
2695 (setq state (py-parse-state))
2696 (if (and (not (zerop (car state)))
2697 (not (eobp)))
2698 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002699 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002700 (forward-line 1))))))
2701
2702;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002703;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002704(defun py-statement-opens-block-p ()
2705 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002706 (let ((start (point))
2707 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2708 (searching t)
2709 (answer nil)
2710 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002711 (goto-char start)
2712 (while searching
2713 ;; look for a colon with nothing after it except whitespace, and
2714 ;; maybe a comment
2715 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2716 finish t)
2717 (if (eq (point) finish) ; note: no `else' clause; just
2718 ; keep searching if we're not at
2719 ; the end yet
2720 ;; sure looks like it opens a block -- but it might
2721 ;; be in a comment
2722 (progn
2723 (setq searching nil) ; search is done either way
2724 (setq state (parse-partial-sexp start
2725 (match-beginning 0)))
2726 (setq answer (not (nth 4 state)))))
2727 ;; search failed: couldn't find another interesting colon
2728 (setq searching nil)))
2729 answer)))
2730
Barry Warsawf831d811996-07-31 20:42:59 +00002731(defun py-statement-closes-block-p ()
2732 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002733 ;; starts with `return', `raise', `break', `continue', and `pass'.
2734 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002735 (let ((here (point)))
2736 (back-to-indentation)
2737 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002738 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002739 (goto-char here))))
2740
Barry Warsaw7ae77681994-12-12 20:38:05 +00002741;; go to point right beyond final line of block begun by the current
2742;; line. This is the same as where py-goto-beyond-final-line goes
2743;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002744;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002745(defun py-goto-beyond-block ()
2746 (if (py-statement-opens-block-p)
2747 (py-mark-block nil 'just-move)
2748 (py-goto-beyond-final-line)))
2749
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002750;; go to start of first statement (not blank or comment or
2751;; continuation line) at or preceding point. returns t if there is
2752;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002753(defun py-goto-statement-at-or-above ()
2754 (py-goto-initial-line)
2755 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002756 ;; skip back over blank & comment lines
2757 ;; note: will skip a blank or comment line that happens to be
2758 ;; a continuation line too
2759 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2760 (progn (py-goto-initial-line) t)
2761 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002762 t))
2763
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002764;; go to start of first statement (not blank or comment or
2765;; continuation line) following the statement containing point returns
2766;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002767(defun py-goto-statement-below ()
2768 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002769 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002770 (py-goto-beyond-final-line)
2771 (while (and
2772 (looking-at py-blank-or-comment-re)
2773 (not (eobp)))
2774 (forward-line 1))
2775 (if (eobp)
2776 (progn (goto-char start) nil)
2777 t)))
2778
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002779;; go to start of statement, at or preceding point, starting with
2780;; keyword KEY. Skips blank lines and non-indenting comments upward
2781;; first. If that statement starts with KEY, done, else go back to
2782;; first enclosing block starting with KEY. If successful, leaves
2783;; point at the start of the KEY line & returns t. Else leaves point
2784;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002785(defun py-go-up-tree-to-keyword (key)
2786 ;; skip blanks and non-indenting #
2787 (py-goto-initial-line)
2788 (while (and
2789 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2790 (zerop (forward-line -1))) ; go back
2791 nil)
2792 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002793 (let* ((re (concat "[ \t]*" key "\\b"))
2794 (case-fold-search nil) ; let* so looking-at sees this
2795 (found (looking-at re))
2796 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002797 (while (not (or found dead))
2798 (condition-case nil ; in case no enclosing block
2799 (py-goto-block-up 'no-mark)
2800 (error (setq dead t)))
2801 (or dead (setq found (looking-at re))))
2802 (beginning-of-line)
2803 found))
2804
2805;; return string in buffer from start of indentation to end of line;
2806;; prefix "..." if leading whitespace was skipped
2807(defun py-suck-up-leading-text ()
2808 (save-excursion
2809 (back-to-indentation)
2810 (concat
2811 (if (bolp) "" "...")
2812 (buffer-substring (point) (progn (end-of-line) (point))))))
2813
2814;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2815;; as a Lisp symbol; return nil if none
2816(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002817 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002818 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2819 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2820 nil)))
2821
Barry Warsawb3e81d51996-09-04 15:12:42 +00002822(defun py-current-defun ()
2823 ;; tell add-log.el how to find the current function/method/variable
2824 (save-excursion
2825 (if (re-search-backward py-defun-start-re nil t)
2826 (or (match-string 3)
2827 (let ((method (match-string 2)))
2828 (if (and (not (zerop (length (match-string 1))))
2829 (re-search-backward py-class-start-re nil t))
2830 (concat (match-string 1) "." method)
2831 method)))
2832 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002833
2834
Barry Warsawfec75d61995-07-05 23:26:15 +00002835(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002836 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002837
Barry Warsaw850437a1995-03-08 21:50:28 +00002838(defun py-version ()
2839 "Echo the current version of `python-mode' in the minibuffer."
2840 (interactive)
2841 (message "Using `python-mode' version %s" py-version)
2842 (py-keep-region-active))
2843
2844;; only works under Emacs 19
2845;(eval-when-compile
2846; (require 'reporter))
2847
2848(defun py-submit-bug-report (enhancement-p)
2849 "Submit via mail a bug report on `python-mode'.
2850With \\[universal-argument] just submit an enhancement request."
2851 (interactive
2852 (list (not (y-or-n-p
2853 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002854 (let ((reporter-prompt-for-summary-p (if enhancement-p
2855 "(Very) brief summary: "
2856 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002857 (require 'reporter)
2858 (reporter-submit-bug-report
2859 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002860 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002861 ;; varlist
2862 (if enhancement-p nil
2863 '(py-python-command
2864 py-indent-offset
2865 py-block-comment-prefix
2866 py-scroll-process-buffer
2867 py-temp-directory
2868 py-beep-if-tab-change))
2869 nil ;pre-hooks
2870 nil ;post-hooks
2871 "Dear Barry,") ;salutation
2872 (if enhancement-p nil
2873 (set-mark (point))
2874 (insert
2875"Please replace this text with a sufficiently large code sample\n\
2876and an exact recipe so that I can reproduce your problem. Failure\n\
2877to do so may mean a greater delay in fixing your bug.\n\n")
2878 (exchange-point-and-mark)
2879 (py-keep-region-active))))
2880
2881
Barry Warsaw47384781997-11-26 05:27:45 +00002882(defun py-kill-emacs-hook ()
2883 (mapcar #'(lambda (filename)
2884 (py-safe (delete-file filename)))
2885 py-file-queue))
2886
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002887;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002888(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002889
2890
2891
2892(provide 'python-mode)
2893;;; python-mode.el ends here