blob: 7c02026b0eacd10557dcd74bbfbeabca35baf7b3 [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.
Barry Warsaw12c92941998-08-10 21:44:37 +0000308When this variable is non-nil and an exception occurs when running
Barry Warsaw9981d221997-12-03 05:25:48 +0000309Python code synchronously in a subprocess, jump immediately to the
Barry Warsaw12c92941998-08-10 21:44:37 +0000310source code of the innermost traceback frame."
Barry Warsaw3bfed5b1998-05-19 16:25:04 +0000311 :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 Warsaw12c92941998-08-10 21:44:37 +00001509 "Jump to the code which caused the Python exception at EVENT.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001510EVENT 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)
Barry Warsaw12c92941998-08-10 21:44:37 +00001844 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#\\)" nil 'move)
1845 (setq done (or (bobp)
1846 (and (eq py-honor-comment-indentation t)
1847 (save-excursion
1848 (back-to-indentation)
1849 (not (looking-at py-block-comment-prefix))
1850 ))
1851 (and (not (eq py-honor-comment-indentation t))
1852 (save-excursion
1853 (back-to-indentation)
1854 (not (zerop (current-column)))))
1855 ))
Barry Warsaw6d627751996-03-06 18:41:38 +00001856 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001857 ;; if we landed inside a string, go to the beginning of that
1858 ;; string. this handles triple quoted, multi-line spanning
1859 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001860 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001861 (skip (and delim (make-string 1 delim))))
1862 (when skip
1863 (save-excursion
1864 (py-safe (search-backward skip))
1865 (if (and (eq (char-before) delim)
1866 (eq (char-before (1- (point))) delim))
1867 (setq skip (make-string 3 delim))))
1868 ;; we're looking at a triple-quoted string
1869 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001870 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001871 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001872 (+ (current-indentation)
1873 (if (py-statement-opens-block-p)
1874 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001875 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001876 (- py-indent-offset)
1877 0)))
1878 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001879
1880(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001881 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00001882
1883By default, make a buffer-local copy of `py-indent-offset' with the
1884new value, so that other Python buffers are not affected. With
1885\\[universal-argument] (programmatically, optional argument GLOBAL),
1886change the global value of `py-indent-offset'. This affects all
1887Python buffers (that don't have their own buffer-local copy), both
1888those currently existing and those created later in the Emacs session.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001889
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001890Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001891There's no excuse for such foolishness, but sometimes you have to deal
1892with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001893`py-indent-offset' to what it thinks it was when they created the
1894mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001895
1896Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001897looking for a line that opens a block of code. `py-indent-offset' is
1898set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001899statement following it. If the search doesn't succeed going forward,
1900it's tried again going backward."
1901 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001902 (let (new-value
1903 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001904 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001905 (found nil)
1906 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001907 (py-goto-initial-line)
1908 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001909 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1910 (not (py-in-literal restart)))
1911 (setq restart (point))
1912 (py-goto-initial-line)
1913 (if (py-statement-opens-block-p)
1914 (setq found t)
1915 (goto-char restart))))
1916 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001917 (goto-char start)
1918 (py-goto-initial-line)
1919 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001920 (setq found (and
1921 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1922 (or (py-goto-initial-line) t) ; always true -- side effect
1923 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001924 (setq colon-indent (current-indentation)
1925 found (and found (zerop (py-next-statement 1)))
1926 new-value (- (current-indentation) colon-indent))
1927 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001928 (if (not found)
1929 (error "Sorry, couldn't guess a value for py-indent-offset")
1930 (funcall (if global 'kill-local-variable 'make-local-variable)
1931 'py-indent-offset)
1932 (setq py-indent-offset new-value)
1933 (message "%s value of py-indent-offset set to %d"
1934 (if global "Global" "Local")
1935 py-indent-offset))
1936 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001937
Barry Warsaw003932a1998-07-07 15:11:24 +00001938(defun py-comment-indent-function ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00001939 "Python version of `comment-indent-function'."
1940 ;; This is required when filladapt is turned off. Without it, when
1941 ;; filladapt is not used, comments which start in column zero
1942 ;; cascade one character to the right
Barry Warsaw003932a1998-07-07 15:11:24 +00001943 (save-excursion
1944 (beginning-of-line)
1945 (let ((eol (py-point 'eol)))
1946 (and comment-start-skip
1947 (re-search-forward comment-start-skip eol t)
1948 (setq eol (match-beginning 0)))
1949 (goto-char eol)
1950 (skip-chars-backward " \t")
1951 (max comment-column (+ (current-column) (if (bolp) 0 1)))
1952 )))
1953
1954
Barry Warsaw7ae77681994-12-12 20:38:05 +00001955(defun py-shift-region (start end count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00001956 "Indent lines from START to END by COUNT spaces."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001957 (save-excursion
Barry Warsaw41a05c71998-08-10 16:33:12 +00001958 (goto-char end)
1959 (beginning-of-line)
1960 (setq end (point))
1961 (goto-char start)
1962 (beginning-of-line)
1963 (setq start (point))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001964 (indent-rigidly start end count)))
1965
1966(defun py-shift-region-left (start end &optional count)
1967 "Shift region of Python code to the left.
1968The lines from the line containing the start of the current region up
1969to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001970shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001971
1972If a prefix argument is given, the region is instead shifted by that
Barry Warsaw41a05c71998-08-10 16:33:12 +00001973many columns. With no active region, dedent only the current line.
1974You cannot dedent the region if any line is already at column zero."
Barry Warsawdea4a291996-07-03 22:59:12 +00001975 (interactive
1976 (let ((p (point))
1977 (m (mark))
1978 (arg current-prefix-arg))
1979 (if m
1980 (list (min p m) (max p m) arg)
1981 (list p (save-excursion (forward-line 1) (point)) arg))))
1982 ;; if any line is at column zero, don't shift the region
1983 (save-excursion
1984 (goto-char start)
1985 (while (< (point) end)
1986 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001987 (if (and (zerop (current-column))
1988 (not (looking-at "\\s *$")))
Barry Warsaw41a05c71998-08-10 16:33:12 +00001989 (error "Region is at left edge"))
Barry Warsawdea4a291996-07-03 22:59:12 +00001990 (forward-line 1)))
1991 (py-shift-region start end (- (prefix-numeric-value
1992 (or count py-indent-offset))))
1993 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001994
1995(defun py-shift-region-right (start end &optional count)
1996 "Shift region of Python code to the right.
1997The lines from the line containing the start of the current region up
1998to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001999shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002000
2001If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00002002many columns. With no active region, indent only the current line."
2003 (interactive
2004 (let ((p (point))
2005 (m (mark))
2006 (arg current-prefix-arg))
2007 (if m
2008 (list (min p m) (max p m) arg)
2009 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002010 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00002011 (or count py-indent-offset)))
2012 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002013
2014(defun py-indent-region (start end &optional indent-offset)
2015 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00002016
Barry Warsaw7ae77681994-12-12 20:38:05 +00002017The lines from the line containing the start of the current region up
2018to (but not including) the line containing the end of the region are
2019reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002020character in the first column, the first line is left alone and the
2021rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00002022region is reindented with respect to the (closest code or indenting
2023comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002024
2025This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002026control structures are introduced or removed, or to reformat code
2027using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002028
2029If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002030the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00002031used.
2032
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002033Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00002034is called! This function does not compute proper indentation from
2035scratch (that's impossible in Python), it merely adjusts the existing
2036indentation to be correct in context.
2037
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002038Warning: This function really has no idea what to do with
2039non-indenting comment lines, and shifts them as if they were indenting
2040comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002041
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002042Special cases: whitespace is deleted from blank lines; continuation
2043lines are shifted by the same amount their initial line was shifted,
2044in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00002045initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002046 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002047 (save-excursion
2048 (goto-char end) (beginning-of-line) (setq end (point-marker))
2049 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002050 (let ((py-indent-offset (prefix-numeric-value
2051 (or indent-offset py-indent-offset)))
2052 (indents '(-1)) ; stack of active indent levels
2053 (target-column 0) ; column to which to indent
2054 (base-shifted-by 0) ; amount last base line was shifted
2055 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002056 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002057 0))
2058 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002059 (while (< (point) end)
2060 (setq ci (current-indentation))
2061 ;; figure out appropriate target column
2062 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002063 ((or (eq (following-char) ?#) ; comment in column 1
2064 (looking-at "[ \t]*$")) ; entirely blank
2065 (setq target-column 0))
2066 ((py-continuation-line-p) ; shift relative to base line
2067 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002068 (t ; new base line
2069 (if (> ci (car indents)) ; going deeper; push it
2070 (setq indents (cons ci indents))
2071 ;; else we should have seen this indent before
2072 (setq indents (memq ci indents)) ; pop deeper indents
2073 (if (null indents)
2074 (error "Bad indentation in region, at line %d"
2075 (save-restriction
2076 (widen)
2077 (1+ (count-lines 1 (point)))))))
2078 (setq target-column (+ indent-base
2079 (* py-indent-offset
2080 (- (length indents) 2))))
2081 (setq base-shifted-by (- target-column ci))))
2082 ;; shift as needed
2083 (if (/= ci target-column)
2084 (progn
2085 (delete-horizontal-space)
2086 (indent-to target-column)))
2087 (forward-line 1))))
2088 (set-marker end nil))
2089
Barry Warsawa7891711996-08-01 15:53:09 +00002090(defun py-comment-region (beg end &optional arg)
2091 "Like `comment-region' but uses double hash (`#') comment starter."
2092 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00002093 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00002094 (comment-region beg end arg)))
2095
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002096
2097;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00002098(defun py-previous-statement (count)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002099 "Go to the start of the COUNTth preceding Python statement.
2100By default, goes to the previous statement. If there is no such
2101statement, goes to the first statement. Return count of statements
2102left to move. `Statements' do not include blank, comment, or
2103continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002104 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002105 (if (< count 0) (py-next-statement (- count))
2106 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002107 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002108 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002109 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002110 (> count 0)
2111 (zerop (forward-line -1))
2112 (py-goto-statement-at-or-above))
2113 (setq count (1- count)))
2114 (if (> count 0) (goto-char start)))
2115 count))
2116
2117(defun py-next-statement (count)
2118 "Go to the start of next Python statement.
2119If the statement at point is the i'th Python statement, goes to the
2120start of statement i+COUNT. If there is no such statement, goes to the
2121last statement. Returns count of statements left to move. `Statements'
2122do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002123 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002124 (if (< count 0) (py-previous-statement (- count))
2125 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002126 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002127 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002128 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002129 (> count 0)
2130 (py-goto-statement-below))
2131 (setq count (1- count)))
2132 (if (> count 0) (goto-char start)))
2133 count))
2134
2135(defun py-goto-block-up (&optional nomark)
2136 "Move up to start of current block.
2137Go to the statement that starts the smallest enclosing block; roughly
2138speaking, this will be the closest preceding statement that ends with a
2139colon and is indented less than the statement you started on. If
2140successful, also sets the mark to the starting point.
2141
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002142`\\[py-mark-block]' can be used afterward to mark the whole code
2143block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002144
2145If called from a program, the mark will not be set if optional argument
2146NOMARK is not nil."
2147 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002148 (let ((start (point))
2149 (found nil)
2150 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002151 (py-goto-initial-line)
2152 ;; if on blank or non-indenting comment line, use the preceding stmt
2153 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2154 (progn
2155 (py-goto-statement-at-or-above)
2156 (setq found (py-statement-opens-block-p))))
2157 ;; search back for colon line indented less
2158 (setq initial-indent (current-indentation))
2159 (if (zerop initial-indent)
2160 ;; force fast exit
2161 (goto-char (point-min)))
2162 (while (not (or found (bobp)))
2163 (setq found
2164 (and
2165 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2166 (or (py-goto-initial-line) t) ; always true -- side effect
2167 (< (current-indentation) initial-indent)
2168 (py-statement-opens-block-p))))
2169 (if found
2170 (progn
2171 (or nomark (push-mark start))
2172 (back-to-indentation))
2173 (goto-char start)
2174 (error "Enclosing block not found"))))
2175
Barry Warsawab0e86c1998-05-19 15:31:46 +00002176(defun py-beginning-of-def-or-class (&optional class count)
2177 "Move point to start of `def' or `class'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002178
2179Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsawab0e86c1998-05-19 15:31:46 +00002180arg, looks for a `class' instead. The docs below assume the `def'
2181case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002182Programmatically, if CLASS is `either', then moves to either `class'
2183or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002184
Barry Warsawab0e86c1998-05-19 15:31:46 +00002185When second optional argument is given programmatically, move to the
2186COUNTth start of `def'.
2187
2188If point is in a `def' statement already, and after the `d', simply
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002189moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002190
Barry Warsawab0e86c1998-05-19 15:31:46 +00002191Otherwise (i.e. when point is not in a `def' statement, or at or
2192before the `d' of a `def' statement), searches for the closest
2193preceding `def' statement, and leaves point at its start. If no such
2194statement can be found, leaves point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002195
Barry Warsawab0e86c1998-05-19 15:31:46 +00002196Returns t iff a `def' statement is found by these rules.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002197
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002198Note that doing this command repeatedly will take you closer to the
2199start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002200
Barry Warsaw7c29b231998-07-07 17:45:38 +00002201To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002202 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002203 (if (not count)
2204 (setq count 1))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002205 (let ((at-or-before-p (<= (current-column) (current-indentation)))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002206 (start-of-line (goto-char (py-point 'bol)))
2207 (start-of-stmt (goto-char (py-point 'bos)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002208 (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
2209 (class "^[ \t]*class\\>")
2210 (t "^[ \t]*def\\>")))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002211 )
2212 ;; searching backward
2213 (if (and (< 0 count)
2214 (or (/= start-of-stmt start-of-line)
2215 (not at-or-before-p)))
2216 (end-of-line))
2217 ;; search forward
2218 (if (and (> 0 count)
2219 (zerop (current-column))
2220 (looking-at start-re))
2221 (end-of-line))
2222 (re-search-backward start-re nil 'move count)
2223 (goto-char (match-beginning 0))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002224
Barry Warsawab0e86c1998-05-19 15:31:46 +00002225;; Backwards compatibility
2226(defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002227
Barry Warsawab0e86c1998-05-19 15:31:46 +00002228(defun py-end-of-def-or-class (&optional class count)
2229 "Move point beyond end of `def' or `class' body.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002230
Barry Warsawab0e86c1998-05-19 15:31:46 +00002231By default, looks for an appropriate `def'. If you supply a prefix
2232arg, looks for a `class' instead. The docs below assume the `def'
2233case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002234Programmatically, if CLASS is `either', then moves to either `class'
2235or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002236
Barry Warsawab0e86c1998-05-19 15:31:46 +00002237When second optional argument is given programmatically, move to the
2238COUNTth end of `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002239
Barry Warsawab0e86c1998-05-19 15:31:46 +00002240If point is in a `def' statement already, this is the `def' we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002241
Barry Warsawab0e86c1998-05-19 15:31:46 +00002242Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2243contains the statement you started on, that's the `def' we use.
2244
2245Otherwise, we search forward for the closest following `def', and use that.
2246
2247If a `def' can be found by these rules, point is moved to the start of
2248the line immediately following the `def' block, and the position of the
2249start of the `def' is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002250
2251Else point is moved to the end of the buffer, and nil is returned.
2252
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002253Note that doing this command repeatedly will take you closer to the
2254end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002255
Barry Warsaw7c29b231998-07-07 17:45:38 +00002256To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002257 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002258 (if (and count (/= count 1))
2259 (py-beginning-of-def-or-class (- 1 count)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002260 (let ((start (progn (py-goto-initial-line) (point)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002261 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2262 (class "class")
2263 (t "def")))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002264 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002265 ;; move point to start of appropriate def/class
2266 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2267 (setq state 'at-beginning)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002268 ;; else see if py-beginning-of-def-or-class hits container
2269 (if (and (py-beginning-of-def-or-class class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002270 (progn (py-goto-beyond-block)
2271 (> (point) start)))
2272 (setq state 'at-end)
2273 ;; else search forward
2274 (goto-char start)
2275 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2276 (progn (setq state 'at-beginning)
2277 (beginning-of-line)))))
2278 (cond
2279 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2280 ((eq state 'at-end) t)
2281 ((eq state 'not-found) nil)
Barry Warsaw41a05c71998-08-10 16:33:12 +00002282 (t (error "Internal error in `py-end-of-def-or-class'")))))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002283
2284;; Backwards compabitility
Barry Warsaw820273d1998-05-19 15:54:45 +00002285(defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002286
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002287
2288;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002289(defun py-mark-block (&optional extend just-move)
2290 "Mark following block of lines. With prefix arg, mark structure.
2291Easier to use than explain. It sets the region to an `interesting'
2292block of succeeding lines. If point is on a blank line, it goes down to
2293the next non-blank line. That will be the start of the region. The end
2294of the region depends on the kind of line at the start:
2295
2296 - If a comment, the region will include all succeeding comment lines up
2297 to (but not including) the next non-comment line (if any).
2298
2299 - Else if a prefix arg is given, and the line begins one of these
2300 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002301
2302 if elif else try except finally for while def class
2303
Barry Warsaw7ae77681994-12-12 20:38:05 +00002304 the region will be set to the body of the structure, including
2305 following blocks that `belong' to it, but excluding trailing blank
2306 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002307 and all (if any) of the following `except' and `finally' blocks
2308 that belong to the `try' structure will be in the region. Ditto
2309 for if/elif/else, for/else and while/else structures, and (a bit
2310 degenerate, since they're always one-block structures) def and
2311 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002312
2313 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002314 block (see list above), and the block is not a `one-liner' (i.e.,
2315 the statement ends with a colon, not with code), the region will
2316 include all succeeding lines up to (but not including) the next
2317 code statement (if any) that's indented no more than the starting
2318 line, except that trailing blank and comment lines are excluded.
2319 E.g., if the starting line begins a multi-statement `def'
2320 structure, the region will be set to the full function definition,
2321 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002322
2323 - Else the region will include all succeeding lines up to (but not
2324 including) the next blank line, or code or indenting-comment line
2325 indented strictly less than the starting line. Trailing indenting
2326 comment lines are included in this case, but not trailing blank
2327 lines.
2328
2329A msg identifying the location of the mark is displayed in the echo
2330area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2331
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002332If called from a program, optional argument EXTEND plays the role of
2333the prefix arg, and if optional argument JUST-MOVE is not nil, just
2334moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002335 (interactive "P") ; raw prefix arg
2336 (py-goto-initial-line)
2337 ;; skip over blank lines
2338 (while (and
2339 (looking-at "[ \t]*$") ; while blank line
2340 (not (eobp))) ; & somewhere to go
2341 (forward-line 1))
2342 (if (eobp)
2343 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002344 (let ((initial-pos (point))
2345 (initial-indent (current-indentation))
2346 last-pos ; position of last stmt in region
2347 (followers
2348 '((if elif else) (elif elif else) (else)
2349 (try except finally) (except except) (finally)
2350 (for else) (while else)
2351 (def) (class) ) )
2352 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002353
2354 (cond
2355 ;; if comment line, suck up the following comment lines
2356 ((looking-at "[ \t]*#")
2357 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2358 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2359 (setq last-pos (point)))
2360
2361 ;; else if line is a block line and EXTEND given, suck up
2362 ;; the whole structure
2363 ((and extend
2364 (setq first-symbol (py-suck-up-first-keyword) )
2365 (assq first-symbol followers))
2366 (while (and
2367 (or (py-goto-beyond-block) t) ; side effect
2368 (forward-line -1) ; side effect
2369 (setq last-pos (point)) ; side effect
2370 (py-goto-statement-below)
2371 (= (current-indentation) initial-indent)
2372 (setq next-symbol (py-suck-up-first-keyword))
2373 (memq next-symbol (cdr (assq first-symbol followers))))
2374 (setq first-symbol next-symbol)))
2375
2376 ;; else if line *opens* a block, search for next stmt indented <=
2377 ((py-statement-opens-block-p)
2378 (while (and
2379 (setq last-pos (point)) ; always true -- side effect
2380 (py-goto-statement-below)
2381 (> (current-indentation) initial-indent))
2382 nil))
2383
2384 ;; else plain code line; stop at next blank line, or stmt or
2385 ;; indenting comment line indented <
2386 (t
2387 (while (and
2388 (setq last-pos (point)) ; always true -- side effect
2389 (or (py-goto-beyond-final-line) t)
2390 (not (looking-at "[ \t]*$")) ; stop at blank line
2391 (or
2392 (>= (current-indentation) initial-indent)
2393 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2394 nil)))
2395
2396 ;; skip to end of last stmt
2397 (goto-char last-pos)
2398 (py-goto-beyond-final-line)
2399
2400 ;; set mark & display
2401 (if just-move
2402 () ; just return
2403 (push-mark (point) 'no-msg)
2404 (forward-line -1)
2405 (message "Mark set after: %s" (py-suck-up-leading-text))
2406 (goto-char initial-pos))))
2407
Barry Warsaw2518c671997-11-05 00:51:08 +00002408(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002409 "Set region to body of def (or class, with prefix arg) enclosing point.
2410Pushes the current mark, then point, on the mark ring (all language
2411modes do this, but although it's handy it's never documented ...).
2412
2413In most Emacs language modes, this function bears at least a
Barry Warsawab0e86c1998-05-19 15:31:46 +00002414hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2415`\\[py-beginning-of-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002416
2417And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002418Turned out that was more confusing than useful: the `goto start' and
2419`goto end' commands are usually used to search through a file, and
2420people expect them to act a lot like `search backward' and `search
2421forward' string-search commands. But because Python `def' and `class'
2422can nest to arbitrary levels, finding the smallest def containing
2423point cannot be done via a simple backward search: the def containing
2424point may not be the closest preceding def, or even the closest
2425preceding def that's indented less. The fancy algorithm required is
2426appropriate for the usual uses of this `mark' command, but not for the
2427`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002428
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002429So the def marked by this command may not be the one either of the
2430`goto' commands find: If point is on a blank or non-indenting comment
2431line, moves back to start of the closest preceding code statement or
2432indenting comment line. If this is a `def' statement, that's the def
2433we use. Else searches for the smallest enclosing `def' block and uses
2434that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002435
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002436When an enclosing def is found: The mark is left immediately beyond
2437the last line of the def block. Point is left at the start of the
2438def, except that: if the def is preceded by a number of comment lines
2439followed by (at most) one optional blank line, point is left at the
2440start of the comments; else if the def is preceded by a blank line,
2441point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002442
2443The intent is to mark the containing def/class and its associated
2444documentation, to make moving and duplicating functions and classes
2445pleasant."
2446 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002447 (let ((start (point))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002448 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2449 (class "class")
2450 (t "def"))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002451 (push-mark start)
2452 (if (not (py-go-up-tree-to-keyword which))
2453 (progn (goto-char start)
Barry Warsaw7c29b231998-07-07 17:45:38 +00002454 (error "Enclosing %s not found"
2455 (if (eq class 'either)
2456 "def or class"
2457 which)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002458 ;; else enclosing def/class found
2459 (setq start (point))
2460 (py-goto-beyond-block)
2461 (push-mark (point))
2462 (goto-char start)
2463 (if (zerop (forward-line -1)) ; if there is a preceding line
2464 (progn
2465 (if (looking-at "[ \t]*$") ; it's blank
2466 (setq start (point)) ; so reset start point
2467 (goto-char start)) ; else try again
2468 (if (zerop (forward-line -1))
2469 (if (looking-at "[ \t]*#") ; a comment
2470 ;; look back for non-comment line
2471 ;; tricky: note that the regexp matches a blank
2472 ;; line, cuz \n is in the 2nd character class
2473 (and
2474 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2475 (forward-line 1))
2476 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002477 (goto-char start)))))))
2478 (exchange-point-and-mark)
2479 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002480
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002481;; ripped from cc-mode
2482(defun py-forward-into-nomenclature (&optional arg)
2483 "Move forward to end of a nomenclature section or word.
Barry Warsaw41a05c71998-08-10 16:33:12 +00002484With \\[universal-argument] (programmatically, optional argument ARG),
2485do it that many times.
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002486
2487A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2488 (interactive "p")
2489 (let ((case-fold-search nil))
2490 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002491 (re-search-forward
2492 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2493 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002494 (while (and (< arg 0)
2495 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002496 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002497 (point-min) 0))
2498 (forward-char 1)
2499 (setq arg (1+ arg)))))
2500 (py-keep-region-active))
2501
2502(defun py-backward-into-nomenclature (&optional arg)
2503 "Move backward to beginning of a nomenclature section or word.
2504With optional ARG, move that many times. If ARG is negative, move
2505forward.
2506
2507A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2508 (interactive "p")
2509 (py-forward-into-nomenclature (- arg))
2510 (py-keep-region-active))
2511
2512
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002513
2514;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002515
2516;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002517;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2518;; out of the right places, along with the keys they're on & current
2519;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002520(defun py-dump-help-string (str)
2521 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002522 (let ((locals (buffer-local-variables))
2523 funckind funcname func funcdoc
2524 (start 0) mstart end
2525 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002526 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2527 (setq mstart (match-beginning 0) end (match-end 0)
2528 funckind (substring str (match-beginning 1) (match-end 1))
2529 funcname (substring str (match-beginning 2) (match-end 2))
2530 func (intern funcname))
2531 (princ (substitute-command-keys (substring str start mstart)))
2532 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002533 ((equal funckind "c") ; command
2534 (setq funcdoc (documentation func)
2535 keys (concat
2536 "Key(s): "
2537 (mapconcat 'key-description
2538 (where-is-internal func py-mode-map)
2539 ", "))))
2540 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002541 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002542 keys (if (assq func locals)
2543 (concat
2544 "Local/Global values: "
2545 (prin1-to-string (symbol-value func))
2546 " / "
2547 (prin1-to-string (default-value func)))
2548 (concat
2549 "Value: "
2550 (prin1-to-string (symbol-value func))))))
2551 (t ; unexpected
2552 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002553 (princ (format "\n-> %s:\t%s\t%s\n\n"
2554 (if (equal funckind "c") "Command" "Variable")
2555 funcname keys))
2556 (princ funcdoc)
2557 (terpri)
2558 (setq start end))
2559 (princ (substitute-command-keys (substring str start))))
2560 (print-help-return-message)))
2561
2562(defun py-describe-mode ()
2563 "Dump long form of Python-mode docs."
2564 (interactive)
2565 (py-dump-help-string "Major mode for editing Python files.
2566Knows about Python indentation, tokens, comments and continuation lines.
2567Paragraphs are separated by blank lines only.
2568
2569Major sections below begin with the string `@'; specific function and
2570variable docs begin with `->'.
2571
2572@EXECUTING PYTHON CODE
2573
Barry Warsaw820273d1998-05-19 15:54:45 +00002574\\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002575\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2576\\[py-execute-region]\tsends the current region
Barry Warsaw820273d1998-05-19 15:54:45 +00002577\\[py-execute-def-or-class]\tsends the current function or class definition
2578\\[py-execute-string]\tsends an arbitrary string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002579\\[py-shell]\tstarts a Python interpreter window; this will be used by
Barry Warsaw820273d1998-05-19 15:54:45 +00002580\tsubsequent Python execution commands
2581%c:py-execute-import-or-reload
Barry Warsaw7ae77681994-12-12 20:38:05 +00002582%c:py-execute-buffer
2583%c:py-execute-region
Barry Warsaw820273d1998-05-19 15:54:45 +00002584%c:py-execute-def-or-class
2585%c:py-execute-string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002586%c:py-shell
2587
2588@VARIABLES
2589
2590py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002591py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002592
2593py-python-command\tshell command to invoke Python interpreter
2594py-scroll-process-buffer\talways scroll Python process buffer
2595py-temp-directory\tdirectory used for temp files (if needed)
2596
2597py-beep-if-tab-change\tring the bell if tab-width is changed
2598%v:py-indent-offset
2599%v:py-block-comment-prefix
2600%v:py-python-command
2601%v:py-scroll-process-buffer
2602%v:py-temp-directory
2603%v:py-beep-if-tab-change
2604
2605@KINDS OF LINES
2606
2607Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002608preceding line ends with a backslash that's not part of a comment, or
2609the paren/bracket/brace nesting level at the start of the line is
2610non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002611
2612An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002613possibly blanks or tabs), a `comment line' (leftmost non-blank
2614character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002615
2616Comment Lines
2617
2618Although all comment lines are treated alike by Python, Python mode
2619recognizes two kinds that act differently with respect to indentation.
2620
2621An `indenting comment line' is a comment line with a blank, tab or
2622nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002623treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002624indenting comment line will be indented like the comment line. All
2625other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002626following the initial `#') are `non-indenting comment lines', and
2627their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002628
2629Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002630whenever possible. Non-indenting comment lines are useful in cases
2631like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002632
2633\ta = b # a very wordy single-line comment that ends up being
2634\t #... continued onto another line
2635
2636\tif a == b:
2637##\t\tprint 'panic!' # old code we've `commented out'
2638\t\treturn a
2639
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002640Since the `#...' and `##' comment lines have a non-whitespace
2641character following the initial `#', Python mode ignores them when
2642computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002643
2644Continuation Lines and Statements
2645
2646The Python-mode commands generally work on statements instead of on
2647individual lines, where a `statement' is a comment or blank line, or a
2648code line and all of its following continuation lines (if any)
2649considered as a single logical unit. The commands in this mode
2650generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002651statement containing point, even if point happens to be in the middle
2652of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002653
2654
2655@INDENTATION
2656
2657Primarily for entering new code:
2658\t\\[indent-for-tab-command]\t indent line appropriately
2659\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002660\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002661
2662Primarily for reindenting existing code:
2663\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2664\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2665
2666\t\\[py-indent-region]\t reindent region to match its context
2667\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2668\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2669
2670Unlike most programming languages, Python uses indentation, and only
2671indentation, to specify block structure. Hence the indentation supplied
2672automatically by Python-mode is just an educated guess: only you know
2673the block structure you intend, so only you can supply correct
2674indentation.
2675
2676The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2677the indentation of preceding statements. E.g., assuming
2678py-indent-offset is 4, after you enter
2679\tif a > 0: \\[py-newline-and-indent]
2680the cursor will be moved to the position of the `_' (_ is not a
2681character in the file, it's just used here to indicate the location of
2682the cursor):
2683\tif a > 0:
2684\t _
2685If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2686to
2687\tif a > 0:
2688\t c = d
2689\t _
2690Python-mode cannot know whether that's what you intended, or whether
2691\tif a > 0:
2692\t c = d
2693\t_
2694was your intent. In general, Python-mode either reproduces the
2695indentation of the (closest code or indenting-comment) preceding
2696statement, or adds an extra py-indent-offset blanks if the preceding
2697statement has `:' as its last significant (non-whitespace and non-
2698comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002699\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002700
2701Continuation lines are given extra indentation. If you don't like the
2702suggested indentation, change it to something you do like, and Python-
2703mode will strive to indent later lines of the statement in the same way.
2704
2705If a line is a continuation line by virtue of being in an unclosed
2706paren/bracket/brace structure (`list', for short), the suggested
2707indentation depends on whether the current line contains the first item
2708in the list. If it does, it's indented py-indent-offset columns beyond
2709the indentation of the line containing the open bracket. If you don't
2710like that, change it by hand. The remaining items in the list will mimic
2711whatever indentation you give to the first item.
2712
2713If a line is a continuation line because the line preceding it ends with
2714a backslash, the third and following lines of the statement inherit their
2715indentation from the line preceding them. The indentation of the second
2716line in the statement depends on the form of the first (base) line: if
2717the base line is an assignment statement with anything more interesting
2718than the backslash following the leftmost assigning `=', the second line
2719is indented two columns beyond that `='. Else it's indented to two
2720columns beyond the leftmost solid chunk of non-whitespace characters on
2721the base line.
2722
2723Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2724repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2725structure you intend.
2726%c:indent-for-tab-command
2727%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002728%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002729
2730
2731The next function may be handy when editing code you didn't write:
2732%c:py-guess-indent-offset
2733
2734
2735The remaining `indent' functions apply to a region of Python code. They
2736assume the block structure (equals indentation, in Python) of the region
2737is correct, and alter the indentation in various ways while preserving
2738the block structure:
2739%c:py-indent-region
2740%c:py-shift-region-left
2741%c:py-shift-region-right
2742
2743@MARKING & MANIPULATING REGIONS OF CODE
2744
2745\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002746\\[py-mark-def-or-class]\t mark smallest enclosing def
2747\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002748\\[comment-region]\t comment out region of code
2749\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002750%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002751%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002752%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002753
2754@MOVING POINT
2755
2756\\[py-previous-statement]\t move to statement preceding point
2757\\[py-next-statement]\t move to statement following point
2758\\[py-goto-block-up]\t move up to start of current block
Barry Warsawab0e86c1998-05-19 15:31:46 +00002759\\[py-beginning-of-def-or-class]\t move to start of def
2760\\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
2761\\[py-end-of-def-or-class]\t move to end of def
2762\\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002763
2764The first two move to one statement beyond the statement that contains
2765point. A numeric prefix argument tells them to move that many
2766statements instead. Blank lines, comment lines, and continuation lines
2767do not count as `statements' for these commands. So, e.g., you can go
2768to the first code statement in a file by entering
2769\t\\[beginning-of-buffer]\t to move to the top of the file
2770\t\\[py-next-statement]\t to skip over initial comments and blank lines
2771Or do `\\[py-previous-statement]' with a huge prefix argument.
2772%c:py-previous-statement
2773%c:py-next-statement
2774%c:py-goto-block-up
Barry Warsawab0e86c1998-05-19 15:31:46 +00002775%c:py-beginning-of-def-or-class
2776%c:py-end-of-def-or-class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002777
2778@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2779
2780`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2781
2782`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2783overall class and def structure of a module.
2784
2785`\\[back-to-indentation]' moves point to a line's first non-blank character.
2786
2787`\\[indent-relative]' is handy for creating odd indentation.
2788
2789@OTHER EMACS HINTS
2790
2791If you don't like the default value of a variable, change its value to
2792whatever you do like by putting a `setq' line in your .emacs file.
2793E.g., to set the indentation increment to 4, put this line in your
2794.emacs:
2795\t(setq py-indent-offset 4)
2796To see the value of a variable, do `\\[describe-variable]' and enter the variable
2797name at the prompt.
2798
2799When entering a key sequence like `C-c C-n', it is not necessary to
2800release the CONTROL key after doing the `C-c' part -- it suffices to
2801press the CONTROL key, press and release `c' (while still holding down
2802CONTROL), press and release `n' (while still holding down CONTROL), &
2803then release CONTROL.
2804
2805Entering Python mode calls with no arguments the value of the variable
2806`python-mode-hook', if that value exists and is not nil; for backward
2807compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2808the Elisp manual for details.
2809
2810Obscure: When python-mode is first loaded, it looks for all bindings
2811to newline-and-indent in the global keymap, and shadows them with
2812local bindings to py-newline-and-indent."))
2813
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002814
2815;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002816(defvar py-parse-state-re
2817 (concat
2818 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2819 "\\|"
2820 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002821
Barry Warsaw7ae77681994-12-12 20:38:05 +00002822(defun py-parse-state ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002823 "Return the parse state at point (see `parse-partial-sexp' docs)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002824 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002825 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002826 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002827 (while (not done)
2828 ;; back up to the first preceding line (if any; else start of
2829 ;; buffer) that begins with a popular Python keyword, or a
2830 ;; non- whitespace and non-comment character. These are good
2831 ;; places to start parsing to see whether where we started is
2832 ;; at a non-zero nesting level. It may be slow for people who
2833 ;; write huge code blocks or huge lists ... tough beans.
2834 (re-search-backward py-parse-state-re nil 'move)
2835 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002836 ;; In XEmacs, we have a much better way to test for whether
2837 ;; we're in a triple-quoted string or not. Emacs does not
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002838 ;; have this built-in function, which is its loss because
Barry Warsawf64b4051998-02-12 16:52:14 +00002839 ;; without scanning from the beginning of the buffer, there's
2840 ;; no accurate way to determine this otherwise.
2841 (if (not (fboundp 'buffer-syntactic-context))
2842 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002843 (progn
2844 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002845 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002846 (setq done (or (not (nth 3 pps))
2847 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002848 ;; XEmacs
2849 (setq done (or (not (buffer-syntactic-context))
2850 (bobp)))
2851 (when done
2852 (setq pps (parse-partial-sexp (point) here)))
2853 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002854 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002855
Barry Warsaw7ae77681994-12-12 20:38:05 +00002856(defun py-nesting-level ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002857 "Return the buffer position of the last unclosed enclosing list.
2858If nesting level is zero, return nil."
Barry Warsawf64b4051998-02-12 16:52:14 +00002859 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002860 (if (zerop (car status))
2861 nil ; not in a nest
2862 (car (cdr status))))) ; char# of open bracket
2863
Barry Warsaw7ae77681994-12-12 20:38:05 +00002864(defun py-backslash-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002865 "Return t iff preceding line ends with backslash that is not in a comment."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002866 (save-excursion
2867 (beginning-of-line)
2868 (and
2869 ;; use a cheap test first to avoid the regexp if possible
2870 ;; use 'eq' because char-after may return nil
2871 (eq (char-after (- (point) 2)) ?\\ )
2872 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002873 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002874 (looking-at py-continued-re))))
2875
Barry Warsaw7ae77681994-12-12 20:38:05 +00002876(defun py-continuation-line-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002877 "Return t iff current line is a continuation line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002878 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002879 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002880 (or (py-backslash-continuation-line-p)
2881 (py-nesting-level))))
2882
Barry Warsaw7ae77681994-12-12 20:38:05 +00002883(defun py-goto-initial-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002884 "Go to the initial line of the current statement.
2885Usually this is the line we're on, but if we're on the 2nd or
2886following lines of a continuation block, we need to go up to the first
2887line of the block."
2888 ;; Tricky: We want to avoid quadratic-time behavior for long
2889 ;; continued blocks, whether of the backslash or open-bracket
2890 ;; varieties, or a mix of the two. The following manages to do that
2891 ;; in the usual cases.
2892 ;;
2893 ;; Also, if we're sitting inside a triple quoted string, this will
2894 ;; drop us at the line that begins the string.
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002895 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002896 (while (py-continuation-line-p)
2897 (beginning-of-line)
2898 (if (py-backslash-continuation-line-p)
2899 (while (py-backslash-continuation-line-p)
2900 (forward-line -1))
2901 ;; else zip out of nested brackets/braces/parens
2902 (while (setq open-bracket-pos (py-nesting-level))
2903 (goto-char open-bracket-pos)))))
2904 (beginning-of-line))
2905
Barry Warsaw7ae77681994-12-12 20:38:05 +00002906(defun py-goto-beyond-final-line ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002907 "Go to the point just beyond the fine line of the current statement.
2908Usually this is the start of the next line, but if this is a
2909multi-line statement we need to skip over the continuation lines."
2910 ;; Tricky: Again we need to be clever to avoid quadratic time
2911 ;; behavior.
2912 ;;
2913 ;; XXX: Not quite the right solution, but deals with multi-line doc
2914 ;; strings
Barry Warsaw751f4931998-05-19 16:06:21 +00002915 (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
2916 (goto-char (match-end 0)))
2917 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +00002918 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002919 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002920 (while (and (py-continuation-line-p)
2921 (not (eobp)))
2922 ;; skip over the backslash flavor
2923 (while (and (py-backslash-continuation-line-p)
2924 (not (eobp)))
2925 (forward-line 1))
2926 ;; if in nest, zip to the end of the nest
2927 (setq state (py-parse-state))
2928 (if (and (not (zerop (car state)))
2929 (not (eobp)))
2930 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002931 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002932 (forward-line 1))))))
2933
Barry Warsaw7ae77681994-12-12 20:38:05 +00002934(defun py-statement-opens-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002935 "Return t iff the current statement opens a block.
2936I.e., iff it ends with a colon that is not in a comment. Point should
2937be at the start of a statement."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002938 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002939 (let ((start (point))
2940 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2941 (searching t)
2942 (answer nil)
2943 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002944 (goto-char start)
2945 (while searching
2946 ;; look for a colon with nothing after it except whitespace, and
2947 ;; maybe a comment
2948 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2949 finish t)
2950 (if (eq (point) finish) ; note: no `else' clause; just
2951 ; keep searching if we're not at
2952 ; the end yet
2953 ;; sure looks like it opens a block -- but it might
2954 ;; be in a comment
2955 (progn
2956 (setq searching nil) ; search is done either way
2957 (setq state (parse-partial-sexp start
2958 (match-beginning 0)))
2959 (setq answer (not (nth 4 state)))))
2960 ;; search failed: couldn't find another interesting colon
2961 (setq searching nil)))
2962 answer)))
2963
Barry Warsawf831d811996-07-31 20:42:59 +00002964(defun py-statement-closes-block-p ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002965 "Return t iff the current statement closes a block.
2966I.e., if the line starts with `return', `raise', `break', `continue',
2967and `pass'. This doesn't catch embedded statements."
Barry Warsawf831d811996-07-31 20:42:59 +00002968 (let ((here (point)))
2969 (back-to-indentation)
2970 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002971 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002972 (goto-char here))))
2973
Barry Warsaw7ae77681994-12-12 20:38:05 +00002974(defun py-goto-beyond-block ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002975 "Go to point just beyond the final line of block begun by the current line.
2976This is the same as where `py-goto-beyond-final-line' goes unless
2977we're on colon line, in which case we go to the end of the block.
2978Assumes point is at the beginning of the line."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002979 (if (py-statement-opens-block-p)
2980 (py-mark-block nil 'just-move)
2981 (py-goto-beyond-final-line)))
2982
Barry Warsaw7ae77681994-12-12 20:38:05 +00002983(defun py-goto-statement-at-or-above ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002984 "Go to the start of the first statement at or preceding point.
2985Return t if there is such a statement, otherwise nil. `Statement'
2986does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002987 (py-goto-initial-line)
2988 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002989 ;; skip back over blank & comment lines
2990 ;; note: will skip a blank or comment line that happens to be
2991 ;; a continuation line too
2992 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2993 (progn (py-goto-initial-line) t)
2994 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002995 t))
2996
Barry Warsaw7ae77681994-12-12 20:38:05 +00002997(defun py-goto-statement-below ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00002998 "Go to start of the first statement following the statement containing point.
2999Return t if there is such a statement, otherwise nil. `Statement'
3000does not include blank lines, comments, or continuation lines."
Barry Warsaw7ae77681994-12-12 20:38:05 +00003001 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003002 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00003003 (py-goto-beyond-final-line)
3004 (while (and
3005 (looking-at py-blank-or-comment-re)
3006 (not (eobp)))
3007 (forward-line 1))
3008 (if (eobp)
3009 (progn (goto-char start) nil)
3010 t)))
3011
Barry Warsaw7ae77681994-12-12 20:38:05 +00003012(defun py-go-up-tree-to-keyword (key)
Barry Warsaw41a05c71998-08-10 16:33:12 +00003013 "Go to begining of statement starting with KEY, at or preceding point.
3014
3015KEY is a regular expression describing a Python keyword. Skip blank
3016lines and non-indenting comments. If the statement found starts with
3017KEY, then stop, otherwise go back to first enclosing block starting
3018with KEY. If successful, leave point at the start of the KEY line and
3019return t. Otherwise, leav point at an undefined place and return nil."
Barry Warsaw7ae77681994-12-12 20:38:05 +00003020 ;; skip blanks and non-indenting #
3021 (py-goto-initial-line)
3022 (while (and
3023 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
3024 (zerop (forward-line -1))) ; go back
3025 nil)
3026 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003027 (let* ((re (concat "[ \t]*" key "\\b"))
3028 (case-fold-search nil) ; let* so looking-at sees this
3029 (found (looking-at re))
3030 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00003031 (while (not (or found dead))
3032 (condition-case nil ; in case no enclosing block
3033 (py-goto-block-up 'no-mark)
3034 (error (setq dead t)))
3035 (or dead (setq found (looking-at re))))
3036 (beginning-of-line)
3037 found))
3038
Barry Warsaw7ae77681994-12-12 20:38:05 +00003039(defun py-suck-up-leading-text ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003040 "Return string in buffer from start of indentation to end of line.
3041Prefix with \"...\" if leading whitespace was skipped."
Barry Warsaw7ae77681994-12-12 20:38:05 +00003042 (save-excursion
3043 (back-to-indentation)
3044 (concat
3045 (if (bolp) "" "...")
3046 (buffer-substring (point) (progn (end-of-line) (point))))))
3047
Barry Warsaw7ae77681994-12-12 20:38:05 +00003048(defun py-suck-up-first-keyword ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003049 "Return first keyword on the line as a Lisp symbol.
3050`Keyword' is defined (essentially) as the regular expression
3051([a-z]+). Returns nil if none was found."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003052 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00003053 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
3054 (intern (buffer-substring (match-beginning 1) (match-end 1)))
3055 nil)))
3056
Barry Warsawb3e81d51996-09-04 15:12:42 +00003057(defun py-current-defun ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003058 "Python value for `add-log-current-defun-function'.
3059This tells add-log.el how to find the current function/method/variable."
Barry Warsawb3e81d51996-09-04 15:12:42 +00003060 (save-excursion
3061 (if (re-search-backward py-defun-start-re nil t)
3062 (or (match-string 3)
3063 (let ((method (match-string 2)))
3064 (if (and (not (zerop (length (match-string 1))))
3065 (re-search-backward py-class-start-re nil t))
3066 (concat (match-string 1) "." method)
3067 method)))
3068 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003069
3070
Barry Warsawfec75d61995-07-05 23:26:15 +00003071(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00003072 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003073
Barry Warsaw850437a1995-03-08 21:50:28 +00003074(defun py-version ()
3075 "Echo the current version of `python-mode' in the minibuffer."
3076 (interactive)
3077 (message "Using `python-mode' version %s" py-version)
3078 (py-keep-region-active))
3079
3080;; only works under Emacs 19
3081;(eval-when-compile
3082; (require 'reporter))
3083
3084(defun py-submit-bug-report (enhancement-p)
3085 "Submit via mail a bug report on `python-mode'.
Barry Warsaw41a05c71998-08-10 16:33:12 +00003086With \\[universal-argument] (programmatically, argument ENHANCEMENT-P
3087non-nil) just submit an enhancement request."
Barry Warsaw850437a1995-03-08 21:50:28 +00003088 (interactive
3089 (list (not (y-or-n-p
Barry Warsaw41a05c71998-08-10 16:33:12 +00003090 "Is this a bug report (hit `n' to send other comments)? "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00003091 (let ((reporter-prompt-for-summary-p (if enhancement-p
3092 "(Very) brief summary: "
3093 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00003094 (require 'reporter)
3095 (reporter-submit-bug-report
3096 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00003097 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00003098 ;; varlist
3099 (if enhancement-p nil
3100 '(py-python-command
3101 py-indent-offset
3102 py-block-comment-prefix
3103 py-scroll-process-buffer
3104 py-temp-directory
3105 py-beep-if-tab-change))
3106 nil ;pre-hooks
3107 nil ;post-hooks
3108 "Dear Barry,") ;salutation
3109 (if enhancement-p nil
3110 (set-mark (point))
3111 (insert
3112"Please replace this text with a sufficiently large code sample\n\
3113and an exact recipe so that I can reproduce your problem. Failure\n\
3114to do so may mean a greater delay in fixing your bug.\n\n")
3115 (exchange-point-and-mark)
3116 (py-keep-region-active))))
3117
3118
Barry Warsaw47384781997-11-26 05:27:45 +00003119(defun py-kill-emacs-hook ()
Barry Warsaw41a05c71998-08-10 16:33:12 +00003120 "Delete files in `py-file-queue'.
3121These are Python temporary files awaiting execution."
Barry Warsaw47384781997-11-26 05:27:45 +00003122 (mapcar #'(lambda (filename)
3123 (py-safe (delete-file filename)))
3124 py-file-queue))
3125
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003126;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00003127(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003128
3129
3130
3131(provide 'python-mode)
3132;;; python-mode.el ends here