blob: 0262210670695fad2f82154d179dce1a567f3794 [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 )
Barry Warsawea609c11998-04-10 16:08:26 +00001212 (message "Using the %s shell" msg)
Barry Warsawa2398801998-04-09 23:28:20 +00001213 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001214
Barry Warsawa97a3f31997-11-04 18:47:06 +00001215;;;###autoload
1216(defun py-shell ()
1217 "Start an interactive Python interpreter in another window.
1218This is like Shell mode, except that Python is running in the window
1219instead of a shell. See the `Interactive Shell' and `Shell Mode'
1220sections of the Emacs manual for details, especially for the key
1221bindings active in the `*Python*' buffer.
1222
1223See the docs for variable `py-scroll-buffer' for info on scrolling
1224behavior in the process window.
1225
Barry Warsawa2398801998-04-09 23:28:20 +00001226Note: You can toggle between using the CPython interpreter and the
1227JPython interpreter by hitting \\[py-toggle-shells]. This toggles
1228buffer local variables which control whether all your subshell
1229interactions happen to the `*JPython*' or `*Python*' buffers (the
1230latter is the name used for the CPython buffer).
1231
Barry Warsawa97a3f31997-11-04 18:47:06 +00001232Warning: Don't use an interactive Python if you change sys.ps1 or
1233sys.ps2 from their default values, or if you're running code that
1234prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1235distinguish your output from Python's output, and assumes that `>>> '
1236at the start of a line is a prompt from Python. Similarly, the Emacs
1237Shell mode code assumes that both `>>> ' and `... ' at the start of a
1238line are Python prompts. Bad things can happen if you fool either
1239mode.
1240
1241Warning: If you do any editing *in* the process buffer *while* the
1242buffer is accepting output from Python, do NOT attempt to `undo' the
1243changes. Some of the output (nowhere near the parts you changed!) may
1244be lost if you do. This appears to be an Emacs bug, an unfortunate
1245interaction between undo and process filters; the same problem exists in
1246non-Python process buffers using the default (Emacs-supplied) process
1247filter."
1248 ;; BAW - should undo be disabled in the python process buffer, if
1249 ;; this bug still exists?
1250 (interactive)
1251 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001252 (switch-to-buffer-other-window
Barry Warsawa2398801998-04-09 23:28:20 +00001253 (apply 'make-comint py-which-bufname py-which-shell nil py-which-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001254 (make-local-variable 'comint-prompt-regexp)
1255 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1256 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1257 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001258 ;; set up keybindings for this subshell
1259 (local-set-key [tab] 'self-insert-command)
1260 (local-set-key "\C-c-" 'py-up-exception)
1261 (local-set-key "\C-c=" 'py-down-exception)
1262 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001263
Barry Warsawa97a3f31997-11-04 18:47:06 +00001264(defun py-clear-queue ()
1265 "Clear the queue of temporary files waiting to execute."
1266 (interactive)
1267 (let ((n (length py-file-queue)))
1268 (mapcar 'delete-file py-file-queue)
1269 (setq py-file-queue nil)
1270 (message "%d pending files de-queued." n)))
1271
1272(defun py-execute-region (start end &optional async)
1273 "Execute the the region in a Python interpreter.
1274The region is first copied into a temporary file (in the directory
1275`py-temp-directory'). If there is no Python interpreter shell
1276running, this file is executed synchronously using
1277`shell-command-on-region'. If the program is long running, use an
1278optional \\[universal-argument] to run the command asynchronously in
1279its own buffer.
1280
1281If the Python interpreter shell is running, the region is execfile()'d
1282in that shell. If you try to execute regions too quickly,
1283`python-mode' will queue them up and execute them one at a time when
1284it sees a `>>> ' prompt from Python. Each time this happens, the
1285process buffer is popped into a window (if it's not already in some
1286window) so you can see it, and a comment of the form
1287
1288 \t## working on region in file <name>...
1289
1290is inserted at the end. See also the command `py-clear-queue'."
1291 (interactive "r\nP")
1292 (or (< start end)
1293 (error "Region is empty"))
1294 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001295 (temp (if (memq 'broken-temp-names py-emacs-features)
1296 (prog1
1297 (format "python-%d" py-serial-number)
1298 (setq py-serial-number (1+ py-serial-number)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001299 (make-temp-name "python-")))
1300 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001301 (write-region start end file nil 'nomsg)
1302 (cond
1303 ;; always run the code in it's own asynchronous subprocess
1304 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001305 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001306 (start-process "Python" buf py-python-command "-u" file)
1307 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001308 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001309 ))
1310 ;; if the Python interpreter shell is running, queue it up for
1311 ;; execution there.
1312 (proc
1313 ;; use the existing python shell
1314 (if (not py-file-queue)
1315 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001316 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001317 (push file py-file-queue)
1318 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001319 (t
1320 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001321 (shell-command-on-region start end py-python-command py-output-buffer)
Barry Warsaw512af041998-03-25 23:27:17 +00001322 ;; shell-command-on-region kills the output buffer if it never
1323 ;; existed and there's no output from the command
1324 (if (not (get-buffer py-output-buffer))
1325 (message "No output.")
1326 (setq py-exception-buffer (current-buffer))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001327 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1328 (pop-to-buffer py-output-buffer)
1329 (if err-p
1330 (pop-to-buffer py-exception-buffer)))
Barry Warsaw512af041998-03-25 23:27:17 +00001331 ))
1332 )))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001333
1334;; Code execution command
1335(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001336 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001337If the file local variable `py-master-file' is non-nil, execute the
1338named file instead of the buffer's file.
1339
Barry Warsaw7ae77681994-12-12 20:38:05 +00001340If there is a *Python* process buffer it is used. If a clipping
1341restriction is in effect, only the accessible portion of the buffer is
1342sent. A trailing newline will be supplied if needed.
1343
1344See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001345 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001346 (if py-master-file
1347 (let* ((filename (expand-file-name py-master-file))
1348 (buffer (or (get-file-buffer filename)
1349 (find-file-noselect filename))))
1350 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001351 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001352
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001353
1354
1355(defun py-jump-to-exception (file line)
1356 (let ((buffer (cond ((string-equal file "<stdin>")
1357 py-exception-buffer)
1358 ((and (consp py-exception-buffer)
1359 (string-equal file (car py-exception-buffer)))
1360 (cdr py-exception-buffer))
1361 ((py-safe (find-file-noselect file)))
1362 ;; could not figure out what file the exception
1363 ;; is pointing to, so prompt for it
1364 (t (find-file (read-file-name "Exception file: "
1365 nil
1366 file t))))))
1367 (pop-to-buffer buffer)
1368 (goto-line line)
1369 (message "Jumping to exception in file %s on line %d" file line)))
1370
1371(defun py-mouseto-exception (event)
1372 (interactive "e")
1373 (cond
1374 ((fboundp 'event-point)
1375 ;; XEmacs
1376 (let* ((point (event-point event))
1377 (buffer (event-buffer event))
1378 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1379 (info (and e (extent-property e 'py-exc-info))))
1380 (message "Event point: %d, info: %s" point info)
1381 (and info
1382 (py-jump-to-exception (car info) (cdr info)))
1383 ))
1384 ;; Emacs -- Please port this!
1385 ))
1386
1387(defun py-goto-exception ()
1388 "Go to the line indicated by the traceback."
1389 (interactive)
1390 (let (file line)
1391 (save-excursion
1392 (beginning-of-line)
1393 (if (looking-at py-traceback-line-re)
1394 (setq file (match-string 1)
1395 line (string-to-int (match-string 2)))))
1396 (if (not file)
1397 (error "Not on a traceback line."))
1398 (py-jump-to-exception file line)))
1399
1400(defun py-find-next-exception (start buffer searchdir errwhere)
1401 ;; Go to start position in buffer, search in the specified
1402 ;; direction, and jump to the exception found. If at the end of the
1403 ;; exception, print error message
1404 (let (file line)
1405 (save-excursion
1406 (set-buffer buffer)
1407 (goto-char (py-point start))
1408 (if (funcall searchdir py-traceback-line-re nil t)
1409 (setq file (match-string 1)
1410 line (string-to-int (match-string 2)))))
1411 (if (and file line)
1412 (py-jump-to-exception file line)
1413 (error "%s of traceback" errwhere))))
1414
1415(defun py-down-exception (&optional bottom)
1416 "Go to the next line down in the traceback.
1417With optional \\[universal-argument], jump to the bottom (innermost)
1418exception in the exception stack."
1419 (interactive "P")
1420 (let* ((proc (get-process "Python"))
1421 (buffer (if proc "*Python*" py-output-buffer)))
1422 (if bottom
1423 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1424 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1425
1426(defun py-up-exception (&optional top)
1427 "Go to the previous line up in the traceback.
1428With optional \\[universal-argument], jump to the top (outermost)
1429exception in the exception stack."
1430 (interactive "P")
1431 (let* ((proc (get-process "Python"))
1432 (buffer (if proc "*Python*" py-output-buffer)))
1433 (if top
1434 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001435 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001436
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001437
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001438;; Electric deletion
1439(defun py-electric-backspace (arg)
1440 "Deletes preceding character or levels of indentation.
1441Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001442with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001443
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001444If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001445
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001446Otherwise, if point is at the leftmost non-whitespace character of a
1447line that is neither a continuation line nor a non-indenting comment
1448line, or if point is at the end of a blank line, this command reduces
1449the indentation to match that of the line that opened the current
1450block of code. The line that opened the block is displayed in the
1451echo area to help you keep track of where you are. With numeric arg,
1452outdents that many blocks (but not past column zero).
1453
1454Otherwise the preceding character is deleted, converting a tab to
1455spaces if needed so that only a single column position is deleted.
1456Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001457 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001458 (if (or (/= (current-indentation) (current-column))
1459 (bolp)
1460 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001461 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001462 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001463 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001464 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001465 ;; force non-blank so py-goto-block-up doesn't ignore it
1466 (insert-char ?* 1)
1467 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001468 (let ((base-indent 0) ; indentation of base line
1469 (base-text "") ; and text of base line
1470 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001471 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001472 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001473 (condition-case nil ; in case no enclosing block
1474 (progn
1475 (py-goto-block-up 'no-mark)
1476 (setq base-indent (current-indentation)
1477 base-text (py-suck-up-leading-text)
1478 base-found-p t))
1479 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001480 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001481 (delete-char 1) ; toss the dummy character
1482 (delete-horizontal-space)
1483 (indent-to base-indent)
1484 (if base-found-p
1485 (message "Closes block: %s" base-text)))))
1486
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001487
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001488(defun py-electric-delete (arg)
1489 "Deletes preceding or following character or levels of whitespace.
1490
1491The behavior of this function depends on the variable
1492`delete-key-deletes-forward'. If this variable is nil (or does not
1493exist, as in older Emacsen), then this function behaves identical to
1494\\[c-electric-backspace].
1495
1496If `delete-key-deletes-forward' is non-nil and is supported in your
1497Emacs, then deletion occurs in the forward direction, by calling the
1498function in `py-delete-function'."
1499 (interactive "*p")
1500 (if (and (boundp 'delete-key-deletes-forward)
1501 delete-key-deletes-forward)
1502 (funcall py-delete-function arg)
1503 ;; else
1504 (py-electric-backspace arg)))
1505
1506;; required for pending-del and delsel modes
1507(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1508(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1509(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1510(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1511
1512
1513
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001514(defun py-indent-line (&optional arg)
1515 "Fix the indentation of the current line according to Python rules.
1516With \\[universal-argument], ignore outdenting rules for block
1517closing statements (e.g. return, raise, break, continue, pass)
1518
1519This function is normally bound to `indent-line-function' so
1520\\[indent-for-tab-command] will call it."
1521 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001522 (let* ((ci (current-indentation))
1523 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001524 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001525 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001526 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001527 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001528 (if (/= ci need)
1529 (save-excursion
1530 (beginning-of-line)
1531 (delete-horizontal-space)
1532 (indent-to need)))
1533 (if move-to-indentation-p (back-to-indentation))))
1534
1535(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001536 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001537This is just `strives to' because correct indentation can't be computed
1538from scratch for Python code. In general, deletes the whitespace before
1539point, inserts a newline, and takes an educated guess as to how you want
1540the new line indented."
1541 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001542 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001543 (if (< ci (current-column)) ; if point beyond indentation
1544 (newline-and-indent)
1545 ;; else try to act like newline-and-indent "normally" acts
1546 (beginning-of-line)
1547 (insert-char ?\n 1)
1548 (move-to-column ci))))
1549
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001550(defun py-compute-indentation (honor-block-close-p)
1551 ;; implements all the rules for indentation computation. when
1552 ;; honor-block-close-p is non-nil, statements such as return, raise,
1553 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001554 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001555 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001556 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001557 (pps (parse-partial-sexp bod (point)))
1558 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001559 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001560 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001561 ((or (and (nth 3 pps) (nth 3 boipps))
1562 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001563 (save-excursion
1564 (if (not py-align-multiline-strings-p) 0
1565 ;; skip back over blank & non-indenting comment lines
1566 ;; note: will skip a blank or non-indenting comment line
1567 ;; that happens to be a continuation line too
1568 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1569 (back-to-indentation)
1570 (current-column))))
1571 ;; are we on a continuation line?
1572 ((py-continuation-line-p)
1573 (let ((startpos (point))
1574 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001575 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001576 (if open-bracket-pos
1577 (progn
1578 ;; align with first item in list; else a normal
1579 ;; indent beyond the line with the open bracket
1580 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1581 ;; is the first list item on the same line?
1582 (skip-chars-forward " \t")
1583 (if (null (memq (following-char) '(?\n ?# ?\\)))
1584 ; yes, so line up with it
1585 (current-column)
1586 ;; first list item on another line, or doesn't exist yet
1587 (forward-line 1)
1588 (while (and (< (point) startpos)
1589 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1590 (forward-line 1))
Barry Warsaw92166d91998-04-01 21:59:41 +00001591 (if (and (< (point) startpos)
1592 (/= startpos
1593 (save-excursion
1594 (goto-char (1+ open-bracket-pos))
Barry Warsaw77d1fce1998-04-16 20:04:59 +00001595 (forward-comment (point-max))
Barry Warsaw92166d91998-04-01 21:59:41 +00001596 (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001597 ;; again mimic the first list item
1598 (current-indentation)
1599 ;; else they're about to enter the first item
1600 (goto-char open-bracket-pos)
1601 (+ (current-indentation) py-indent-offset))))
1602
1603 ;; else on backslash continuation line
1604 (forward-line -1)
1605 (if (py-continuation-line-p) ; on at least 3rd line in block
1606 (current-indentation) ; so just continue the pattern
1607 ;; else started on 2nd line in block, so indent more.
1608 ;; if base line is an assignment with a start on a RHS,
1609 ;; indent to 2 beyond the leftmost "="; else skip first
1610 ;; chunk of non-whitespace characters on base line, + 1 more
1611 ;; column
1612 (end-of-line)
1613 (setq endpos (point) searching t)
1614 (back-to-indentation)
1615 (setq startpos (point))
1616 ;; look at all "=" from left to right, stopping at first
1617 ;; one not nested in a list or string
1618 (while searching
1619 (skip-chars-forward "^=" endpos)
1620 (if (= (point) endpos)
1621 (setq searching nil)
1622 (forward-char 1)
1623 (setq state (parse-partial-sexp startpos (point)))
1624 (if (and (zerop (car state)) ; not in a bracket
1625 (null (nth 3 state))) ; & not in a string
1626 (progn
1627 (setq searching nil) ; done searching in any case
1628 (setq found
1629 (not (or
1630 (eq (following-char) ?=)
1631 (memq (char-after (- (point) 2))
1632 '(?< ?> ?!)))))))))
1633 (if (or (not found) ; not an assignment
1634 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1635 (progn
1636 (goto-char startpos)
1637 (skip-chars-forward "^ \t\n")))
1638 (1+ (current-column))))))
1639
1640 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001641 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001642
Barry Warsawa7891711996-08-01 15:53:09 +00001643 ;; Dfn: "Indenting comment line". A line containing only a
1644 ;; comment, but which is treated like a statement for
1645 ;; indentation calculation purposes. Such lines are only
1646 ;; treated specially by the mode; they are not treated
1647 ;; specially by the Python interpreter.
1648
1649 ;; The rules for indenting comment lines are a line where:
1650 ;; - the first non-whitespace character is `#', and
1651 ;; - the character following the `#' is whitespace, and
1652 ;; - the line is outdented with respect to (i.e. to the left
1653 ;; of) the indentation of the preceding non-blank line.
1654
1655 ;; The first non-blank line following an indenting comment
1656 ;; line is given the same amount of indentation as the
1657 ;; indenting comment line.
1658
1659 ;; All other comment-only lines are ignored for indentation
1660 ;; purposes.
1661
1662 ;; Are we looking at a comment-only line which is *not* an
1663 ;; indenting comment line? If so, we assume that its been
1664 ;; placed at the desired indentation, so leave it alone.
1665 ;; Indenting comment lines are aligned as statements down
1666 ;; below.
1667 ((and (looking-at "[ \t]*#[^ \t\n]")
1668 ;; NOTE: this test will not be performed in older Emacsen
1669 (fboundp 'forward-comment)
1670 (<= (current-indentation)
1671 (save-excursion
1672 (forward-comment (- (point-max)))
1673 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001674 (current-indentation))
1675
1676 ;; else indentation based on that of the statement that
1677 ;; precedes us; use the first line of that statement to
1678 ;; establish the base, in case the user forced a non-std
1679 ;; indentation for the continuation lines (if any)
1680 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001681 ;; skip back over blank & non-indenting comment lines note:
1682 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001683 ;; happens to be a continuation line too. use fast Emacs 19
1684 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001685 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001686 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001687 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001688 (let (done)
1689 (while (not done)
1690 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1691 nil 'move)
1692 (setq done (or (eq py-honor-comment-indentation t)
1693 (bobp)
1694 (/= (following-char) ?#)
1695 (not (zerop (current-column)))))
1696 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001697 ;; if we landed inside a string, go to the beginning of that
1698 ;; string. this handles triple quoted, multi-line spanning
1699 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001700 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001701 (skip (and delim (make-string 1 delim))))
1702 (when skip
1703 (save-excursion
1704 (py-safe (search-backward skip))
1705 (if (and (eq (char-before) delim)
1706 (eq (char-before (1- (point))) delim))
1707 (setq skip (make-string 3 delim))))
1708 ;; we're looking at a triple-quoted string
1709 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001710 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001711 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001712 (+ (current-indentation)
1713 (if (py-statement-opens-block-p)
1714 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001715 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001716 (- py-indent-offset)
1717 0)))
1718 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001719
1720(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001721 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001722By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001723`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001724Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001725`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001726their own buffer-local copy), both those currently existing and those
1727created later in the Emacs session.
1728
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001729Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001730There's no excuse for such foolishness, but sometimes you have to deal
1731with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001732`py-indent-offset' to what it thinks it was when they created the
1733mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001734
1735Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001736looking for a line that opens a block of code. `py-indent-offset' is
1737set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001738statement following it. If the search doesn't succeed going forward,
1739it's tried again going backward."
1740 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001741 (let (new-value
1742 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001743 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001744 (found nil)
1745 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001746 (py-goto-initial-line)
1747 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001748 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1749 (not (py-in-literal restart)))
1750 (setq restart (point))
1751 (py-goto-initial-line)
1752 (if (py-statement-opens-block-p)
1753 (setq found t)
1754 (goto-char restart))))
1755 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001756 (goto-char start)
1757 (py-goto-initial-line)
1758 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001759 (setq found (and
1760 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1761 (or (py-goto-initial-line) t) ; always true -- side effect
1762 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001763 (setq colon-indent (current-indentation)
1764 found (and found (zerop (py-next-statement 1)))
1765 new-value (- (current-indentation) colon-indent))
1766 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001767 (if (not found)
1768 (error "Sorry, couldn't guess a value for py-indent-offset")
1769 (funcall (if global 'kill-local-variable 'make-local-variable)
1770 'py-indent-offset)
1771 (setq py-indent-offset new-value)
1772 (message "%s value of py-indent-offset set to %d"
1773 (if global "Global" "Local")
1774 py-indent-offset))
1775 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001776
1777(defun py-shift-region (start end count)
1778 (save-excursion
1779 (goto-char end) (beginning-of-line) (setq end (point))
1780 (goto-char start) (beginning-of-line) (setq start (point))
1781 (indent-rigidly start end count)))
1782
1783(defun py-shift-region-left (start end &optional count)
1784 "Shift region of Python code to the left.
1785The lines from the line containing the start of the current region up
1786to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001787shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001788
1789If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001790many columns. With no active region, outdent only the current line.
1791You cannot outdent the region if any line is already at column zero."
1792 (interactive
1793 (let ((p (point))
1794 (m (mark))
1795 (arg current-prefix-arg))
1796 (if m
1797 (list (min p m) (max p m) arg)
1798 (list p (save-excursion (forward-line 1) (point)) arg))))
1799 ;; if any line is at column zero, don't shift the region
1800 (save-excursion
1801 (goto-char start)
1802 (while (< (point) end)
1803 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001804 (if (and (zerop (current-column))
1805 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001806 (error "Region is at left edge."))
1807 (forward-line 1)))
1808 (py-shift-region start end (- (prefix-numeric-value
1809 (or count py-indent-offset))))
1810 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001811
1812(defun py-shift-region-right (start end &optional count)
1813 "Shift region of Python code to the right.
1814The lines from the line containing the start of the current region up
1815to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001816shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001817
1818If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001819many columns. With no active region, indent only the current line."
1820 (interactive
1821 (let ((p (point))
1822 (m (mark))
1823 (arg current-prefix-arg))
1824 (if m
1825 (list (min p m) (max p m) arg)
1826 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001827 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001828 (or count py-indent-offset)))
1829 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001830
1831(defun py-indent-region (start end &optional indent-offset)
1832 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001833
Barry Warsaw7ae77681994-12-12 20:38:05 +00001834The lines from the line containing the start of the current region up
1835to (but not including) the line containing the end of the region are
1836reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001837character in the first column, the first line is left alone and the
1838rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001839region is reindented with respect to the (closest code or indenting
1840comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001841
1842This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001843control structures are introduced or removed, or to reformat code
1844using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001845
1846If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001847the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001848used.
1849
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001850Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001851is called! This function does not compute proper indentation from
1852scratch (that's impossible in Python), it merely adjusts the existing
1853indentation to be correct in context.
1854
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001855Warning: This function really has no idea what to do with
1856non-indenting comment lines, and shifts them as if they were indenting
1857comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001858
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001859Special cases: whitespace is deleted from blank lines; continuation
1860lines are shifted by the same amount their initial line was shifted,
1861in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001862initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001863 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001864 (save-excursion
1865 (goto-char end) (beginning-of-line) (setq end (point-marker))
1866 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001867 (let ((py-indent-offset (prefix-numeric-value
1868 (or indent-offset py-indent-offset)))
1869 (indents '(-1)) ; stack of active indent levels
1870 (target-column 0) ; column to which to indent
1871 (base-shifted-by 0) ; amount last base line was shifted
1872 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001873 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001874 0))
1875 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001876 (while (< (point) end)
1877 (setq ci (current-indentation))
1878 ;; figure out appropriate target column
1879 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001880 ((or (eq (following-char) ?#) ; comment in column 1
1881 (looking-at "[ \t]*$")) ; entirely blank
1882 (setq target-column 0))
1883 ((py-continuation-line-p) ; shift relative to base line
1884 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001885 (t ; new base line
1886 (if (> ci (car indents)) ; going deeper; push it
1887 (setq indents (cons ci indents))
1888 ;; else we should have seen this indent before
1889 (setq indents (memq ci indents)) ; pop deeper indents
1890 (if (null indents)
1891 (error "Bad indentation in region, at line %d"
1892 (save-restriction
1893 (widen)
1894 (1+ (count-lines 1 (point)))))))
1895 (setq target-column (+ indent-base
1896 (* py-indent-offset
1897 (- (length indents) 2))))
1898 (setq base-shifted-by (- target-column ci))))
1899 ;; shift as needed
1900 (if (/= ci target-column)
1901 (progn
1902 (delete-horizontal-space)
1903 (indent-to target-column)))
1904 (forward-line 1))))
1905 (set-marker end nil))
1906
Barry Warsawa7891711996-08-01 15:53:09 +00001907(defun py-comment-region (beg end &optional arg)
1908 "Like `comment-region' but uses double hash (`#') comment starter."
1909 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001910 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001911 (comment-region beg end arg)))
1912
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001913
1914;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001915(defun py-previous-statement (count)
1916 "Go to the start of previous Python statement.
1917If the statement at point is the i'th Python statement, goes to the
1918start of statement i-COUNT. If there is no such statement, goes to the
1919first statement. Returns count of statements left to move.
1920`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001921 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001922 (if (< count 0) (py-next-statement (- count))
1923 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001924 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001925 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001926 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001927 (> count 0)
1928 (zerop (forward-line -1))
1929 (py-goto-statement-at-or-above))
1930 (setq count (1- count)))
1931 (if (> count 0) (goto-char start)))
1932 count))
1933
1934(defun py-next-statement (count)
1935 "Go to the start of next Python statement.
1936If the statement at point is the i'th Python statement, goes to the
1937start of statement i+COUNT. If there is no such statement, goes to the
1938last statement. Returns count of statements left to move. `Statements'
1939do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001940 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001941 (if (< count 0) (py-previous-statement (- count))
1942 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001943 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001944 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001945 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001946 (> count 0)
1947 (py-goto-statement-below))
1948 (setq count (1- count)))
1949 (if (> count 0) (goto-char start)))
1950 count))
1951
1952(defun py-goto-block-up (&optional nomark)
1953 "Move up to start of current block.
1954Go to the statement that starts the smallest enclosing block; roughly
1955speaking, this will be the closest preceding statement that ends with a
1956colon and is indented less than the statement you started on. If
1957successful, also sets the mark to the starting point.
1958
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001959`\\[py-mark-block]' can be used afterward to mark the whole code
1960block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001961
1962If called from a program, the mark will not be set if optional argument
1963NOMARK is not nil."
1964 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001965 (let ((start (point))
1966 (found nil)
1967 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001968 (py-goto-initial-line)
1969 ;; if on blank or non-indenting comment line, use the preceding stmt
1970 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1971 (progn
1972 (py-goto-statement-at-or-above)
1973 (setq found (py-statement-opens-block-p))))
1974 ;; search back for colon line indented less
1975 (setq initial-indent (current-indentation))
1976 (if (zerop initial-indent)
1977 ;; force fast exit
1978 (goto-char (point-min)))
1979 (while (not (or found (bobp)))
1980 (setq found
1981 (and
1982 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1983 (or (py-goto-initial-line) t) ; always true -- side effect
1984 (< (current-indentation) initial-indent)
1985 (py-statement-opens-block-p))))
1986 (if found
1987 (progn
1988 (or nomark (push-mark start))
1989 (back-to-indentation))
1990 (goto-char start)
1991 (error "Enclosing block not found"))))
1992
1993(defun beginning-of-python-def-or-class (&optional class)
1994 "Move point to start of def (or class, with prefix arg).
1995
1996Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001997arg, looks for a `class' instead. The docs assume the `def' case;
1998just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001999
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002000If point is in a def statement already, and after the `d', simply
2001moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002002
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002003Else (point is not in a def statement, or at or before the `d' of a
2004def statement), searches for the closest preceding def statement, and
2005leaves point at its start. If no such statement can be found, leaves
2006point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002007
2008Returns t iff a def statement is found by these rules.
2009
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002010Note that doing this command repeatedly will take you closer to the
2011start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002012
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002013If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00002014`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002015 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002016 (let ((at-or-before-p (<= (current-column) (current-indentation)))
2017 (start-of-line (progn (beginning-of-line) (point)))
2018 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002019 (if (or (/= start-of-stmt start-of-line)
2020 (not at-or-before-p))
2021 (end-of-line)) ; OK to match on this line
2022 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002023 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002024
2025(defun end-of-python-def-or-class (&optional class)
2026 "Move point beyond end of def (or class, with prefix arg) body.
2027
2028By default, looks for an appropriate `def'. If you supply a prefix arg,
2029looks for a `class' instead. The docs assume the `def' case; just
2030substitute `class' for `def' for the other case.
2031
2032If point is in a def statement already, this is the def we use.
2033
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002034Else if the def found by `\\[beginning-of-python-def-or-class]'
2035contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002036
2037Else we search forward for the closest following def, and use that.
2038
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002039If a def can be found by these rules, point is moved to the start of
2040the line immediately following the def block, and the position of the
2041start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002042
2043Else point is moved to the end of the buffer, and nil is returned.
2044
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002045Note that doing this command repeatedly will take you closer to the
2046end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002047
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002048If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00002049`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002050 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002051 (let ((start (progn (py-goto-initial-line) (point)))
2052 (which (if class "class" "def"))
2053 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002054 ;; move point to start of appropriate def/class
2055 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2056 (setq state 'at-beginning)
2057 ;; else see if beginning-of-python-def-or-class hits container
2058 (if (and (beginning-of-python-def-or-class class)
2059 (progn (py-goto-beyond-block)
2060 (> (point) start)))
2061 (setq state 'at-end)
2062 ;; else search forward
2063 (goto-char start)
2064 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2065 (progn (setq state 'at-beginning)
2066 (beginning-of-line)))))
2067 (cond
2068 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2069 ((eq state 'at-end) t)
2070 ((eq state 'not-found) nil)
2071 (t (error "internal error in end-of-python-def-or-class")))))
2072
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002073
2074;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002075(defun py-mark-block (&optional extend just-move)
2076 "Mark following block of lines. With prefix arg, mark structure.
2077Easier to use than explain. It sets the region to an `interesting'
2078block of succeeding lines. If point is on a blank line, it goes down to
2079the next non-blank line. That will be the start of the region. The end
2080of the region depends on the kind of line at the start:
2081
2082 - If a comment, the region will include all succeeding comment lines up
2083 to (but not including) the next non-comment line (if any).
2084
2085 - Else if a prefix arg is given, and the line begins one of these
2086 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002087
2088 if elif else try except finally for while def class
2089
Barry Warsaw7ae77681994-12-12 20:38:05 +00002090 the region will be set to the body of the structure, including
2091 following blocks that `belong' to it, but excluding trailing blank
2092 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002093 and all (if any) of the following `except' and `finally' blocks
2094 that belong to the `try' structure will be in the region. Ditto
2095 for if/elif/else, for/else and while/else structures, and (a bit
2096 degenerate, since they're always one-block structures) def and
2097 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002098
2099 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002100 block (see list above), and the block is not a `one-liner' (i.e.,
2101 the statement ends with a colon, not with code), the region will
2102 include all succeeding lines up to (but not including) the next
2103 code statement (if any) that's indented no more than the starting
2104 line, except that trailing blank and comment lines are excluded.
2105 E.g., if the starting line begins a multi-statement `def'
2106 structure, the region will be set to the full function definition,
2107 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002108
2109 - Else the region will include all succeeding lines up to (but not
2110 including) the next blank line, or code or indenting-comment line
2111 indented strictly less than the starting line. Trailing indenting
2112 comment lines are included in this case, but not trailing blank
2113 lines.
2114
2115A msg identifying the location of the mark is displayed in the echo
2116area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2117
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002118If called from a program, optional argument EXTEND plays the role of
2119the prefix arg, and if optional argument JUST-MOVE is not nil, just
2120moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002121 (interactive "P") ; raw prefix arg
2122 (py-goto-initial-line)
2123 ;; skip over blank lines
2124 (while (and
2125 (looking-at "[ \t]*$") ; while blank line
2126 (not (eobp))) ; & somewhere to go
2127 (forward-line 1))
2128 (if (eobp)
2129 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002130 (let ((initial-pos (point))
2131 (initial-indent (current-indentation))
2132 last-pos ; position of last stmt in region
2133 (followers
2134 '((if elif else) (elif elif else) (else)
2135 (try except finally) (except except) (finally)
2136 (for else) (while else)
2137 (def) (class) ) )
2138 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002139
2140 (cond
2141 ;; if comment line, suck up the following comment lines
2142 ((looking-at "[ \t]*#")
2143 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2144 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2145 (setq last-pos (point)))
2146
2147 ;; else if line is a block line and EXTEND given, suck up
2148 ;; the whole structure
2149 ((and extend
2150 (setq first-symbol (py-suck-up-first-keyword) )
2151 (assq first-symbol followers))
2152 (while (and
2153 (or (py-goto-beyond-block) t) ; side effect
2154 (forward-line -1) ; side effect
2155 (setq last-pos (point)) ; side effect
2156 (py-goto-statement-below)
2157 (= (current-indentation) initial-indent)
2158 (setq next-symbol (py-suck-up-first-keyword))
2159 (memq next-symbol (cdr (assq first-symbol followers))))
2160 (setq first-symbol next-symbol)))
2161
2162 ;; else if line *opens* a block, search for next stmt indented <=
2163 ((py-statement-opens-block-p)
2164 (while (and
2165 (setq last-pos (point)) ; always true -- side effect
2166 (py-goto-statement-below)
2167 (> (current-indentation) initial-indent))
2168 nil))
2169
2170 ;; else plain code line; stop at next blank line, or stmt or
2171 ;; indenting comment line indented <
2172 (t
2173 (while (and
2174 (setq last-pos (point)) ; always true -- side effect
2175 (or (py-goto-beyond-final-line) t)
2176 (not (looking-at "[ \t]*$")) ; stop at blank line
2177 (or
2178 (>= (current-indentation) initial-indent)
2179 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2180 nil)))
2181
2182 ;; skip to end of last stmt
2183 (goto-char last-pos)
2184 (py-goto-beyond-final-line)
2185
2186 ;; set mark & display
2187 (if just-move
2188 () ; just return
2189 (push-mark (point) 'no-msg)
2190 (forward-line -1)
2191 (message "Mark set after: %s" (py-suck-up-leading-text))
2192 (goto-char initial-pos))))
2193
Barry Warsaw2518c671997-11-05 00:51:08 +00002194(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002195 "Set region to body of def (or class, with prefix arg) enclosing point.
2196Pushes the current mark, then point, on the mark ring (all language
2197modes do this, but although it's handy it's never documented ...).
2198
2199In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002200hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
2201`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002202
2203And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002204Turned out that was more confusing than useful: the `goto start' and
2205`goto end' commands are usually used to search through a file, and
2206people expect them to act a lot like `search backward' and `search
2207forward' string-search commands. But because Python `def' and `class'
2208can nest to arbitrary levels, finding the smallest def containing
2209point cannot be done via a simple backward search: the def containing
2210point may not be the closest preceding def, or even the closest
2211preceding def that's indented less. The fancy algorithm required is
2212appropriate for the usual uses of this `mark' command, but not for the
2213`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002214
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002215So the def marked by this command may not be the one either of the
2216`goto' commands find: If point is on a blank or non-indenting comment
2217line, moves back to start of the closest preceding code statement or
2218indenting comment line. If this is a `def' statement, that's the def
2219we use. Else searches for the smallest enclosing `def' block and uses
2220that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002221
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002222When an enclosing def is found: The mark is left immediately beyond
2223the last line of the def block. Point is left at the start of the
2224def, except that: if the def is preceded by a number of comment lines
2225followed by (at most) one optional blank line, point is left at the
2226start of the comments; else if the def is preceded by a blank line,
2227point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002228
2229The intent is to mark the containing def/class and its associated
2230documentation, to make moving and duplicating functions and classes
2231pleasant."
2232 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002233 (let ((start (point))
2234 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002235 (push-mark start)
2236 (if (not (py-go-up-tree-to-keyword which))
2237 (progn (goto-char start)
2238 (error "Enclosing %s not found" which))
2239 ;; else enclosing def/class found
2240 (setq start (point))
2241 (py-goto-beyond-block)
2242 (push-mark (point))
2243 (goto-char start)
2244 (if (zerop (forward-line -1)) ; if there is a preceding line
2245 (progn
2246 (if (looking-at "[ \t]*$") ; it's blank
2247 (setq start (point)) ; so reset start point
2248 (goto-char start)) ; else try again
2249 (if (zerop (forward-line -1))
2250 (if (looking-at "[ \t]*#") ; a comment
2251 ;; look back for non-comment line
2252 ;; tricky: note that the regexp matches a blank
2253 ;; line, cuz \n is in the 2nd character class
2254 (and
2255 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2256 (forward-line 1))
2257 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002258 (goto-char start)))))))
2259 (exchange-point-and-mark)
2260 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002261
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002262;; ripped from cc-mode
2263(defun py-forward-into-nomenclature (&optional arg)
2264 "Move forward to end of a nomenclature section or word.
2265With arg, to it arg times.
2266
2267A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2268 (interactive "p")
2269 (let ((case-fold-search nil))
2270 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002271 (re-search-forward
2272 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2273 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002274 (while (and (< arg 0)
2275 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002276 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002277 (point-min) 0))
2278 (forward-char 1)
2279 (setq arg (1+ arg)))))
2280 (py-keep-region-active))
2281
2282(defun py-backward-into-nomenclature (&optional arg)
2283 "Move backward to beginning of a nomenclature section or word.
2284With optional ARG, move that many times. If ARG is negative, move
2285forward.
2286
2287A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2288 (interactive "p")
2289 (py-forward-into-nomenclature (- arg))
2290 (py-keep-region-active))
2291
2292
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002293
2294;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002295
2296;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002297;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2298;; out of the right places, along with the keys they're on & current
2299;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002300(defun py-dump-help-string (str)
2301 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002302 (let ((locals (buffer-local-variables))
2303 funckind funcname func funcdoc
2304 (start 0) mstart end
2305 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002306 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2307 (setq mstart (match-beginning 0) end (match-end 0)
2308 funckind (substring str (match-beginning 1) (match-end 1))
2309 funcname (substring str (match-beginning 2) (match-end 2))
2310 func (intern funcname))
2311 (princ (substitute-command-keys (substring str start mstart)))
2312 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002313 ((equal funckind "c") ; command
2314 (setq funcdoc (documentation func)
2315 keys (concat
2316 "Key(s): "
2317 (mapconcat 'key-description
2318 (where-is-internal func py-mode-map)
2319 ", "))))
2320 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002321 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002322 keys (if (assq func locals)
2323 (concat
2324 "Local/Global values: "
2325 (prin1-to-string (symbol-value func))
2326 " / "
2327 (prin1-to-string (default-value func)))
2328 (concat
2329 "Value: "
2330 (prin1-to-string (symbol-value func))))))
2331 (t ; unexpected
2332 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002333 (princ (format "\n-> %s:\t%s\t%s\n\n"
2334 (if (equal funckind "c") "Command" "Variable")
2335 funcname keys))
2336 (princ funcdoc)
2337 (terpri)
2338 (setq start end))
2339 (princ (substitute-command-keys (substring str start))))
2340 (print-help-return-message)))
2341
2342(defun py-describe-mode ()
2343 "Dump long form of Python-mode docs."
2344 (interactive)
2345 (py-dump-help-string "Major mode for editing Python files.
2346Knows about Python indentation, tokens, comments and continuation lines.
2347Paragraphs are separated by blank lines only.
2348
2349Major sections below begin with the string `@'; specific function and
2350variable docs begin with `->'.
2351
2352@EXECUTING PYTHON CODE
2353
2354\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2355\\[py-execute-region]\tsends the current region
2356\\[py-shell]\tstarts a Python interpreter window; this will be used by
2357\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2358%c:py-execute-buffer
2359%c:py-execute-region
2360%c:py-shell
2361
2362@VARIABLES
2363
2364py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002365py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002366
2367py-python-command\tshell command to invoke Python interpreter
2368py-scroll-process-buffer\talways scroll Python process buffer
2369py-temp-directory\tdirectory used for temp files (if needed)
2370
2371py-beep-if-tab-change\tring the bell if tab-width is changed
2372%v:py-indent-offset
2373%v:py-block-comment-prefix
2374%v:py-python-command
2375%v:py-scroll-process-buffer
2376%v:py-temp-directory
2377%v:py-beep-if-tab-change
2378
2379@KINDS OF LINES
2380
2381Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002382preceding line ends with a backslash that's not part of a comment, or
2383the paren/bracket/brace nesting level at the start of the line is
2384non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002385
2386An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002387possibly blanks or tabs), a `comment line' (leftmost non-blank
2388character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002389
2390Comment Lines
2391
2392Although all comment lines are treated alike by Python, Python mode
2393recognizes two kinds that act differently with respect to indentation.
2394
2395An `indenting comment line' is a comment line with a blank, tab or
2396nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002397treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002398indenting comment line will be indented like the comment line. All
2399other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002400following the initial `#') are `non-indenting comment lines', and
2401their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002402
2403Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002404whenever possible. Non-indenting comment lines are useful in cases
2405like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002406
2407\ta = b # a very wordy single-line comment that ends up being
2408\t #... continued onto another line
2409
2410\tif a == b:
2411##\t\tprint 'panic!' # old code we've `commented out'
2412\t\treturn a
2413
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002414Since the `#...' and `##' comment lines have a non-whitespace
2415character following the initial `#', Python mode ignores them when
2416computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002417
2418Continuation Lines and Statements
2419
2420The Python-mode commands generally work on statements instead of on
2421individual lines, where a `statement' is a comment or blank line, or a
2422code line and all of its following continuation lines (if any)
2423considered as a single logical unit. The commands in this mode
2424generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002425statement containing point, even if point happens to be in the middle
2426of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002427
2428
2429@INDENTATION
2430
2431Primarily for entering new code:
2432\t\\[indent-for-tab-command]\t indent line appropriately
2433\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002434\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002435
2436Primarily for reindenting existing code:
2437\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2438\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2439
2440\t\\[py-indent-region]\t reindent region to match its context
2441\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2442\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2443
2444Unlike most programming languages, Python uses indentation, and only
2445indentation, to specify block structure. Hence the indentation supplied
2446automatically by Python-mode is just an educated guess: only you know
2447the block structure you intend, so only you can supply correct
2448indentation.
2449
2450The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2451the indentation of preceding statements. E.g., assuming
2452py-indent-offset is 4, after you enter
2453\tif a > 0: \\[py-newline-and-indent]
2454the cursor will be moved to the position of the `_' (_ is not a
2455character in the file, it's just used here to indicate the location of
2456the cursor):
2457\tif a > 0:
2458\t _
2459If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2460to
2461\tif a > 0:
2462\t c = d
2463\t _
2464Python-mode cannot know whether that's what you intended, or whether
2465\tif a > 0:
2466\t c = d
2467\t_
2468was your intent. In general, Python-mode either reproduces the
2469indentation of the (closest code or indenting-comment) preceding
2470statement, or adds an extra py-indent-offset blanks if the preceding
2471statement has `:' as its last significant (non-whitespace and non-
2472comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002473\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002474
2475Continuation lines are given extra indentation. If you don't like the
2476suggested indentation, change it to something you do like, and Python-
2477mode will strive to indent later lines of the statement in the same way.
2478
2479If a line is a continuation line by virtue of being in an unclosed
2480paren/bracket/brace structure (`list', for short), the suggested
2481indentation depends on whether the current line contains the first item
2482in the list. If it does, it's indented py-indent-offset columns beyond
2483the indentation of the line containing the open bracket. If you don't
2484like that, change it by hand. The remaining items in the list will mimic
2485whatever indentation you give to the first item.
2486
2487If a line is a continuation line because the line preceding it ends with
2488a backslash, the third and following lines of the statement inherit their
2489indentation from the line preceding them. The indentation of the second
2490line in the statement depends on the form of the first (base) line: if
2491the base line is an assignment statement with anything more interesting
2492than the backslash following the leftmost assigning `=', the second line
2493is indented two columns beyond that `='. Else it's indented to two
2494columns beyond the leftmost solid chunk of non-whitespace characters on
2495the base line.
2496
2497Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2498repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2499structure you intend.
2500%c:indent-for-tab-command
2501%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002502%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002503
2504
2505The next function may be handy when editing code you didn't write:
2506%c:py-guess-indent-offset
2507
2508
2509The remaining `indent' functions apply to a region of Python code. They
2510assume the block structure (equals indentation, in Python) of the region
2511is correct, and alter the indentation in various ways while preserving
2512the block structure:
2513%c:py-indent-region
2514%c:py-shift-region-left
2515%c:py-shift-region-right
2516
2517@MARKING & MANIPULATING REGIONS OF CODE
2518
2519\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002520\\[py-mark-def-or-class]\t mark smallest enclosing def
2521\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002522\\[comment-region]\t comment out region of code
2523\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002524%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002525%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002526%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002527
2528@MOVING POINT
2529
2530\\[py-previous-statement]\t move to statement preceding point
2531\\[py-next-statement]\t move to statement following point
2532\\[py-goto-block-up]\t move up to start of current block
2533\\[beginning-of-python-def-or-class]\t move to start of def
2534\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2535\\[end-of-python-def-or-class]\t move to end of def
2536\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2537
2538The first two move to one statement beyond the statement that contains
2539point. A numeric prefix argument tells them to move that many
2540statements instead. Blank lines, comment lines, and continuation lines
2541do not count as `statements' for these commands. So, e.g., you can go
2542to the first code statement in a file by entering
2543\t\\[beginning-of-buffer]\t to move to the top of the file
2544\t\\[py-next-statement]\t to skip over initial comments and blank lines
2545Or do `\\[py-previous-statement]' with a huge prefix argument.
2546%c:py-previous-statement
2547%c:py-next-statement
2548%c:py-goto-block-up
2549%c:beginning-of-python-def-or-class
2550%c:end-of-python-def-or-class
2551
2552@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2553
2554`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2555
2556`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2557overall class and def structure of a module.
2558
2559`\\[back-to-indentation]' moves point to a line's first non-blank character.
2560
2561`\\[indent-relative]' is handy for creating odd indentation.
2562
2563@OTHER EMACS HINTS
2564
2565If you don't like the default value of a variable, change its value to
2566whatever you do like by putting a `setq' line in your .emacs file.
2567E.g., to set the indentation increment to 4, put this line in your
2568.emacs:
2569\t(setq py-indent-offset 4)
2570To see the value of a variable, do `\\[describe-variable]' and enter the variable
2571name at the prompt.
2572
2573When entering a key sequence like `C-c C-n', it is not necessary to
2574release the CONTROL key after doing the `C-c' part -- it suffices to
2575press the CONTROL key, press and release `c' (while still holding down
2576CONTROL), press and release `n' (while still holding down CONTROL), &
2577then release CONTROL.
2578
2579Entering Python mode calls with no arguments the value of the variable
2580`python-mode-hook', if that value exists and is not nil; for backward
2581compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2582the Elisp manual for details.
2583
2584Obscure: When python-mode is first loaded, it looks for all bindings
2585to newline-and-indent in the global keymap, and shadows them with
2586local bindings to py-newline-and-indent."))
2587
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002588
2589;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002590(defvar py-parse-state-re
2591 (concat
2592 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2593 "\\|"
2594 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002595
Barry Warsaw7ae77681994-12-12 20:38:05 +00002596;; returns the parse state at point (see parse-partial-sexp docs)
2597(defun py-parse-state ()
2598 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002599 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002600 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002601 (while (not done)
2602 ;; back up to the first preceding line (if any; else start of
2603 ;; buffer) that begins with a popular Python keyword, or a
2604 ;; non- whitespace and non-comment character. These are good
2605 ;; places to start parsing to see whether where we started is
2606 ;; at a non-zero nesting level. It may be slow for people who
2607 ;; write huge code blocks or huge lists ... tough beans.
2608 (re-search-backward py-parse-state-re nil 'move)
2609 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002610 ;; In XEmacs, we have a much better way to test for whether
2611 ;; we're in a triple-quoted string or not. Emacs does not
2612 ;; have this built-in function, which is it's loss because
2613 ;; without scanning from the beginning of the buffer, there's
2614 ;; no accurate way to determine this otherwise.
2615 (if (not (fboundp 'buffer-syntactic-context))
2616 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002617 (progn
2618 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002619 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002620 (setq done (or (not (nth 3 pps))
2621 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002622 ;; XEmacs
2623 (setq done (or (not (buffer-syntactic-context))
2624 (bobp)))
2625 (when done
2626 (setq pps (parse-partial-sexp (point) here)))
2627 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002628 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002629
2630;; if point is at a non-zero nesting level, returns the number of the
2631;; character that opens the smallest enclosing unclosed list; else
2632;; returns nil.
2633(defun py-nesting-level ()
Barry Warsawf64b4051998-02-12 16:52:14 +00002634 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002635 (if (zerop (car status))
2636 nil ; not in a nest
2637 (car (cdr status))))) ; char# of open bracket
2638
2639;; t iff preceding line ends with backslash that's not in a comment
2640(defun py-backslash-continuation-line-p ()
2641 (save-excursion
2642 (beginning-of-line)
2643 (and
2644 ;; use a cheap test first to avoid the regexp if possible
2645 ;; use 'eq' because char-after may return nil
2646 (eq (char-after (- (point) 2)) ?\\ )
2647 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002648 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002649 (looking-at py-continued-re))))
2650
2651;; t iff current line is a continuation line
2652(defun py-continuation-line-p ()
2653 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002654 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002655 (or (py-backslash-continuation-line-p)
2656 (py-nesting-level))))
2657
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002658;; go to initial line of current statement; usually this is the line
2659;; we're on, but if we're on the 2nd or following lines of a
2660;; continuation block, we need to go up to the first line of the
2661;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002662;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002663;; Tricky: We want to avoid quadratic-time behavior for long continued
2664;; blocks, whether of the backslash or open-bracket varieties, or a
2665;; mix of the two. The following manages to do that in the usual
2666;; cases.
Barry Warsawc210e691998-01-20 22:52:56 +00002667;;
2668;; Also, if we're sitting inside a triple quoted string, this will
2669;; drop us at the line that begins the string.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002670(defun py-goto-initial-line ()
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002671 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002672 (while (py-continuation-line-p)
2673 (beginning-of-line)
2674 (if (py-backslash-continuation-line-p)
2675 (while (py-backslash-continuation-line-p)
2676 (forward-line -1))
2677 ;; else zip out of nested brackets/braces/parens
2678 (while (setq open-bracket-pos (py-nesting-level))
2679 (goto-char open-bracket-pos)))))
2680 (beginning-of-line))
2681
2682;; go to point right beyond final line of current statement; usually
2683;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002684;; statement we need to skip over the continuation lines. Tricky:
2685;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002686(defun py-goto-beyond-final-line ()
2687 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002688 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002689 (while (and (py-continuation-line-p)
2690 (not (eobp)))
2691 ;; skip over the backslash flavor
2692 (while (and (py-backslash-continuation-line-p)
2693 (not (eobp)))
2694 (forward-line 1))
2695 ;; if in nest, zip to the end of the nest
2696 (setq state (py-parse-state))
2697 (if (and (not (zerop (car state)))
2698 (not (eobp)))
2699 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002700 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002701 (forward-line 1))))))
2702
2703;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002704;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002705(defun py-statement-opens-block-p ()
2706 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002707 (let ((start (point))
2708 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2709 (searching t)
2710 (answer nil)
2711 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002712 (goto-char start)
2713 (while searching
2714 ;; look for a colon with nothing after it except whitespace, and
2715 ;; maybe a comment
2716 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2717 finish t)
2718 (if (eq (point) finish) ; note: no `else' clause; just
2719 ; keep searching if we're not at
2720 ; the end yet
2721 ;; sure looks like it opens a block -- but it might
2722 ;; be in a comment
2723 (progn
2724 (setq searching nil) ; search is done either way
2725 (setq state (parse-partial-sexp start
2726 (match-beginning 0)))
2727 (setq answer (not (nth 4 state)))))
2728 ;; search failed: couldn't find another interesting colon
2729 (setq searching nil)))
2730 answer)))
2731
Barry Warsawf831d811996-07-31 20:42:59 +00002732(defun py-statement-closes-block-p ()
2733 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002734 ;; starts with `return', `raise', `break', `continue', and `pass'.
2735 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002736 (let ((here (point)))
2737 (back-to-indentation)
2738 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002739 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002740 (goto-char here))))
2741
Barry Warsaw7ae77681994-12-12 20:38:05 +00002742;; go to point right beyond final line of block begun by the current
2743;; line. This is the same as where py-goto-beyond-final-line goes
2744;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002745;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002746(defun py-goto-beyond-block ()
2747 (if (py-statement-opens-block-p)
2748 (py-mark-block nil 'just-move)
2749 (py-goto-beyond-final-line)))
2750
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002751;; go to start of first statement (not blank or comment or
2752;; continuation line) at or preceding point. returns t if there is
2753;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002754(defun py-goto-statement-at-or-above ()
2755 (py-goto-initial-line)
2756 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002757 ;; skip back over blank & comment lines
2758 ;; note: will skip a blank or comment line that happens to be
2759 ;; a continuation line too
2760 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2761 (progn (py-goto-initial-line) t)
2762 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002763 t))
2764
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002765;; go to start of first statement (not blank or comment or
2766;; continuation line) following the statement containing point returns
2767;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002768(defun py-goto-statement-below ()
2769 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002770 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002771 (py-goto-beyond-final-line)
2772 (while (and
2773 (looking-at py-blank-or-comment-re)
2774 (not (eobp)))
2775 (forward-line 1))
2776 (if (eobp)
2777 (progn (goto-char start) nil)
2778 t)))
2779
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002780;; go to start of statement, at or preceding point, starting with
2781;; keyword KEY. Skips blank lines and non-indenting comments upward
2782;; first. If that statement starts with KEY, done, else go back to
2783;; first enclosing block starting with KEY. If successful, leaves
2784;; point at the start of the KEY line & returns t. Else leaves point
2785;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002786(defun py-go-up-tree-to-keyword (key)
2787 ;; skip blanks and non-indenting #
2788 (py-goto-initial-line)
2789 (while (and
2790 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2791 (zerop (forward-line -1))) ; go back
2792 nil)
2793 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002794 (let* ((re (concat "[ \t]*" key "\\b"))
2795 (case-fold-search nil) ; let* so looking-at sees this
2796 (found (looking-at re))
2797 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002798 (while (not (or found dead))
2799 (condition-case nil ; in case no enclosing block
2800 (py-goto-block-up 'no-mark)
2801 (error (setq dead t)))
2802 (or dead (setq found (looking-at re))))
2803 (beginning-of-line)
2804 found))
2805
2806;; return string in buffer from start of indentation to end of line;
2807;; prefix "..." if leading whitespace was skipped
2808(defun py-suck-up-leading-text ()
2809 (save-excursion
2810 (back-to-indentation)
2811 (concat
2812 (if (bolp) "" "...")
2813 (buffer-substring (point) (progn (end-of-line) (point))))))
2814
2815;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2816;; as a Lisp symbol; return nil if none
2817(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002818 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002819 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2820 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2821 nil)))
2822
Barry Warsawb3e81d51996-09-04 15:12:42 +00002823(defun py-current-defun ()
2824 ;; tell add-log.el how to find the current function/method/variable
2825 (save-excursion
2826 (if (re-search-backward py-defun-start-re nil t)
2827 (or (match-string 3)
2828 (let ((method (match-string 2)))
2829 (if (and (not (zerop (length (match-string 1))))
2830 (re-search-backward py-class-start-re nil t))
2831 (concat (match-string 1) "." method)
2832 method)))
2833 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002834
2835
Barry Warsawfec75d61995-07-05 23:26:15 +00002836(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002837 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002838
Barry Warsaw850437a1995-03-08 21:50:28 +00002839(defun py-version ()
2840 "Echo the current version of `python-mode' in the minibuffer."
2841 (interactive)
2842 (message "Using `python-mode' version %s" py-version)
2843 (py-keep-region-active))
2844
2845;; only works under Emacs 19
2846;(eval-when-compile
2847; (require 'reporter))
2848
2849(defun py-submit-bug-report (enhancement-p)
2850 "Submit via mail a bug report on `python-mode'.
2851With \\[universal-argument] just submit an enhancement request."
2852 (interactive
2853 (list (not (y-or-n-p
2854 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002855 (let ((reporter-prompt-for-summary-p (if enhancement-p
2856 "(Very) brief summary: "
2857 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002858 (require 'reporter)
2859 (reporter-submit-bug-report
2860 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002861 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002862 ;; varlist
2863 (if enhancement-p nil
2864 '(py-python-command
2865 py-indent-offset
2866 py-block-comment-prefix
2867 py-scroll-process-buffer
2868 py-temp-directory
2869 py-beep-if-tab-change))
2870 nil ;pre-hooks
2871 nil ;post-hooks
2872 "Dear Barry,") ;salutation
2873 (if enhancement-p nil
2874 (set-mark (point))
2875 (insert
2876"Please replace this text with a sufficiently large code sample\n\
2877and an exact recipe so that I can reproduce your problem. Failure\n\
2878to do so may mean a greater delay in fixing your bug.\n\n")
2879 (exchange-point-and-mark)
2880 (py-keep-region-active))))
2881
2882
Barry Warsaw47384781997-11-26 05:27:45 +00002883(defun py-kill-emacs-hook ()
2884 (mapcar #'(lambda (filename)
2885 (py-safe (delete-file filename)))
2886 py-file-queue))
2887
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002888;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002889(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002890
2891
2892
2893(provide 'python-mode)
2894;;; python-mode.el ends here