blob: 1cb3dba70cdab9287900869000157dc34b0da5aa [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Barry Warsawf64b4051998-02-12 16:52:14 +00005;; Author: 1995-1998 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
Barry Warsawa97a3f31997-11-04 18:47:06 +00007;; Maintainer: python-mode@python.org
8;; Created: Feb 1992
9;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000010
Barry Warsaw5204b4a1998-04-02 19:27:18 +000011(defconst py-version "$Revision$"
Barry Warsawc72c11c1997-08-09 06:42:08 +000012 "`python-mode' version number.")
13
Barry Warsawcfec3591995-03-10 15:58:16 +000014;; This software is provided as-is, without express or implied
15;; warranty. Permission to use, copy, modify, distribute or sell this
16;; software, without fee, for any purpose and by any individual or
17;; organization, is hereby granted, provided that the above copyright
18;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000019
20;;; Commentary:
Barry Warsaw755c6711996-08-01 20:02:55 +000021
Barry Warsaw7b0f5681995-03-08 21:33:04 +000022;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000023;; by Tim Peters after an original idea by Michael A. Guravage. Tim
24;; subsequently left the net; in 1995, Barry Warsaw inherited the
25;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000026
Barry Warsaw37231521997-12-11 17:23:13 +000027;; COMPATIBILITY:
Barry Warsaw7b0f5681995-03-08 21:33:04 +000028
Barry Warsaw37231521997-12-11 17:23:13 +000029;; This version of python-mode.el is no longer compatible with Emacs
30;; 18. For a gabazillion reasons, I highly recommend upgrading to
31;; X/Emacs 19 or X/Emacs 20. I recommend at least Emacs 19.34 or
32;; XEmacs 19.15. Any of the v20 X/Emacsen should be fine.
Barry Warsaw673d05f1997-12-02 21:51:57 +000033
Barry Warsaw37231521997-12-11 17:23:13 +000034;; NOTE TO FSF EMACS USERS:
35
36;; You may need to acquire the Custom library -- this applies to users
37;; of Emacs 19.34 and NTEmacs based on 19.34, but not to Emacs 20
38;; users. You must also byte-compile this file before use -- this
39;; applies to FSF's Emacs 19.34, 20.x, and NTEmacs based on 19.34.
40;; None of this applies to XEmacs (although byte compilation is still
41;; recommended). You will also need to add the following to your
42;; .emacs file so that the .py files come up in python-mode:
Barry Warsaw7ae77681994-12-12 20:38:05 +000043;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000044;; (autoload 'python-mode "python-mode" "Python editing mode." t)
45;; (setq auto-mode-alist
46;; (cons '("\\.py$" . python-mode) auto-mode-alist))
47;; (setq interpreter-mode-alist
48;; (cons '("python" . python-mode) interpreter-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000049;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000050;; Assuming python-mode.el is on your load-path, it will be invoked
51;; when you visit a .py file, or a file with a first line that looks
52;; like:
53;;
54;; #! /usr/bin/env python
55
Barry Warsaw37231521997-12-11 17:23:13 +000056;; NOTE TO XEMACS USERS:
57
58;; An older version of this file was distributed with XEmacs 19.15,
59;; 19.16 and 20.3. By default, in XEmacs when you visit a .py file,
60;; the buffer is put in Python mode. Likewise for executable scripts
61;; with the word `python' on the first line. You shouldn't need to do
62;; much except make sure this new version is earlier in your
63;; load-path, and byte-compile this file.
64
65;; FOR MORE INFORMATION:
66
Barry Warsaw145ab1c1998-05-19 14:49:49 +000067;; Please see <http://www.python.org/emacs/python-mode/> for the
Barry Warsaw37231521997-12-11 17:23:13 +000068;; latest information and compatibility notes.
69
70;; BUG REPORTING:
Barry Warsaw7ae77681994-12-12 20:38:05 +000071
Barry Warsawaffc0ca1997-11-03 16:59:38 +000072;; To submit bug reports, use C-c C-b. Please include a complete, but
73;; concise code sample and a recipe for reproducing the bug. Send
74;; suggestions and other comments to python-mode@python.org.
75
76;; When in a Python mode buffer, do a C-h m for more help. It's
Barry Warsaw37231521997-12-11 17:23:13 +000077;; doubtful that a texinfo manual would be very useful, but if you
78;; want to contribute one, I'll certainly accept it!
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000079
Barry Warsaw5ea20d51997-12-06 00:00:47 +000080;; If you are using XEmacs, you may also want to check out OO-Browser
81;; that comes bundled with it, including documentation in the info
82;; pages. For GNU Emacs you have to install it yourself. To read
83;; more about OO-Browser, follow these links:
84
85;; http://www.python.org/workshops/1996-06/papers/h.pasanen/oobr_contents.html
86;; http://www.infodock.com/manuals/alt-oobr-cover.html
87
Barry Warsaw37231521997-12-11 17:23:13 +000088;; You may also want to take a look at Harri Pasanen's "Python Library
89;; Reference Hot-Key Help System for XEmacs (or PLRHKHSX for short ;),
90;; version 1.0"
Barry Warsaw7b0f5681995-03-08 21:33:04 +000091;;
Barry Warsaw37231521997-12-11 17:23:13 +000092;; <http://www.iki.fi/hpa/>
93
94;; TO DO LIST:
95
96;; - Better integration with pdb.py and gud-mode for debugging.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000097;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000098;; - possibly force indent-tabs-mode == nil, and add a
99;; write-file-hooks that runs untabify on the whole buffer (to work
100;; around potential tab/space mismatch problems). In practice this
101;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +0000102;; - have py-execute-region on indented code act as if the region is
Barry Warsaw37231521997-12-11 17:23:13 +0000103;; left justified. Avoids syntax errors.
104;; - add a py-goto-block-down, bound to C-c C-d
Barry Warsaw7ae77681994-12-12 20:38:05 +0000105
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000106;;; Code:
107
Barry Warsawc72c11c1997-08-09 06:42:08 +0000108(require 'custom)
Barry Warsaw8529ebb1997-12-01 20:03:12 +0000109(eval-when-compile
Barry Warsaw673d05f1997-12-02 21:51:57 +0000110 (require 'cl)
Barry Warsawb6c1f1f1998-03-19 22:33:06 +0000111 (if (not (and (condition-case nil
112 (require 'custom)
113 (error nil))
114 ;; Stock Emacs 19.34 has a broken/old Custom library
115 ;; that does more harm than good. Fortunately, it is
116 ;; missing defcustom
117 (fboundp 'defcustom)))
Barry Warsaw673d05f1997-12-02 21:51:57 +0000118 (error "STOP! STOP! STOP! STOP!
119
120The Custom library was not found or is out of date. A more current
121version is required. Please download and install the latest version
122of the Custom library from:
123
124 <http://www.dina.kvl.dk/~abraham/custom/>
125
126See the Python Mode home page for details:
127
128 <http://www.python.org/ftp/emacs/>
129")))
130
Barry Warsawc72c11c1997-08-09 06:42:08 +0000131
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000132
133;; user definable variables
134;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000135
Barry Warsawc72c11c1997-08-09 06:42:08 +0000136(defgroup python nil
137 "Support for the Python programming language, <http://www.python.org/>"
138 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000139
Barry Warsawc72c11c1997-08-09 06:42:08 +0000140(defcustom py-python-command "python"
141 "*Shell command used to start Python interpreter."
142 :type 'string
143 :group 'python)
144
Barry Warsawa2398801998-04-09 23:28:20 +0000145(defcustom py-jpython-command "jpython"
146 "*Shell command used to start the JPython interpreter."
147 :type 'string
148 :group 'python)
149
Barry Warsaw8f972b71998-02-05 20:45:49 +0000150(defcustom py-python-command-args '("-i")
151 "*List of string arguments to be used when starting a Python shell."
152 :type '(repeat string)
153 :group 'python)
154
Barry Warsawa2398801998-04-09 23:28:20 +0000155(defcustom py-jpython-command-args '("-i")
156 "*List of string arguments to be used when starting a JPython shell."
157 :type '(repeat string)
158 :group 'python)
159
Barry Warsawc72c11c1997-08-09 06:42:08 +0000160(defcustom py-indent-offset 4
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
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000215opposed to one that starts with `py-block-comment-prefix'), then its
Barry Warsaw6d627751996-03-06 18:41:38 +0000216indentation is used as a hint for this line's indentation. Lines that
217begin with `py-block-comment-prefix' are ignored for indentation
218purposes.
219
220When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000221indentation hints, unless the comment character is in column zero."
222 :type '(choice
223 (const :tag "Skip all comment lines (fast)" nil)
224 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000225 (const :tag "Single # `sets' indentation except at column zero"
226 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000227 )
228 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000229
Barry 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 Warsaw145ab1c1998-05-19 14:49:49 +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
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000827previous definition from the alist. In its place it adds all
Barry Warsaw81437461996-08-01 19:48:02 +0000828definitions 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))
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000994 ;; It's okay if this fails to guess a good value
Barry Warsaw742a5111998-03-13 17:29:15 +0000995 (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
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001050 ;; put there on purpose. It's highly annoying to have `:' indent
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001051 ;; 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)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001255 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
Barry Warsawa97a3f31997-11-04 18:47:06 +00001256 (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
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001303 ;; always run the code in its own asynchronous subprocess
Barry Warsawa97a3f31997-11-04 18:47:06 +00001304 (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>")
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001357 (if (consp py-exception-buffer)
1358 (cdr py-exception-buffer)
1359 py-exception-buffer))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001360 ((and (consp py-exception-buffer)
1361 (string-equal file (car py-exception-buffer)))
1362 (cdr py-exception-buffer))
1363 ((py-safe (find-file-noselect file)))
1364 ;; could not figure out what file the exception
1365 ;; is pointing to, so prompt for it
1366 (t (find-file (read-file-name "Exception file: "
1367 nil
1368 file t))))))
1369 (pop-to-buffer buffer)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001370 ;; Force Python mode
1371 (if (not (eq major-mode) 'python-mode)
1372 (python-mode))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001373 (goto-line line)
1374 (message "Jumping to exception in file %s on line %d" file line)))
1375
1376(defun py-mouseto-exception (event)
1377 (interactive "e")
1378 (cond
1379 ((fboundp 'event-point)
1380 ;; XEmacs
1381 (let* ((point (event-point event))
1382 (buffer (event-buffer event))
1383 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1384 (info (and e (extent-property e 'py-exc-info))))
1385 (message "Event point: %d, info: %s" point info)
1386 (and info
1387 (py-jump-to-exception (car info) (cdr info)))
1388 ))
1389 ;; Emacs -- Please port this!
1390 ))
1391
1392(defun py-goto-exception ()
1393 "Go to the line indicated by the traceback."
1394 (interactive)
1395 (let (file line)
1396 (save-excursion
1397 (beginning-of-line)
1398 (if (looking-at py-traceback-line-re)
1399 (setq file (match-string 1)
1400 line (string-to-int (match-string 2)))))
1401 (if (not file)
1402 (error "Not on a traceback line."))
1403 (py-jump-to-exception file line)))
1404
1405(defun py-find-next-exception (start buffer searchdir errwhere)
1406 ;; Go to start position in buffer, search in the specified
1407 ;; direction, and jump to the exception found. If at the end of the
1408 ;; exception, print error message
1409 (let (file line)
1410 (save-excursion
1411 (set-buffer buffer)
1412 (goto-char (py-point start))
1413 (if (funcall searchdir py-traceback-line-re nil t)
1414 (setq file (match-string 1)
1415 line (string-to-int (match-string 2)))))
1416 (if (and file line)
1417 (py-jump-to-exception file line)
1418 (error "%s of traceback" errwhere))))
1419
1420(defun py-down-exception (&optional bottom)
1421 "Go to the next line down in the traceback.
1422With optional \\[universal-argument], jump to the bottom (innermost)
1423exception in the exception stack."
1424 (interactive "P")
1425 (let* ((proc (get-process "Python"))
1426 (buffer (if proc "*Python*" py-output-buffer)))
1427 (if bottom
1428 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1429 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1430
1431(defun py-up-exception (&optional top)
1432 "Go to the previous line up in the traceback.
1433With optional \\[universal-argument], jump to the top (outermost)
1434exception in the exception stack."
1435 (interactive "P")
1436 (let* ((proc (get-process "Python"))
1437 (buffer (if proc "*Python*" py-output-buffer)))
1438 (if top
1439 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001440 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001441
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001442
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001443;; Electric deletion
1444(defun py-electric-backspace (arg)
1445 "Deletes preceding character or levels of indentation.
1446Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001447with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001448
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001449If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001450
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001451Otherwise, if point is at the leftmost non-whitespace character of a
1452line that is neither a continuation line nor a non-indenting comment
1453line, or if point is at the end of a blank line, this command reduces
1454the indentation to match that of the line that opened the current
1455block of code. The line that opened the block is displayed in the
1456echo area to help you keep track of where you are. With numeric arg,
1457outdents that many blocks (but not past column zero).
1458
1459Otherwise the preceding character is deleted, converting a tab to
1460spaces if needed so that only a single column position is deleted.
1461Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001462 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001463 (if (or (/= (current-indentation) (current-column))
1464 (bolp)
1465 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001466 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001467 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001468 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001469 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001470 ;; force non-blank so py-goto-block-up doesn't ignore it
1471 (insert-char ?* 1)
1472 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001473 (let ((base-indent 0) ; indentation of base line
1474 (base-text "") ; and text of base line
1475 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001476 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001477 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001478 (condition-case nil ; in case no enclosing block
1479 (progn
1480 (py-goto-block-up 'no-mark)
1481 (setq base-indent (current-indentation)
1482 base-text (py-suck-up-leading-text)
1483 base-found-p t))
1484 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001485 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001486 (delete-char 1) ; toss the dummy character
1487 (delete-horizontal-space)
1488 (indent-to base-indent)
1489 (if base-found-p
1490 (message "Closes block: %s" base-text)))))
1491
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001492
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001493(defun py-electric-delete (arg)
1494 "Deletes preceding or following character or levels of whitespace.
1495
1496The behavior of this function depends on the variable
1497`delete-key-deletes-forward'. If this variable is nil (or does not
1498exist, as in older Emacsen), then this function behaves identical to
1499\\[c-electric-backspace].
1500
1501If `delete-key-deletes-forward' is non-nil and is supported in your
1502Emacs, then deletion occurs in the forward direction, by calling the
1503function in `py-delete-function'."
1504 (interactive "*p")
1505 (if (and (boundp 'delete-key-deletes-forward)
1506 delete-key-deletes-forward)
1507 (funcall py-delete-function arg)
1508 ;; else
1509 (py-electric-backspace arg)))
1510
1511;; required for pending-del and delsel modes
1512(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1513(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1514(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1515(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1516
1517
1518
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001519(defun py-indent-line (&optional arg)
1520 "Fix the indentation of the current line according to Python rules.
1521With \\[universal-argument], ignore outdenting rules for block
1522closing statements (e.g. return, raise, break, continue, pass)
1523
1524This function is normally bound to `indent-line-function' so
1525\\[indent-for-tab-command] will call it."
1526 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001527 (let* ((ci (current-indentation))
1528 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001529 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001530 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001531 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001532 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001533 (if (/= ci need)
1534 (save-excursion
1535 (beginning-of-line)
1536 (delete-horizontal-space)
1537 (indent-to need)))
1538 (if move-to-indentation-p (back-to-indentation))))
1539
1540(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001541 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001542This is just `strives to' because correct indentation can't be computed
1543from scratch for Python code. In general, deletes the whitespace before
1544point, inserts a newline, and takes an educated guess as to how you want
1545the new line indented."
1546 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001547 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001548 (if (< ci (current-column)) ; if point beyond indentation
1549 (newline-and-indent)
1550 ;; else try to act like newline-and-indent "normally" acts
1551 (beginning-of-line)
1552 (insert-char ?\n 1)
1553 (move-to-column ci))))
1554
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001555(defun py-compute-indentation (honor-block-close-p)
1556 ;; implements all the rules for indentation computation. when
1557 ;; honor-block-close-p is non-nil, statements such as return, raise,
1558 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001559 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001560 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001561 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001562 (pps (parse-partial-sexp bod (point)))
1563 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001564 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001565 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001566 ((or (and (nth 3 pps) (nth 3 boipps))
1567 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001568 (save-excursion
1569 (if (not py-align-multiline-strings-p) 0
1570 ;; skip back over blank & non-indenting comment lines
1571 ;; note: will skip a blank or non-indenting comment line
1572 ;; that happens to be a continuation line too
1573 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1574 (back-to-indentation)
1575 (current-column))))
1576 ;; are we on a continuation line?
1577 ((py-continuation-line-p)
1578 (let ((startpos (point))
1579 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001580 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001581 (if open-bracket-pos
1582 (progn
1583 ;; align with first item in list; else a normal
1584 ;; indent beyond the line with the open bracket
1585 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1586 ;; is the first list item on the same line?
1587 (skip-chars-forward " \t")
1588 (if (null (memq (following-char) '(?\n ?# ?\\)))
1589 ; yes, so line up with it
1590 (current-column)
1591 ;; first list item on another line, or doesn't exist yet
1592 (forward-line 1)
1593 (while (and (< (point) startpos)
1594 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1595 (forward-line 1))
Barry Warsaw92166d91998-04-01 21:59:41 +00001596 (if (and (< (point) startpos)
1597 (/= startpos
1598 (save-excursion
1599 (goto-char (1+ open-bracket-pos))
Barry Warsaw77d1fce1998-04-16 20:04:59 +00001600 (forward-comment (point-max))
Barry Warsaw92166d91998-04-01 21:59:41 +00001601 (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001602 ;; again mimic the first list item
1603 (current-indentation)
1604 ;; else they're about to enter the first item
1605 (goto-char open-bracket-pos)
1606 (+ (current-indentation) py-indent-offset))))
1607
1608 ;; else on backslash continuation line
1609 (forward-line -1)
1610 (if (py-continuation-line-p) ; on at least 3rd line in block
1611 (current-indentation) ; so just continue the pattern
1612 ;; else started on 2nd line in block, so indent more.
1613 ;; if base line is an assignment with a start on a RHS,
1614 ;; indent to 2 beyond the leftmost "="; else skip first
1615 ;; chunk of non-whitespace characters on base line, + 1 more
1616 ;; column
1617 (end-of-line)
1618 (setq endpos (point) searching t)
1619 (back-to-indentation)
1620 (setq startpos (point))
1621 ;; look at all "=" from left to right, stopping at first
1622 ;; one not nested in a list or string
1623 (while searching
1624 (skip-chars-forward "^=" endpos)
1625 (if (= (point) endpos)
1626 (setq searching nil)
1627 (forward-char 1)
1628 (setq state (parse-partial-sexp startpos (point)))
1629 (if (and (zerop (car state)) ; not in a bracket
1630 (null (nth 3 state))) ; & not in a string
1631 (progn
1632 (setq searching nil) ; done searching in any case
1633 (setq found
1634 (not (or
1635 (eq (following-char) ?=)
1636 (memq (char-after (- (point) 2))
1637 '(?< ?> ?!)))))))))
1638 (if (or (not found) ; not an assignment
1639 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1640 (progn
1641 (goto-char startpos)
1642 (skip-chars-forward "^ \t\n")))
1643 (1+ (current-column))))))
1644
1645 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001646 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001647
Barry Warsawa7891711996-08-01 15:53:09 +00001648 ;; Dfn: "Indenting comment line". A line containing only a
1649 ;; comment, but which is treated like a statement for
1650 ;; indentation calculation purposes. Such lines are only
1651 ;; treated specially by the mode; they are not treated
1652 ;; specially by the Python interpreter.
1653
1654 ;; The rules for indenting comment lines are a line where:
1655 ;; - the first non-whitespace character is `#', and
1656 ;; - the character following the `#' is whitespace, and
1657 ;; - the line is outdented with respect to (i.e. to the left
1658 ;; of) the indentation of the preceding non-blank line.
1659
1660 ;; The first non-blank line following an indenting comment
1661 ;; line is given the same amount of indentation as the
1662 ;; indenting comment line.
1663
1664 ;; All other comment-only lines are ignored for indentation
1665 ;; purposes.
1666
1667 ;; Are we looking at a comment-only line which is *not* an
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001668 ;; indenting comment line? If so, we assume that it's been
Barry Warsawa7891711996-08-01 15:53:09 +00001669 ;; placed at the desired indentation, so leave it alone.
1670 ;; Indenting comment lines are aligned as statements down
1671 ;; below.
1672 ((and (looking-at "[ \t]*#[^ \t\n]")
1673 ;; NOTE: this test will not be performed in older Emacsen
1674 (fboundp 'forward-comment)
1675 (<= (current-indentation)
1676 (save-excursion
1677 (forward-comment (- (point-max)))
1678 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001679 (current-indentation))
1680
1681 ;; else indentation based on that of the statement that
1682 ;; precedes us; use the first line of that statement to
1683 ;; establish the base, in case the user forced a non-std
1684 ;; indentation for the continuation lines (if any)
1685 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001686 ;; skip back over blank & non-indenting comment lines note:
1687 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001688 ;; happens to be a continuation line too. use fast Emacs 19
1689 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001690 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001691 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001692 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001693 (let (done)
1694 (while (not done)
1695 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1696 nil 'move)
1697 (setq done (or (eq py-honor-comment-indentation t)
1698 (bobp)
1699 (/= (following-char) ?#)
1700 (not (zerop (current-column)))))
1701 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001702 ;; if we landed inside a string, go to the beginning of that
1703 ;; string. this handles triple quoted, multi-line spanning
1704 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001705 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001706 (skip (and delim (make-string 1 delim))))
1707 (when skip
1708 (save-excursion
1709 (py-safe (search-backward skip))
1710 (if (and (eq (char-before) delim)
1711 (eq (char-before (1- (point))) delim))
1712 (setq skip (make-string 3 delim))))
1713 ;; we're looking at a triple-quoted string
1714 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001715 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001716 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001717 (+ (current-indentation)
1718 (if (py-statement-opens-block-p)
1719 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001720 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001721 (- py-indent-offset)
1722 0)))
1723 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001724
1725(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001726 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001727By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001728`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001729Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001730`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001731their own buffer-local copy), both those currently existing and those
1732created later in the Emacs session.
1733
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001734Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001735There's no excuse for such foolishness, but sometimes you have to deal
1736with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001737`py-indent-offset' to what it thinks it was when they created the
1738mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001739
1740Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001741looking for a line that opens a block of code. `py-indent-offset' is
1742set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001743statement following it. If the search doesn't succeed going forward,
1744it's tried again going backward."
1745 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001746 (let (new-value
1747 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001748 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001749 (found nil)
1750 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001751 (py-goto-initial-line)
1752 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001753 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1754 (not (py-in-literal restart)))
1755 (setq restart (point))
1756 (py-goto-initial-line)
1757 (if (py-statement-opens-block-p)
1758 (setq found t)
1759 (goto-char restart))))
1760 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001761 (goto-char start)
1762 (py-goto-initial-line)
1763 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001764 (setq found (and
1765 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1766 (or (py-goto-initial-line) t) ; always true -- side effect
1767 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001768 (setq colon-indent (current-indentation)
1769 found (and found (zerop (py-next-statement 1)))
1770 new-value (- (current-indentation) colon-indent))
1771 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001772 (if (not found)
1773 (error "Sorry, couldn't guess a value for py-indent-offset")
1774 (funcall (if global 'kill-local-variable 'make-local-variable)
1775 'py-indent-offset)
1776 (setq py-indent-offset new-value)
1777 (message "%s value of py-indent-offset set to %d"
1778 (if global "Global" "Local")
1779 py-indent-offset))
1780 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001781
1782(defun py-shift-region (start end count)
1783 (save-excursion
1784 (goto-char end) (beginning-of-line) (setq end (point))
1785 (goto-char start) (beginning-of-line) (setq start (point))
1786 (indent-rigidly start end count)))
1787
1788(defun py-shift-region-left (start end &optional count)
1789 "Shift region of Python code to the left.
1790The lines from the line containing the start of the current region up
1791to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001792shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001793
1794If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001795many columns. With no active region, outdent only the current line.
1796You cannot outdent the region if any line is already at column zero."
1797 (interactive
1798 (let ((p (point))
1799 (m (mark))
1800 (arg current-prefix-arg))
1801 (if m
1802 (list (min p m) (max p m) arg)
1803 (list p (save-excursion (forward-line 1) (point)) arg))))
1804 ;; if any line is at column zero, don't shift the region
1805 (save-excursion
1806 (goto-char start)
1807 (while (< (point) end)
1808 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001809 (if (and (zerop (current-column))
1810 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001811 (error "Region is at left edge."))
1812 (forward-line 1)))
1813 (py-shift-region start end (- (prefix-numeric-value
1814 (or count py-indent-offset))))
1815 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001816
1817(defun py-shift-region-right (start end &optional count)
1818 "Shift region of Python code to the right.
1819The lines from the line containing the start of the current region up
1820to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001821shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001822
1823If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001824many columns. With no active region, indent only the current line."
1825 (interactive
1826 (let ((p (point))
1827 (m (mark))
1828 (arg current-prefix-arg))
1829 (if m
1830 (list (min p m) (max p m) arg)
1831 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001832 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001833 (or count py-indent-offset)))
1834 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001835
1836(defun py-indent-region (start end &optional indent-offset)
1837 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001838
Barry Warsaw7ae77681994-12-12 20:38:05 +00001839The lines from the line containing the start of the current region up
1840to (but not including) the line containing the end of the region are
1841reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001842character in the first column, the first line is left alone and the
1843rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001844region is reindented with respect to the (closest code or indenting
1845comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001846
1847This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001848control structures are introduced or removed, or to reformat code
1849using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001850
1851If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001852the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001853used.
1854
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001855Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001856is called! This function does not compute proper indentation from
1857scratch (that's impossible in Python), it merely adjusts the existing
1858indentation to be correct in context.
1859
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001860Warning: This function really has no idea what to do with
1861non-indenting comment lines, and shifts them as if they were indenting
1862comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001863
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001864Special cases: whitespace is deleted from blank lines; continuation
1865lines are shifted by the same amount their initial line was shifted,
1866in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001867initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001868 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001869 (save-excursion
1870 (goto-char end) (beginning-of-line) (setq end (point-marker))
1871 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001872 (let ((py-indent-offset (prefix-numeric-value
1873 (or indent-offset py-indent-offset)))
1874 (indents '(-1)) ; stack of active indent levels
1875 (target-column 0) ; column to which to indent
1876 (base-shifted-by 0) ; amount last base line was shifted
1877 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001878 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001879 0))
1880 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001881 (while (< (point) end)
1882 (setq ci (current-indentation))
1883 ;; figure out appropriate target column
1884 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001885 ((or (eq (following-char) ?#) ; comment in column 1
1886 (looking-at "[ \t]*$")) ; entirely blank
1887 (setq target-column 0))
1888 ((py-continuation-line-p) ; shift relative to base line
1889 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001890 (t ; new base line
1891 (if (> ci (car indents)) ; going deeper; push it
1892 (setq indents (cons ci indents))
1893 ;; else we should have seen this indent before
1894 (setq indents (memq ci indents)) ; pop deeper indents
1895 (if (null indents)
1896 (error "Bad indentation in region, at line %d"
1897 (save-restriction
1898 (widen)
1899 (1+ (count-lines 1 (point)))))))
1900 (setq target-column (+ indent-base
1901 (* py-indent-offset
1902 (- (length indents) 2))))
1903 (setq base-shifted-by (- target-column ci))))
1904 ;; shift as needed
1905 (if (/= ci target-column)
1906 (progn
1907 (delete-horizontal-space)
1908 (indent-to target-column)))
1909 (forward-line 1))))
1910 (set-marker end nil))
1911
Barry Warsawa7891711996-08-01 15:53:09 +00001912(defun py-comment-region (beg end &optional arg)
1913 "Like `comment-region' but uses double hash (`#') comment starter."
1914 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001915 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001916 (comment-region beg end arg)))
1917
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001918
1919;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001920(defun py-previous-statement (count)
1921 "Go to the start of previous Python statement.
1922If the statement at point is the i'th Python statement, goes to the
1923start of statement i-COUNT. If there is no such statement, goes to the
1924first statement. Returns count of statements left to move.
1925`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001926 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001927 (if (< count 0) (py-next-statement (- count))
1928 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001929 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001930 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001931 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001932 (> count 0)
1933 (zerop (forward-line -1))
1934 (py-goto-statement-at-or-above))
1935 (setq count (1- count)))
1936 (if (> count 0) (goto-char start)))
1937 count))
1938
1939(defun py-next-statement (count)
1940 "Go to the start of next Python statement.
1941If the statement at point is the i'th Python statement, goes to the
1942start of statement i+COUNT. If there is no such statement, goes to the
1943last statement. Returns count of statements left to move. `Statements'
1944do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001945 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001946 (if (< count 0) (py-previous-statement (- count))
1947 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001948 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001949 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001950 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001951 (> count 0)
1952 (py-goto-statement-below))
1953 (setq count (1- count)))
1954 (if (> count 0) (goto-char start)))
1955 count))
1956
1957(defun py-goto-block-up (&optional nomark)
1958 "Move up to start of current block.
1959Go to the statement that starts the smallest enclosing block; roughly
1960speaking, this will be the closest preceding statement that ends with a
1961colon and is indented less than the statement you started on. If
1962successful, also sets the mark to the starting point.
1963
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001964`\\[py-mark-block]' can be used afterward to mark the whole code
1965block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001966
1967If called from a program, the mark will not be set if optional argument
1968NOMARK is not nil."
1969 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001970 (let ((start (point))
1971 (found nil)
1972 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001973 (py-goto-initial-line)
1974 ;; if on blank or non-indenting comment line, use the preceding stmt
1975 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1976 (progn
1977 (py-goto-statement-at-or-above)
1978 (setq found (py-statement-opens-block-p))))
1979 ;; search back for colon line indented less
1980 (setq initial-indent (current-indentation))
1981 (if (zerop initial-indent)
1982 ;; force fast exit
1983 (goto-char (point-min)))
1984 (while (not (or found (bobp)))
1985 (setq found
1986 (and
1987 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1988 (or (py-goto-initial-line) t) ; always true -- side effect
1989 (< (current-indentation) initial-indent)
1990 (py-statement-opens-block-p))))
1991 (if found
1992 (progn
1993 (or nomark (push-mark start))
1994 (back-to-indentation))
1995 (goto-char start)
1996 (error "Enclosing block not found"))))
1997
1998(defun beginning-of-python-def-or-class (&optional class)
1999 "Move point to start of def (or class, with prefix arg).
2000
2001Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002002arg, looks for a `class' instead. The docs assume the `def' case;
2003just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002004
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002005If point is in a def statement already, and after the `d', simply
2006moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002007
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002008Else (point is not in a def statement, or at or before the `d' of a
2009def statement), searches for the closest preceding def statement, and
2010leaves point at its start. If no such statement can be found, leaves
2011point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002012
2013Returns t iff a def statement is found by these rules.
2014
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002015Note that doing this command repeatedly will take you closer to the
2016start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002017
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002018If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00002019`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002020 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002021 (let ((at-or-before-p (<= (current-column) (current-indentation)))
2022 (start-of-line (progn (beginning-of-line) (point)))
2023 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002024 (if (or (/= start-of-stmt start-of-line)
2025 (not at-or-before-p))
2026 (end-of-line)) ; OK to match on this line
2027 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002028 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002029
2030(defun end-of-python-def-or-class (&optional class)
2031 "Move point beyond end of def (or class, with prefix arg) body.
2032
2033By default, looks for an appropriate `def'. If you supply a prefix arg,
2034looks for a `class' instead. The docs assume the `def' case; just
2035substitute `class' for `def' for the other case.
2036
2037If point is in a def statement already, this is the def we use.
2038
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002039Else if the def found by `\\[beginning-of-python-def-or-class]'
2040contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002041
2042Else we search forward for the closest following def, and use that.
2043
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002044If a def can be found by these rules, point is moved to the start of
2045the line immediately following the def block, and the position of the
2046start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002047
2048Else point is moved to the end of the buffer, and nil is returned.
2049
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002050Note that doing this command repeatedly will take you closer to the
2051end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002052
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002053If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00002054`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002055 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002056 (let ((start (progn (py-goto-initial-line) (point)))
2057 (which (if class "class" "def"))
2058 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002059 ;; move point to start of appropriate def/class
2060 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2061 (setq state 'at-beginning)
2062 ;; else see if beginning-of-python-def-or-class hits container
2063 (if (and (beginning-of-python-def-or-class class)
2064 (progn (py-goto-beyond-block)
2065 (> (point) start)))
2066 (setq state 'at-end)
2067 ;; else search forward
2068 (goto-char start)
2069 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2070 (progn (setq state 'at-beginning)
2071 (beginning-of-line)))))
2072 (cond
2073 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2074 ((eq state 'at-end) t)
2075 ((eq state 'not-found) nil)
2076 (t (error "internal error in end-of-python-def-or-class")))))
2077
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002078
2079;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002080(defun py-mark-block (&optional extend just-move)
2081 "Mark following block of lines. With prefix arg, mark structure.
2082Easier to use than explain. It sets the region to an `interesting'
2083block of succeeding lines. If point is on a blank line, it goes down to
2084the next non-blank line. That will be the start of the region. The end
2085of the region depends on the kind of line at the start:
2086
2087 - If a comment, the region will include all succeeding comment lines up
2088 to (but not including) the next non-comment line (if any).
2089
2090 - Else if a prefix arg is given, and the line begins one of these
2091 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002092
2093 if elif else try except finally for while def class
2094
Barry Warsaw7ae77681994-12-12 20:38:05 +00002095 the region will be set to the body of the structure, including
2096 following blocks that `belong' to it, but excluding trailing blank
2097 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002098 and all (if any) of the following `except' and `finally' blocks
2099 that belong to the `try' structure will be in the region. Ditto
2100 for if/elif/else, for/else and while/else structures, and (a bit
2101 degenerate, since they're always one-block structures) def and
2102 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002103
2104 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002105 block (see list above), and the block is not a `one-liner' (i.e.,
2106 the statement ends with a colon, not with code), the region will
2107 include all succeeding lines up to (but not including) the next
2108 code statement (if any) that's indented no more than the starting
2109 line, except that trailing blank and comment lines are excluded.
2110 E.g., if the starting line begins a multi-statement `def'
2111 structure, the region will be set to the full function definition,
2112 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002113
2114 - Else the region will include all succeeding lines up to (but not
2115 including) the next blank line, or code or indenting-comment line
2116 indented strictly less than the starting line. Trailing indenting
2117 comment lines are included in this case, but not trailing blank
2118 lines.
2119
2120A msg identifying the location of the mark is displayed in the echo
2121area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2122
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002123If called from a program, optional argument EXTEND plays the role of
2124the prefix arg, and if optional argument JUST-MOVE is not nil, just
2125moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002126 (interactive "P") ; raw prefix arg
2127 (py-goto-initial-line)
2128 ;; skip over blank lines
2129 (while (and
2130 (looking-at "[ \t]*$") ; while blank line
2131 (not (eobp))) ; & somewhere to go
2132 (forward-line 1))
2133 (if (eobp)
2134 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002135 (let ((initial-pos (point))
2136 (initial-indent (current-indentation))
2137 last-pos ; position of last stmt in region
2138 (followers
2139 '((if elif else) (elif elif else) (else)
2140 (try except finally) (except except) (finally)
2141 (for else) (while else)
2142 (def) (class) ) )
2143 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002144
2145 (cond
2146 ;; if comment line, suck up the following comment lines
2147 ((looking-at "[ \t]*#")
2148 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2149 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2150 (setq last-pos (point)))
2151
2152 ;; else if line is a block line and EXTEND given, suck up
2153 ;; the whole structure
2154 ((and extend
2155 (setq first-symbol (py-suck-up-first-keyword) )
2156 (assq first-symbol followers))
2157 (while (and
2158 (or (py-goto-beyond-block) t) ; side effect
2159 (forward-line -1) ; side effect
2160 (setq last-pos (point)) ; side effect
2161 (py-goto-statement-below)
2162 (= (current-indentation) initial-indent)
2163 (setq next-symbol (py-suck-up-first-keyword))
2164 (memq next-symbol (cdr (assq first-symbol followers))))
2165 (setq first-symbol next-symbol)))
2166
2167 ;; else if line *opens* a block, search for next stmt indented <=
2168 ((py-statement-opens-block-p)
2169 (while (and
2170 (setq last-pos (point)) ; always true -- side effect
2171 (py-goto-statement-below)
2172 (> (current-indentation) initial-indent))
2173 nil))
2174
2175 ;; else plain code line; stop at next blank line, or stmt or
2176 ;; indenting comment line indented <
2177 (t
2178 (while (and
2179 (setq last-pos (point)) ; always true -- side effect
2180 (or (py-goto-beyond-final-line) t)
2181 (not (looking-at "[ \t]*$")) ; stop at blank line
2182 (or
2183 (>= (current-indentation) initial-indent)
2184 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2185 nil)))
2186
2187 ;; skip to end of last stmt
2188 (goto-char last-pos)
2189 (py-goto-beyond-final-line)
2190
2191 ;; set mark & display
2192 (if just-move
2193 () ; just return
2194 (push-mark (point) 'no-msg)
2195 (forward-line -1)
2196 (message "Mark set after: %s" (py-suck-up-leading-text))
2197 (goto-char initial-pos))))
2198
Barry Warsaw2518c671997-11-05 00:51:08 +00002199(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002200 "Set region to body of def (or class, with prefix arg) enclosing point.
2201Pushes the current mark, then point, on the mark ring (all language
2202modes do this, but although it's handy it's never documented ...).
2203
2204In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002205hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
2206`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002207
2208And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002209Turned out that was more confusing than useful: the `goto start' and
2210`goto end' commands are usually used to search through a file, and
2211people expect them to act a lot like `search backward' and `search
2212forward' string-search commands. But because Python `def' and `class'
2213can nest to arbitrary levels, finding the smallest def containing
2214point cannot be done via a simple backward search: the def containing
2215point may not be the closest preceding def, or even the closest
2216preceding def that's indented less. The fancy algorithm required is
2217appropriate for the usual uses of this `mark' command, but not for the
2218`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002219
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002220So the def marked by this command may not be the one either of the
2221`goto' commands find: If point is on a blank or non-indenting comment
2222line, moves back to start of the closest preceding code statement or
2223indenting comment line. If this is a `def' statement, that's the def
2224we use. Else searches for the smallest enclosing `def' block and uses
2225that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002226
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002227When an enclosing def is found: The mark is left immediately beyond
2228the last line of the def block. Point is left at the start of the
2229def, except that: if the def is preceded by a number of comment lines
2230followed by (at most) one optional blank line, point is left at the
2231start of the comments; else if the def is preceded by a blank line,
2232point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002233
2234The intent is to mark the containing def/class and its associated
2235documentation, to make moving and duplicating functions and classes
2236pleasant."
2237 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002238 (let ((start (point))
2239 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002240 (push-mark start)
2241 (if (not (py-go-up-tree-to-keyword which))
2242 (progn (goto-char start)
2243 (error "Enclosing %s not found" which))
2244 ;; else enclosing def/class found
2245 (setq start (point))
2246 (py-goto-beyond-block)
2247 (push-mark (point))
2248 (goto-char start)
2249 (if (zerop (forward-line -1)) ; if there is a preceding line
2250 (progn
2251 (if (looking-at "[ \t]*$") ; it's blank
2252 (setq start (point)) ; so reset start point
2253 (goto-char start)) ; else try again
2254 (if (zerop (forward-line -1))
2255 (if (looking-at "[ \t]*#") ; a comment
2256 ;; look back for non-comment line
2257 ;; tricky: note that the regexp matches a blank
2258 ;; line, cuz \n is in the 2nd character class
2259 (and
2260 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2261 (forward-line 1))
2262 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002263 (goto-char start)))))))
2264 (exchange-point-and-mark)
2265 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002266
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002267;; ripped from cc-mode
2268(defun py-forward-into-nomenclature (&optional arg)
2269 "Move forward to end of a nomenclature section or word.
2270With arg, to it arg times.
2271
2272A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2273 (interactive "p")
2274 (let ((case-fold-search nil))
2275 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002276 (re-search-forward
2277 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2278 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002279 (while (and (< arg 0)
2280 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002281 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002282 (point-min) 0))
2283 (forward-char 1)
2284 (setq arg (1+ arg)))))
2285 (py-keep-region-active))
2286
2287(defun py-backward-into-nomenclature (&optional arg)
2288 "Move backward to beginning of a nomenclature section or word.
2289With optional ARG, move that many times. If ARG is negative, move
2290forward.
2291
2292A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2293 (interactive "p")
2294 (py-forward-into-nomenclature (- arg))
2295 (py-keep-region-active))
2296
2297
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002298
2299;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002300
2301;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002302;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2303;; out of the right places, along with the keys they're on & current
2304;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002305(defun py-dump-help-string (str)
2306 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002307 (let ((locals (buffer-local-variables))
2308 funckind funcname func funcdoc
2309 (start 0) mstart end
2310 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002311 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2312 (setq mstart (match-beginning 0) end (match-end 0)
2313 funckind (substring str (match-beginning 1) (match-end 1))
2314 funcname (substring str (match-beginning 2) (match-end 2))
2315 func (intern funcname))
2316 (princ (substitute-command-keys (substring str start mstart)))
2317 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002318 ((equal funckind "c") ; command
2319 (setq funcdoc (documentation func)
2320 keys (concat
2321 "Key(s): "
2322 (mapconcat 'key-description
2323 (where-is-internal func py-mode-map)
2324 ", "))))
2325 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002326 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002327 keys (if (assq func locals)
2328 (concat
2329 "Local/Global values: "
2330 (prin1-to-string (symbol-value func))
2331 " / "
2332 (prin1-to-string (default-value func)))
2333 (concat
2334 "Value: "
2335 (prin1-to-string (symbol-value func))))))
2336 (t ; unexpected
2337 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002338 (princ (format "\n-> %s:\t%s\t%s\n\n"
2339 (if (equal funckind "c") "Command" "Variable")
2340 funcname keys))
2341 (princ funcdoc)
2342 (terpri)
2343 (setq start end))
2344 (princ (substitute-command-keys (substring str start))))
2345 (print-help-return-message)))
2346
2347(defun py-describe-mode ()
2348 "Dump long form of Python-mode docs."
2349 (interactive)
2350 (py-dump-help-string "Major mode for editing Python files.
2351Knows about Python indentation, tokens, comments and continuation lines.
2352Paragraphs are separated by blank lines only.
2353
2354Major sections below begin with the string `@'; specific function and
2355variable docs begin with `->'.
2356
2357@EXECUTING PYTHON CODE
2358
2359\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2360\\[py-execute-region]\tsends the current region
2361\\[py-shell]\tstarts a Python interpreter window; this will be used by
2362\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2363%c:py-execute-buffer
2364%c:py-execute-region
2365%c:py-shell
2366
2367@VARIABLES
2368
2369py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002370py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002371
2372py-python-command\tshell command to invoke Python interpreter
2373py-scroll-process-buffer\talways scroll Python process buffer
2374py-temp-directory\tdirectory used for temp files (if needed)
2375
2376py-beep-if-tab-change\tring the bell if tab-width is changed
2377%v:py-indent-offset
2378%v:py-block-comment-prefix
2379%v:py-python-command
2380%v:py-scroll-process-buffer
2381%v:py-temp-directory
2382%v:py-beep-if-tab-change
2383
2384@KINDS OF LINES
2385
2386Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002387preceding line ends with a backslash that's not part of a comment, or
2388the paren/bracket/brace nesting level at the start of the line is
2389non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002390
2391An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002392possibly blanks or tabs), a `comment line' (leftmost non-blank
2393character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002394
2395Comment Lines
2396
2397Although all comment lines are treated alike by Python, Python mode
2398recognizes two kinds that act differently with respect to indentation.
2399
2400An `indenting comment line' is a comment line with a blank, tab or
2401nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002402treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002403indenting comment line will be indented like the comment line. All
2404other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002405following the initial `#') are `non-indenting comment lines', and
2406their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002407
2408Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002409whenever possible. Non-indenting comment lines are useful in cases
2410like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002411
2412\ta = b # a very wordy single-line comment that ends up being
2413\t #... continued onto another line
2414
2415\tif a == b:
2416##\t\tprint 'panic!' # old code we've `commented out'
2417\t\treturn a
2418
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002419Since the `#...' and `##' comment lines have a non-whitespace
2420character following the initial `#', Python mode ignores them when
2421computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002422
2423Continuation Lines and Statements
2424
2425The Python-mode commands generally work on statements instead of on
2426individual lines, where a `statement' is a comment or blank line, or a
2427code line and all of its following continuation lines (if any)
2428considered as a single logical unit. The commands in this mode
2429generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002430statement containing point, even if point happens to be in the middle
2431of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002432
2433
2434@INDENTATION
2435
2436Primarily for entering new code:
2437\t\\[indent-for-tab-command]\t indent line appropriately
2438\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002439\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002440
2441Primarily for reindenting existing code:
2442\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2443\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2444
2445\t\\[py-indent-region]\t reindent region to match its context
2446\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2447\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2448
2449Unlike most programming languages, Python uses indentation, and only
2450indentation, to specify block structure. Hence the indentation supplied
2451automatically by Python-mode is just an educated guess: only you know
2452the block structure you intend, so only you can supply correct
2453indentation.
2454
2455The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2456the indentation of preceding statements. E.g., assuming
2457py-indent-offset is 4, after you enter
2458\tif a > 0: \\[py-newline-and-indent]
2459the cursor will be moved to the position of the `_' (_ is not a
2460character in the file, it's just used here to indicate the location of
2461the cursor):
2462\tif a > 0:
2463\t _
2464If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2465to
2466\tif a > 0:
2467\t c = d
2468\t _
2469Python-mode cannot know whether that's what you intended, or whether
2470\tif a > 0:
2471\t c = d
2472\t_
2473was your intent. In general, Python-mode either reproduces the
2474indentation of the (closest code or indenting-comment) preceding
2475statement, or adds an extra py-indent-offset blanks if the preceding
2476statement has `:' as its last significant (non-whitespace and non-
2477comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002478\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002479
2480Continuation lines are given extra indentation. If you don't like the
2481suggested indentation, change it to something you do like, and Python-
2482mode will strive to indent later lines of the statement in the same way.
2483
2484If a line is a continuation line by virtue of being in an unclosed
2485paren/bracket/brace structure (`list', for short), the suggested
2486indentation depends on whether the current line contains the first item
2487in the list. If it does, it's indented py-indent-offset columns beyond
2488the indentation of the line containing the open bracket. If you don't
2489like that, change it by hand. The remaining items in the list will mimic
2490whatever indentation you give to the first item.
2491
2492If a line is a continuation line because the line preceding it ends with
2493a backslash, the third and following lines of the statement inherit their
2494indentation from the line preceding them. The indentation of the second
2495line in the statement depends on the form of the first (base) line: if
2496the base line is an assignment statement with anything more interesting
2497than the backslash following the leftmost assigning `=', the second line
2498is indented two columns beyond that `='. Else it's indented to two
2499columns beyond the leftmost solid chunk of non-whitespace characters on
2500the base line.
2501
2502Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2503repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2504structure you intend.
2505%c:indent-for-tab-command
2506%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002507%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002508
2509
2510The next function may be handy when editing code you didn't write:
2511%c:py-guess-indent-offset
2512
2513
2514The remaining `indent' functions apply to a region of Python code. They
2515assume the block structure (equals indentation, in Python) of the region
2516is correct, and alter the indentation in various ways while preserving
2517the block structure:
2518%c:py-indent-region
2519%c:py-shift-region-left
2520%c:py-shift-region-right
2521
2522@MARKING & MANIPULATING REGIONS OF CODE
2523
2524\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002525\\[py-mark-def-or-class]\t mark smallest enclosing def
2526\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002527\\[comment-region]\t comment out region of code
2528\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002529%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002530%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002531%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002532
2533@MOVING POINT
2534
2535\\[py-previous-statement]\t move to statement preceding point
2536\\[py-next-statement]\t move to statement following point
2537\\[py-goto-block-up]\t move up to start of current block
2538\\[beginning-of-python-def-or-class]\t move to start of def
2539\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2540\\[end-of-python-def-or-class]\t move to end of def
2541\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2542
2543The first two move to one statement beyond the statement that contains
2544point. A numeric prefix argument tells them to move that many
2545statements instead. Blank lines, comment lines, and continuation lines
2546do not count as `statements' for these commands. So, e.g., you can go
2547to the first code statement in a file by entering
2548\t\\[beginning-of-buffer]\t to move to the top of the file
2549\t\\[py-next-statement]\t to skip over initial comments and blank lines
2550Or do `\\[py-previous-statement]' with a huge prefix argument.
2551%c:py-previous-statement
2552%c:py-next-statement
2553%c:py-goto-block-up
2554%c:beginning-of-python-def-or-class
2555%c:end-of-python-def-or-class
2556
2557@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2558
2559`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2560
2561`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2562overall class and def structure of a module.
2563
2564`\\[back-to-indentation]' moves point to a line's first non-blank character.
2565
2566`\\[indent-relative]' is handy for creating odd indentation.
2567
2568@OTHER EMACS HINTS
2569
2570If you don't like the default value of a variable, change its value to
2571whatever you do like by putting a `setq' line in your .emacs file.
2572E.g., to set the indentation increment to 4, put this line in your
2573.emacs:
2574\t(setq py-indent-offset 4)
2575To see the value of a variable, do `\\[describe-variable]' and enter the variable
2576name at the prompt.
2577
2578When entering a key sequence like `C-c C-n', it is not necessary to
2579release the CONTROL key after doing the `C-c' part -- it suffices to
2580press the CONTROL key, press and release `c' (while still holding down
2581CONTROL), press and release `n' (while still holding down CONTROL), &
2582then release CONTROL.
2583
2584Entering Python mode calls with no arguments the value of the variable
2585`python-mode-hook', if that value exists and is not nil; for backward
2586compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2587the Elisp manual for details.
2588
2589Obscure: When python-mode is first loaded, it looks for all bindings
2590to newline-and-indent in the global keymap, and shadows them with
2591local bindings to py-newline-and-indent."))
2592
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002593
2594;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002595(defvar py-parse-state-re
2596 (concat
2597 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2598 "\\|"
2599 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002600
Barry Warsaw7ae77681994-12-12 20:38:05 +00002601;; returns the parse state at point (see parse-partial-sexp docs)
2602(defun py-parse-state ()
2603 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002604 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002605 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002606 (while (not done)
2607 ;; back up to the first preceding line (if any; else start of
2608 ;; buffer) that begins with a popular Python keyword, or a
2609 ;; non- whitespace and non-comment character. These are good
2610 ;; places to start parsing to see whether where we started is
2611 ;; at a non-zero nesting level. It may be slow for people who
2612 ;; write huge code blocks or huge lists ... tough beans.
2613 (re-search-backward py-parse-state-re nil 'move)
2614 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002615 ;; In XEmacs, we have a much better way to test for whether
2616 ;; we're in a triple-quoted string or not. Emacs does not
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002617 ;; have this built-in function, which is its loss because
Barry Warsawf64b4051998-02-12 16:52:14 +00002618 ;; without scanning from the beginning of the buffer, there's
2619 ;; no accurate way to determine this otherwise.
2620 (if (not (fboundp 'buffer-syntactic-context))
2621 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002622 (progn
2623 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002624 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002625 (setq done (or (not (nth 3 pps))
2626 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002627 ;; XEmacs
2628 (setq done (or (not (buffer-syntactic-context))
2629 (bobp)))
2630 (when done
2631 (setq pps (parse-partial-sexp (point) here)))
2632 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002633 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002634
2635;; if point is at a non-zero nesting level, returns the number of the
2636;; character that opens the smallest enclosing unclosed list; else
2637;; returns nil.
2638(defun py-nesting-level ()
Barry Warsawf64b4051998-02-12 16:52:14 +00002639 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002640 (if (zerop (car status))
2641 nil ; not in a nest
2642 (car (cdr status))))) ; char# of open bracket
2643
2644;; t iff preceding line ends with backslash that's not in a comment
2645(defun py-backslash-continuation-line-p ()
2646 (save-excursion
2647 (beginning-of-line)
2648 (and
2649 ;; use a cheap test first to avoid the regexp if possible
2650 ;; use 'eq' because char-after may return nil
2651 (eq (char-after (- (point) 2)) ?\\ )
2652 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002653 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002654 (looking-at py-continued-re))))
2655
2656;; t iff current line is a continuation line
2657(defun py-continuation-line-p ()
2658 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002659 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002660 (or (py-backslash-continuation-line-p)
2661 (py-nesting-level))))
2662
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002663;; go to initial line of current statement; usually this is the line
2664;; we're on, but if we're on the 2nd or following lines of a
2665;; continuation block, we need to go up to the first line of the
2666;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002667;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002668;; Tricky: We want to avoid quadratic-time behavior for long continued
2669;; blocks, whether of the backslash or open-bracket varieties, or a
2670;; mix of the two. The following manages to do that in the usual
2671;; cases.
Barry Warsawc210e691998-01-20 22:52:56 +00002672;;
2673;; Also, if we're sitting inside a triple quoted string, this will
2674;; drop us at the line that begins the string.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002675(defun py-goto-initial-line ()
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002676 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002677 (while (py-continuation-line-p)
2678 (beginning-of-line)
2679 (if (py-backslash-continuation-line-p)
2680 (while (py-backslash-continuation-line-p)
2681 (forward-line -1))
2682 ;; else zip out of nested brackets/braces/parens
2683 (while (setq open-bracket-pos (py-nesting-level))
2684 (goto-char open-bracket-pos)))))
2685 (beginning-of-line))
2686
2687;; go to point right beyond final line of current statement; usually
2688;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002689;; statement we need to skip over the continuation lines. Tricky:
2690;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002691(defun py-goto-beyond-final-line ()
2692 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002693 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002694 (while (and (py-continuation-line-p)
2695 (not (eobp)))
2696 ;; skip over the backslash flavor
2697 (while (and (py-backslash-continuation-line-p)
2698 (not (eobp)))
2699 (forward-line 1))
2700 ;; if in nest, zip to the end of the nest
2701 (setq state (py-parse-state))
2702 (if (and (not (zerop (car state)))
2703 (not (eobp)))
2704 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002705 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002706 (forward-line 1))))))
2707
2708;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002709;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002710(defun py-statement-opens-block-p ()
2711 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002712 (let ((start (point))
2713 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2714 (searching t)
2715 (answer nil)
2716 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002717 (goto-char start)
2718 (while searching
2719 ;; look for a colon with nothing after it except whitespace, and
2720 ;; maybe a comment
2721 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2722 finish t)
2723 (if (eq (point) finish) ; note: no `else' clause; just
2724 ; keep searching if we're not at
2725 ; the end yet
2726 ;; sure looks like it opens a block -- but it might
2727 ;; be in a comment
2728 (progn
2729 (setq searching nil) ; search is done either way
2730 (setq state (parse-partial-sexp start
2731 (match-beginning 0)))
2732 (setq answer (not (nth 4 state)))))
2733 ;; search failed: couldn't find another interesting colon
2734 (setq searching nil)))
2735 answer)))
2736
Barry Warsawf831d811996-07-31 20:42:59 +00002737(defun py-statement-closes-block-p ()
2738 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002739 ;; starts with `return', `raise', `break', `continue', and `pass'.
2740 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002741 (let ((here (point)))
2742 (back-to-indentation)
2743 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002744 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002745 (goto-char here))))
2746
Barry Warsaw7ae77681994-12-12 20:38:05 +00002747;; go to point right beyond final line of block begun by the current
2748;; line. This is the same as where py-goto-beyond-final-line goes
2749;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002750;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002751(defun py-goto-beyond-block ()
2752 (if (py-statement-opens-block-p)
2753 (py-mark-block nil 'just-move)
2754 (py-goto-beyond-final-line)))
2755
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002756;; Go to start of first statement (not blank or comment or
2757;; continuation line) at or preceding point. Returns t if there is
2758;; one, else nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002759(defun py-goto-statement-at-or-above ()
2760 (py-goto-initial-line)
2761 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002762 ;; skip back over blank & comment lines
2763 ;; note: will skip a blank or comment line that happens to be
2764 ;; a continuation line too
2765 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2766 (progn (py-goto-initial-line) t)
2767 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002768 t))
2769
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002770;; Go to start of first statement (not blank or comment or
2771;; continuation line) following the statement containing point.
2772;; Returns t if there is one, else nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002773(defun py-goto-statement-below ()
2774 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002775 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002776 (py-goto-beyond-final-line)
2777 (while (and
2778 (looking-at py-blank-or-comment-re)
2779 (not (eobp)))
2780 (forward-line 1))
2781 (if (eobp)
2782 (progn (goto-char start) nil)
2783 t)))
2784
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002785;; Go to start of statement, at or preceding point, starting with
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002786;; keyword KEY. Skips blank lines and non-indenting comments upward
2787;; first. If that statement starts with KEY, done, else go back to
2788;; first enclosing block starting with KEY. If successful, leaves
2789;; point at the start of the KEY line & returns t. Else leaves point
2790;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002791(defun py-go-up-tree-to-keyword (key)
2792 ;; skip blanks and non-indenting #
2793 (py-goto-initial-line)
2794 (while (and
2795 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2796 (zerop (forward-line -1))) ; go back
2797 nil)
2798 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002799 (let* ((re (concat "[ \t]*" key "\\b"))
2800 (case-fold-search nil) ; let* so looking-at sees this
2801 (found (looking-at re))
2802 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002803 (while (not (or found dead))
2804 (condition-case nil ; in case no enclosing block
2805 (py-goto-block-up 'no-mark)
2806 (error (setq dead t)))
2807 (or dead (setq found (looking-at re))))
2808 (beginning-of-line)
2809 found))
2810
2811;; return string in buffer from start of indentation to end of line;
2812;; prefix "..." if leading whitespace was skipped
2813(defun py-suck-up-leading-text ()
2814 (save-excursion
2815 (back-to-indentation)
2816 (concat
2817 (if (bolp) "" "...")
2818 (buffer-substring (point) (progn (end-of-line) (point))))))
2819
2820;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2821;; as a Lisp symbol; return nil if none
2822(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002823 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002824 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2825 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2826 nil)))
2827
Barry Warsawb3e81d51996-09-04 15:12:42 +00002828(defun py-current-defun ()
2829 ;; tell add-log.el how to find the current function/method/variable
2830 (save-excursion
2831 (if (re-search-backward py-defun-start-re nil t)
2832 (or (match-string 3)
2833 (let ((method (match-string 2)))
2834 (if (and (not (zerop (length (match-string 1))))
2835 (re-search-backward py-class-start-re nil t))
2836 (concat (match-string 1) "." method)
2837 method)))
2838 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002839
2840
Barry Warsawfec75d61995-07-05 23:26:15 +00002841(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002842 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002843
Barry Warsaw850437a1995-03-08 21:50:28 +00002844(defun py-version ()
2845 "Echo the current version of `python-mode' in the minibuffer."
2846 (interactive)
2847 (message "Using `python-mode' version %s" py-version)
2848 (py-keep-region-active))
2849
2850;; only works under Emacs 19
2851;(eval-when-compile
2852; (require 'reporter))
2853
2854(defun py-submit-bug-report (enhancement-p)
2855 "Submit via mail a bug report on `python-mode'.
2856With \\[universal-argument] just submit an enhancement request."
2857 (interactive
2858 (list (not (y-or-n-p
2859 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002860 (let ((reporter-prompt-for-summary-p (if enhancement-p
2861 "(Very) brief summary: "
2862 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002863 (require 'reporter)
2864 (reporter-submit-bug-report
2865 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002866 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002867 ;; varlist
2868 (if enhancement-p nil
2869 '(py-python-command
2870 py-indent-offset
2871 py-block-comment-prefix
2872 py-scroll-process-buffer
2873 py-temp-directory
2874 py-beep-if-tab-change))
2875 nil ;pre-hooks
2876 nil ;post-hooks
2877 "Dear Barry,") ;salutation
2878 (if enhancement-p nil
2879 (set-mark (point))
2880 (insert
2881"Please replace this text with a sufficiently large code sample\n\
2882and an exact recipe so that I can reproduce your problem. Failure\n\
2883to do so may mean a greater delay in fixing your bug.\n\n")
2884 (exchange-point-and-mark)
2885 (py-keep-region-active))))
2886
2887
Barry Warsaw47384781997-11-26 05:27:45 +00002888(defun py-kill-emacs-hook ()
2889 (mapcar #'(lambda (filename)
2890 (py-safe (delete-file filename)))
2891 py-file-queue))
2892
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002893;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002894(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002895
2896
2897
2898(provide 'python-mode)
2899;;; python-mode.el ends here