blob: 9d42b0c1f41542878dae3a414d26991d3dc0ab67 [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Barry Warsawf64b4051998-02-12 16:52:14 +00005;; Author: 1995-1998 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
Barry Warsawa97a3f31997-11-04 18:47:06 +00007;; Maintainer: python-mode@python.org
8;; Created: Feb 1992
9;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000010
Barry Warsaw5204b4a1998-04-02 19:27:18 +000011(defconst py-version "$Revision$"
Barry Warsawc72c11c1997-08-09 06:42:08 +000012 "`python-mode' version number.")
13
Barry Warsawcfec3591995-03-10 15:58:16 +000014;; This software is provided as-is, without express or implied
15;; warranty. Permission to use, copy, modify, distribute or sell this
16;; software, without fee, for any purpose and by any individual or
17;; organization, is hereby granted, provided that the above copyright
18;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000019
20;;; Commentary:
Barry Warsaw755c6711996-08-01 20:02:55 +000021
Barry Warsaw7b0f5681995-03-08 21:33:04 +000022;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000023;; by Tim Peters after an original idea by Michael A. Guravage. Tim
24;; subsequently left the net; in 1995, Barry Warsaw inherited the
25;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000026
Barry Warsaw37231521997-12-11 17:23:13 +000027;; COMPATIBILITY:
Barry Warsaw7b0f5681995-03-08 21:33:04 +000028
Barry Warsaw37231521997-12-11 17:23:13 +000029;; This version of python-mode.el is no longer compatible with Emacs
30;; 18. For a gabazillion reasons, I highly recommend upgrading to
31;; X/Emacs 19 or X/Emacs 20. I recommend at least Emacs 19.34 or
32;; XEmacs 19.15. Any of the v20 X/Emacsen should be fine.
Barry Warsaw673d05f1997-12-02 21:51:57 +000033
Barry Warsaw37231521997-12-11 17:23:13 +000034;; NOTE TO FSF EMACS USERS:
35
36;; You may need to acquire the Custom library -- this applies to users
37;; of Emacs 19.34 and NTEmacs based on 19.34, but not to Emacs 20
38;; users. You must also byte-compile this file before use -- this
39;; applies to FSF's Emacs 19.34, 20.x, and NTEmacs based on 19.34.
40;; None of this applies to XEmacs (although byte compilation is still
41;; recommended). You will also need to add the following to your
42;; .emacs file so that the .py files come up in python-mode:
Barry Warsaw7ae77681994-12-12 20:38:05 +000043;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000044;; (autoload 'python-mode "python-mode" "Python editing mode." t)
45;; (setq auto-mode-alist
46;; (cons '("\\.py$" . python-mode) auto-mode-alist))
47;; (setq interpreter-mode-alist
48;; (cons '("python" . python-mode) interpreter-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000049;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000050;; Assuming python-mode.el is on your load-path, it will be invoked
51;; when you visit a .py file, or a file with a first line that looks
52;; like:
53;;
54;; #! /usr/bin/env python
55
Barry Warsaw37231521997-12-11 17:23:13 +000056;; NOTE TO XEMACS USERS:
57
58;; An older version of this file was distributed with XEmacs 19.15,
59;; 19.16 and 20.3. By default, in XEmacs when you visit a .py file,
60;; the buffer is put in Python mode. Likewise for executable scripts
61;; with the word `python' on the first line. You shouldn't need to do
62;; much except make sure this new version is earlier in your
63;; load-path, and byte-compile this file.
64
65;; FOR MORE INFORMATION:
66
Barry Warsaw145ab1c1998-05-19 14:49:49 +000067;; Please see <http://www.python.org/emacs/python-mode/> for the
Barry Warsaw37231521997-12-11 17:23:13 +000068;; latest information and compatibility notes.
69
70;; BUG REPORTING:
Barry Warsaw7ae77681994-12-12 20:38:05 +000071
Barry Warsawaffc0ca1997-11-03 16:59:38 +000072;; To submit bug reports, use C-c C-b. Please include a complete, but
73;; concise code sample and a recipe for reproducing the bug. Send
74;; suggestions and other comments to python-mode@python.org.
75
76;; When in a Python mode buffer, do a C-h m for more help. It's
Barry Warsaw37231521997-12-11 17:23:13 +000077;; doubtful that a texinfo manual would be very useful, but if you
78;; want to contribute one, I'll certainly accept it!
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000079
Barry Warsaw5ea20d51997-12-06 00:00:47 +000080;; If you are using XEmacs, you may also want to check out OO-Browser
81;; that comes bundled with it, including documentation in the info
82;; pages. For GNU Emacs you have to install it yourself. To read
83;; more about OO-Browser, follow these links:
84
85;; http://www.python.org/workshops/1996-06/papers/h.pasanen/oobr_contents.html
86;; http://www.infodock.com/manuals/alt-oobr-cover.html
87
Barry Warsaw37231521997-12-11 17:23:13 +000088;; You may also want to take a look at Harri Pasanen's "Python Library
89;; Reference Hot-Key Help System for XEmacs (or PLRHKHSX for short ;),
90;; version 1.0"
Barry Warsaw7b0f5681995-03-08 21:33:04 +000091;;
Barry Warsaw37231521997-12-11 17:23:13 +000092;; <http://www.iki.fi/hpa/>
93
94;; TO DO LIST:
95
96;; - Better integration with pdb.py and gud-mode for debugging.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000097;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000098;; - possibly force indent-tabs-mode == nil, and add a
99;; write-file-hooks that runs untabify on the whole buffer (to work
100;; around potential tab/space mismatch problems). In practice this
101;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +0000102;; - have py-execute-region on indented code act as if the region is
Barry Warsaw37231521997-12-11 17:23:13 +0000103;; left justified. Avoids syntax errors.
104;; - add a py-goto-block-down, bound to C-c C-d
Barry Warsaw7ae77681994-12-12 20:38:05 +0000105
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000106;;; Code:
107
Barry Warsawc72c11c1997-08-09 06:42:08 +0000108(require 'custom)
Barry Warsaw8529ebb1997-12-01 20:03:12 +0000109(eval-when-compile
Barry Warsaw673d05f1997-12-02 21:51:57 +0000110 (require 'cl)
Barry Warsawb6c1f1f1998-03-19 22:33:06 +0000111 (if (not (and (condition-case nil
112 (require 'custom)
113 (error nil))
114 ;; Stock Emacs 19.34 has a broken/old Custom library
115 ;; that does more harm than good. Fortunately, it is
116 ;; missing defcustom
117 (fboundp 'defcustom)))
Barry Warsaw673d05f1997-12-02 21:51:57 +0000118 (error "STOP! STOP! STOP! STOP!
119
120The Custom library was not found or is out of date. A more current
121version is required. Please download and install the latest version
122of the Custom library from:
123
124 <http://www.dina.kvl.dk/~abraham/custom/>
125
126See the Python Mode home page for details:
127
128 <http://www.python.org/ftp/emacs/>
129")))
130
Barry Warsawc72c11c1997-08-09 06:42:08 +0000131
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000132
133;; user definable variables
134;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000135
Barry Warsawc72c11c1997-08-09 06:42:08 +0000136(defgroup python nil
137 "Support for the Python programming language, <http://www.python.org/>"
138 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000139
Barry Warsawc72c11c1997-08-09 06:42:08 +0000140(defcustom py-python-command "python"
141 "*Shell command used to start Python interpreter."
142 :type 'string
143 :group 'python)
144
Barry Warsawa2398801998-04-09 23:28:20 +0000145(defcustom py-jpython-command "jpython"
146 "*Shell command used to start the JPython interpreter."
147 :type 'string
148 :group 'python)
149
Barry Warsaw8f972b71998-02-05 20:45:49 +0000150(defcustom py-python-command-args '("-i")
151 "*List of string arguments to be used when starting a Python shell."
152 :type '(repeat string)
153 :group 'python)
154
Barry Warsawa2398801998-04-09 23:28:20 +0000155(defcustom py-jpython-command-args '("-i")
156 "*List of string arguments to be used when starting a JPython shell."
157 :type '(repeat string)
158 :group 'python)
159
Barry Warsawc72c11c1997-08-09 06:42:08 +0000160(defcustom py-indent-offset 4
Barry Warsaw41a05c71998-08-10 16:33:12 +0000161 "*Amount of offset per level of indentation.
162`\\[py-guess-indent-offset]' can usually guess a good value when
163you're editing someone else's Python code."
Barry Warsawc72c11c1997-08-09 06:42:08 +0000164 :type 'integer
165 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000166
Barry Warsaw742a5111998-03-13 17:29:15 +0000167(defcustom py-smart-indentation t
168 "*Should `python-mode' try to automagically set some indentation variables?
169When this variable is non-nil, two things happen when a buffer is set
170to `python-mode':
171
172 1. `py-indent-offset' is guess from existing code in the buffer.
Barry Warsaw639eea61998-03-16 18:12:13 +0000173 Only guessed values between 2 and 8 are considered. If a valid
Barry Warsaw742a5111998-03-13 17:29:15 +0000174 guess can't be made (perhaps because you are visiting a new
Barry Warsaw639eea61998-03-16 18:12:13 +0000175 file), then the value in `py-indent-offset' is used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000176
Barry Warsaw639eea61998-03-16 18:12:13 +0000177 2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
178 equal `tab-width' (`indent-tabs-mode' is never turned on by
179 Python mode). This means that for newly written code, tabs are
180 only inserted in indentation if one tab is one indentation
181 level, otherwise only spaces are used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000182
Barry Warsaw8046bef1998-03-13 20:04:52 +0000183Note that both these settings occur *after* `python-mode-hook' is run,
184so if you want to defeat the automagic configuration, you must also
185set `py-smart-indentation' to nil in your `python-mode-hook'."
Barry Warsaw742a5111998-03-13 17:29:15 +0000186 :type 'boolean
187 :group 'python)
188
Barry Warsawc72c11c1997-08-09 06:42:08 +0000189(defcustom py-align-multiline-strings-p t
190 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000191When this flag is non-nil, continuation lines are lined up under the
192preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000193lines are aligned to column zero."
194 :type '(choice (const :tag "Align under preceding line" t)
195 (const :tag "Align to column zero" nil))
196 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000197
Barry Warsawc72c11c1997-08-09 06:42:08 +0000198(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000199 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000200This should follow the convention for non-indenting comment lines so
201that the indentation commands won't get confused (i.e., the string
202should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000203`...' is arbitrary)."
204 :type 'string
205 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000206
Barry Warsawc72c11c1997-08-09 06:42:08 +0000207(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000208 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000209
Barry Warsaw6d627751996-03-06 18:41:38 +0000210When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000211if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000212
213When t, lines that begin with a single `#' are a hint to subsequent
214line indentation. If the previous line is such a comment line (as
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000215opposed to one that starts with `py-block-comment-prefix'), then its
Barry Warsaw6d627751996-03-06 18:41:38 +0000216indentation is used as a hint for this line's indentation. Lines that
217begin with `py-block-comment-prefix' are ignored for indentation
218purposes.
219
220When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000221indentation hints, unless the comment character is in column zero."
222 :type '(choice
223 (const :tag "Skip all comment lines (fast)" nil)
224 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000225 (const :tag "Single # `sets' indentation except at column zero"
226 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000227 )
228 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000229
Barry 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
Barry Warsaw41a05c71998-08-10 16:33:12 +0000243 being the one the cursor is in). The usual behavior for `shell-mode'
Barry Warsaw7ae77681994-12-12 20:38:05 +0000244 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
Barry Warsaw41a05c71998-08-10 16:33:12 +0000251 output. The usual behavior for a `shell-mode' buffer is to stay
Barry Warsaw7ae77681994-12-12 20:38:05 +0000252 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 Warsaw41a05c71998-08-10 16:33:12 +0000293 "*Ring the bell if `tab-width' is changed.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000294If 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
Barry Warsaw3bfed5b1998-05-19 16:25:04 +0000310source code of the innermost frame."
311 :type 'boolean
312 :group 'python)
313
314(defcustom py-ask-about-save t
315 "If not nil, ask about which buffers to save before executing some code.
316Otherwise, all modified buffers are saved without asking."
317 :type 'boolean
318 :group 'python)
Barry Warsaw9981d221997-12-03 05:25:48 +0000319
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000320(defcustom py-backspace-function 'backward-delete-char-untabify
321 "*Function called by `py-electric-backspace' when deleting backwards."
322 :type 'function
323 :group 'python)
324
325(defcustom py-delete-function 'delete-char
326 "*Function called by `py-electric-delete' when deleting forwards."
327 :type 'function
328 :group 'python)
329
Barry Warsawc0ecb531998-01-20 21:43:34 +0000330;; Not customizable
331(defvar py-master-file nil
332 "If non-nil, execute the named file instead of the buffer's file.
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000333The intent is to allow you to set this variable in the file's local
Barry Warsawc0ecb531998-01-20 21:43:34 +0000334variable section, e.g.:
335
336 # Local Variables:
337 # py-master-file: \"master.py\"
338 # End:
339
Barry Warsaw41a05c71998-08-10 16:33:12 +0000340so that typing \\[py-execute-buffer] in that buffer executes the named
341master file instead of the buffer's file. Note that if the file name
342has a relative path, the value of `default-directory' for the buffer
343is prepended to come up with a file name.")
Barry Warsawc0ecb531998-01-20 21:43:34 +0000344(make-variable-buffer-local 'py-master-file)
345
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000346
Barry Warsawc72c11c1997-08-09 06:42:08 +0000347
348;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
349;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
350
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000351(defconst py-emacs-features
352 (let (features)
353 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
354 ;; the same string.
355 (let ((tmp1 (make-temp-name ""))
356 (tmp2 (make-temp-name "")))
357 (if (string-equal tmp1 tmp2)
358 (push 'broken-temp-names features)))
359 ;; return the features
360 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000361 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000362There are many flavors of Emacs out there, with different levels of
363support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000364
Barry Warsawfb07f401997-02-24 03:37:22 +0000365(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000366 (let ((kw1 (mapconcat 'identity
367 '("and" "assert" "break" "class"
368 "continue" "def" "del" "elif"
369 "else" "except" "exec" "for"
370 "from" "global" "if" "import"
371 "in" "is" "lambda" "not"
372 "or" "pass" "print" "raise"
373 "return" "while"
374 )
375 "\\|"))
376 (kw2 (mapconcat 'identity
377 '("else:" "except:" "finally:" "try:")
378 "\\|"))
379 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000380 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000381 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000382 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
383 ;; block introducing keywords with immediately following colons.
384 ;; Yes "except" is in both lists.
385 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000386 ;; classes
387 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
388 1 font-lock-type-face)
389 ;; functions
390 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
391 1 font-lock-function-name-face)
392 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000393 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000394(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
395
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000396
Barry Warsaw81437461996-08-01 19:48:02 +0000397(defvar imenu-example--python-show-method-args-p nil
398 "*Controls echoing of arguments of functions & methods in the imenu buffer.
399When non-nil, arguments are printed.")
400
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000401(make-variable-buffer-local 'py-indent-offset)
402
Barry Warsawe467bfb1997-11-26 05:40:58 +0000403;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000404(defvar py-file-queue nil
405 "Queue of Python temp files awaiting execution.
406Currently-active file is at the head of the list.")
407
Barry Warsawc72c11c1997-08-09 06:42:08 +0000408
409;; Constants
410
Barry Warsawc72c11c1997-08-09 06:42:08 +0000411(defconst py-stringlit-re
412 (concat
Barry Warsaw751f4931998-05-19 16:06:21 +0000413 ;; These fail if backslash-quote ends the string (not worth
414 ;; fixing?). They precede the short versions so that the first two
415 ;; quotes don't look like an empty short string.
416 ;;
417 ;; (maybe raw), long single quoted triple quoted strings (SQTQ),
418 ;; with potential embedded single quotes
419 "[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
420 "\\|"
421 ;; (maybe raw), long double quoted triple quoted strings (DQTQ),
422 ;; with potential embedded double quotes
423 "[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
424 "\\|"
425 "[rR]?'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
Barry Warsawc72c11c1997-08-09 06:42:08 +0000426 "\\|" ; or
Barry Warsaw751f4931998-05-19 16:06:21 +0000427 "[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\"" ; double-quoted
Barry Warsaw41a05c71998-08-10 16:33:12 +0000428 )
429 "Regular expression matching a Python string literal.")
Barry Warsaw751f4931998-05-19 16:06:21 +0000430
Barry Warsawc72c11c1997-08-09 06:42:08 +0000431(defconst py-continued-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000432 ;; This is tricky because a trailing backslash does not mean
433 ;; continuation if it's in a comment
Barry Warsawc72c11c1997-08-09 06:42:08 +0000434 (concat
435 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
Barry Warsaw41a05c71998-08-10 16:33:12 +0000436 "\\\\$")
437 "Regular expression matching Python backslash continuation lines.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000438
Barry Warsaw41a05c71998-08-10 16:33:12 +0000439(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
Barry Warsaw71c3adb1998-08-10 16:34:33 +0000440 "Regular expression matching a blank or comment line.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000441
Barry Warsawc72c11c1997-08-09 06:42:08 +0000442(defconst py-outdent-re
443 (concat "\\(" (mapconcat 'identity
444 '("else:"
445 "except\\(\\s +.*\\)?:"
446 "finally:"
447 "elif\\s +.*:")
448 "\\|")
Barry Warsaw41a05c71998-08-10 16:33:12 +0000449 "\\)")
450 "Regular expression matching statements to be dedented one level.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000451
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000452(defconst py-block-closing-keywords-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000453 "\\(return\\|raise\\|break\\|continue\\|pass\\)"
454 "Regular expression matching keywords which typically close a block.")
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000455
Barry Warsawc72c11c1997-08-09 06:42:08 +0000456(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000457 (concat
458 "\\("
459 (mapconcat 'identity
460 (list "try:"
461 "except\\(\\s +.*\\)?:"
462 "while\\s +.*:"
463 "for\\s +.*:"
464 "if\\s +.*:"
465 "elif\\s +.*:"
466 (concat py-block-closing-keywords-re "[ \t\n]")
467 )
468 "\\|")
Barry Warsaw41a05c71998-08-10 16:33:12 +0000469 "\\)")
470 "Regular expression matching lines not to dedent after.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000471
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000472(defconst py-defun-start-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000473 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*="
474 ;; If you change this, you probably have to change py-current-defun
475 ;; as well. This is only used by py-current-defun to find the name
476 ;; for add-log.el.
Barry Warsaw71c3adb1998-08-10 16:34:33 +0000477 "Regular expression matching a function, method, or variable assignment.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000478
Barry Warsaw41a05c71998-08-10 16:33:12 +0000479(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)"
480 ;; If you change this, you probably have to change py-current-defun
481 ;; as well. This is only used by py-current-defun to find the name
482 ;; for add-log.el.
483 "Regular expression for finding a class name.")
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000484
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000485(defconst py-traceback-line-re
Barry Warsaw41a05c71998-08-10 16:33:12 +0000486 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)"
487 "Regular expression that describes tracebacks.")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000488
489
490
491;; Utilities
492
493(defmacro py-safe (&rest body)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000494 "Safely execute BODY, return nil if an error occurred."
Barry Warsawc72c11c1997-08-09 06:42:08 +0000495 (` (condition-case nil
496 (progn (,@ body))
497 (error nil))))
498
499(defsubst py-keep-region-active ()
Barry Warsaw41a05c71998-08-10 16:33:12 +0000500 "Keep the region active in XEmacs."
Barry Warsawc72c11c1997-08-09 06:42:08 +0000501 ;; Ignore byte-compiler warnings you might see. Also note that
502 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
503 ;; to take explicit action.
504 (and (boundp 'zmacs-region-stays)
505 (setq zmacs-region-stays t)))
506
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000507(defsubst py-point (position)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000508 "Returns the value of point at certain commonly referenced POSITIONs.
509POSITION can be one of the following symbols:
510
511 bol -- beginning of line
512 eol -- end of line
513 bod -- beginning of def or class
514 eod -- end of def or class
515 bob -- beginning of buffer
516 eob -- end of buffer
517 boi -- back to indentation
518 bos -- beginning of statement
519
520This function does not modify point or mark."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000521 (let ((here (point)))
522 (cond
523 ((eq position 'bol) (beginning-of-line))
524 ((eq position 'eol) (end-of-line))
Barry Warsawab0e86c1998-05-19 15:31:46 +0000525 ((eq position 'bod) (py-beginning-of-def-or-class))
Barry Warsaw41a05c71998-08-10 16:33:12 +0000526 ((eq position 'eod) (py-end-of-def-or-class))
Barry Warsawab0e86c1998-05-19 15:31:46 +0000527 ;; Kind of funny, I know, but useful for py-up-exception.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000528 ((eq position 'bob) (beginning-of-buffer))
529 ((eq position 'eob) (end-of-buffer))
530 ((eq position 'boi) (back-to-indentation))
Barry Warsawab0e86c1998-05-19 15:31:46 +0000531 ((eq position 'bos) (py-goto-initial-line))
Barry Warsaw41a05c71998-08-10 16:33:12 +0000532 (t (error "Unknown buffer position requested: %s" position))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000533 )
534 (prog1
535 (point)
536 (goto-char here))))
537
538(defsubst py-highlight-line (from to file line)
539 (cond
540 ((fboundp 'make-extent)
541 ;; XEmacs
542 (let ((e (make-extent from to)))
543 (set-extent-property e 'mouse-face 'highlight)
544 (set-extent-property e 'py-exc-info (cons file line))
545 (set-extent-property e 'keymap py-mode-output-map)))
546 (t
547 ;; Emacs -- Please port this!
548 )
549 ))
550
Barry Warsawe908b6b1998-03-19 22:48:02 +0000551(defun py-in-literal (&optional lim)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000552 "Return non-nil if point is in a Python literal (a comment or string).
553Optional argument LIM indicates the beginning of the containing form,
554i.e. the limit on how far back to scan."
555 ;; This is the version used for non-XEmacs, which has a nicer
556 ;; interface.
Barry Warsawe908b6b1998-03-19 22:48:02 +0000557 ;;
558 ;; WARNING: Watch out for infinite recursion.
559 (let* ((lim (or lim (c-point 'bod)))
560 (state (parse-partial-sexp lim (point))))
561 (cond
562 ((nth 3 state) 'string)
563 ((nth 4 state) 'comment)
564 (t nil))))
565
566;; XEmacs has a built-in function that should make this much quicker.
567;; In this case, lim is ignored
568(defun py-fast-in-literal (&optional lim)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000569 "Fast version of `py-in-literal', used only by XEmacs.
570Optional LIM is ignored."
Barry Warsawe908b6b1998-03-19 22:48:02 +0000571 ;; don't have to worry about context == 'block-comment
572 (buffer-syntactic-context))
573
574(if (fboundp 'buffer-syntactic-context)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000575 (defalias 'py-in-literal 'py-fast-in-literal))
Barry Warsawe908b6b1998-03-19 22:48:02 +0000576
577
Barry Warsawc72c11c1997-08-09 06:42:08 +0000578
579;; Major mode boilerplate
580
Barry Warsaw7ae77681994-12-12 20:38:05 +0000581;; define a mode-specific abbrev table for those who use such things
582(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000583 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000584(define-abbrev-table 'python-mode-abbrev-table nil)
585
Barry Warsaw7ae77681994-12-12 20:38:05 +0000586(defvar python-mode-hook nil
587 "*Hook called by `python-mode'.")
588
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000589;; In previous version of python-mode.el, the hook was incorrectly
590;; called py-mode-hook, and was not defvar'd. Deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000591(and (fboundp 'make-obsolete-variable)
592 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
593
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000594(defvar py-mode-map ()
595 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000596(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000597 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000598 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000599 ;; electric keys
600 (define-key py-mode-map ":" 'py-electric-colon)
601 ;; indentation level modifiers
602 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
603 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
604 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
605 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
606 ;; subprocess commands
607 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
Barry Warsaw820273d1998-05-19 15:54:45 +0000608 (define-key py-mode-map "\C-c\C-m" 'py-execute-import-or-reload)
Barry Warsaw1d0364b1998-05-19 16:15:26 +0000609 (define-key py-mode-map "\C-c\C-s" 'py-execute-string)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000610 (define-key py-mode-map "\C-c|" 'py-execute-region)
Barry Warsaw820273d1998-05-19 15:54:45 +0000611 (define-key py-mode-map "\e\C-x" 'py-execute-def-or-class)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000612 (define-key py-mode-map "\C-c!" 'py-shell)
Barry Warsawa2398801998-04-09 23:28:20 +0000613 (define-key py-mode-map "\C-c\C-t" 'py-toggle-shells)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000614 ;; Caution! Enter here at your own risk. We are trying to support
615 ;; several behaviors and it gets disgusting. :-( This logic ripped
616 ;; largely from CC Mode.
617 ;;
618 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
619 ;; backwards deletion behavior to DEL, which both Delete and
620 ;; Backspace get translated to. There's no way to separate this
621 ;; behavior in a clean way, so deal with it! Besides, it's been
622 ;; this way since the dawn of time.
623 (if (not (boundp 'delete-key-deletes-forward))
624 (define-key py-mode-map "\177" 'py-electric-backspace)
625 ;; However, XEmacs 20 actually achieved enlightenment. It is
626 ;; possible to sanely define both backward and forward deletion
627 ;; behavior under X separately (TTYs are forever beyond hope, but
628 ;; who cares? XEmacs 20 does the right thing with these too).
629 (define-key py-mode-map [delete] 'py-electric-delete)
630 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000631 ;; Separate M-BS from C-M-h. The former should remain
632 ;; backward-kill-word.
633 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000634 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000635 ;; Miscellaneous
636 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
637 (define-key py-mode-map "\C-c\t" 'py-indent-region)
638 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
639 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
640 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000641 (define-key py-mode-map "\C-c#" 'py-comment-region)
642 (define-key py-mode-map "\C-c?" 'py-describe-mode)
643 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
Barry Warsawab0e86c1998-05-19 15:31:46 +0000644 (define-key py-mode-map "\e\C-a" 'py-beginning-of-def-or-class)
645 (define-key py-mode-map "\e\C-e" 'py-end-of-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000646 (define-key py-mode-map "\C-c-" 'py-up-exception)
647 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000648 ;; information
649 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
650 (define-key py-mode-map "\C-c\C-v" 'py-version)
651 ;; py-newline-and-indent mappings
Barry Warsaw82aecb91998-01-21 05:14:24 +0000652 (define-key py-mode-map "\n" 'py-newline-and-indent)
653 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000654 ;; shadow global bindings for newline-and-indent w/ the py- version.
655 ;; BAW - this is extremely bad form, but I'm not going to change it
656 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000657 (mapcar #'(lambda (key)
658 (define-key py-mode-map key 'py-newline-and-indent))
659 (where-is-internal 'newline-and-indent))
660 )
661
662(defvar py-mode-output-map nil
Barry Warsaw41a05c71998-08-10 16:33:12 +0000663 "Keymap used in *Python Output* buffers.")
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000664(if py-mode-output-map
665 nil
666 (setq py-mode-output-map (make-sparse-keymap))
667 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
668 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
669 ;; TBD: Disable all self-inserting keys. This is bogus, we should
670 ;; really implement this as *Python Output* buffer being read-only
671 (mapcar #' (lambda (key)
672 (define-key py-mode-output-map key
673 #'(lambda () (interactive) (beep))))
674 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000675 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000676
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000677(defvar py-mode-syntax-table nil
678 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000679(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000680 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000681 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000682 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
683 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
684 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
685 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
686 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
687 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
688 ;; Add operator symbols misassigned in the std table
689 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
690 (modify-syntax-entry ?\% "." py-mode-syntax-table)
691 (modify-syntax-entry ?\& "." py-mode-syntax-table)
692 (modify-syntax-entry ?\* "." py-mode-syntax-table)
693 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
694 (modify-syntax-entry ?\- "." py-mode-syntax-table)
695 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
696 (modify-syntax-entry ?\< "." py-mode-syntax-table)
697 (modify-syntax-entry ?\= "." py-mode-syntax-table)
698 (modify-syntax-entry ?\> "." py-mode-syntax-table)
699 (modify-syntax-entry ?\| "." py-mode-syntax-table)
700 ;; For historical reasons, underscore is word class instead of
701 ;; symbol class. GNU conventions say it should be symbol class, but
702 ;; there's a natural conflict between what major mode authors want
703 ;; and what users expect from `forward-word' and `backward-word'.
704 ;; Guido and I have hashed this out and have decided to keep
705 ;; underscore in word class. If you're tempted to change it, try
706 ;; binding M-f and M-b to py-forward-into-nomenclature and
707 ;; py-backward-into-nomenclature instead.
708 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
709 ;; Both single quote and double quote are string delimiters
710 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
711 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
712 ;; backquote is open and close paren
713 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
714 ;; comment delimiters
715 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
716 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
717 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000718
Barry Warsawb3e81d51996-09-04 15:12:42 +0000719
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000720
Barry Warsaw42f707f1996-07-29 21:05:05 +0000721;; Menu definitions, only relevent if you have the easymenu.el package
722;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000723(defvar py-menu nil
724 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000725This menu will get created automatically if you have the `easymenu'
726package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000727
Barry Warsawc72c11c1997-08-09 06:42:08 +0000728(and (py-safe (require 'easymenu) t)
729 (easy-menu-define
730 py-menu py-mode-map "Python Mode menu"
731 '("Python"
732 ["Comment Out Region" py-comment-region (mark)]
733 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
734 "-"
735 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000736 ["Mark current def" py-mark-def-or-class t]
737 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000738 "-"
739 ["Shift region left" py-shift-region-left (mark)]
740 ["Shift region right" py-shift-region-right (mark)]
741 "-"
Barry Warsaw820273d1998-05-19 15:54:45 +0000742 ["Import/reload file" py-execute-import-or-reload t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000743 ["Execute buffer" py-execute-buffer t]
744 ["Execute region" py-execute-region (mark)]
Barry Warsaw820273d1998-05-19 15:54:45 +0000745 ["Execute def or class" py-execute-def-or-class (mark)]
Barry Warsaw1d0364b1998-05-19 16:15:26 +0000746 ["Execute string" py-execute-string t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000747 ["Start interpreter..." py-shell t]
748 "-"
749 ["Go to start of block" py-goto-block-up t]
Barry Warsawab0e86c1998-05-19 15:31:46 +0000750 ["Go to start of class" (py-beginning-of-def-or-class t) t]
751 ["Move to end of class" (py-end-of-def-or-class t) t]
752 ["Move to start of def" py-beginning-of-def-or-class t]
753 ["Move to end of def" py-end-of-def-or-class t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000754 "-"
755 ["Describe mode" py-describe-mode t]
756 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000757
Barry Warsaw81437461996-08-01 19:48:02 +0000758
759
760;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
761(defvar imenu-example--python-class-regexp
762 (concat ; <<classes>>
763 "\\(" ;
764 "^[ \t]*" ; newline and maybe whitespace
765 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
766 ; possibly multiple superclasses
Barry Warsaw3179fe01998-04-04 21:36:53 +0000767 "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
Barry Warsaw81437461996-08-01 19:48:02 +0000768 "[ \t]*:" ; and the final :
769 "\\)" ; >>classes<<
770 )
771 "Regexp for Python classes for use with the imenu package."
772 )
773
774(defvar imenu-example--python-method-regexp
775 (concat ; <<methods and functions>>
776 "\\(" ;
777 "^[ \t]*" ; new line and maybe whitespace
778 "\\(def[ \t]+" ; function definitions start with def
779 "\\([a-zA-Z0-9_]+\\)" ; name is here
780 ; function arguments...
781 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
782 "\\)" ; end of def
783 "[ \t]*:" ; and then the :
784 "\\)" ; >>methods and functions<<
785 )
786 "Regexp for Python methods/functions for use with the imenu package."
787 )
788
789(defvar imenu-example--python-method-no-arg-parens '(2 8)
790 "Indicies into groups of the Python regexp for use with imenu.
791
792Using these values will result in smaller imenu lists, as arguments to
793functions are not listed.
794
795See the variable `imenu-example--python-show-method-args-p' for more
796information.")
797
798(defvar imenu-example--python-method-arg-parens '(2 7)
799 "Indicies into groups of the Python regexp for use with imenu.
800Using these values will result in large imenu lists, as arguments to
801functions are listed.
802
803See the variable `imenu-example--python-show-method-args-p' for more
804information.")
805
806;; Note that in this format, this variable can still be used with the
807;; imenu--generic-function. Otherwise, there is no real reason to have
808;; it.
809(defvar imenu-example--generic-python-expression
810 (cons
811 (concat
812 imenu-example--python-class-regexp
813 "\\|" ; or...
814 imenu-example--python-method-regexp
815 )
816 imenu-example--python-method-no-arg-parens)
817 "Generic Python expression which may be used directly with imenu.
818Used by setting the variable `imenu-generic-expression' to this value.
819Also, see the function \\[imenu-example--create-python-index] for a
820better alternative for finding the index.")
821
822;; These next two variables are used when searching for the python
823;; class/definitions. Just saving some time in accessing the
824;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000825(defvar imenu-example--python-generic-regexp nil)
826(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000827
828
Barry Warsaw81437461996-08-01 19:48:02 +0000829(defun imenu-example--create-python-index ()
830 "Python interface function for imenu package.
831Finds all python classes and functions/methods. Calls function
832\\[imenu-example--create-python-index-engine]. See that function for
833the details of how this works."
834 (setq imenu-example--python-generic-regexp
835 (car imenu-example--generic-python-expression))
836 (setq imenu-example--python-generic-parens
837 (if imenu-example--python-show-method-args-p
838 imenu-example--python-method-arg-parens
839 imenu-example--python-method-no-arg-parens))
840 (goto-char (point-min))
841 (imenu-example--create-python-index-engine nil))
842
843(defun imenu-example--create-python-index-engine (&optional start-indent)
844 "Function for finding imenu definitions in Python.
845
846Finds all definitions (classes, methods, or functions) in a Python
847file for the imenu package.
848
849Returns a possibly nested alist of the form
850
851 (INDEX-NAME . INDEX-POSITION)
852
853The second element of the alist may be an alist, producing a nested
854list as in
855
856 (INDEX-NAME . INDEX-ALIST)
857
858This function should not be called directly, as it calls itself
859recursively and requires some setup. Rather this is the engine for
860the function \\[imenu-example--create-python-index].
861
862It works recursively by looking for all definitions at the current
863indention level. When it finds one, it adds it to the alist. If it
864finds a definition at a greater indentation level, it removes the
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000865previous definition from the alist. In its place it adds all
Barry Warsaw81437461996-08-01 19:48:02 +0000866definitions found at the next indentation level. When it finds a
867definition that is less indented then the current level, it retuns the
868alist it has created thus far.
869
870The optional argument START-INDENT indicates the starting indentation
871at which to continue looking for Python classes, methods, or
872functions. If this is not supplied, the function uses the indentation
873of the first definition found."
874 (let ((index-alist '())
875 (sub-method-alist '())
876 looking-p
877 def-name prev-name
878 cur-indent def-pos
879 (class-paren (first imenu-example--python-generic-parens))
880 (def-paren (second imenu-example--python-generic-parens)))
881 (setq looking-p
882 (re-search-forward imenu-example--python-generic-regexp
883 (point-max) t))
884 (while looking-p
885 (save-excursion
886 ;; used to set def-name to this value but generic-extract-name is
887 ;; new to imenu-1.14. this way it still works with imenu-1.11
888 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
889 (let ((cur-paren (if (match-beginning class-paren)
890 class-paren def-paren)))
891 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000892 (buffer-substring-no-properties (match-beginning cur-paren)
893 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000894 (beginning-of-line)
895 (setq cur-indent (current-indentation)))
896
897 ;; HACK: want to go to the next correct definition location. we
898 ;; explicitly list them here. would be better to have them in a
899 ;; list.
900 (setq def-pos
901 (or (match-beginning class-paren)
902 (match-beginning def-paren)))
903
904 ;; if we don't have a starting indent level, take this one
905 (or start-indent
906 (setq start-indent cur-indent))
907
908 ;; if we don't have class name yet, take this one
909 (or prev-name
910 (setq prev-name def-name))
911
912 ;; what level is the next definition on? must be same, deeper
913 ;; or shallower indentation
914 (cond
915 ;; at the same indent level, add it to the list...
916 ((= start-indent cur-indent)
917
918 ;; if we don't have push, use the following...
919 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
920 (push (cons def-name def-pos) index-alist))
921
922 ;; deeper indented expression, recur...
923 ((< start-indent cur-indent)
924
925 ;; the point is currently on the expression we're supposed to
926 ;; start on, so go back to the last expression. The recursive
927 ;; call will find this place again and add it to the correct
928 ;; list
929 (re-search-backward imenu-example--python-generic-regexp
930 (point-min) 'move)
931 (setq sub-method-alist (imenu-example--create-python-index-engine
932 cur-indent))
933
934 (if sub-method-alist
935 ;; we put the last element on the index-alist on the start
936 ;; of the submethod alist so the user can still get to it.
937 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000938 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000939 (cons save-elmt sub-method-alist))
940 index-alist))))
941
942 ;; found less indented expression, we're done.
943 (t
944 (setq looking-p nil)
945 (re-search-backward imenu-example--python-generic-regexp
946 (point-min) t)))
947 (setq prev-name def-name)
948 (and looking-p
949 (setq looking-p
950 (re-search-forward imenu-example--python-generic-regexp
951 (point-max) 'move))))
952 (nreverse index-alist)))
953
Barry Warsaw42f707f1996-07-29 21:05:05 +0000954
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000955;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000956(defun python-mode ()
957 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000958To submit a problem report, enter `\\[py-submit-bug-report]' from a
959`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
960documentation. To see what version of `python-mode' you are running,
961enter `\\[py-version]'.
962
963This mode knows about Python indentation, tokens, comments and
964continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000965
966COMMANDS
967\\{py-mode-map}
968VARIABLES
969
Barry Warsaw42f707f1996-07-29 21:05:05 +0000970py-indent-offset\t\tindentation increment
Barry Warsaw41a05c71998-08-10 16:33:12 +0000971py-block-comment-prefix\t\tcomment string used by `comment-region'
Barry Warsaw42f707f1996-07-29 21:05:05 +0000972py-python-command\t\tshell command to invoke Python interpreter
973py-scroll-process-buffer\t\talways scroll Python process buffer
974py-temp-directory\t\tdirectory used for temp files (if needed)
Barry Warsaw41a05c71998-08-10 16:33:12 +0000975py-beep-if-tab-change\t\tring the bell if `tab-width' is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000976 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000977 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000978 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000979 (make-local-variable 'font-lock-defaults)
980 (make-local-variable 'paragraph-separate)
981 (make-local-variable 'paragraph-start)
982 (make-local-variable 'require-final-newline)
983 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000984 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000985 (make-local-variable 'comment-start-skip)
986 (make-local-variable 'comment-column)
Barry Warsaw003932a1998-07-07 15:11:24 +0000987 (make-local-variable 'comment-indent-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000988 (make-local-variable 'indent-region-function)
989 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000990 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000991 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000992 (set-syntax-table py-mode-syntax-table)
Barry Warsaw003932a1998-07-07 15:11:24 +0000993 (setq major-mode 'python-mode
994 mode-name "Python"
995 local-abbrev-table python-mode-abbrev-table
996 font-lock-defaults '(python-font-lock-keywords)
997 paragraph-separate "^[ \t]*$"
998 paragraph-start "^[ \t]*$"
999 require-final-newline t
1000 comment-start "# "
1001 comment-end ""
1002 comment-start-skip "# *"
1003 comment-column 40
1004 comment-indent-function 'py-comment-indent-function
1005 indent-region-function 'py-indent-region
1006 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +00001007 ;; tell add-log.el how to find the current function/method/variable
1008 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +00001009 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001010 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +00001011 ;; add the menu
1012 (if py-menu
1013 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +00001014 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +00001015 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +00001016 (setq comment-multi-line nil))
Barry Warsaw742a5111998-03-13 17:29:15 +00001017 ;; Install Imenu, only works for Emacs.
1018 (when (py-safe (require 'imenu))
1019 (make-variable-buffer-local 'imenu-create-index-function)
1020 (setq imenu-create-index-function
1021 (function imenu-example--create-python-index))
1022 (setq imenu-generic-expression
1023 imenu-example--generic-python-expression)
1024 (if (fboundp 'imenu-add-to-menubar)
1025 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
1026 )
1027 ;; Run the mode hook. Note that py-mode-hook is deprecated.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001028 (if python-mode-hook
1029 (run-hooks 'python-mode-hook)
Barry Warsaw742a5111998-03-13 17:29:15 +00001030 (run-hooks 'py-mode-hook))
1031 ;; Now do the automagical guessing
1032 (if py-smart-indentation
1033 (let ((offset py-indent-offset))
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001034 ;; It's okay if this fails to guess a good value
Barry Warsaw742a5111998-03-13 17:29:15 +00001035 (if (and (py-safe (py-guess-indent-offset))
1036 (<= py-indent-offset 8)
1037 (>= py-indent-offset 2))
1038 (setq offset py-indent-offset))
1039 (setq py-indent-offset offset)
Barry Warsaw639eea61998-03-16 18:12:13 +00001040 ;; Only turn indent-tabs-mode off if tab-width !=
1041 ;; py-indent-offset. Never turn it on, because the user must
1042 ;; have explicitly turned it off.
1043 (if (/= tab-width py-indent-offset)
1044 (setq indent-tabs-mode nil))
Barry Warsaw742a5111998-03-13 17:29:15 +00001045 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001046
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001047
Barry Warsawb91b7431995-03-14 15:55:20 +00001048;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001049(defun py-outdent-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00001050 "Returns non-nil if the current line should dedent one level."
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001051 (save-excursion
1052 (and (progn (back-to-indentation)
1053 (looking-at py-outdent-re))
Barry Warsawf06777d1998-01-21 05:36:18 +00001054 (progn (forward-line -1)
1055 (py-goto-initial-line)
1056 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001057 (while (or (looking-at py-blank-or-comment-re)
1058 (bobp))
1059 (backward-to-indentation 1))
1060 (not (looking-at py-no-outdent-re)))
1061 )))
1062
Barry Warsawb91b7431995-03-14 15:55:20 +00001063(defun py-electric-colon (arg)
1064 "Insert a colon.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001065In certain cases the line is dedented appropriately. If a numeric
1066argument ARG is provided, that many colons are inserted
1067non-electrically. Electric behavior is inhibited inside a string or
1068comment."
Barry Warsawb91b7431995-03-14 15:55:20 +00001069 (interactive "P")
1070 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001071 ;; are we in a string or comment?
1072 (if (save-excursion
1073 (let ((pps (parse-partial-sexp (save-excursion
Barry Warsawab0e86c1998-05-19 15:31:46 +00001074 (py-beginning-of-def-or-class)
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001075 (point))
1076 (point))))
1077 (not (or (nth 3 pps) (nth 4 pps)))))
1078 (save-excursion
1079 (let ((here (point))
1080 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001081 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001082 (if (and (not arg)
1083 (py-outdent-p)
1084 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +00001085 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001086 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001087 )
1088 (setq outdent py-indent-offset))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001089 ;; Don't indent, only dedent. This assumes that any lines
1090 ;; that are already dedented relative to
1091 ;; py-compute-indentation were put there on purpose. It's
1092 ;; highly annoying to have `:' indent for you. Use TAB, C-c
1093 ;; C-l or C-c C-r to adjust. TBD: Is there a better way to
1094 ;; determine this???
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001095 (if (< (current-indentation) indent) nil
1096 (goto-char here)
1097 (beginning-of-line)
1098 (delete-horizontal-space)
1099 (indent-to (- indent outdent))
1100 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001101
1102
Barry Warsawa97a3f31997-11-04 18:47:06 +00001103;; Python subprocess utilities and filters
1104(defun py-execute-file (proc filename)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001105 "Send to Python interpreter process PROC \"execfile('FILENAME')\".
1106Make that process's buffer visible and force display. Also make
1107comint believe the user typed this string so that
1108`kill-output-from-shell' does The Right Thing."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001109 (let ((curbuf (current-buffer))
1110 (procbuf (process-buffer proc))
1111 (comint-scroll-to-bottom-on-output t)
1112 (msg (format "## working on region in file %s...\n" filename))
1113 (cmd (format "execfile('%s')\n" filename)))
1114 (unwind-protect
1115 (progn
1116 (set-buffer procbuf)
1117 (goto-char (point-max))
1118 (move-marker (process-mark proc) (point))
1119 (funcall (process-filter proc) proc msg))
1120 (set-buffer curbuf))
1121 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001122
1123(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001124 (let ((curbuf (current-buffer))
1125 (pbuf (process-buffer pyproc))
1126 (pmark (process-mark pyproc))
1127 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001128 ;; make sure we switch to a different buffer at least once. if we
1129 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001130 ;; window, and point is before the end, and lots of output is
1131 ;; coming at a fast pace, then (a) simple cursor-movement commands
1132 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
1133 ;; to have a visible effect (the window just doesn't get updated,
1134 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
1135 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001136 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001137 ;; #b makes no sense to me at all. #a almost makes sense: unless
1138 ;; we actually change buffers, set_buffer_internal in buffer.c
1139 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1140 ;; seems to make the Emacs command loop reluctant to update the
1141 ;; display. Perhaps the default process filter in process.c's
1142 ;; read_process_output has update_mode_lines++ for a similar
1143 ;; reason? beats me ...
1144
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001145 (unwind-protect
1146 ;; make sure current buffer is restored
1147 ;; BAW - we want to check to see if this still applies
1148 (progn
1149 ;; mysterious ugly hack
1150 (if (eq curbuf pbuf)
1151 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001152
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001153 (set-buffer pbuf)
1154 (let* ((start (point))
1155 (goback (< start pmark))
1156 (goend (and (not goback) (= start (point-max))))
1157 (buffer-read-only nil))
1158 (goto-char pmark)
1159 (insert string)
1160 (move-marker pmark (point))
1161 (setq file-finished
1162 (and py-file-queue
1163 (equal ">>> "
1164 (buffer-substring
1165 (prog2 (beginning-of-line) (point)
1166 (goto-char pmark))
1167 (point)))))
1168 (if goback (goto-char start)
1169 ;; else
1170 (if py-scroll-process-buffer
1171 (let* ((pop-up-windows t)
1172 (pwin (display-buffer pbuf)))
1173 (set-window-point pwin (point)))))
1174 (set-buffer curbuf)
1175 (if file-finished
1176 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001177 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001178 (setq py-file-queue (cdr py-file-queue))
1179 (if py-file-queue
1180 (py-execute-file pyproc (car py-file-queue)))))
1181 (and goend
1182 (progn (set-buffer pbuf)
1183 (goto-char (point-max))))
1184 ))
1185 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001186
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001187(defun py-postprocess-output-buffer (buf)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001188 "Highlight exceptions found in BUF.
1189If an exception occurred return t, otherwise return nil. BUF must exist."
Barry Warsawf9b99f41998-03-26 16:08:59 +00001190 (let (line file bol err-p)
Barry Warsaw9981d221997-12-03 05:25:48 +00001191 (save-excursion
1192 (set-buffer buf)
1193 (beginning-of-buffer)
1194 (while (re-search-forward py-traceback-line-re nil t)
1195 (setq file (match-string 1)
1196 line (string-to-int (match-string 2))
1197 bol (py-point 'bol))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001198 (py-highlight-line bol (py-point 'eol) file line)))
1199 (when (and py-jump-on-exception line)
1200 (beep)
1201 (py-jump-to-exception file line)
1202 (setq err-p t))
1203 err-p))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001204
Barry Warsaw9981d221997-12-03 05:25:48 +00001205
Barry Warsawa97a3f31997-11-04 18:47:06 +00001206
1207;;; Subprocess commands
1208
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001209;; only used when (memq 'broken-temp-names py-emacs-features)
1210(defvar py-serial-number 0)
1211(defvar py-exception-buffer nil)
1212(defconst py-output-buffer "*Python Output*")
Barry Warsawa2398801998-04-09 23:28:20 +00001213(make-variable-buffer-local 'py-output-buffer)
1214
1215;; for toggling between CPython and JPython
1216(defvar py-which-shell py-python-command)
1217(defvar py-which-args py-python-command-args)
1218(defvar py-which-bufname "Python")
1219(make-variable-buffer-local 'py-which-shell)
1220(make-variable-buffer-local 'py-which-args)
1221(make-variable-buffer-local 'py-which-bufname)
1222
1223(defun py-toggle-shells (arg)
1224 "Toggles between the CPython and JPython shells.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001225With positive argument ARG (interactively \\[universal-argument]),
1226uses the CPython shell, with negative ARG uses the JPython shell, and
1227with a zero argument, toggles the shell."
Barry Warsawa2398801998-04-09 23:28:20 +00001228 (interactive "P")
1229 ;; default is to toggle
1230 (if (null arg)
1231 (setq arg 0))
1232 ;; toggle if zero
1233 (if (= arg 0)
1234 (if (string-equal py-which-bufname "Python")
1235 (setq arg -1)
1236 (setq arg 1)))
1237 (let (msg)
1238 (cond
1239 ((< 0 arg)
1240 ;; set to CPython
1241 (setq py-which-shell py-python-command
1242 py-which-args py-python-command-args
1243 py-which-bufname "Python"
1244 msg "CPython"
1245 mode-name "Python"))
1246 ((> 0 arg)
1247 (setq py-which-shell py-jpython-command
1248 py-which-args py-jpython-command-args
1249 py-which-bufname "JPython"
1250 msg "JPython"
1251 mode-name "JPython"))
1252 )
Barry Warsawea609c11998-04-10 16:08:26 +00001253 (message "Using the %s shell" msg)
Barry Warsawa2398801998-04-09 23:28:20 +00001254 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001255
Barry Warsawa97a3f31997-11-04 18:47:06 +00001256;;;###autoload
1257(defun py-shell ()
1258 "Start an interactive Python interpreter in another window.
1259This is like Shell mode, except that Python is running in the window
1260instead of a shell. See the `Interactive Shell' and `Shell Mode'
1261sections of the Emacs manual for details, especially for the key
1262bindings active in the `*Python*' buffer.
1263
1264See the docs for variable `py-scroll-buffer' for info on scrolling
1265behavior in the process window.
1266
Barry Warsawa2398801998-04-09 23:28:20 +00001267Note: You can toggle between using the CPython interpreter and the
1268JPython interpreter by hitting \\[py-toggle-shells]. This toggles
1269buffer local variables which control whether all your subshell
1270interactions happen to the `*JPython*' or `*Python*' buffers (the
1271latter is the name used for the CPython buffer).
1272
Barry Warsawa97a3f31997-11-04 18:47:06 +00001273Warning: Don't use an interactive Python if you change sys.ps1 or
1274sys.ps2 from their default values, or if you're running code that
1275prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1276distinguish your output from Python's output, and assumes that `>>> '
1277at the start of a line is a prompt from Python. Similarly, the Emacs
1278Shell mode code assumes that both `>>> ' and `... ' at the start of a
1279line are Python prompts. Bad things can happen if you fool either
1280mode.
1281
1282Warning: If you do any editing *in* the process buffer *while* the
1283buffer is accepting output from Python, do NOT attempt to `undo' the
1284changes. Some of the output (nowhere near the parts you changed!) may
1285be lost if you do. This appears to be an Emacs bug, an unfortunate
1286interaction between undo and process filters; the same problem exists in
1287non-Python process buffers using the default (Emacs-supplied) process
1288filter."
1289 ;; BAW - should undo be disabled in the python process buffer, if
1290 ;; this bug still exists?
1291 (interactive)
1292 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001293 (switch-to-buffer-other-window
Barry Warsawa2398801998-04-09 23:28:20 +00001294 (apply 'make-comint py-which-bufname py-which-shell nil py-which-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001295 (make-local-variable 'comint-prompt-regexp)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001296 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
Barry Warsawa97a3f31997-11-04 18:47:06 +00001297 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1298 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001299 ;; set up keybindings for this subshell
1300 (local-set-key [tab] 'self-insert-command)
1301 (local-set-key "\C-c-" 'py-up-exception)
1302 (local-set-key "\C-c=" 'py-down-exception)
1303 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001304
Barry Warsawa97a3f31997-11-04 18:47:06 +00001305(defun py-clear-queue ()
1306 "Clear the queue of temporary files waiting to execute."
1307 (interactive)
1308 (let ((n (length py-file-queue)))
1309 (mapcar 'delete-file py-file-queue)
1310 (setq py-file-queue nil)
1311 (message "%d pending files de-queued." n)))
1312
Barry Warsaw820273d1998-05-19 15:54:45 +00001313
Barry Warsawa97a3f31997-11-04 18:47:06 +00001314(defun py-execute-region (start end &optional async)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001315 "Execute the region in a Python interpreter.
1316
Barry Warsawa97a3f31997-11-04 18:47:06 +00001317The region is first copied into a temporary file (in the directory
1318`py-temp-directory'). If there is no Python interpreter shell
1319running, this file is executed synchronously using
Barry Warsaw41a05c71998-08-10 16:33:12 +00001320`shell-command-on-region'. If the program is long running, use
1321\\[universal-argument] to run the command asynchronously in its own
1322buffer.
1323
1324When this function is used programmatically, arguments START and END
1325specify the region to execute, and optional third argument ASYNC, if
1326non-nil, specifies to run the command asynchronously in its own
1327buffer.
Barry Warsawa97a3f31997-11-04 18:47:06 +00001328
1329If the Python interpreter shell is running, the region is execfile()'d
1330in that shell. If you try to execute regions too quickly,
1331`python-mode' will queue them up and execute them one at a time when
1332it sees a `>>> ' prompt from Python. Each time this happens, the
1333process buffer is popped into a window (if it's not already in some
1334window) so you can see it, and a comment of the form
1335
1336 \t## working on region in file <name>...
1337
1338is inserted at the end. See also the command `py-clear-queue'."
1339 (interactive "r\nP")
1340 (or (< start end)
1341 (error "Region is empty"))
1342 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001343 (temp (if (memq 'broken-temp-names py-emacs-features)
Barry Warsaw1b344241998-08-07 22:24:16 +00001344 (let
1345 ((sn py-serial-number)
1346 (pid (and (fboundp 'emacs-pid) (emacs-pid))))
1347 (setq py-serial-number (1+ py-serial-number))
1348 (if pid
1349 (format "python-%d-%d" sn pid)
1350 (format "python-%d" sn)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001351 (make-temp-name "python-")))
1352 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001353 (write-region start end file nil 'nomsg)
1354 (cond
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001355 ;; always run the code in its own asynchronous subprocess
Barry Warsawa97a3f31997-11-04 18:47:06 +00001356 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001357 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001358 (start-process "Python" buf py-python-command "-u" file)
1359 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001360 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001361 ))
1362 ;; if the Python interpreter shell is running, queue it up for
1363 ;; execution there.
1364 (proc
1365 ;; use the existing python shell
1366 (if (not py-file-queue)
1367 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001368 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001369 (push file py-file-queue)
1370 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001371 (t
1372 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001373 (shell-command-on-region start end py-python-command py-output-buffer)
Barry Warsaw512af041998-03-25 23:27:17 +00001374 ;; shell-command-on-region kills the output buffer if it never
1375 ;; existed and there's no output from the command
1376 (if (not (get-buffer py-output-buffer))
1377 (message "No output.")
1378 (setq py-exception-buffer (current-buffer))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001379 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1380 (pop-to-buffer py-output-buffer)
1381 (if err-p
1382 (pop-to-buffer py-exception-buffer)))
Barry Warsaw512af041998-03-25 23:27:17 +00001383 ))
1384 )))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001385
Barry Warsaw820273d1998-05-19 15:54:45 +00001386
1387;; Code execution commands
Barry Warsawa97a3f31997-11-04 18:47:06 +00001388(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001389 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001390If the file local variable `py-master-file' is non-nil, execute the
1391named file instead of the buffer's file.
1392
Barry Warsaw7ae77681994-12-12 20:38:05 +00001393If there is a *Python* process buffer it is used. If a clipping
1394restriction is in effect, only the accessible portion of the buffer is
1395sent. A trailing newline will be supplied if needed.
1396
Barry Warsaw41a05c71998-08-10 16:33:12 +00001397See the `\\[py-execute-region]' docs for an account of some
1398subtleties, including the use of the optional ASYNC argument."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001399 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001400 (if py-master-file
1401 (let* ((filename (expand-file-name py-master-file))
1402 (buffer (or (get-file-buffer filename)
1403 (find-file-noselect filename))))
1404 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001405 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001406
Barry Warsaw820273d1998-05-19 15:54:45 +00001407(defun py-execute-import-or-reload (&optional async)
1408 "Import the current buffer's file in a Python interpreter.
1409
1410If the file has already been imported, then do reload instead to get
Barry Warsaw7c29b231998-07-07 17:45:38 +00001411the latest version.
1412
1413If the file's name does not end in \".py\", then do execfile instead.
1414
1415If the current buffer is not visiting a file, do `py-execute-buffer'
1416instead.
1417
1418If the file local variable `py-master-file' is non-nil, import or
1419reload the named file instead of the buffer's file. The file may be
1420saved based on the value of `py-execute-import-or-reload-save-p'.
Barry Warsaw820273d1998-05-19 15:54:45 +00001421
Barry Warsaw41a05c71998-08-10 16:33:12 +00001422See the `\\[py-execute-region]' docs for an account of some
1423subtleties, including the use of the optional ASYNC argument.
Barry Warsaw820273d1998-05-19 15:54:45 +00001424
Barry Warsaw7c29b231998-07-07 17:45:38 +00001425This may be preferable to `\\[py-execute-buffer]' because:
Barry Warsaw820273d1998-05-19 15:54:45 +00001426
1427 - Definitions stay in their module rather than appearing at top
1428 level, where they would clutter the global namespace and not affect
1429 uses of qualified names (MODULE.NAME).
1430
1431 - The Python debugger gets line number information about the functions."
1432 (interactive "P")
1433 ;; Check file local variable py-master-file
1434 (if py-master-file
1435 (let* ((filename (expand-file-name py-master-file))
1436 (buffer (or (get-file-buffer filename)
1437 (find-file-noselect filename))))
1438 (set-buffer buffer)))
1439 (let ((file (buffer-file-name (current-buffer))))
1440 (if file
1441 (progn
Barry Warsaw3bfed5b1998-05-19 16:25:04 +00001442 ;; Maybe save some buffers
1443 (save-some-buffers (not py-ask-about-save) nil)
Barry Warsaw820273d1998-05-19 15:54:45 +00001444 (py-execute-string
1445 (if (string-match "\\.py$" file)
1446 (let ((f (file-name-sans-extension
1447 (file-name-nondirectory file))))
1448 (format "if globals().has_key('%s'):\n reload(%s)\nelse:\n import %s\n"
1449 f f f))
1450 (format "execfile('%s')\n" file))
1451 async))
1452 ;; else
1453 (py-execute-buffer async))))
1454
1455
1456(defun py-execute-def-or-class (&optional async)
1457 "Send the current function or class definition to a Python interpreter.
1458
1459If there is a *Python* process buffer it is used.
1460
Barry Warsaw41a05c71998-08-10 16:33:12 +00001461See the `\\[py-execute-region]' docs for an account of some
1462subtleties, including the use of the optional ASYNC argument."
Barry Warsaw820273d1998-05-19 15:54:45 +00001463 (interactive "P")
1464 (save-excursion
1465 (py-mark-def-or-class)
1466 ;; mark is before point
1467 (py-execute-region (mark) (point) async)))
1468
1469
1470(defun py-execute-string (string &optional async)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001471 "Send the argument STRING to a Python interpreter.
Barry Warsaw820273d1998-05-19 15:54:45 +00001472
1473If there is a *Python* process buffer it is used.
1474
Barry Warsaw41a05c71998-08-10 16:33:12 +00001475See the `\\[py-execute-region]' docs for an account of some
1476subtleties, including the use of the optional ASYNC argument."
Barry Warsaw820273d1998-05-19 15:54:45 +00001477 (interactive "sExecute Python command: ")
1478 (save-excursion
1479 (set-buffer (get-buffer-create
1480 (generate-new-buffer-name " *Python Command*")))
1481 (insert string)
1482 (py-execute-region (point-min) (point-max) async)))
1483
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001484
1485
1486(defun py-jump-to-exception (file line)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001487 "Jump to the Python code in FILE at LINE."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001488 (let ((buffer (cond ((string-equal file "<stdin>")
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001489 (if (consp py-exception-buffer)
1490 (cdr py-exception-buffer)
1491 py-exception-buffer))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001492 ((and (consp py-exception-buffer)
1493 (string-equal file (car py-exception-buffer)))
1494 (cdr py-exception-buffer))
1495 ((py-safe (find-file-noselect file)))
1496 ;; could not figure out what file the exception
1497 ;; is pointing to, so prompt for it
1498 (t (find-file (read-file-name "Exception file: "
1499 nil
1500 file t))))))
1501 (pop-to-buffer buffer)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001502 ;; Force Python mode
Barry Warsaw820273d1998-05-19 15:54:45 +00001503 (if (not (eq major-mode 'python-mode))
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001504 (python-mode))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001505 (goto-line line)
1506 (message "Jumping to exception in file %s on line %d" file line)))
1507
1508(defun py-mouseto-exception (event)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001509 "Jump to the code which cased the Python exception at EVENT.
1510EVENT is usually a mouse click."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001511 (interactive "e")
1512 (cond
1513 ((fboundp 'event-point)
1514 ;; XEmacs
1515 (let* ((point (event-point event))
1516 (buffer (event-buffer event))
1517 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1518 (info (and e (extent-property e 'py-exc-info))))
1519 (message "Event point: %d, info: %s" point info)
1520 (and info
1521 (py-jump-to-exception (car info) (cdr info)))
1522 ))
1523 ;; Emacs -- Please port this!
1524 ))
1525
1526(defun py-goto-exception ()
1527 "Go to the line indicated by the traceback."
1528 (interactive)
1529 (let (file line)
1530 (save-excursion
1531 (beginning-of-line)
1532 (if (looking-at py-traceback-line-re)
1533 (setq file (match-string 1)
1534 line (string-to-int (match-string 2)))))
1535 (if (not file)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001536 (error "Not on a traceback line"))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001537 (py-jump-to-exception file line)))
1538
1539(defun py-find-next-exception (start buffer searchdir errwhere)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001540 "Find the next Python exception and jump to the code that caused it.
1541START is the buffer position in BUFFER from which to begin searching
1542for an exception. SEARCHDIR is a function, either
1543`re-search-backward' or `re-search-forward' indicating the direction
1544to search. ERRWHERE is used in an error message if the limit (top or
1545bottom) of the trackback stack is encountered."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001546 (let (file line)
1547 (save-excursion
1548 (set-buffer buffer)
1549 (goto-char (py-point start))
1550 (if (funcall searchdir py-traceback-line-re nil t)
1551 (setq file (match-string 1)
1552 line (string-to-int (match-string 2)))))
1553 (if (and file line)
1554 (py-jump-to-exception file line)
1555 (error "%s of traceback" errwhere))))
1556
1557(defun py-down-exception (&optional bottom)
1558 "Go to the next line down in the traceback.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001559With \\[univeral-argument] (programmatically, optional argument
1560BOTTOM), jump to the bottom (innermost) exception in the exception
1561stack."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001562 (interactive "P")
1563 (let* ((proc (get-process "Python"))
1564 (buffer (if proc "*Python*" py-output-buffer)))
1565 (if bottom
1566 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1567 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1568
1569(defun py-up-exception (&optional top)
1570 "Go to the previous line up in the traceback.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001571With \\[universal-argument] (programmatically, optional argument TOP)
1572jump to the top (outermost) exception in the exception stack."
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001573 (interactive "P")
1574 (let* ((proc (get-process "Python"))
1575 (buffer (if proc "*Python*" py-output-buffer)))
1576 (if top
1577 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001578 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001579
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001580
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001581;; Electric deletion
1582(defun py-electric-backspace (arg)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001583 "Delete preceding character or levels of indentation.
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001584Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001585with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001586
Barry Warsaw41a05c71998-08-10 16:33:12 +00001587If point is at the leftmost column, delete the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001588
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001589Otherwise, if point is at the leftmost non-whitespace character of a
1590line that is neither a continuation line nor a non-indenting comment
1591line, or if point is at the end of a blank line, this command reduces
1592the indentation to match that of the line that opened the current
1593block of code. The line that opened the block is displayed in the
Barry Warsaw41a05c71998-08-10 16:33:12 +00001594echo area to help you keep track of where you are. With
1595\\[universal-argument] dedents that many blocks (but not past column
1596zero).
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001597
1598Otherwise the preceding character is deleted, converting a tab to
1599spaces if needed so that only a single column position is deleted.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001600\\[universal-argument] specifies how many characters to delete
1601(default is 1).
1602
1603When used programmatically, argument ARG specifies the number of
1604blocks to dedent, or the number of characters to delete, as indicated
1605above."
Barry Warsaw03970731996-07-03 23:12:52 +00001606 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001607 (if (or (/= (current-indentation) (current-column))
1608 (bolp)
1609 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001610 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001611 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001612 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001613 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001614 ;; force non-blank so py-goto-block-up doesn't ignore it
1615 (insert-char ?* 1)
1616 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001617 (let ((base-indent 0) ; indentation of base line
1618 (base-text "") ; and text of base line
1619 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001620 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001621 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001622 (condition-case nil ; in case no enclosing block
1623 (progn
1624 (py-goto-block-up 'no-mark)
1625 (setq base-indent (current-indentation)
1626 base-text (py-suck-up-leading-text)
1627 base-found-p t))
1628 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001629 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001630 (delete-char 1) ; toss the dummy character
1631 (delete-horizontal-space)
1632 (indent-to base-indent)
1633 (if base-found-p
1634 (message "Closes block: %s" base-text)))))
1635
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001636
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001637(defun py-electric-delete (arg)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001638 "Delete preceding or following character or levels of whitespace.
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001639
1640The behavior of this function depends on the variable
1641`delete-key-deletes-forward'. If this variable is nil (or does not
Barry Warsaw41a05c71998-08-10 16:33:12 +00001642exist, as in older Emacsen and non-XEmacs versions), then this
1643function behaves identically to \\[c-electric-backspace].
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001644
1645If `delete-key-deletes-forward' is non-nil and is supported in your
1646Emacs, then deletion occurs in the forward direction, by calling the
Barry Warsaw41a05c71998-08-10 16:33:12 +00001647function in `py-delete-function'.
1648
1649\\[universal-argument] (programmatically, argument ARG) specifies the
1650number of characters to delete (default is 1)."
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001651 (interactive "*p")
1652 (if (and (boundp 'delete-key-deletes-forward)
1653 delete-key-deletes-forward)
1654 (funcall py-delete-function arg)
1655 ;; else
1656 (py-electric-backspace arg)))
1657
1658;; required for pending-del and delsel modes
1659(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1660(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1661(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1662(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1663
1664
1665
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001666(defun py-indent-line (&optional arg)
1667 "Fix the indentation of the current line according to Python rules.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001668With \\[universal-argument] (programmatically, the optional argument
1669ARG non-nil), ignore dedenting rules for block closing statements
1670(e.g. return, raise, break, continue, pass)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001671
1672This function is normally bound to `indent-line-function' so
1673\\[indent-for-tab-command] will call it."
1674 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001675 (let* ((ci (current-indentation))
1676 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001677 (need (py-compute-indentation (not arg))))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001678 ;; see if we need to dedent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001679 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001680 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001681 (if (/= ci need)
1682 (save-excursion
1683 (beginning-of-line)
1684 (delete-horizontal-space)
1685 (indent-to need)))
1686 (if move-to-indentation-p (back-to-indentation))))
1687
1688(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001689 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001690This is just `strives to' because correct indentation can't be computed
1691from scratch for Python code. In general, deletes the whitespace before
1692point, inserts a newline, and takes an educated guess as to how you want
1693the new line indented."
1694 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001695 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001696 (if (< ci (current-column)) ; if point beyond indentation
1697 (newline-and-indent)
1698 ;; else try to act like newline-and-indent "normally" acts
1699 (beginning-of-line)
1700 (insert-char ?\n 1)
1701 (move-to-column ci))))
1702
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001703(defun py-compute-indentation (honor-block-close-p)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001704 "Compute Python indentation.
1705When HONOR-BLOCK-CLOSE-P is non-nil, statements such as `return',
1706`raise', `break', `continue', and `pass' force one level of
1707dedenting."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001708 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001709 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001710 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001711 (pps (parse-partial-sexp bod (point)))
1712 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001713 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001714 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001715 ((or (and (nth 3 pps) (nth 3 boipps))
1716 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001717 (save-excursion
1718 (if (not py-align-multiline-strings-p) 0
1719 ;; skip back over blank & non-indenting comment lines
1720 ;; note: will skip a blank or non-indenting comment line
1721 ;; that happens to be a continuation line too
1722 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1723 (back-to-indentation)
1724 (current-column))))
1725 ;; are we on a continuation line?
1726 ((py-continuation-line-p)
1727 (let ((startpos (point))
1728 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001729 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001730 (if open-bracket-pos
1731 (progn
1732 ;; align with first item in list; else a normal
1733 ;; indent beyond the line with the open bracket
1734 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1735 ;; is the first list item on the same line?
1736 (skip-chars-forward " \t")
1737 (if (null (memq (following-char) '(?\n ?# ?\\)))
1738 ; yes, so line up with it
1739 (current-column)
1740 ;; first list item on another line, or doesn't exist yet
1741 (forward-line 1)
1742 (while (and (< (point) startpos)
1743 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1744 (forward-line 1))
Barry Warsaw92166d91998-04-01 21:59:41 +00001745 (if (and (< (point) startpos)
1746 (/= startpos
1747 (save-excursion
1748 (goto-char (1+ open-bracket-pos))
Barry Warsaw77d1fce1998-04-16 20:04:59 +00001749 (forward-comment (point-max))
Barry Warsaw92166d91998-04-01 21:59:41 +00001750 (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001751 ;; again mimic the first list item
1752 (current-indentation)
1753 ;; else they're about to enter the first item
1754 (goto-char open-bracket-pos)
1755 (+ (current-indentation) py-indent-offset))))
1756
1757 ;; else on backslash continuation line
1758 (forward-line -1)
1759 (if (py-continuation-line-p) ; on at least 3rd line in block
1760 (current-indentation) ; so just continue the pattern
1761 ;; else started on 2nd line in block, so indent more.
1762 ;; if base line is an assignment with a start on a RHS,
1763 ;; indent to 2 beyond the leftmost "="; else skip first
1764 ;; chunk of non-whitespace characters on base line, + 1 more
1765 ;; column
1766 (end-of-line)
1767 (setq endpos (point) searching t)
1768 (back-to-indentation)
1769 (setq startpos (point))
1770 ;; look at all "=" from left to right, stopping at first
1771 ;; one not nested in a list or string
1772 (while searching
1773 (skip-chars-forward "^=" endpos)
1774 (if (= (point) endpos)
1775 (setq searching nil)
1776 (forward-char 1)
1777 (setq state (parse-partial-sexp startpos (point)))
1778 (if (and (zerop (car state)) ; not in a bracket
1779 (null (nth 3 state))) ; & not in a string
1780 (progn
1781 (setq searching nil) ; done searching in any case
1782 (setq found
1783 (not (or
1784 (eq (following-char) ?=)
1785 (memq (char-after (- (point) 2))
1786 '(?< ?> ?!)))))))))
1787 (if (or (not found) ; not an assignment
1788 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1789 (progn
1790 (goto-char startpos)
1791 (skip-chars-forward "^ \t\n")))
1792 (1+ (current-column))))))
1793
1794 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001795 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001796
Barry Warsawa7891711996-08-01 15:53:09 +00001797 ;; Dfn: "Indenting comment line". A line containing only a
1798 ;; comment, but which is treated like a statement for
1799 ;; indentation calculation purposes. Such lines are only
1800 ;; treated specially by the mode; they are not treated
1801 ;; specially by the Python interpreter.
1802
1803 ;; The rules for indenting comment lines are a line where:
1804 ;; - the first non-whitespace character is `#', and
1805 ;; - the character following the `#' is whitespace, and
Barry Warsaw41a05c71998-08-10 16:33:12 +00001806 ;; - the line is dedented with respect to (i.e. to the left
Barry Warsawa7891711996-08-01 15:53:09 +00001807 ;; of) the indentation of the preceding non-blank line.
1808
1809 ;; The first non-blank line following an indenting comment
1810 ;; line is given the same amount of indentation as the
1811 ;; indenting comment line.
1812
1813 ;; All other comment-only lines are ignored for indentation
1814 ;; purposes.
1815
1816 ;; Are we looking at a comment-only line which is *not* an
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001817 ;; indenting comment line? If so, we assume that it's been
Barry Warsawa7891711996-08-01 15:53:09 +00001818 ;; placed at the desired indentation, so leave it alone.
1819 ;; Indenting comment lines are aligned as statements down
1820 ;; below.
1821 ((and (looking-at "[ \t]*#[^ \t\n]")
1822 ;; NOTE: this test will not be performed in older Emacsen
1823 (fboundp 'forward-comment)
1824 (<= (current-indentation)
1825 (save-excursion
1826 (forward-comment (- (point-max)))
1827 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001828 (current-indentation))
1829
1830 ;; else indentation based on that of the statement that
1831 ;; precedes us; use the first line of that statement to
1832 ;; establish the base, in case the user forced a non-std
1833 ;; indentation for the continuation lines (if any)
1834 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001835 ;; skip back over blank & non-indenting comment lines note:
1836 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001837 ;; happens to be a continuation line too. use fast Emacs 19
1838 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001839 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001840 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001841 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001842 (let (done)
1843 (while (not done)
1844 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1845 nil 'move)
1846 (setq done (or (eq py-honor-comment-indentation t)
1847 (bobp)
1848 (/= (following-char) ?#)
1849 (not (zerop (current-column)))))
1850 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001851 ;; if we landed inside a string, go to the beginning of that
1852 ;; string. this handles triple quoted, multi-line spanning
1853 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001854 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001855 (skip (and delim (make-string 1 delim))))
1856 (when skip
1857 (save-excursion
1858 (py-safe (search-backward skip))
1859 (if (and (eq (char-before) delim)
1860 (eq (char-before (1- (point))) delim))
1861 (setq skip (make-string 3 delim))))
1862 ;; we're looking at a triple-quoted string
1863 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001864 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001865 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001866 (+ (current-indentation)
1867 (if (py-statement-opens-block-p)
1868 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001869 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001870 (- py-indent-offset)
1871 0)))
1872 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001873
1874(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001875 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001876
1877By default, make a buffer-local copy of `py-indent-offset' with the
1878new value, so that other Python buffers are not affected. With
1879\\[universal-argument] (programmatically, optional argument GLOBAL),
1880change the global value of `py-indent-offset'. This affects all
1881Python buffers (that don't have their own buffer-local copy), both
1882those currently existing and those created later in the Emacs session.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001883
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001884Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001885There's no excuse for such foolishness, but sometimes you have to deal
1886with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001887`py-indent-offset' to what it thinks it was when they created the
1888mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001889
1890Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001891looking for a line that opens a block of code. `py-indent-offset' is
1892set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001893statement following it. If the search doesn't succeed going forward,
1894it's tried again going backward."
1895 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001896 (let (new-value
1897 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001898 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001899 (found nil)
1900 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001901 (py-goto-initial-line)
1902 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001903 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1904 (not (py-in-literal restart)))
1905 (setq restart (point))
1906 (py-goto-initial-line)
1907 (if (py-statement-opens-block-p)
1908 (setq found t)
1909 (goto-char restart))))
1910 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001911 (goto-char start)
1912 (py-goto-initial-line)
1913 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001914 (setq found (and
1915 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1916 (or (py-goto-initial-line) t) ; always true -- side effect
1917 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001918 (setq colon-indent (current-indentation)
1919 found (and found (zerop (py-next-statement 1)))
1920 new-value (- (current-indentation) colon-indent))
1921 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001922 (if (not found)
1923 (error "Sorry, couldn't guess a value for py-indent-offset")
1924 (funcall (if global 'kill-local-variable 'make-local-variable)
1925 'py-indent-offset)
1926 (setq py-indent-offset new-value)
1927 (message "%s value of py-indent-offset set to %d"
1928 (if global "Global" "Local")
1929 py-indent-offset))
1930 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001931
Barry Warsaw003932a1998-07-07 15:11:24 +00001932(defun py-comment-indent-function ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00001933 "Python version of `comment-indent-function'."
1934 ;; This is required when filladapt is turned off. Without it, when
1935 ;; filladapt is not used, comments which start in column zero
1936 ;; cascade one character to the right
Barry Warsaw003932a1998-07-07 15:11:24 +00001937 (save-excursion
1938 (beginning-of-line)
1939 (let ((eol (py-point 'eol)))
1940 (and comment-start-skip
1941 (re-search-forward comment-start-skip eol t)
1942 (setq eol (match-beginning 0)))
1943 (goto-char eol)
1944 (skip-chars-backward " \t")
1945 (max comment-column (+ (current-column) (if (bolp) 0 1)))
1946 )))
1947
1948
Barry Warsaw7ae77681994-12-12 20:38:05 +00001949(defun py-shift-region (start end count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001950 "Indent lines from START to END by COUNT spaces."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001951 (save-excursion
Barry Warsaw41a05c71998-08-10 16:33:12 +00001952 (goto-char end)
1953 (beginning-of-line)
1954 (setq end (point))
1955 (goto-char start)
1956 (beginning-of-line)
1957 (setq start (point))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001958 (indent-rigidly start end count)))
1959
1960(defun py-shift-region-left (start end &optional count)
1961 "Shift region of Python code to the left.
1962The lines from the line containing the start of the current region up
1963to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001964shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001965
1966If a prefix argument is given, the region is instead shifted by that
Barry Warsaw41a05c71998-08-10 16:33:12 +00001967many columns. With no active region, dedent only the current line.
1968You cannot dedent the region if any line is already at column zero."
Barry Warsawdea4a291996-07-03 22:59:12 +00001969 (interactive
1970 (let ((p (point))
1971 (m (mark))
1972 (arg current-prefix-arg))
1973 (if m
1974 (list (min p m) (max p m) arg)
1975 (list p (save-excursion (forward-line 1) (point)) arg))))
1976 ;; if any line is at column zero, don't shift the region
1977 (save-excursion
1978 (goto-char start)
1979 (while (< (point) end)
1980 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001981 (if (and (zerop (current-column))
1982 (not (looking-at "\\s *$")))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001983 (error "Region is at left edge"))
Barry Warsawdea4a291996-07-03 22:59:12 +00001984 (forward-line 1)))
1985 (py-shift-region start end (- (prefix-numeric-value
1986 (or count py-indent-offset))))
1987 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001988
1989(defun py-shift-region-right (start end &optional count)
1990 "Shift region of Python code to the right.
1991The lines from the line containing the start of the current region up
1992to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001993shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001994
1995If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001996many columns. With no active region, indent only the current line."
1997 (interactive
1998 (let ((p (point))
1999 (m (mark))
2000 (arg current-prefix-arg))
2001 (if m
2002 (list (min p m) (max p m) arg)
2003 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002004 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00002005 (or count py-indent-offset)))
2006 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002007
2008(defun py-indent-region (start end &optional indent-offset)
2009 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00002010
Barry Warsaw7ae77681994-12-12 20:38:05 +00002011The lines from the line containing the start of the current region up
2012to (but not including) the line containing the end of the region are
2013reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002014character in the first column, the first line is left alone and the
2015rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00002016region is reindented with respect to the (closest code or indenting
2017comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002018
2019This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002020control structures are introduced or removed, or to reformat code
2021using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002022
2023If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002024the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00002025used.
2026
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002027Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00002028is called! This function does not compute proper indentation from
2029scratch (that's impossible in Python), it merely adjusts the existing
2030indentation to be correct in context.
2031
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002032Warning: This function really has no idea what to do with
2033non-indenting comment lines, and shifts them as if they were indenting
2034comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002035
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002036Special cases: whitespace is deleted from blank lines; continuation
2037lines are shifted by the same amount their initial line was shifted,
2038in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00002039initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002040 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002041 (save-excursion
2042 (goto-char end) (beginning-of-line) (setq end (point-marker))
2043 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002044 (let ((py-indent-offset (prefix-numeric-value
2045 (or indent-offset py-indent-offset)))
2046 (indents '(-1)) ; stack of active indent levels
2047 (target-column 0) ; column to which to indent
2048 (base-shifted-by 0) ; amount last base line was shifted
2049 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002050 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002051 0))
2052 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002053 (while (< (point) end)
2054 (setq ci (current-indentation))
2055 ;; figure out appropriate target column
2056 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002057 ((or (eq (following-char) ?#) ; comment in column 1
2058 (looking-at "[ \t]*$")) ; entirely blank
2059 (setq target-column 0))
2060 ((py-continuation-line-p) ; shift relative to base line
2061 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002062 (t ; new base line
2063 (if (> ci (car indents)) ; going deeper; push it
2064 (setq indents (cons ci indents))
2065 ;; else we should have seen this indent before
2066 (setq indents (memq ci indents)) ; pop deeper indents
2067 (if (null indents)
2068 (error "Bad indentation in region, at line %d"
2069 (save-restriction
2070 (widen)
2071 (1+ (count-lines 1 (point)))))))
2072 (setq target-column (+ indent-base
2073 (* py-indent-offset
2074 (- (length indents) 2))))
2075 (setq base-shifted-by (- target-column ci))))
2076 ;; shift as needed
2077 (if (/= ci target-column)
2078 (progn
2079 (delete-horizontal-space)
2080 (indent-to target-column)))
2081 (forward-line 1))))
2082 (set-marker end nil))
2083
Barry Warsawa7891711996-08-01 15:53:09 +00002084(defun py-comment-region (beg end &optional arg)
2085 "Like `comment-region' but uses double hash (`#') comment starter."
2086 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00002087 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00002088 (comment-region beg end arg)))
2089
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002090
2091;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00002092(defun py-previous-statement (count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002093 "Go to the start of the COUNTth preceding Python statement.
2094By default, goes to the previous statement. If there is no such
2095statement, goes to the first statement. Return count of statements
2096left to move. `Statements' do not include blank, comment, or
2097continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002098 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002099 (if (< count 0) (py-next-statement (- count))
2100 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002101 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002102 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002103 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002104 (> count 0)
2105 (zerop (forward-line -1))
2106 (py-goto-statement-at-or-above))
2107 (setq count (1- count)))
2108 (if (> count 0) (goto-char start)))
2109 count))
2110
2111(defun py-next-statement (count)
2112 "Go to the start of next Python statement.
2113If the statement at point is the i'th Python statement, goes to the
2114start of statement i+COUNT. If there is no such statement, goes to the
2115last statement. Returns count of statements left to move. `Statements'
2116do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002117 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002118 (if (< count 0) (py-previous-statement (- count))
2119 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002120 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002121 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002122 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002123 (> count 0)
2124 (py-goto-statement-below))
2125 (setq count (1- count)))
2126 (if (> count 0) (goto-char start)))
2127 count))
2128
2129(defun py-goto-block-up (&optional nomark)
2130 "Move up to start of current block.
2131Go to the statement that starts the smallest enclosing block; roughly
2132speaking, this will be the closest preceding statement that ends with a
2133colon and is indented less than the statement you started on. If
2134successful, also sets the mark to the starting point.
2135
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002136`\\[py-mark-block]' can be used afterward to mark the whole code
2137block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002138
2139If called from a program, the mark will not be set if optional argument
2140NOMARK is not nil."
2141 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002142 (let ((start (point))
2143 (found nil)
2144 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002145 (py-goto-initial-line)
2146 ;; if on blank or non-indenting comment line, use the preceding stmt
2147 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2148 (progn
2149 (py-goto-statement-at-or-above)
2150 (setq found (py-statement-opens-block-p))))
2151 ;; search back for colon line indented less
2152 (setq initial-indent (current-indentation))
2153 (if (zerop initial-indent)
2154 ;; force fast exit
2155 (goto-char (point-min)))
2156 (while (not (or found (bobp)))
2157 (setq found
2158 (and
2159 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2160 (or (py-goto-initial-line) t) ; always true -- side effect
2161 (< (current-indentation) initial-indent)
2162 (py-statement-opens-block-p))))
2163 (if found
2164 (progn
2165 (or nomark (push-mark start))
2166 (back-to-indentation))
2167 (goto-char start)
2168 (error "Enclosing block not found"))))
2169
Barry Warsawab0e86c1998-05-19 15:31:46 +00002170(defun py-beginning-of-def-or-class (&optional class count)
2171 "Move point to start of `def' or `class'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002172
2173Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsawab0e86c1998-05-19 15:31:46 +00002174arg, looks for a `class' instead. The docs below assume the `def'
2175case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002176Programmatically, if CLASS is `either', then moves to either `class'
2177or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002178
Barry Warsawab0e86c1998-05-19 15:31:46 +00002179When second optional argument is given programmatically, move to the
2180COUNTth start of `def'.
2181
2182If point is in a `def' statement already, and after the `d', simply
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002183moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002184
Barry Warsawab0e86c1998-05-19 15:31:46 +00002185Otherwise (i.e. when point is not in a `def' statement, or at or
2186before the `d' of a `def' statement), searches for the closest
2187preceding `def' statement, and leaves point at its start. If no such
2188statement can be found, leaves point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002189
Barry Warsawab0e86c1998-05-19 15:31:46 +00002190Returns t iff a `def' statement is found by these rules.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002191
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002192Note that doing this command repeatedly will take you closer to the
2193start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002194
Barry Warsaw7c29b231998-07-07 17:45:38 +00002195To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002196 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002197 (if (not count)
2198 (setq count 1))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002199 (let ((at-or-before-p (<= (current-column) (current-indentation)))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002200 (start-of-line (goto-char (py-point 'bol)))
2201 (start-of-stmt (goto-char (py-point 'bos)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002202 (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
2203 (class "^[ \t]*class\\>")
2204 (t "^[ \t]*def\\>")))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002205 )
2206 ;; searching backward
2207 (if (and (< 0 count)
2208 (or (/= start-of-stmt start-of-line)
2209 (not at-or-before-p)))
2210 (end-of-line))
2211 ;; search forward
2212 (if (and (> 0 count)
2213 (zerop (current-column))
2214 (looking-at start-re))
2215 (end-of-line))
2216 (re-search-backward start-re nil 'move count)
2217 (goto-char (match-beginning 0))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002218
Barry Warsawab0e86c1998-05-19 15:31:46 +00002219;; Backwards compatibility
2220(defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002221
Barry Warsawab0e86c1998-05-19 15:31:46 +00002222(defun py-end-of-def-or-class (&optional class count)
2223 "Move point beyond end of `def' or `class' body.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002224
Barry Warsawab0e86c1998-05-19 15:31:46 +00002225By default, looks for an appropriate `def'. If you supply a prefix
2226arg, looks for a `class' instead. The docs below assume the `def'
2227case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002228Programmatically, if CLASS is `either', then moves to either `class'
2229or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002230
Barry Warsawab0e86c1998-05-19 15:31:46 +00002231When second optional argument is given programmatically, move to the
2232COUNTth end of `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002233
Barry Warsawab0e86c1998-05-19 15:31:46 +00002234If point is in a `def' statement already, this is the `def' we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002235
Barry Warsawab0e86c1998-05-19 15:31:46 +00002236Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2237contains the statement you started on, that's the `def' we use.
2238
2239Otherwise, we search forward for the closest following `def', and use that.
2240
2241If a `def' can be found by these rules, point is moved to the start of
2242the line immediately following the `def' block, and the position of the
2243start of the `def' is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002244
2245Else point is moved to the end of the buffer, and nil is returned.
2246
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002247Note that doing this command repeatedly will take you closer to the
2248end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002249
Barry Warsaw7c29b231998-07-07 17:45:38 +00002250To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002251 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002252 (if (and count (/= count 1))
2253 (py-beginning-of-def-or-class (- 1 count)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002254 (let ((start (progn (py-goto-initial-line) (point)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002255 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2256 (class "class")
2257 (t "def")))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002258 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002259 ;; move point to start of appropriate def/class
2260 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2261 (setq state 'at-beginning)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002262 ;; else see if py-beginning-of-def-or-class hits container
2263 (if (and (py-beginning-of-def-or-class class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002264 (progn (py-goto-beyond-block)
2265 (> (point) start)))
2266 (setq state 'at-end)
2267 ;; else search forward
2268 (goto-char start)
2269 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2270 (progn (setq state 'at-beginning)
2271 (beginning-of-line)))))
2272 (cond
2273 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2274 ((eq state 'at-end) t)
2275 ((eq state 'not-found) nil)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002276 (t (error "Internal error in `py-end-of-def-or-class'")))))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002277
2278;; Backwards compabitility
Barry Warsaw820273d1998-05-19 15:54:45 +00002279(defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002280
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002281
2282;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002283(defun py-mark-block (&optional extend just-move)
2284 "Mark following block of lines. With prefix arg, mark structure.
2285Easier to use than explain. It sets the region to an `interesting'
2286block of succeeding lines. If point is on a blank line, it goes down to
2287the next non-blank line. That will be the start of the region. The end
2288of the region depends on the kind of line at the start:
2289
2290 - If a comment, the region will include all succeeding comment lines up
2291 to (but not including) the next non-comment line (if any).
2292
2293 - Else if a prefix arg is given, and the line begins one of these
2294 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002295
2296 if elif else try except finally for while def class
2297
Barry Warsaw7ae77681994-12-12 20:38:05 +00002298 the region will be set to the body of the structure, including
2299 following blocks that `belong' to it, but excluding trailing blank
2300 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002301 and all (if any) of the following `except' and `finally' blocks
2302 that belong to the `try' structure will be in the region. Ditto
2303 for if/elif/else, for/else and while/else structures, and (a bit
2304 degenerate, since they're always one-block structures) def and
2305 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002306
2307 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002308 block (see list above), and the block is not a `one-liner' (i.e.,
2309 the statement ends with a colon, not with code), the region will
2310 include all succeeding lines up to (but not including) the next
2311 code statement (if any) that's indented no more than the starting
2312 line, except that trailing blank and comment lines are excluded.
2313 E.g., if the starting line begins a multi-statement `def'
2314 structure, the region will be set to the full function definition,
2315 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002316
2317 - Else the region will include all succeeding lines up to (but not
2318 including) the next blank line, or code or indenting-comment line
2319 indented strictly less than the starting line. Trailing indenting
2320 comment lines are included in this case, but not trailing blank
2321 lines.
2322
2323A msg identifying the location of the mark is displayed in the echo
2324area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2325
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002326If called from a program, optional argument EXTEND plays the role of
2327the prefix arg, and if optional argument JUST-MOVE is not nil, just
2328moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002329 (interactive "P") ; raw prefix arg
2330 (py-goto-initial-line)
2331 ;; skip over blank lines
2332 (while (and
2333 (looking-at "[ \t]*$") ; while blank line
2334 (not (eobp))) ; & somewhere to go
2335 (forward-line 1))
2336 (if (eobp)
2337 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002338 (let ((initial-pos (point))
2339 (initial-indent (current-indentation))
2340 last-pos ; position of last stmt in region
2341 (followers
2342 '((if elif else) (elif elif else) (else)
2343 (try except finally) (except except) (finally)
2344 (for else) (while else)
2345 (def) (class) ) )
2346 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002347
2348 (cond
2349 ;; if comment line, suck up the following comment lines
2350 ((looking-at "[ \t]*#")
2351 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2352 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2353 (setq last-pos (point)))
2354
2355 ;; else if line is a block line and EXTEND given, suck up
2356 ;; the whole structure
2357 ((and extend
2358 (setq first-symbol (py-suck-up-first-keyword) )
2359 (assq first-symbol followers))
2360 (while (and
2361 (or (py-goto-beyond-block) t) ; side effect
2362 (forward-line -1) ; side effect
2363 (setq last-pos (point)) ; side effect
2364 (py-goto-statement-below)
2365 (= (current-indentation) initial-indent)
2366 (setq next-symbol (py-suck-up-first-keyword))
2367 (memq next-symbol (cdr (assq first-symbol followers))))
2368 (setq first-symbol next-symbol)))
2369
2370 ;; else if line *opens* a block, search for next stmt indented <=
2371 ((py-statement-opens-block-p)
2372 (while (and
2373 (setq last-pos (point)) ; always true -- side effect
2374 (py-goto-statement-below)
2375 (> (current-indentation) initial-indent))
2376 nil))
2377
2378 ;; else plain code line; stop at next blank line, or stmt or
2379 ;; indenting comment line indented <
2380 (t
2381 (while (and
2382 (setq last-pos (point)) ; always true -- side effect
2383 (or (py-goto-beyond-final-line) t)
2384 (not (looking-at "[ \t]*$")) ; stop at blank line
2385 (or
2386 (>= (current-indentation) initial-indent)
2387 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2388 nil)))
2389
2390 ;; skip to end of last stmt
2391 (goto-char last-pos)
2392 (py-goto-beyond-final-line)
2393
2394 ;; set mark & display
2395 (if just-move
2396 () ; just return
2397 (push-mark (point) 'no-msg)
2398 (forward-line -1)
2399 (message "Mark set after: %s" (py-suck-up-leading-text))
2400 (goto-char initial-pos))))
2401
Barry Warsaw2518c671997-11-05 00:51:08 +00002402(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002403 "Set region to body of def (or class, with prefix arg) enclosing point.
2404Pushes the current mark, then point, on the mark ring (all language
2405modes do this, but although it's handy it's never documented ...).
2406
2407In most Emacs language modes, this function bears at least a
Barry Warsawab0e86c1998-05-19 15:31:46 +00002408hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2409`\\[py-beginning-of-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002410
2411And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002412Turned out that was more confusing than useful: the `goto start' and
2413`goto end' commands are usually used to search through a file, and
2414people expect them to act a lot like `search backward' and `search
2415forward' string-search commands. But because Python `def' and `class'
2416can nest to arbitrary levels, finding the smallest def containing
2417point cannot be done via a simple backward search: the def containing
2418point may not be the closest preceding def, or even the closest
2419preceding def that's indented less. The fancy algorithm required is
2420appropriate for the usual uses of this `mark' command, but not for the
2421`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002422
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002423So the def marked by this command may not be the one either of the
2424`goto' commands find: If point is on a blank or non-indenting comment
2425line, moves back to start of the closest preceding code statement or
2426indenting comment line. If this is a `def' statement, that's the def
2427we use. Else searches for the smallest enclosing `def' block and uses
2428that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002429
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002430When an enclosing def is found: The mark is left immediately beyond
2431the last line of the def block. Point is left at the start of the
2432def, except that: if the def is preceded by a number of comment lines
2433followed by (at most) one optional blank line, point is left at the
2434start of the comments; else if the def is preceded by a blank line,
2435point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002436
2437The intent is to mark the containing def/class and its associated
2438documentation, to make moving and duplicating functions and classes
2439pleasant."
2440 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002441 (let ((start (point))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002442 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2443 (class "class")
2444 (t "def"))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002445 (push-mark start)
2446 (if (not (py-go-up-tree-to-keyword which))
2447 (progn (goto-char start)
Barry Warsaw7c29b231998-07-07 17:45:38 +00002448 (error "Enclosing %s not found"
2449 (if (eq class 'either)
2450 "def or class"
2451 which)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002452 ;; else enclosing def/class found
2453 (setq start (point))
2454 (py-goto-beyond-block)
2455 (push-mark (point))
2456 (goto-char start)
2457 (if (zerop (forward-line -1)) ; if there is a preceding line
2458 (progn
2459 (if (looking-at "[ \t]*$") ; it's blank
2460 (setq start (point)) ; so reset start point
2461 (goto-char start)) ; else try again
2462 (if (zerop (forward-line -1))
2463 (if (looking-at "[ \t]*#") ; a comment
2464 ;; look back for non-comment line
2465 ;; tricky: note that the regexp matches a blank
2466 ;; line, cuz \n is in the 2nd character class
2467 (and
2468 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2469 (forward-line 1))
2470 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002471 (goto-char start)))))))
2472 (exchange-point-and-mark)
2473 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002474
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002475;; ripped from cc-mode
2476(defun py-forward-into-nomenclature (&optional arg)
2477 "Move forward to end of a nomenclature section or word.
Barry Warsaw41a05c71998-08-10 16:33:12 +00002478With \\[universal-argument] (programmatically, optional argument ARG),
2479do it that many times.
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002480
2481A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2482 (interactive "p")
2483 (let ((case-fold-search nil))
2484 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002485 (re-search-forward
2486 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2487 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002488 (while (and (< arg 0)
2489 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002490 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002491 (point-min) 0))
2492 (forward-char 1)
2493 (setq arg (1+ arg)))))
2494 (py-keep-region-active))
2495
2496(defun py-backward-into-nomenclature (&optional arg)
2497 "Move backward to beginning of a nomenclature section or word.
2498With optional ARG, move that many times. If ARG is negative, move
2499forward.
2500
2501A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2502 (interactive "p")
2503 (py-forward-into-nomenclature (- arg))
2504 (py-keep-region-active))
2505
2506
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002507
2508;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002509
2510;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002511;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2512;; out of the right places, along with the keys they're on & current
2513;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002514(defun py-dump-help-string (str)
2515 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002516 (let ((locals (buffer-local-variables))
2517 funckind funcname func funcdoc
2518 (start 0) mstart end
2519 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002520 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2521 (setq mstart (match-beginning 0) end (match-end 0)
2522 funckind (substring str (match-beginning 1) (match-end 1))
2523 funcname (substring str (match-beginning 2) (match-end 2))
2524 func (intern funcname))
2525 (princ (substitute-command-keys (substring str start mstart)))
2526 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002527 ((equal funckind "c") ; command
2528 (setq funcdoc (documentation func)
2529 keys (concat
2530 "Key(s): "
2531 (mapconcat 'key-description
2532 (where-is-internal func py-mode-map)
2533 ", "))))
2534 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002535 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002536 keys (if (assq func locals)
2537 (concat
2538 "Local/Global values: "
2539 (prin1-to-string (symbol-value func))
2540 " / "
2541 (prin1-to-string (default-value func)))
2542 (concat
2543 "Value: "
2544 (prin1-to-string (symbol-value func))))))
2545 (t ; unexpected
2546 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002547 (princ (format "\n-> %s:\t%s\t%s\n\n"
2548 (if (equal funckind "c") "Command" "Variable")
2549 funcname keys))
2550 (princ funcdoc)
2551 (terpri)
2552 (setq start end))
2553 (princ (substitute-command-keys (substring str start))))
2554 (print-help-return-message)))
2555
2556(defun py-describe-mode ()
2557 "Dump long form of Python-mode docs."
2558 (interactive)
2559 (py-dump-help-string "Major mode for editing Python files.
2560Knows about Python indentation, tokens, comments and continuation lines.
2561Paragraphs are separated by blank lines only.
2562
2563Major sections below begin with the string `@'; specific function and
2564variable docs begin with `->'.
2565
2566@EXECUTING PYTHON CODE
2567
Barry Warsaw820273d1998-05-19 15:54:45 +00002568\\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002569\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2570\\[py-execute-region]\tsends the current region
Barry Warsaw820273d1998-05-19 15:54:45 +00002571\\[py-execute-def-or-class]\tsends the current function or class definition
2572\\[py-execute-string]\tsends an arbitrary string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002573\\[py-shell]\tstarts a Python interpreter window; this will be used by
Barry Warsaw820273d1998-05-19 15:54:45 +00002574\tsubsequent Python execution commands
2575%c:py-execute-import-or-reload
Barry Warsaw7ae77681994-12-12 20:38:05 +00002576%c:py-execute-buffer
2577%c:py-execute-region
Barry Warsaw820273d1998-05-19 15:54:45 +00002578%c:py-execute-def-or-class
2579%c:py-execute-string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002580%c:py-shell
2581
2582@VARIABLES
2583
2584py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002585py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002586
2587py-python-command\tshell command to invoke Python interpreter
2588py-scroll-process-buffer\talways scroll Python process buffer
2589py-temp-directory\tdirectory used for temp files (if needed)
2590
2591py-beep-if-tab-change\tring the bell if tab-width is changed
2592%v:py-indent-offset
2593%v:py-block-comment-prefix
2594%v:py-python-command
2595%v:py-scroll-process-buffer
2596%v:py-temp-directory
2597%v:py-beep-if-tab-change
2598
2599@KINDS OF LINES
2600
2601Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002602preceding line ends with a backslash that's not part of a comment, or
2603the paren/bracket/brace nesting level at the start of the line is
2604non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002605
2606An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002607possibly blanks or tabs), a `comment line' (leftmost non-blank
2608character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002609
2610Comment Lines
2611
2612Although all comment lines are treated alike by Python, Python mode
2613recognizes two kinds that act differently with respect to indentation.
2614
2615An `indenting comment line' is a comment line with a blank, tab or
2616nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002617treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002618indenting comment line will be indented like the comment line. All
2619other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002620following the initial `#') are `non-indenting comment lines', and
2621their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002622
2623Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002624whenever possible. Non-indenting comment lines are useful in cases
2625like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002626
2627\ta = b # a very wordy single-line comment that ends up being
2628\t #... continued onto another line
2629
2630\tif a == b:
2631##\t\tprint 'panic!' # old code we've `commented out'
2632\t\treturn a
2633
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002634Since the `#...' and `##' comment lines have a non-whitespace
2635character following the initial `#', Python mode ignores them when
2636computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002637
2638Continuation Lines and Statements
2639
2640The Python-mode commands generally work on statements instead of on
2641individual lines, where a `statement' is a comment or blank line, or a
2642code line and all of its following continuation lines (if any)
2643considered as a single logical unit. The commands in this mode
2644generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002645statement containing point, even if point happens to be in the middle
2646of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002647
2648
2649@INDENTATION
2650
2651Primarily for entering new code:
2652\t\\[indent-for-tab-command]\t indent line appropriately
2653\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002654\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002655
2656Primarily for reindenting existing code:
2657\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2658\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2659
2660\t\\[py-indent-region]\t reindent region to match its context
2661\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2662\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2663
2664Unlike most programming languages, Python uses indentation, and only
2665indentation, to specify block structure. Hence the indentation supplied
2666automatically by Python-mode is just an educated guess: only you know
2667the block structure you intend, so only you can supply correct
2668indentation.
2669
2670The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2671the indentation of preceding statements. E.g., assuming
2672py-indent-offset is 4, after you enter
2673\tif a > 0: \\[py-newline-and-indent]
2674the cursor will be moved to the position of the `_' (_ is not a
2675character in the file, it's just used here to indicate the location of
2676the cursor):
2677\tif a > 0:
2678\t _
2679If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2680to
2681\tif a > 0:
2682\t c = d
2683\t _
2684Python-mode cannot know whether that's what you intended, or whether
2685\tif a > 0:
2686\t c = d
2687\t_
2688was your intent. In general, Python-mode either reproduces the
2689indentation of the (closest code or indenting-comment) preceding
2690statement, or adds an extra py-indent-offset blanks if the preceding
2691statement has `:' as its last significant (non-whitespace and non-
2692comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002693\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002694
2695Continuation lines are given extra indentation. If you don't like the
2696suggested indentation, change it to something you do like, and Python-
2697mode will strive to indent later lines of the statement in the same way.
2698
2699If a line is a continuation line by virtue of being in an unclosed
2700paren/bracket/brace structure (`list', for short), the suggested
2701indentation depends on whether the current line contains the first item
2702in the list. If it does, it's indented py-indent-offset columns beyond
2703the indentation of the line containing the open bracket. If you don't
2704like that, change it by hand. The remaining items in the list will mimic
2705whatever indentation you give to the first item.
2706
2707If a line is a continuation line because the line preceding it ends with
2708a backslash, the third and following lines of the statement inherit their
2709indentation from the line preceding them. The indentation of the second
2710line in the statement depends on the form of the first (base) line: if
2711the base line is an assignment statement with anything more interesting
2712than the backslash following the leftmost assigning `=', the second line
2713is indented two columns beyond that `='. Else it's indented to two
2714columns beyond the leftmost solid chunk of non-whitespace characters on
2715the base line.
2716
2717Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2718repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2719structure you intend.
2720%c:indent-for-tab-command
2721%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002722%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002723
2724
2725The next function may be handy when editing code you didn't write:
2726%c:py-guess-indent-offset
2727
2728
2729The remaining `indent' functions apply to a region of Python code. They
2730assume the block structure (equals indentation, in Python) of the region
2731is correct, and alter the indentation in various ways while preserving
2732the block structure:
2733%c:py-indent-region
2734%c:py-shift-region-left
2735%c:py-shift-region-right
2736
2737@MARKING & MANIPULATING REGIONS OF CODE
2738
2739\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002740\\[py-mark-def-or-class]\t mark smallest enclosing def
2741\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002742\\[comment-region]\t comment out region of code
2743\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002744%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002745%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002746%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002747
2748@MOVING POINT
2749
2750\\[py-previous-statement]\t move to statement preceding point
2751\\[py-next-statement]\t move to statement following point
2752\\[py-goto-block-up]\t move up to start of current block
Barry Warsawab0e86c1998-05-19 15:31:46 +00002753\\[py-beginning-of-def-or-class]\t move to start of def
2754\\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
2755\\[py-end-of-def-or-class]\t move to end of def
2756\\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002757
2758The first two move to one statement beyond the statement that contains
2759point. A numeric prefix argument tells them to move that many
2760statements instead. Blank lines, comment lines, and continuation lines
2761do not count as `statements' for these commands. So, e.g., you can go
2762to the first code statement in a file by entering
2763\t\\[beginning-of-buffer]\t to move to the top of the file
2764\t\\[py-next-statement]\t to skip over initial comments and blank lines
2765Or do `\\[py-previous-statement]' with a huge prefix argument.
2766%c:py-previous-statement
2767%c:py-next-statement
2768%c:py-goto-block-up
Barry Warsawab0e86c1998-05-19 15:31:46 +00002769%c:py-beginning-of-def-or-class
2770%c:py-end-of-def-or-class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002771
2772@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2773
2774`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2775
2776`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2777overall class and def structure of a module.
2778
2779`\\[back-to-indentation]' moves point to a line's first non-blank character.
2780
2781`\\[indent-relative]' is handy for creating odd indentation.
2782
2783@OTHER EMACS HINTS
2784
2785If you don't like the default value of a variable, change its value to
2786whatever you do like by putting a `setq' line in your .emacs file.
2787E.g., to set the indentation increment to 4, put this line in your
2788.emacs:
2789\t(setq py-indent-offset 4)
2790To see the value of a variable, do `\\[describe-variable]' and enter the variable
2791name at the prompt.
2792
2793When entering a key sequence like `C-c C-n', it is not necessary to
2794release the CONTROL key after doing the `C-c' part -- it suffices to
2795press the CONTROL key, press and release `c' (while still holding down
2796CONTROL), press and release `n' (while still holding down CONTROL), &
2797then release CONTROL.
2798
2799Entering Python mode calls with no arguments the value of the variable
2800`python-mode-hook', if that value exists and is not nil; for backward
2801compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2802the Elisp manual for details.
2803
2804Obscure: When python-mode is first loaded, it looks for all bindings
2805to newline-and-indent in the global keymap, and shadows them with
2806local bindings to py-newline-and-indent."))
2807
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002808
2809;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002810(defvar py-parse-state-re
2811 (concat
2812 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2813 "\\|"
2814 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002815
Barry Warsaw7ae77681994-12-12 20:38:05 +00002816(defun py-parse-state ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002817 "Return the parse state at point (see `parse-partial-sexp' docs)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002818 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002819 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002820 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002821 (while (not done)
2822 ;; back up to the first preceding line (if any; else start of
2823 ;; buffer) that begins with a popular Python keyword, or a
2824 ;; non- whitespace and non-comment character. These are good
2825 ;; places to start parsing to see whether where we started is
2826 ;; at a non-zero nesting level. It may be slow for people who
2827 ;; write huge code blocks or huge lists ... tough beans.
2828 (re-search-backward py-parse-state-re nil 'move)
2829 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002830 ;; In XEmacs, we have a much better way to test for whether
2831 ;; we're in a triple-quoted string or not. Emacs does not
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002832 ;; have this built-in function, which is its loss because
Barry Warsawf64b4051998-02-12 16:52:14 +00002833 ;; without scanning from the beginning of the buffer, there's
2834 ;; no accurate way to determine this otherwise.
2835 (if (not (fboundp 'buffer-syntactic-context))
2836 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002837 (progn
2838 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002839 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002840 (setq done (or (not (nth 3 pps))
2841 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002842 ;; XEmacs
2843 (setq done (or (not (buffer-syntactic-context))
2844 (bobp)))
2845 (when done
2846 (setq pps (parse-partial-sexp (point) here)))
2847 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002848 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002849
Barry Warsaw7ae77681994-12-12 20:38:05 +00002850(defun py-nesting-level ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002851 "Return the buffer position of the last unclosed enclosing list.
2852If nesting level is zero, return nil."
Barry Warsawf64b4051998-02-12 16:52:14 +00002853 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002854 (if (zerop (car status))
2855 nil ; not in a nest
2856 (car (cdr status))))) ; char# of open bracket
2857
Barry Warsaw7ae77681994-12-12 20:38:05 +00002858(defun py-backslash-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002859 "Return t iff preceding line ends with backslash that is not in a comment."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002860 (save-excursion
2861 (beginning-of-line)
2862 (and
2863 ;; use a cheap test first to avoid the regexp if possible
2864 ;; use 'eq' because char-after may return nil
2865 (eq (char-after (- (point) 2)) ?\\ )
2866 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002867 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002868 (looking-at py-continued-re))))
2869
Barry Warsaw7ae77681994-12-12 20:38:05 +00002870(defun py-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002871 "Return t iff current line is a continuation line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002872 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002873 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002874 (or (py-backslash-continuation-line-p)
2875 (py-nesting-level))))
2876
Barry Warsaw7ae77681994-12-12 20:38:05 +00002877(defun py-goto-initial-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002878 "Go to the initial line of the current statement.
2879Usually this is the line we're on, but if we're on the 2nd or
2880following lines of a continuation block, we need to go up to the first
2881line of the block."
2882 ;; Tricky: We want to avoid quadratic-time behavior for long
2883 ;; continued blocks, whether of the backslash or open-bracket
2884 ;; varieties, or a mix of the two. The following manages to do that
2885 ;; in the usual cases.
2886 ;;
2887 ;; Also, if we're sitting inside a triple quoted string, this will
2888 ;; drop us at the line that begins the string.
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002889 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002890 (while (py-continuation-line-p)
2891 (beginning-of-line)
2892 (if (py-backslash-continuation-line-p)
2893 (while (py-backslash-continuation-line-p)
2894 (forward-line -1))
2895 ;; else zip out of nested brackets/braces/parens
2896 (while (setq open-bracket-pos (py-nesting-level))
2897 (goto-char open-bracket-pos)))))
2898 (beginning-of-line))
2899
Barry Warsaw7ae77681994-12-12 20:38:05 +00002900(defun py-goto-beyond-final-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002901 "Go to the point just beyond the fine line of the current statement.
2902Usually this is the start of the next line, but if this is a
2903multi-line statement we need to skip over the continuation lines."
2904 ;; Tricky: Again we need to be clever to avoid quadratic time
2905 ;; behavior.
2906 ;;
2907 ;; XXX: Not quite the right solution, but deals with multi-line doc
2908 ;; strings
Barry Warsaw751f4931998-05-19 16:06:21 +00002909 (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
2910 (goto-char (match-end 0)))
2911 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +00002912 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002913 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002914 (while (and (py-continuation-line-p)
2915 (not (eobp)))
2916 ;; skip over the backslash flavor
2917 (while (and (py-backslash-continuation-line-p)
2918 (not (eobp)))
2919 (forward-line 1))
2920 ;; if in nest, zip to the end of the nest
2921 (setq state (py-parse-state))
2922 (if (and (not (zerop (car state)))
2923 (not (eobp)))
2924 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002925 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002926 (forward-line 1))))))
2927
Barry Warsaw7ae77681994-12-12 20:38:05 +00002928(defun py-statement-opens-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002929 "Return t iff the current statement opens a block.
2930I.e., iff it ends with a colon that is not in a comment. Point should
2931be at the start of a statement."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002932 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002933 (let ((start (point))
2934 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2935 (searching t)
2936 (answer nil)
2937 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002938 (goto-char start)
2939 (while searching
2940 ;; look for a colon with nothing after it except whitespace, and
2941 ;; maybe a comment
2942 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2943 finish t)
2944 (if (eq (point) finish) ; note: no `else' clause; just
2945 ; keep searching if we're not at
2946 ; the end yet
2947 ;; sure looks like it opens a block -- but it might
2948 ;; be in a comment
2949 (progn
2950 (setq searching nil) ; search is done either way
2951 (setq state (parse-partial-sexp start
2952 (match-beginning 0)))
2953 (setq answer (not (nth 4 state)))))
2954 ;; search failed: couldn't find another interesting colon
2955 (setq searching nil)))
2956 answer)))
2957
Barry Warsawf831d811996-07-31 20:42:59 +00002958(defun py-statement-closes-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002959 "Return t iff the current statement closes a block.
2960I.e., if the line starts with `return', `raise', `break', `continue',
2961and `pass'. This doesn't catch embedded statements."
Barry Warsawf831d811996-07-31 20:42:59 +00002962 (let ((here (point)))
2963 (back-to-indentation)
2964 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002965 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002966 (goto-char here))))
2967
Barry Warsaw7ae77681994-12-12 20:38:05 +00002968(defun py-goto-beyond-block ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002969 "Go to point just beyond the final line of block begun by the current line.
2970This is the same as where `py-goto-beyond-final-line' goes unless
2971we're on colon line, in which case we go to the end of the block.
2972Assumes point is at the beginning of the line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002973 (if (py-statement-opens-block-p)
2974 (py-mark-block nil 'just-move)
2975 (py-goto-beyond-final-line)))
2976
Barry Warsaw7ae77681994-12-12 20:38:05 +00002977(defun py-goto-statement-at-or-above ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002978 "Go to the start of the first statement at or preceding point.
2979Return t if there is such a statement, otherwise nil. `Statement'
2980does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002981 (py-goto-initial-line)
2982 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002983 ;; skip back over blank & comment lines
2984 ;; note: will skip a blank or comment line that happens to be
2985 ;; a continuation line too
2986 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2987 (progn (py-goto-initial-line) t)
2988 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002989 t))
2990
Barry Warsaw7ae77681994-12-12 20:38:05 +00002991(defun py-goto-statement-below ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002992 "Go to start of the first statement following the statement containing point.
2993Return t if there is such a statement, otherwise nil. `Statement'
2994does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002995 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002996 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002997 (py-goto-beyond-final-line)
2998 (while (and
2999 (looking-at py-blank-or-comment-re)
3000 (not (eobp)))
3001 (forward-line 1))
3002 (if (eobp)
3003 (progn (goto-char start) nil)
3004 t)))
3005
Barry Warsaw7ae77681994-12-12 20:38:05 +00003006(defun py-go-up-tree-to-keyword (key)
Barry Warsaw41a05c71998-08-10 16:33:12 +00003007 "Go to begining of statement starting with KEY, at or preceding point.
3008
3009KEY is a regular expression describing a Python keyword. Skip blank
3010lines and non-indenting comments. If the statement found starts with
3011KEY, then stop, otherwise go back to first enclosing block starting
3012with KEY. If successful, leave point at the start of the KEY line and
3013return t. Otherwise, leav point at an undefined place and return nil."
Barry Warsaw7ae77681994-12-12 20:38:05 +00003014 ;; skip blanks and non-indenting #
3015 (py-goto-initial-line)
3016 (while (and
3017 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
3018 (zerop (forward-line -1))) ; go back
3019 nil)
3020 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003021 (let* ((re (concat "[ \t]*" key "\\b"))
3022 (case-fold-search nil) ; let* so looking-at sees this
3023 (found (looking-at re))
3024 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00003025 (while (not (or found dead))
3026 (condition-case nil ; in case no enclosing block
3027 (py-goto-block-up 'no-mark)
3028 (error (setq dead t)))
3029 (or dead (setq found (looking-at re))))
3030 (beginning-of-line)
3031 found))
3032
Barry Warsaw7ae77681994-12-12 20:38:05 +00003033(defun py-suck-up-leading-text ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003034 "Return string in buffer from start of indentation to end of line.
3035Prefix with \"...\" if leading whitespace was skipped."
Barry Warsaw7ae77681994-12-12 20:38:05 +00003036 (save-excursion
3037 (back-to-indentation)
3038 (concat
3039 (if (bolp) "" "...")
3040 (buffer-substring (point) (progn (end-of-line) (point))))))
3041
Barry Warsaw7ae77681994-12-12 20:38:05 +00003042(defun py-suck-up-first-keyword ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003043 "Return first keyword on the line as a Lisp symbol.
3044`Keyword' is defined (essentially) as the regular expression
3045([a-z]+). Returns nil if none was found."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003046 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00003047 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
3048 (intern (buffer-substring (match-beginning 1) (match-end 1)))
3049 nil)))
3050
Barry Warsawb3e81d51996-09-04 15:12:42 +00003051(defun py-current-defun ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003052 "Python value for `add-log-current-defun-function'.
3053This tells add-log.el how to find the current function/method/variable."
Barry Warsawb3e81d51996-09-04 15:12:42 +00003054 (save-excursion
3055 (if (re-search-backward py-defun-start-re nil t)
3056 (or (match-string 3)
3057 (let ((method (match-string 2)))
3058 (if (and (not (zerop (length (match-string 1))))
3059 (re-search-backward py-class-start-re nil t))
3060 (concat (match-string 1) "." method)
3061 method)))
3062 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003063
3064
Barry Warsawfec75d61995-07-05 23:26:15 +00003065(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00003066 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003067
Barry Warsaw850437a1995-03-08 21:50:28 +00003068(defun py-version ()
3069 "Echo the current version of `python-mode' in the minibuffer."
3070 (interactive)
3071 (message "Using `python-mode' version %s" py-version)
3072 (py-keep-region-active))
3073
3074;; only works under Emacs 19
3075;(eval-when-compile
3076; (require 'reporter))
3077
3078(defun py-submit-bug-report (enhancement-p)
3079 "Submit via mail a bug report on `python-mode'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00003080With \\[universal-argument] (programmatically, argument ENHANCEMENT-P
3081non-nil) just submit an enhancement request."
Barry Warsaw850437a1995-03-08 21:50:28 +00003082 (interactive
3083 (list (not (y-or-n-p
Barry Warsaw41a05c71998-08-10 16:33:12 +00003084 "Is this a bug report (hit `n' to send other comments)? "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00003085 (let ((reporter-prompt-for-summary-p (if enhancement-p
3086 "(Very) brief summary: "
3087 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00003088 (require 'reporter)
3089 (reporter-submit-bug-report
3090 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00003091 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00003092 ;; varlist
3093 (if enhancement-p nil
3094 '(py-python-command
3095 py-indent-offset
3096 py-block-comment-prefix
3097 py-scroll-process-buffer
3098 py-temp-directory
3099 py-beep-if-tab-change))
3100 nil ;pre-hooks
3101 nil ;post-hooks
3102 "Dear Barry,") ;salutation
3103 (if enhancement-p nil
3104 (set-mark (point))
3105 (insert
3106"Please replace this text with a sufficiently large code sample\n\
3107and an exact recipe so that I can reproduce your problem. Failure\n\
3108to do so may mean a greater delay in fixing your bug.\n\n")
3109 (exchange-point-and-mark)
3110 (py-keep-region-active))))
3111
3112
Barry Warsaw47384781997-11-26 05:27:45 +00003113(defun py-kill-emacs-hook ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003114 "Delete files in `py-file-queue'.
3115These are Python temporary files awaiting execution."
Barry Warsaw47384781997-11-26 05:27:45 +00003116 (mapcar #'(lambda (filename)
3117 (py-safe (delete-file filename)))
3118 py-file-queue))
3119
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003120;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00003121(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003122
3123
3124
3125(provide 'python-mode)
3126;;; python-mode.el ends here