blob: 0159d2dcc9477419e45e3022efe925135620cfb6 [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Barry Warsawf64b4051998-02-12 16:52:14 +00005;; Author: 1995-1998 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
Barry Warsawa97a3f31997-11-04 18:47:06 +00007;; Maintainer: python-mode@python.org
8;; Created: Feb 1992
9;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000010
Barry Warsaw5204b4a1998-04-02 19:27:18 +000011(defconst py-version "$Revision$"
Barry Warsawc72c11c1997-08-09 06:42:08 +000012 "`python-mode' version number.")
13
Barry Warsawcfec3591995-03-10 15:58:16 +000014;; This software is provided as-is, without express or implied
15;; warranty. Permission to use, copy, modify, distribute or sell this
16;; software, without fee, for any purpose and by any individual or
17;; organization, is hereby granted, provided that the above copyright
18;; notice and this paragraph appear in all copies.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000019
20;;; Commentary:
Barry Warsaw755c6711996-08-01 20:02:55 +000021
Barry Warsaw7b0f5681995-03-08 21:33:04 +000022;; This is a major mode for editing Python programs. It was developed
Barry Warsaw261f87d1996-08-20 19:57:34 +000023;; by Tim Peters after an original idea by Michael A. Guravage. Tim
24;; subsequently left the net; in 1995, Barry Warsaw inherited the
25;; mode and is the current maintainer.
Barry Warsaw7b0f5681995-03-08 21:33:04 +000026
Barry Warsaw37231521997-12-11 17:23:13 +000027;; COMPATIBILITY:
Barry Warsaw7b0f5681995-03-08 21:33:04 +000028
Barry Warsaw37231521997-12-11 17:23:13 +000029;; This version of python-mode.el is no longer compatible with Emacs
30;; 18. For a gabazillion reasons, I highly recommend upgrading to
31;; X/Emacs 19 or X/Emacs 20. I recommend at least Emacs 19.34 or
32;; XEmacs 19.15. Any of the v20 X/Emacsen should be fine.
Barry Warsaw673d05f1997-12-02 21:51:57 +000033
Barry Warsaw37231521997-12-11 17:23:13 +000034;; NOTE TO FSF EMACS USERS:
35
36;; You may need to acquire the Custom library -- this applies to users
37;; of Emacs 19.34 and NTEmacs based on 19.34, but not to Emacs 20
38;; users. You must also byte-compile this file before use -- this
39;; applies to FSF's Emacs 19.34, 20.x, and NTEmacs based on 19.34.
40;; None of this applies to XEmacs (although byte compilation is still
41;; recommended). You will also need to add the following to your
42;; .emacs file so that the .py files come up in python-mode:
Barry Warsaw7ae77681994-12-12 20:38:05 +000043;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000044;; (autoload 'python-mode "python-mode" "Python editing mode." t)
45;; (setq auto-mode-alist
46;; (cons '("\\.py$" . python-mode) auto-mode-alist))
47;; (setq interpreter-mode-alist
48;; (cons '("python" . python-mode) interpreter-mode-alist))
Barry Warsaw44b72201996-07-05 20:11:35 +000049;;
Barry Warsawaffc0ca1997-11-03 16:59:38 +000050;; Assuming python-mode.el is on your load-path, it will be invoked
51;; when you visit a .py file, or a file with a first line that looks
52;; like:
53;;
54;; #! /usr/bin/env python
55
Barry Warsaw37231521997-12-11 17:23:13 +000056;; NOTE TO XEMACS USERS:
57
58;; An older version of this file was distributed with XEmacs 19.15,
59;; 19.16 and 20.3. By default, in XEmacs when you visit a .py file,
60;; the buffer is put in Python mode. Likewise for executable scripts
61;; with the word `python' on the first line. You shouldn't need to do
62;; much except make sure this new version is earlier in your
63;; load-path, and byte-compile this file.
64
65;; FOR MORE INFORMATION:
66
Barry Warsaw145ab1c1998-05-19 14:49:49 +000067;; Please see <http://www.python.org/emacs/python-mode/> for the
Barry Warsaw37231521997-12-11 17:23:13 +000068;; latest information and compatibility notes.
69
70;; BUG REPORTING:
Barry Warsaw7ae77681994-12-12 20:38:05 +000071
Barry Warsawaffc0ca1997-11-03 16:59:38 +000072;; To submit bug reports, use C-c C-b. Please include a complete, but
73;; concise code sample and a recipe for reproducing the bug. Send
74;; suggestions and other comments to python-mode@python.org.
75
76;; When in a Python mode buffer, do a C-h m for more help. It's
Barry Warsaw37231521997-12-11 17:23:13 +000077;; doubtful that a texinfo manual would be very useful, but if you
78;; want to contribute one, I'll certainly accept it!
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000079
Barry Warsaw5ea20d51997-12-06 00:00:47 +000080;; If you are using XEmacs, you may also want to check out OO-Browser
81;; that comes bundled with it, including documentation in the info
82;; pages. For GNU Emacs you have to install it yourself. To read
83;; more about OO-Browser, follow these links:
84
85;; http://www.python.org/workshops/1996-06/papers/h.pasanen/oobr_contents.html
86;; http://www.infodock.com/manuals/alt-oobr-cover.html
87
Barry Warsaw37231521997-12-11 17:23:13 +000088;; You may also want to take a look at Harri Pasanen's "Python Library
89;; Reference Hot-Key Help System for XEmacs (or PLRHKHSX for short ;),
90;; version 1.0"
Barry Warsaw7b0f5681995-03-08 21:33:04 +000091;;
Barry Warsaw37231521997-12-11 17:23:13 +000092;; <http://www.iki.fi/hpa/>
93
94;; TO DO LIST:
95
96;; - Better integration with pdb.py and gud-mode for debugging.
Barry Warsawb5e0ecb1995-03-14 18:32:54 +000097;; - Rewrite according to GNU Emacs Lisp standards.
Barry Warsaw5c0d00f1996-07-31 21:30:21 +000098;; - possibly force indent-tabs-mode == nil, and add a
99;; write-file-hooks that runs untabify on the whole buffer (to work
100;; around potential tab/space mismatch problems). In practice this
101;; hasn't been a problem... yet.
Barry Warsaw9e277db1996-07-31 22:33:40 +0000102;; - have py-execute-region on indented code act as if the region is
Barry Warsaw37231521997-12-11 17:23:13 +0000103;; left justified. Avoids syntax errors.
104;; - add a py-goto-block-down, bound to C-c C-d
Barry Warsaw7ae77681994-12-12 20:38:05 +0000105
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000106;;; Code:
107
Barry Warsawc72c11c1997-08-09 06:42:08 +0000108(require 'custom)
Barry Warsaw8529ebb1997-12-01 20:03:12 +0000109(eval-when-compile
Barry Warsaw673d05f1997-12-02 21:51:57 +0000110 (require 'cl)
Barry Warsawb6c1f1f1998-03-19 22:33:06 +0000111 (if (not (and (condition-case nil
112 (require 'custom)
113 (error nil))
114 ;; Stock Emacs 19.34 has a broken/old Custom library
115 ;; that does more harm than good. Fortunately, it is
116 ;; missing defcustom
117 (fboundp 'defcustom)))
Barry Warsaw673d05f1997-12-02 21:51:57 +0000118 (error "STOP! STOP! STOP! STOP!
119
120The Custom library was not found or is out of date. A more current
121version is required. Please download and install the latest version
122of the Custom library from:
123
124 <http://www.dina.kvl.dk/~abraham/custom/>
125
126See the Python Mode home page for details:
127
128 <http://www.python.org/ftp/emacs/>
129")))
130
Barry Warsawc72c11c1997-08-09 06:42:08 +0000131
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000132
133;; user definable variables
134;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000135
Barry Warsawc72c11c1997-08-09 06:42:08 +0000136(defgroup python nil
137 "Support for the Python programming language, <http://www.python.org/>"
138 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000139
Barry Warsawc72c11c1997-08-09 06:42:08 +0000140(defcustom py-python-command "python"
141 "*Shell command used to start Python interpreter."
142 :type 'string
143 :group 'python)
144
Barry Warsawa2398801998-04-09 23:28:20 +0000145(defcustom py-jpython-command "jpython"
146 "*Shell command used to start the JPython interpreter."
147 :type 'string
148 :group 'python)
149
Barry Warsaw8f972b71998-02-05 20:45:49 +0000150(defcustom py-python-command-args '("-i")
151 "*List of string arguments to be used when starting a Python shell."
152 :type '(repeat string)
153 :group 'python)
154
Barry Warsawa2398801998-04-09 23:28:20 +0000155(defcustom py-jpython-command-args '("-i")
156 "*List of string arguments to be used when starting a JPython shell."
157 :type '(repeat string)
158 :group 'python)
159
Barry Warsawc72c11c1997-08-09 06:42:08 +0000160(defcustom py-indent-offset 4
161 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000162Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +0000163when you're editing someone else's Python code."
164 :type 'integer
165 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000166
Barry Warsaw742a5111998-03-13 17:29:15 +0000167(defcustom py-smart-indentation t
168 "*Should `python-mode' try to automagically set some indentation variables?
169When this variable is non-nil, two things happen when a buffer is set
170to `python-mode':
171
172 1. `py-indent-offset' is guess from existing code in the buffer.
Barry Warsaw639eea61998-03-16 18:12:13 +0000173 Only guessed values between 2 and 8 are considered. If a valid
Barry Warsaw742a5111998-03-13 17:29:15 +0000174 guess can't be made (perhaps because you are visiting a new
Barry Warsaw639eea61998-03-16 18:12:13 +0000175 file), then the value in `py-indent-offset' is used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000176
Barry Warsaw639eea61998-03-16 18:12:13 +0000177 2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
178 equal `tab-width' (`indent-tabs-mode' is never turned on by
179 Python mode). This means that for newly written code, tabs are
180 only inserted in indentation if one tab is one indentation
181 level, otherwise only spaces are used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000182
Barry Warsaw8046bef1998-03-13 20:04:52 +0000183Note that both these settings occur *after* `python-mode-hook' is run,
184so if you want to defeat the automagic configuration, you must also
185set `py-smart-indentation' to nil in your `python-mode-hook'."
Barry Warsaw742a5111998-03-13 17:29:15 +0000186 :type 'boolean
187 :group 'python)
188
Barry Warsawc72c11c1997-08-09 06:42:08 +0000189(defcustom py-align-multiline-strings-p t
190 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000191When this flag is non-nil, continuation lines are lined up under the
192preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000193lines are aligned to column zero."
194 :type '(choice (const :tag "Align under preceding line" t)
195 (const :tag "Align to column zero" nil))
196 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000197
Barry Warsawc72c11c1997-08-09 06:42:08 +0000198(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000199 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000200This should follow the convention for non-indenting comment lines so
201that the indentation commands won't get confused (i.e., the string
202should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000203`...' is arbitrary)."
204 :type 'string
205 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000206
Barry Warsawc72c11c1997-08-09 06:42:08 +0000207(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000208 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000209
Barry Warsaw6d627751996-03-06 18:41:38 +0000210When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000211if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000212
213When t, lines that begin with a single `#' are a hint to subsequent
214line indentation. If the previous line is such a comment line (as
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000215opposed to one that starts with `py-block-comment-prefix'), then its
Barry Warsaw6d627751996-03-06 18:41:38 +0000216indentation is used as a hint for this line's indentation. Lines that
217begin with `py-block-comment-prefix' are ignored for indentation
218purposes.
219
220When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000221indentation hints, unless the comment character is in column zero."
222 :type '(choice
223 (const :tag "Skip all comment lines (fast)" nil)
224 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000225 (const :tag "Single # `sets' indentation except at column zero"
226 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000227 )
228 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000229
Barry Warsaw8ee4a601998-02-06 16:01:52 +0000230(defcustom py-scroll-process-buffer nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000231 "*Scroll Python process buffer as output arrives.
232If nil, the Python process buffer acts, with respect to scrolling, like
233Shell-mode buffers normally act. This is surprisingly complicated and
234so won't be explained here; in fact, you can't get the whole story
235without studying the Emacs C code.
236
237If non-nil, the behavior is different in two respects (which are
238slightly inaccurate in the interest of brevity):
239
240 - If the buffer is in a window, and you left point at its end, the
241 window will scroll as new output arrives, and point will move to the
242 buffer's end, even if the window is not the selected window (that
243 being the one the cursor is in). The usual behavior for shell-mode
244 windows is not to scroll, and to leave point where it was, if the
245 buffer is in a window other than the selected window.
246
247 - If the buffer is not visible in any window, and you left point at
248 its end, the buffer will be popped into a window as soon as more
249 output arrives. This is handy if you have a long-running
250 computation and don't want to tie up screen area waiting for the
251 output. The usual behavior for a shell-mode buffer is to stay
252 invisible until you explicitly visit it.
253
254Note the `and if you left point at its end' clauses in both of the
255above: you can `turn off' the special behaviors while output is in
256progress, by visiting the Python buffer and moving point to anywhere
257besides the end. Then the buffer won't scroll, point will remain where
258you leave it, and if you hide the buffer it will stay hidden until you
259visit it again. You can enable and disable the special behaviors as
260often as you like, while output is in progress, by (respectively) moving
261point to, or away from, the end of the buffer.
262
263Warning: If you expect a large amount of output, you'll probably be
264happier setting this option to nil.
265
266Obscure: `End of buffer' above should really say `at or beyond the
267process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000268told <grin>."
269 :type 'boolean
270 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000271
Barry Warsaw516b6201997-08-09 06:43:20 +0000272(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000273 (let ((ok '(lambda (x)
274 (and x
275 (setq x (expand-file-name x)) ; always true
276 (file-directory-p x)
277 (file-writable-p x)
278 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000279 (or (funcall ok (getenv "TMPDIR"))
280 (funcall ok "/usr/tmp")
281 (funcall ok "/tmp")
282 (funcall ok ".")
283 (error
Barry Warsaw6c6db0a1998-02-25 16:33:56 +0000284 "Couldn't find a usable temp directory -- set `py-temp-directory'")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000285 "*Directory used for temp files created by a *Python* process.
286By default, the first directory from this list that exists and that you
287can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000288/usr/tmp, /tmp, or the current directory."
289 :type 'string
290 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000291
Barry Warsaw516b6201997-08-09 06:43:20 +0000292(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000293 "*Ring the bell if tab-width is changed.
294If a comment of the form
295
296 \t# vi:set tabsize=<number>:
297
298is found before the first code line when the file is entered, and the
299current value of (the general Emacs variable) `tab-width' does not
300equal <number>, `tab-width' is set to <number>, a message saying so is
301displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000302the Emacs bell is also rung as a warning."
303 :type 'boolean
304 :group 'python)
305
Barry Warsaw9981d221997-12-03 05:25:48 +0000306(defcustom py-jump-on-exception t
307 "*Jump to innermost exception frame in *Python Output* buffer.
308When this variable is non-nil and ane exception occurs when running
309Python code synchronously in a subprocess, jump immediately to the
310source code of the innermost frame.")
311
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000312(defcustom py-backspace-function 'backward-delete-char-untabify
313 "*Function called by `py-electric-backspace' when deleting backwards."
314 :type 'function
315 :group 'python)
316
317(defcustom py-delete-function 'delete-char
318 "*Function called by `py-electric-delete' when deleting forwards."
319 :type 'function
320 :group 'python)
321
Barry Warsawc0ecb531998-01-20 21:43:34 +0000322;; Not customizable
323(defvar py-master-file nil
324 "If non-nil, execute the named file instead of the buffer's file.
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000325The intent is to allow you to set this variable in the file's local
Barry Warsawc0ecb531998-01-20 21:43:34 +0000326variable section, e.g.:
327
328 # Local Variables:
329 # py-master-file: \"master.py\"
330 # End:
331
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000332so that typing \\[py-execute-buffer] in that buffer executes the
Barry Warsawc0ecb531998-01-20 21:43:34 +0000333named master file instead of the buffer's file. Note that if the file
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000334name has a relative path, the `default-directory' for the buffer is
335prepended to come up with a file name.")
Barry Warsawc0ecb531998-01-20 21:43:34 +0000336(make-variable-buffer-local 'py-master-file)
337
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000338
Barry Warsawc72c11c1997-08-09 06:42:08 +0000339
340;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
341;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
342
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000343(defconst py-emacs-features
344 (let (features)
345 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
346 ;; the same string.
347 (let ((tmp1 (make-temp-name ""))
348 (tmp2 (make-temp-name "")))
349 (if (string-equal tmp1 tmp2)
350 (push 'broken-temp-names features)))
351 ;; return the features
352 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000353 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000354There are many flavors of Emacs out there, with different levels of
355support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000356
Barry Warsawfb07f401997-02-24 03:37:22 +0000357(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000358 (let ((kw1 (mapconcat 'identity
359 '("and" "assert" "break" "class"
360 "continue" "def" "del" "elif"
361 "else" "except" "exec" "for"
362 "from" "global" "if" "import"
363 "in" "is" "lambda" "not"
364 "or" "pass" "print" "raise"
365 "return" "while"
366 )
367 "\\|"))
368 (kw2 (mapconcat 'identity
369 '("else:" "except:" "finally:" "try:")
370 "\\|"))
371 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000372 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000373 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000374 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
375 ;; block introducing keywords with immediately following colons.
376 ;; Yes "except" is in both lists.
377 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000378 ;; classes
379 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
380 1 font-lock-type-face)
381 ;; functions
382 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
383 1 font-lock-function-name-face)
384 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000385 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000386(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
387
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000388
Barry Warsaw81437461996-08-01 19:48:02 +0000389(defvar imenu-example--python-show-method-args-p nil
390 "*Controls echoing of arguments of functions & methods in the imenu buffer.
391When non-nil, arguments are printed.")
392
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000393(make-variable-buffer-local 'py-indent-offset)
394
Barry Warsawe467bfb1997-11-26 05:40:58 +0000395;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000396(defvar py-file-queue nil
397 "Queue of Python temp files awaiting execution.
398Currently-active file is at the head of the list.")
399
Barry Warsawc72c11c1997-08-09 06:42:08 +0000400
401;; Constants
402
403;; Regexp matching a Python string literal
404(defconst py-stringlit-re
405 (concat
406 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
407 "\\|" ; or
408 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
409
410;; Regexp matching Python lines that are continued via backslash.
411;; This is tricky because a trailing backslash does not mean
412;; continuation if it's in a comment
413(defconst py-continued-re
414 (concat
415 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
416 "\\\\$"))
417
418;; Regexp matching blank or comment lines.
419(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
420
421;; Regexp matching clauses to be outdented one level.
422(defconst py-outdent-re
423 (concat "\\(" (mapconcat 'identity
424 '("else:"
425 "except\\(\\s +.*\\)?:"
426 "finally:"
427 "elif\\s +.*:")
428 "\\|")
429 "\\)"))
430
431
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000432;; Regexp matching keywords which typically close a block
433(defconst py-block-closing-keywords-re
434 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
435
Barry Warsawc72c11c1997-08-09 06:42:08 +0000436;; Regexp matching lines to not outdent after.
437(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000438 (concat
439 "\\("
440 (mapconcat 'identity
441 (list "try:"
442 "except\\(\\s +.*\\)?:"
443 "while\\s +.*:"
444 "for\\s +.*:"
445 "if\\s +.*:"
446 "elif\\s +.*:"
447 (concat py-block-closing-keywords-re "[ \t\n]")
448 )
449 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000450 "\\)"))
451
452;; Regexp matching a function, method or variable assignment. If you
453;; change this, you probably have to change `py-current-defun' as
454;; well. This is only used by `py-current-defun' to find the name for
455;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000456(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000457 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
458
459;; Regexp for finding a class name. If you change this, you probably
460;; have to change `py-current-defun' as well. This is only used by
461;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000462(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
463
464;; Regexp that describes tracebacks
465(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000466 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000467
468
469
470;; Utilities
471
472(defmacro py-safe (&rest body)
473 ;; safely execute BODY, return nil if an error occurred
474 (` (condition-case nil
475 (progn (,@ body))
476 (error nil))))
477
478(defsubst py-keep-region-active ()
479 ;; Do whatever is necessary to keep the region active in XEmacs.
480 ;; Ignore byte-compiler warnings you might see. Also note that
481 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
482 ;; to take explicit action.
483 (and (boundp 'zmacs-region-stays)
484 (setq zmacs-region-stays t)))
485
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000486(defsubst py-point (position)
487 ;; Returns the value of point at certain commonly referenced POSITIONs.
488 ;; POSITION can be one of the following symbols:
489 ;;
490 ;; bol -- beginning of line
491 ;; eol -- end of line
492 ;; bod -- beginning of defun
Barry Warsawab0e86c1998-05-19 15:31:46 +0000493 ;; bob -- beginning of buffer
494 ;; eob -- end of buffer
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000495 ;; boi -- back to indentation
Barry Warsawab0e86c1998-05-19 15:31:46 +0000496 ;; bos -- beginning of statement
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000497 ;;
498 ;; This function does not modify point or mark.
499 (let ((here (point)))
500 (cond
501 ((eq position 'bol) (beginning-of-line))
502 ((eq position 'eol) (end-of-line))
Barry Warsawab0e86c1998-05-19 15:31:46 +0000503 ((eq position 'bod) (py-beginning-of-def-or-class))
504 ;; Kind of funny, I know, but useful for py-up-exception.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000505 ((eq position 'bob) (beginning-of-buffer))
506 ((eq position 'eob) (end-of-buffer))
507 ((eq position 'boi) (back-to-indentation))
Barry Warsawab0e86c1998-05-19 15:31:46 +0000508 ((eq position 'bos) (py-goto-initial-line))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000509 (t (error "unknown buffer position requested: %s" position))
510 )
511 (prog1
512 (point)
513 (goto-char here))))
514
515(defsubst py-highlight-line (from to file line)
516 (cond
517 ((fboundp 'make-extent)
518 ;; XEmacs
519 (let ((e (make-extent from to)))
520 (set-extent-property e 'mouse-face 'highlight)
521 (set-extent-property e 'py-exc-info (cons file line))
522 (set-extent-property e 'keymap py-mode-output-map)))
523 (t
524 ;; Emacs -- Please port this!
525 )
526 ))
527
Barry Warsawe908b6b1998-03-19 22:48:02 +0000528(defun py-in-literal (&optional lim)
529 ;; Determine if point is in a Python literal, defined as a comment
530 ;; or string. This is the version used for non-XEmacs, which has a
531 ;; nicer interface.
532 ;;
533 ;; WARNING: Watch out for infinite recursion.
534 (let* ((lim (or lim (c-point 'bod)))
535 (state (parse-partial-sexp lim (point))))
536 (cond
537 ((nth 3 state) 'string)
538 ((nth 4 state) 'comment)
539 (t nil))))
540
541;; XEmacs has a built-in function that should make this much quicker.
542;; In this case, lim is ignored
543(defun py-fast-in-literal (&optional lim)
544 ;; don't have to worry about context == 'block-comment
545 (buffer-syntactic-context))
546
547(if (fboundp 'buffer-syntactic-context)
548 (defalias 'c-in-literal 'c-fast-in-literal))
549
550
Barry Warsawc72c11c1997-08-09 06:42:08 +0000551
552;; Major mode boilerplate
553
Barry Warsaw7ae77681994-12-12 20:38:05 +0000554;; define a mode-specific abbrev table for those who use such things
555(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000556 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000557(define-abbrev-table 'python-mode-abbrev-table nil)
558
Barry Warsaw7ae77681994-12-12 20:38:05 +0000559(defvar python-mode-hook nil
560 "*Hook called by `python-mode'.")
561
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000562;; In previous version of python-mode.el, the hook was incorrectly
563;; called py-mode-hook, and was not defvar'd. Deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000564(and (fboundp 'make-obsolete-variable)
565 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
566
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000567(defvar py-mode-map ()
568 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000569(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000570 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000571 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000572 ;; electric keys
573 (define-key py-mode-map ":" 'py-electric-colon)
574 ;; indentation level modifiers
575 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
576 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
577 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
578 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
579 ;; subprocess commands
580 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
581 (define-key py-mode-map "\C-c|" 'py-execute-region)
582 (define-key py-mode-map "\C-c!" 'py-shell)
Barry Warsawa2398801998-04-09 23:28:20 +0000583 (define-key py-mode-map "\C-c\C-t" 'py-toggle-shells)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000584 ;; Caution! Enter here at your own risk. We are trying to support
585 ;; several behaviors and it gets disgusting. :-( This logic ripped
586 ;; largely from CC Mode.
587 ;;
588 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
589 ;; backwards deletion behavior to DEL, which both Delete and
590 ;; Backspace get translated to. There's no way to separate this
591 ;; behavior in a clean way, so deal with it! Besides, it's been
592 ;; this way since the dawn of time.
593 (if (not (boundp 'delete-key-deletes-forward))
594 (define-key py-mode-map "\177" 'py-electric-backspace)
595 ;; However, XEmacs 20 actually achieved enlightenment. It is
596 ;; possible to sanely define both backward and forward deletion
597 ;; behavior under X separately (TTYs are forever beyond hope, but
598 ;; who cares? XEmacs 20 does the right thing with these too).
599 (define-key py-mode-map [delete] 'py-electric-delete)
600 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000601 ;; Separate M-BS from C-M-h. The former should remain
602 ;; backward-kill-word.
603 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000604 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000605 ;; Miscellaneous
606 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
607 (define-key py-mode-map "\C-c\t" 'py-indent-region)
608 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
609 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
610 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000611 (define-key py-mode-map "\C-c#" 'py-comment-region)
612 (define-key py-mode-map "\C-c?" 'py-describe-mode)
613 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
Barry Warsawab0e86c1998-05-19 15:31:46 +0000614 (define-key py-mode-map "\e\C-a" 'py-beginning-of-def-or-class)
615 (define-key py-mode-map "\e\C-e" 'py-end-of-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000616 (define-key py-mode-map "\C-c-" 'py-up-exception)
617 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000618 ;; information
619 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
620 (define-key py-mode-map "\C-c\C-v" 'py-version)
621 ;; py-newline-and-indent mappings
Barry Warsaw82aecb91998-01-21 05:14:24 +0000622 (define-key py-mode-map "\n" 'py-newline-and-indent)
623 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000624 ;; shadow global bindings for newline-and-indent w/ the py- version.
625 ;; BAW - this is extremely bad form, but I'm not going to change it
626 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000627 (mapcar #'(lambda (key)
628 (define-key py-mode-map key 'py-newline-and-indent))
629 (where-is-internal 'newline-and-indent))
630 )
631
632(defvar py-mode-output-map nil
633 "Keymap used in *Python Output* buffers*")
634(if py-mode-output-map
635 nil
636 (setq py-mode-output-map (make-sparse-keymap))
637 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
638 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
639 ;; TBD: Disable all self-inserting keys. This is bogus, we should
640 ;; really implement this as *Python Output* buffer being read-only
641 (mapcar #' (lambda (key)
642 (define-key py-mode-output-map key
643 #'(lambda () (interactive) (beep))))
644 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000645 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000646
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000647(defvar py-mode-syntax-table nil
648 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000649(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000650 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000651 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000652 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
653 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
654 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
655 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
656 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
657 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
658 ;; Add operator symbols misassigned in the std table
659 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
660 (modify-syntax-entry ?\% "." py-mode-syntax-table)
661 (modify-syntax-entry ?\& "." py-mode-syntax-table)
662 (modify-syntax-entry ?\* "." py-mode-syntax-table)
663 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
664 (modify-syntax-entry ?\- "." py-mode-syntax-table)
665 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
666 (modify-syntax-entry ?\< "." py-mode-syntax-table)
667 (modify-syntax-entry ?\= "." py-mode-syntax-table)
668 (modify-syntax-entry ?\> "." py-mode-syntax-table)
669 (modify-syntax-entry ?\| "." py-mode-syntax-table)
670 ;; For historical reasons, underscore is word class instead of
671 ;; symbol class. GNU conventions say it should be symbol class, but
672 ;; there's a natural conflict between what major mode authors want
673 ;; and what users expect from `forward-word' and `backward-word'.
674 ;; Guido and I have hashed this out and have decided to keep
675 ;; underscore in word class. If you're tempted to change it, try
676 ;; binding M-f and M-b to py-forward-into-nomenclature and
677 ;; py-backward-into-nomenclature instead.
678 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
679 ;; Both single quote and double quote are string delimiters
680 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
681 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
682 ;; backquote is open and close paren
683 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
684 ;; comment delimiters
685 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
686 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
687 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000688
Barry Warsawb3e81d51996-09-04 15:12:42 +0000689
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000690
Barry Warsaw42f707f1996-07-29 21:05:05 +0000691;; Menu definitions, only relevent if you have the easymenu.el package
692;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000693(defvar py-menu nil
694 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000695This menu will get created automatically if you have the `easymenu'
696package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000697
Barry Warsawc72c11c1997-08-09 06:42:08 +0000698(and (py-safe (require 'easymenu) t)
699 (easy-menu-define
700 py-menu py-mode-map "Python Mode menu"
701 '("Python"
702 ["Comment Out Region" py-comment-region (mark)]
703 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
704 "-"
705 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000706 ["Mark current def" py-mark-def-or-class t]
707 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000708 "-"
709 ["Shift region left" py-shift-region-left (mark)]
710 ["Shift region right" py-shift-region-right (mark)]
711 "-"
712 ["Execute buffer" py-execute-buffer t]
713 ["Execute region" py-execute-region (mark)]
714 ["Start interpreter..." py-shell t]
715 "-"
716 ["Go to start of block" py-goto-block-up t]
Barry Warsawab0e86c1998-05-19 15:31:46 +0000717 ["Go to start of class" (py-beginning-of-def-or-class t) t]
718 ["Move to end of class" (py-end-of-def-or-class t) t]
719 ["Move to start of def" py-beginning-of-def-or-class t]
720 ["Move to end of def" py-end-of-def-or-class t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000721 "-"
722 ["Describe mode" py-describe-mode t]
723 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000724
Barry Warsaw81437461996-08-01 19:48:02 +0000725
726
727;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
728(defvar imenu-example--python-class-regexp
729 (concat ; <<classes>>
730 "\\(" ;
731 "^[ \t]*" ; newline and maybe whitespace
732 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
733 ; possibly multiple superclasses
Barry Warsaw3179fe01998-04-04 21:36:53 +0000734 "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
Barry Warsaw81437461996-08-01 19:48:02 +0000735 "[ \t]*:" ; and the final :
736 "\\)" ; >>classes<<
737 )
738 "Regexp for Python classes for use with the imenu package."
739 )
740
741(defvar imenu-example--python-method-regexp
742 (concat ; <<methods and functions>>
743 "\\(" ;
744 "^[ \t]*" ; new line and maybe whitespace
745 "\\(def[ \t]+" ; function definitions start with def
746 "\\([a-zA-Z0-9_]+\\)" ; name is here
747 ; function arguments...
748 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
749 "\\)" ; end of def
750 "[ \t]*:" ; and then the :
751 "\\)" ; >>methods and functions<<
752 )
753 "Regexp for Python methods/functions for use with the imenu package."
754 )
755
756(defvar imenu-example--python-method-no-arg-parens '(2 8)
757 "Indicies into groups of the Python regexp for use with imenu.
758
759Using these values will result in smaller imenu lists, as arguments to
760functions are not listed.
761
762See the variable `imenu-example--python-show-method-args-p' for more
763information.")
764
765(defvar imenu-example--python-method-arg-parens '(2 7)
766 "Indicies into groups of the Python regexp for use with imenu.
767Using these values will result in large imenu lists, as arguments to
768functions are listed.
769
770See the variable `imenu-example--python-show-method-args-p' for more
771information.")
772
773;; Note that in this format, this variable can still be used with the
774;; imenu--generic-function. Otherwise, there is no real reason to have
775;; it.
776(defvar imenu-example--generic-python-expression
777 (cons
778 (concat
779 imenu-example--python-class-regexp
780 "\\|" ; or...
781 imenu-example--python-method-regexp
782 )
783 imenu-example--python-method-no-arg-parens)
784 "Generic Python expression which may be used directly with imenu.
785Used by setting the variable `imenu-generic-expression' to this value.
786Also, see the function \\[imenu-example--create-python-index] for a
787better alternative for finding the index.")
788
789;; These next two variables are used when searching for the python
790;; class/definitions. Just saving some time in accessing the
791;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000792(defvar imenu-example--python-generic-regexp nil)
793(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000794
795
Barry Warsaw81437461996-08-01 19:48:02 +0000796(defun imenu-example--create-python-index ()
797 "Python interface function for imenu package.
798Finds all python classes and functions/methods. Calls function
799\\[imenu-example--create-python-index-engine]. See that function for
800the details of how this works."
801 (setq imenu-example--python-generic-regexp
802 (car imenu-example--generic-python-expression))
803 (setq imenu-example--python-generic-parens
804 (if imenu-example--python-show-method-args-p
805 imenu-example--python-method-arg-parens
806 imenu-example--python-method-no-arg-parens))
807 (goto-char (point-min))
808 (imenu-example--create-python-index-engine nil))
809
810(defun imenu-example--create-python-index-engine (&optional start-indent)
811 "Function for finding imenu definitions in Python.
812
813Finds all definitions (classes, methods, or functions) in a Python
814file for the imenu package.
815
816Returns a possibly nested alist of the form
817
818 (INDEX-NAME . INDEX-POSITION)
819
820The second element of the alist may be an alist, producing a nested
821list as in
822
823 (INDEX-NAME . INDEX-ALIST)
824
825This function should not be called directly, as it calls itself
826recursively and requires some setup. Rather this is the engine for
827the function \\[imenu-example--create-python-index].
828
829It works recursively by looking for all definitions at the current
830indention level. When it finds one, it adds it to the alist. If it
831finds a definition at a greater indentation level, it removes the
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000832previous definition from the alist. In its place it adds all
Barry Warsaw81437461996-08-01 19:48:02 +0000833definitions found at the next indentation level. When it finds a
834definition that is less indented then the current level, it retuns the
835alist it has created thus far.
836
837The optional argument START-INDENT indicates the starting indentation
838at which to continue looking for Python classes, methods, or
839functions. If this is not supplied, the function uses the indentation
840of the first definition found."
841 (let ((index-alist '())
842 (sub-method-alist '())
843 looking-p
844 def-name prev-name
845 cur-indent def-pos
846 (class-paren (first imenu-example--python-generic-parens))
847 (def-paren (second imenu-example--python-generic-parens)))
848 (setq looking-p
849 (re-search-forward imenu-example--python-generic-regexp
850 (point-max) t))
851 (while looking-p
852 (save-excursion
853 ;; used to set def-name to this value but generic-extract-name is
854 ;; new to imenu-1.14. this way it still works with imenu-1.11
855 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
856 (let ((cur-paren (if (match-beginning class-paren)
857 class-paren def-paren)))
858 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000859 (buffer-substring-no-properties (match-beginning cur-paren)
860 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000861 (beginning-of-line)
862 (setq cur-indent (current-indentation)))
863
864 ;; HACK: want to go to the next correct definition location. we
865 ;; explicitly list them here. would be better to have them in a
866 ;; list.
867 (setq def-pos
868 (or (match-beginning class-paren)
869 (match-beginning def-paren)))
870
871 ;; if we don't have a starting indent level, take this one
872 (or start-indent
873 (setq start-indent cur-indent))
874
875 ;; if we don't have class name yet, take this one
876 (or prev-name
877 (setq prev-name def-name))
878
879 ;; what level is the next definition on? must be same, deeper
880 ;; or shallower indentation
881 (cond
882 ;; at the same indent level, add it to the list...
883 ((= start-indent cur-indent)
884
885 ;; if we don't have push, use the following...
886 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
887 (push (cons def-name def-pos) index-alist))
888
889 ;; deeper indented expression, recur...
890 ((< start-indent cur-indent)
891
892 ;; the point is currently on the expression we're supposed to
893 ;; start on, so go back to the last expression. The recursive
894 ;; call will find this place again and add it to the correct
895 ;; list
896 (re-search-backward imenu-example--python-generic-regexp
897 (point-min) 'move)
898 (setq sub-method-alist (imenu-example--create-python-index-engine
899 cur-indent))
900
901 (if sub-method-alist
902 ;; we put the last element on the index-alist on the start
903 ;; of the submethod alist so the user can still get to it.
904 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000905 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000906 (cons save-elmt sub-method-alist))
907 index-alist))))
908
909 ;; found less indented expression, we're done.
910 (t
911 (setq looking-p nil)
912 (re-search-backward imenu-example--python-generic-regexp
913 (point-min) t)))
914 (setq prev-name def-name)
915 (and looking-p
916 (setq looking-p
917 (re-search-forward imenu-example--python-generic-regexp
918 (point-max) 'move))))
919 (nreverse index-alist)))
920
Barry Warsaw42f707f1996-07-29 21:05:05 +0000921
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000922;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000923(defun python-mode ()
924 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000925To submit a problem report, enter `\\[py-submit-bug-report]' from a
926`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
927documentation. To see what version of `python-mode' you are running,
928enter `\\[py-version]'.
929
930This mode knows about Python indentation, tokens, comments and
931continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000932
933COMMANDS
934\\{py-mode-map}
935VARIABLES
936
Barry Warsaw42f707f1996-07-29 21:05:05 +0000937py-indent-offset\t\tindentation increment
938py-block-comment-prefix\t\tcomment string used by comment-region
939py-python-command\t\tshell command to invoke Python interpreter
940py-scroll-process-buffer\t\talways scroll Python process buffer
941py-temp-directory\t\tdirectory used for temp files (if needed)
942py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000943 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000944 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000945 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000946 (make-local-variable 'font-lock-defaults)
947 (make-local-variable 'paragraph-separate)
948 (make-local-variable 'paragraph-start)
949 (make-local-variable 'require-final-newline)
950 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000951 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000952 (make-local-variable 'comment-start-skip)
953 (make-local-variable 'comment-column)
954 (make-local-variable 'indent-region-function)
955 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000956 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000957 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000958 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000959 (setq major-mode 'python-mode
960 mode-name "Python"
961 local-abbrev-table python-mode-abbrev-table
Barry Warsaw5c38bf61997-12-02 22:01:04 +0000962 font-lock-defaults '(python-font-lock-keywords)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000963 paragraph-separate "^[ \t]*$"
964 paragraph-start "^[ \t]*$"
965 require-final-newline t
966 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000967 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000968 comment-start-skip "# *"
969 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000970 indent-region-function 'py-indent-region
971 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000972 ;; tell add-log.el how to find the current function/method/variable
973 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000974 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000975 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000976 ;; add the menu
977 (if py-menu
978 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000979 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000980 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000981 (setq comment-multi-line nil))
Barry Warsaw742a5111998-03-13 17:29:15 +0000982 ;; Install Imenu, only works for Emacs.
983 (when (py-safe (require 'imenu))
984 (make-variable-buffer-local 'imenu-create-index-function)
985 (setq imenu-create-index-function
986 (function imenu-example--create-python-index))
987 (setq imenu-generic-expression
988 imenu-example--generic-python-expression)
989 (if (fboundp 'imenu-add-to-menubar)
990 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
991 )
992 ;; Run the mode hook. Note that py-mode-hook is deprecated.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000993 (if python-mode-hook
994 (run-hooks 'python-mode-hook)
Barry Warsaw742a5111998-03-13 17:29:15 +0000995 (run-hooks 'py-mode-hook))
996 ;; Now do the automagical guessing
997 (if py-smart-indentation
998 (let ((offset py-indent-offset))
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000999 ;; It's okay if this fails to guess a good value
Barry Warsaw742a5111998-03-13 17:29:15 +00001000 (if (and (py-safe (py-guess-indent-offset))
1001 (<= py-indent-offset 8)
1002 (>= py-indent-offset 2))
1003 (setq offset py-indent-offset))
1004 (setq py-indent-offset offset)
Barry Warsaw639eea61998-03-16 18:12:13 +00001005 ;; Only turn indent-tabs-mode off if tab-width !=
1006 ;; py-indent-offset. Never turn it on, because the user must
1007 ;; have explicitly turned it off.
1008 (if (/= tab-width py-indent-offset)
1009 (setq indent-tabs-mode nil))
Barry Warsaw742a5111998-03-13 17:29:15 +00001010 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001011
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001012
Barry Warsawb91b7431995-03-14 15:55:20 +00001013;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001014(defun py-outdent-p ()
1015 ;; returns non-nil if the current line should outdent one level
1016 (save-excursion
1017 (and (progn (back-to-indentation)
1018 (looking-at py-outdent-re))
Barry Warsawf06777d1998-01-21 05:36:18 +00001019 (progn (forward-line -1)
1020 (py-goto-initial-line)
1021 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001022 (while (or (looking-at py-blank-or-comment-re)
1023 (bobp))
1024 (backward-to-indentation 1))
1025 (not (looking-at py-no-outdent-re)))
1026 )))
1027
Barry Warsawb91b7431995-03-14 15:55:20 +00001028(defun py-electric-colon (arg)
1029 "Insert a colon.
1030In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001031argument is provided, that many colons are inserted non-electrically.
1032Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +00001033 (interactive "P")
1034 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001035 ;; are we in a string or comment?
1036 (if (save-excursion
1037 (let ((pps (parse-partial-sexp (save-excursion
Barry Warsawab0e86c1998-05-19 15:31:46 +00001038 (py-beginning-of-def-or-class)
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001039 (point))
1040 (point))))
1041 (not (or (nth 3 pps) (nth 4 pps)))))
1042 (save-excursion
1043 (let ((here (point))
1044 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001045 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001046 (if (and (not arg)
1047 (py-outdent-p)
1048 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +00001049 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001050 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001051 )
1052 (setq outdent py-indent-offset))
1053 ;; Don't indent, only outdent. This assumes that any lines that
1054 ;; are already outdented relative to py-compute-indentation were
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001055 ;; put there on purpose. It's highly annoying to have `:' indent
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001056 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
1057 ;; there a better way to determine this???
1058 (if (< (current-indentation) indent) nil
1059 (goto-char here)
1060 (beginning-of-line)
1061 (delete-horizontal-space)
1062 (indent-to (- indent outdent))
1063 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001064
1065
Barry Warsawa97a3f31997-11-04 18:47:06 +00001066;; Python subprocess utilities and filters
1067(defun py-execute-file (proc filename)
1068 ;; Send a properly formatted execfile('FILENAME') to the underlying
1069 ;; Python interpreter process FILENAME. Make that process's buffer
1070 ;; visible and force display. Also make comint believe the user
1071 ;; typed this string so that kill-output-from-shell does The Right
1072 ;; Thing.
1073 (let ((curbuf (current-buffer))
1074 (procbuf (process-buffer proc))
1075 (comint-scroll-to-bottom-on-output t)
1076 (msg (format "## working on region in file %s...\n" filename))
1077 (cmd (format "execfile('%s')\n" filename)))
1078 (unwind-protect
1079 (progn
1080 (set-buffer procbuf)
1081 (goto-char (point-max))
1082 (move-marker (process-mark proc) (point))
1083 (funcall (process-filter proc) proc msg))
1084 (set-buffer curbuf))
1085 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001086
1087(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001088 (let ((curbuf (current-buffer))
1089 (pbuf (process-buffer pyproc))
1090 (pmark (process-mark pyproc))
1091 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001092 ;; make sure we switch to a different buffer at least once. if we
1093 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001094 ;; window, and point is before the end, and lots of output is
1095 ;; coming at a fast pace, then (a) simple cursor-movement commands
1096 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
1097 ;; to have a visible effect (the window just doesn't get updated,
1098 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
1099 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001100 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001101 ;; #b makes no sense to me at all. #a almost makes sense: unless
1102 ;; we actually change buffers, set_buffer_internal in buffer.c
1103 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1104 ;; seems to make the Emacs command loop reluctant to update the
1105 ;; display. Perhaps the default process filter in process.c's
1106 ;; read_process_output has update_mode_lines++ for a similar
1107 ;; reason? beats me ...
1108
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001109 (unwind-protect
1110 ;; make sure current buffer is restored
1111 ;; BAW - we want to check to see if this still applies
1112 (progn
1113 ;; mysterious ugly hack
1114 (if (eq curbuf pbuf)
1115 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001116
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001117 (set-buffer pbuf)
1118 (let* ((start (point))
1119 (goback (< start pmark))
1120 (goend (and (not goback) (= start (point-max))))
1121 (buffer-read-only nil))
1122 (goto-char pmark)
1123 (insert string)
1124 (move-marker pmark (point))
1125 (setq file-finished
1126 (and py-file-queue
1127 (equal ">>> "
1128 (buffer-substring
1129 (prog2 (beginning-of-line) (point)
1130 (goto-char pmark))
1131 (point)))))
1132 (if goback (goto-char start)
1133 ;; else
1134 (if py-scroll-process-buffer
1135 (let* ((pop-up-windows t)
1136 (pwin (display-buffer pbuf)))
1137 (set-window-point pwin (point)))))
1138 (set-buffer curbuf)
1139 (if file-finished
1140 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001141 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001142 (setq py-file-queue (cdr py-file-queue))
1143 (if py-file-queue
1144 (py-execute-file pyproc (car py-file-queue)))))
1145 (and goend
1146 (progn (set-buffer pbuf)
1147 (goto-char (point-max))))
1148 ))
1149 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001150
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001151(defun py-postprocess-output-buffer (buf)
Barry Warsawf9b99f41998-03-26 16:08:59 +00001152 ;; Highlight exceptions found in BUF. If an exception occurred
1153 ;; return t, otherwise return nil. BUF must exist.
1154 (let (line file bol err-p)
Barry Warsaw9981d221997-12-03 05:25:48 +00001155 (save-excursion
1156 (set-buffer buf)
1157 (beginning-of-buffer)
1158 (while (re-search-forward py-traceback-line-re nil t)
1159 (setq file (match-string 1)
1160 line (string-to-int (match-string 2))
1161 bol (py-point 'bol))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001162 (py-highlight-line bol (py-point 'eol) file line)))
1163 (when (and py-jump-on-exception line)
1164 (beep)
1165 (py-jump-to-exception file line)
1166 (setq err-p t))
1167 err-p))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001168
Barry Warsaw9981d221997-12-03 05:25:48 +00001169
Barry Warsawa97a3f31997-11-04 18:47:06 +00001170
1171;;; Subprocess commands
1172
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001173;; only used when (memq 'broken-temp-names py-emacs-features)
1174(defvar py-serial-number 0)
1175(defvar py-exception-buffer nil)
1176(defconst py-output-buffer "*Python Output*")
Barry Warsawa2398801998-04-09 23:28:20 +00001177(make-variable-buffer-local 'py-output-buffer)
1178
1179;; for toggling between CPython and JPython
1180(defvar py-which-shell py-python-command)
1181(defvar py-which-args py-python-command-args)
1182(defvar py-which-bufname "Python")
1183(make-variable-buffer-local 'py-which-shell)
1184(make-variable-buffer-local 'py-which-args)
1185(make-variable-buffer-local 'py-which-bufname)
1186
1187(defun py-toggle-shells (arg)
1188 "Toggles between the CPython and JPython shells.
1189With positive \\[universal-argument], uses the CPython shell, with
1190negative \\[universal-argument] uses the JPython shell, and with a
1191zero argument, toggles the shell."
1192 (interactive "P")
1193 ;; default is to toggle
1194 (if (null arg)
1195 (setq arg 0))
1196 ;; toggle if zero
1197 (if (= arg 0)
1198 (if (string-equal py-which-bufname "Python")
1199 (setq arg -1)
1200 (setq arg 1)))
1201 (let (msg)
1202 (cond
1203 ((< 0 arg)
1204 ;; set to CPython
1205 (setq py-which-shell py-python-command
1206 py-which-args py-python-command-args
1207 py-which-bufname "Python"
1208 msg "CPython"
1209 mode-name "Python"))
1210 ((> 0 arg)
1211 (setq py-which-shell py-jpython-command
1212 py-which-args py-jpython-command-args
1213 py-which-bufname "JPython"
1214 msg "JPython"
1215 mode-name "JPython"))
1216 )
Barry Warsawea609c11998-04-10 16:08:26 +00001217 (message "Using the %s shell" msg)
Barry Warsawa2398801998-04-09 23:28:20 +00001218 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001219
Barry Warsawa97a3f31997-11-04 18:47:06 +00001220;;;###autoload
1221(defun py-shell ()
1222 "Start an interactive Python interpreter in another window.
1223This is like Shell mode, except that Python is running in the window
1224instead of a shell. See the `Interactive Shell' and `Shell Mode'
1225sections of the Emacs manual for details, especially for the key
1226bindings active in the `*Python*' buffer.
1227
1228See the docs for variable `py-scroll-buffer' for info on scrolling
1229behavior in the process window.
1230
Barry Warsawa2398801998-04-09 23:28:20 +00001231Note: You can toggle between using the CPython interpreter and the
1232JPython interpreter by hitting \\[py-toggle-shells]. This toggles
1233buffer local variables which control whether all your subshell
1234interactions happen to the `*JPython*' or `*Python*' buffers (the
1235latter is the name used for the CPython buffer).
1236
Barry Warsawa97a3f31997-11-04 18:47:06 +00001237Warning: Don't use an interactive Python if you change sys.ps1 or
1238sys.ps2 from their default values, or if you're running code that
1239prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1240distinguish your output from Python's output, and assumes that `>>> '
1241at the start of a line is a prompt from Python. Similarly, the Emacs
1242Shell mode code assumes that both `>>> ' and `... ' at the start of a
1243line are Python prompts. Bad things can happen if you fool either
1244mode.
1245
1246Warning: If you do any editing *in* the process buffer *while* the
1247buffer is accepting output from Python, do NOT attempt to `undo' the
1248changes. Some of the output (nowhere near the parts you changed!) may
1249be lost if you do. This appears to be an Emacs bug, an unfortunate
1250interaction between undo and process filters; the same problem exists in
1251non-Python process buffers using the default (Emacs-supplied) process
1252filter."
1253 ;; BAW - should undo be disabled in the python process buffer, if
1254 ;; this bug still exists?
1255 (interactive)
1256 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001257 (switch-to-buffer-other-window
Barry Warsawa2398801998-04-09 23:28:20 +00001258 (apply 'make-comint py-which-bufname py-which-shell nil py-which-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001259 (make-local-variable 'comint-prompt-regexp)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001260 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
Barry Warsawa97a3f31997-11-04 18:47:06 +00001261 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1262 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001263 ;; set up keybindings for this subshell
1264 (local-set-key [tab] 'self-insert-command)
1265 (local-set-key "\C-c-" 'py-up-exception)
1266 (local-set-key "\C-c=" 'py-down-exception)
1267 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001268
Barry Warsawa97a3f31997-11-04 18:47:06 +00001269(defun py-clear-queue ()
1270 "Clear the queue of temporary files waiting to execute."
1271 (interactive)
1272 (let ((n (length py-file-queue)))
1273 (mapcar 'delete-file py-file-queue)
1274 (setq py-file-queue nil)
1275 (message "%d pending files de-queued." n)))
1276
1277(defun py-execute-region (start end &optional async)
1278 "Execute the the region in a Python interpreter.
1279The region is first copied into a temporary file (in the directory
1280`py-temp-directory'). If there is no Python interpreter shell
1281running, this file is executed synchronously using
1282`shell-command-on-region'. If the program is long running, use an
1283optional \\[universal-argument] to run the command asynchronously in
1284its own buffer.
1285
1286If the Python interpreter shell is running, the region is execfile()'d
1287in that shell. If you try to execute regions too quickly,
1288`python-mode' will queue them up and execute them one at a time when
1289it sees a `>>> ' prompt from Python. Each time this happens, the
1290process buffer is popped into a window (if it's not already in some
1291window) so you can see it, and a comment of the form
1292
1293 \t## working on region in file <name>...
1294
1295is inserted at the end. See also the command `py-clear-queue'."
1296 (interactive "r\nP")
1297 (or (< start end)
1298 (error "Region is empty"))
1299 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001300 (temp (if (memq 'broken-temp-names py-emacs-features)
1301 (prog1
1302 (format "python-%d" py-serial-number)
1303 (setq py-serial-number (1+ py-serial-number)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001304 (make-temp-name "python-")))
1305 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001306 (write-region start end file nil 'nomsg)
1307 (cond
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001308 ;; always run the code in its own asynchronous subprocess
Barry Warsawa97a3f31997-11-04 18:47:06 +00001309 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001310 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001311 (start-process "Python" buf py-python-command "-u" file)
1312 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001313 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001314 ))
1315 ;; if the Python interpreter shell is running, queue it up for
1316 ;; execution there.
1317 (proc
1318 ;; use the existing python shell
1319 (if (not py-file-queue)
1320 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001321 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001322 (push file py-file-queue)
1323 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001324 (t
1325 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001326 (shell-command-on-region start end py-python-command py-output-buffer)
Barry Warsaw512af041998-03-25 23:27:17 +00001327 ;; shell-command-on-region kills the output buffer if it never
1328 ;; existed and there's no output from the command
1329 (if (not (get-buffer py-output-buffer))
1330 (message "No output.")
1331 (setq py-exception-buffer (current-buffer))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001332 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1333 (pop-to-buffer py-output-buffer)
1334 (if err-p
1335 (pop-to-buffer py-exception-buffer)))
Barry Warsaw512af041998-03-25 23:27:17 +00001336 ))
1337 )))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001338
1339;; Code execution command
1340(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001341 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001342If the file local variable `py-master-file' is non-nil, execute the
1343named file instead of the buffer's file.
1344
Barry Warsaw7ae77681994-12-12 20:38:05 +00001345If there is a *Python* process buffer it is used. If a clipping
1346restriction is in effect, only the accessible portion of the buffer is
1347sent. A trailing newline will be supplied if needed.
1348
1349See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001350 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001351 (if py-master-file
1352 (let* ((filename (expand-file-name py-master-file))
1353 (buffer (or (get-file-buffer filename)
1354 (find-file-noselect filename))))
1355 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001356 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001357
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001358
1359
1360(defun py-jump-to-exception (file line)
1361 (let ((buffer (cond ((string-equal file "<stdin>")
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001362 (if (consp py-exception-buffer)
1363 (cdr py-exception-buffer)
1364 py-exception-buffer))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001365 ((and (consp py-exception-buffer)
1366 (string-equal file (car py-exception-buffer)))
1367 (cdr py-exception-buffer))
1368 ((py-safe (find-file-noselect file)))
1369 ;; could not figure out what file the exception
1370 ;; is pointing to, so prompt for it
1371 (t (find-file (read-file-name "Exception file: "
1372 nil
1373 file t))))))
1374 (pop-to-buffer buffer)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001375 ;; Force Python mode
1376 (if (not (eq major-mode) 'python-mode)
1377 (python-mode))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001378 (goto-line line)
1379 (message "Jumping to exception in file %s on line %d" file line)))
1380
1381(defun py-mouseto-exception (event)
1382 (interactive "e")
1383 (cond
1384 ((fboundp 'event-point)
1385 ;; XEmacs
1386 (let* ((point (event-point event))
1387 (buffer (event-buffer event))
1388 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1389 (info (and e (extent-property e 'py-exc-info))))
1390 (message "Event point: %d, info: %s" point info)
1391 (and info
1392 (py-jump-to-exception (car info) (cdr info)))
1393 ))
1394 ;; Emacs -- Please port this!
1395 ))
1396
1397(defun py-goto-exception ()
1398 "Go to the line indicated by the traceback."
1399 (interactive)
1400 (let (file line)
1401 (save-excursion
1402 (beginning-of-line)
1403 (if (looking-at py-traceback-line-re)
1404 (setq file (match-string 1)
1405 line (string-to-int (match-string 2)))))
1406 (if (not file)
1407 (error "Not on a traceback line."))
1408 (py-jump-to-exception file line)))
1409
1410(defun py-find-next-exception (start buffer searchdir errwhere)
1411 ;; Go to start position in buffer, search in the specified
1412 ;; direction, and jump to the exception found. If at the end of the
1413 ;; exception, print error message
1414 (let (file line)
1415 (save-excursion
1416 (set-buffer buffer)
1417 (goto-char (py-point start))
1418 (if (funcall searchdir py-traceback-line-re nil t)
1419 (setq file (match-string 1)
1420 line (string-to-int (match-string 2)))))
1421 (if (and file line)
1422 (py-jump-to-exception file line)
1423 (error "%s of traceback" errwhere))))
1424
1425(defun py-down-exception (&optional bottom)
1426 "Go to the next line down in the traceback.
1427With optional \\[universal-argument], jump to the bottom (innermost)
1428exception in the exception stack."
1429 (interactive "P")
1430 (let* ((proc (get-process "Python"))
1431 (buffer (if proc "*Python*" py-output-buffer)))
1432 (if bottom
1433 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1434 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1435
1436(defun py-up-exception (&optional top)
1437 "Go to the previous line up in the traceback.
1438With optional \\[universal-argument], jump to the top (outermost)
1439exception in the exception stack."
1440 (interactive "P")
1441 (let* ((proc (get-process "Python"))
1442 (buffer (if proc "*Python*" py-output-buffer)))
1443 (if top
1444 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001445 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001446
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001447
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001448;; Electric deletion
1449(defun py-electric-backspace (arg)
1450 "Deletes preceding character or levels of indentation.
1451Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001452with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001453
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001454If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001455
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001456Otherwise, if point is at the leftmost non-whitespace character of a
1457line that is neither a continuation line nor a non-indenting comment
1458line, or if point is at the end of a blank line, this command reduces
1459the indentation to match that of the line that opened the current
1460block of code. The line that opened the block is displayed in the
1461echo area to help you keep track of where you are. With numeric arg,
1462outdents that many blocks (but not past column zero).
1463
1464Otherwise the preceding character is deleted, converting a tab to
1465spaces if needed so that only a single column position is deleted.
1466Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001467 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001468 (if (or (/= (current-indentation) (current-column))
1469 (bolp)
1470 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001471 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001472 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001473 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001474 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001475 ;; force non-blank so py-goto-block-up doesn't ignore it
1476 (insert-char ?* 1)
1477 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001478 (let ((base-indent 0) ; indentation of base line
1479 (base-text "") ; and text of base line
1480 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001481 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001482 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001483 (condition-case nil ; in case no enclosing block
1484 (progn
1485 (py-goto-block-up 'no-mark)
1486 (setq base-indent (current-indentation)
1487 base-text (py-suck-up-leading-text)
1488 base-found-p t))
1489 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001490 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001491 (delete-char 1) ; toss the dummy character
1492 (delete-horizontal-space)
1493 (indent-to base-indent)
1494 (if base-found-p
1495 (message "Closes block: %s" base-text)))))
1496
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001497
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001498(defun py-electric-delete (arg)
1499 "Deletes preceding or following character or levels of whitespace.
1500
1501The behavior of this function depends on the variable
1502`delete-key-deletes-forward'. If this variable is nil (or does not
1503exist, as in older Emacsen), then this function behaves identical to
1504\\[c-electric-backspace].
1505
1506If `delete-key-deletes-forward' is non-nil and is supported in your
1507Emacs, then deletion occurs in the forward direction, by calling the
1508function in `py-delete-function'."
1509 (interactive "*p")
1510 (if (and (boundp 'delete-key-deletes-forward)
1511 delete-key-deletes-forward)
1512 (funcall py-delete-function arg)
1513 ;; else
1514 (py-electric-backspace arg)))
1515
1516;; required for pending-del and delsel modes
1517(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1518(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1519(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1520(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1521
1522
1523
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001524(defun py-indent-line (&optional arg)
1525 "Fix the indentation of the current line according to Python rules.
1526With \\[universal-argument], ignore outdenting rules for block
1527closing statements (e.g. return, raise, break, continue, pass)
1528
1529This function is normally bound to `indent-line-function' so
1530\\[indent-for-tab-command] will call it."
1531 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001532 (let* ((ci (current-indentation))
1533 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001534 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001535 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001536 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001537 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001538 (if (/= ci need)
1539 (save-excursion
1540 (beginning-of-line)
1541 (delete-horizontal-space)
1542 (indent-to need)))
1543 (if move-to-indentation-p (back-to-indentation))))
1544
1545(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001546 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001547This is just `strives to' because correct indentation can't be computed
1548from scratch for Python code. In general, deletes the whitespace before
1549point, inserts a newline, and takes an educated guess as to how you want
1550the new line indented."
1551 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001552 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001553 (if (< ci (current-column)) ; if point beyond indentation
1554 (newline-and-indent)
1555 ;; else try to act like newline-and-indent "normally" acts
1556 (beginning-of-line)
1557 (insert-char ?\n 1)
1558 (move-to-column ci))))
1559
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001560(defun py-compute-indentation (honor-block-close-p)
1561 ;; implements all the rules for indentation computation. when
1562 ;; honor-block-close-p is non-nil, statements such as return, raise,
1563 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001564 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001565 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001566 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001567 (pps (parse-partial-sexp bod (point)))
1568 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001569 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001570 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001571 ((or (and (nth 3 pps) (nth 3 boipps))
1572 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001573 (save-excursion
1574 (if (not py-align-multiline-strings-p) 0
1575 ;; skip back over blank & non-indenting comment lines
1576 ;; note: will skip a blank or non-indenting comment line
1577 ;; that happens to be a continuation line too
1578 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1579 (back-to-indentation)
1580 (current-column))))
1581 ;; are we on a continuation line?
1582 ((py-continuation-line-p)
1583 (let ((startpos (point))
1584 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001585 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001586 (if open-bracket-pos
1587 (progn
1588 ;; align with first item in list; else a normal
1589 ;; indent beyond the line with the open bracket
1590 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1591 ;; is the first list item on the same line?
1592 (skip-chars-forward " \t")
1593 (if (null (memq (following-char) '(?\n ?# ?\\)))
1594 ; yes, so line up with it
1595 (current-column)
1596 ;; first list item on another line, or doesn't exist yet
1597 (forward-line 1)
1598 (while (and (< (point) startpos)
1599 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1600 (forward-line 1))
Barry Warsaw92166d91998-04-01 21:59:41 +00001601 (if (and (< (point) startpos)
1602 (/= startpos
1603 (save-excursion
1604 (goto-char (1+ open-bracket-pos))
Barry Warsaw77d1fce1998-04-16 20:04:59 +00001605 (forward-comment (point-max))
Barry Warsaw92166d91998-04-01 21:59:41 +00001606 (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001607 ;; again mimic the first list item
1608 (current-indentation)
1609 ;; else they're about to enter the first item
1610 (goto-char open-bracket-pos)
1611 (+ (current-indentation) py-indent-offset))))
1612
1613 ;; else on backslash continuation line
1614 (forward-line -1)
1615 (if (py-continuation-line-p) ; on at least 3rd line in block
1616 (current-indentation) ; so just continue the pattern
1617 ;; else started on 2nd line in block, so indent more.
1618 ;; if base line is an assignment with a start on a RHS,
1619 ;; indent to 2 beyond the leftmost "="; else skip first
1620 ;; chunk of non-whitespace characters on base line, + 1 more
1621 ;; column
1622 (end-of-line)
1623 (setq endpos (point) searching t)
1624 (back-to-indentation)
1625 (setq startpos (point))
1626 ;; look at all "=" from left to right, stopping at first
1627 ;; one not nested in a list or string
1628 (while searching
1629 (skip-chars-forward "^=" endpos)
1630 (if (= (point) endpos)
1631 (setq searching nil)
1632 (forward-char 1)
1633 (setq state (parse-partial-sexp startpos (point)))
1634 (if (and (zerop (car state)) ; not in a bracket
1635 (null (nth 3 state))) ; & not in a string
1636 (progn
1637 (setq searching nil) ; done searching in any case
1638 (setq found
1639 (not (or
1640 (eq (following-char) ?=)
1641 (memq (char-after (- (point) 2))
1642 '(?< ?> ?!)))))))))
1643 (if (or (not found) ; not an assignment
1644 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1645 (progn
1646 (goto-char startpos)
1647 (skip-chars-forward "^ \t\n")))
1648 (1+ (current-column))))))
1649
1650 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001651 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001652
Barry Warsawa7891711996-08-01 15:53:09 +00001653 ;; Dfn: "Indenting comment line". A line containing only a
1654 ;; comment, but which is treated like a statement for
1655 ;; indentation calculation purposes. Such lines are only
1656 ;; treated specially by the mode; they are not treated
1657 ;; specially by the Python interpreter.
1658
1659 ;; The rules for indenting comment lines are a line where:
1660 ;; - the first non-whitespace character is `#', and
1661 ;; - the character following the `#' is whitespace, and
1662 ;; - the line is outdented with respect to (i.e. to the left
1663 ;; of) the indentation of the preceding non-blank line.
1664
1665 ;; The first non-blank line following an indenting comment
1666 ;; line is given the same amount of indentation as the
1667 ;; indenting comment line.
1668
1669 ;; All other comment-only lines are ignored for indentation
1670 ;; purposes.
1671
1672 ;; Are we looking at a comment-only line which is *not* an
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001673 ;; indenting comment line? If so, we assume that it's been
Barry Warsawa7891711996-08-01 15:53:09 +00001674 ;; placed at the desired indentation, so leave it alone.
1675 ;; Indenting comment lines are aligned as statements down
1676 ;; below.
1677 ((and (looking-at "[ \t]*#[^ \t\n]")
1678 ;; NOTE: this test will not be performed in older Emacsen
1679 (fboundp 'forward-comment)
1680 (<= (current-indentation)
1681 (save-excursion
1682 (forward-comment (- (point-max)))
1683 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001684 (current-indentation))
1685
1686 ;; else indentation based on that of the statement that
1687 ;; precedes us; use the first line of that statement to
1688 ;; establish the base, in case the user forced a non-std
1689 ;; indentation for the continuation lines (if any)
1690 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001691 ;; skip back over blank & non-indenting comment lines note:
1692 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001693 ;; happens to be a continuation line too. use fast Emacs 19
1694 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001695 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001696 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001697 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001698 (let (done)
1699 (while (not done)
1700 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1701 nil 'move)
1702 (setq done (or (eq py-honor-comment-indentation t)
1703 (bobp)
1704 (/= (following-char) ?#)
1705 (not (zerop (current-column)))))
1706 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001707 ;; if we landed inside a string, go to the beginning of that
1708 ;; string. this handles triple quoted, multi-line spanning
1709 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001710 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001711 (skip (and delim (make-string 1 delim))))
1712 (when skip
1713 (save-excursion
1714 (py-safe (search-backward skip))
1715 (if (and (eq (char-before) delim)
1716 (eq (char-before (1- (point))) delim))
1717 (setq skip (make-string 3 delim))))
1718 ;; we're looking at a triple-quoted string
1719 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001720 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001721 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001722 (+ (current-indentation)
1723 (if (py-statement-opens-block-p)
1724 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001725 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001726 (- py-indent-offset)
1727 0)))
1728 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001729
1730(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001731 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001732By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001733`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001734Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001735`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001736their own buffer-local copy), both those currently existing and those
1737created later in the Emacs session.
1738
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001739Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001740There's no excuse for such foolishness, but sometimes you have to deal
1741with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001742`py-indent-offset' to what it thinks it was when they created the
1743mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001744
1745Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001746looking for a line that opens a block of code. `py-indent-offset' is
1747set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001748statement following it. If the search doesn't succeed going forward,
1749it's tried again going backward."
1750 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001751 (let (new-value
1752 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001753 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001754 (found nil)
1755 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001756 (py-goto-initial-line)
1757 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001758 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1759 (not (py-in-literal restart)))
1760 (setq restart (point))
1761 (py-goto-initial-line)
1762 (if (py-statement-opens-block-p)
1763 (setq found t)
1764 (goto-char restart))))
1765 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001766 (goto-char start)
1767 (py-goto-initial-line)
1768 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001769 (setq found (and
1770 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1771 (or (py-goto-initial-line) t) ; always true -- side effect
1772 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001773 (setq colon-indent (current-indentation)
1774 found (and found (zerop (py-next-statement 1)))
1775 new-value (- (current-indentation) colon-indent))
1776 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001777 (if (not found)
1778 (error "Sorry, couldn't guess a value for py-indent-offset")
1779 (funcall (if global 'kill-local-variable 'make-local-variable)
1780 'py-indent-offset)
1781 (setq py-indent-offset new-value)
1782 (message "%s value of py-indent-offset set to %d"
1783 (if global "Global" "Local")
1784 py-indent-offset))
1785 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001786
1787(defun py-shift-region (start end count)
1788 (save-excursion
1789 (goto-char end) (beginning-of-line) (setq end (point))
1790 (goto-char start) (beginning-of-line) (setq start (point))
1791 (indent-rigidly start end count)))
1792
1793(defun py-shift-region-left (start end &optional count)
1794 "Shift region of Python code to the left.
1795The lines from the line containing the start of the current region up
1796to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001797shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001798
1799If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001800many columns. With no active region, outdent only the current line.
1801You cannot outdent the region if any line is already at column zero."
1802 (interactive
1803 (let ((p (point))
1804 (m (mark))
1805 (arg current-prefix-arg))
1806 (if m
1807 (list (min p m) (max p m) arg)
1808 (list p (save-excursion (forward-line 1) (point)) arg))))
1809 ;; if any line is at column zero, don't shift the region
1810 (save-excursion
1811 (goto-char start)
1812 (while (< (point) end)
1813 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001814 (if (and (zerop (current-column))
1815 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001816 (error "Region is at left edge."))
1817 (forward-line 1)))
1818 (py-shift-region start end (- (prefix-numeric-value
1819 (or count py-indent-offset))))
1820 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001821
1822(defun py-shift-region-right (start end &optional count)
1823 "Shift region of Python code to the right.
1824The lines from the line containing the start of the current region up
1825to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001826shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001827
1828If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001829many columns. With no active region, indent only the current line."
1830 (interactive
1831 (let ((p (point))
1832 (m (mark))
1833 (arg current-prefix-arg))
1834 (if m
1835 (list (min p m) (max p m) arg)
1836 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001837 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001838 (or count py-indent-offset)))
1839 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001840
1841(defun py-indent-region (start end &optional indent-offset)
1842 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001843
Barry Warsaw7ae77681994-12-12 20:38:05 +00001844The lines from the line containing the start of the current region up
1845to (but not including) the line containing the end of the region are
1846reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001847character in the first column, the first line is left alone and the
1848rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001849region is reindented with respect to the (closest code or indenting
1850comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001851
1852This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001853control structures are introduced or removed, or to reformat code
1854using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001855
1856If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001857the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001858used.
1859
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001860Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001861is called! This function does not compute proper indentation from
1862scratch (that's impossible in Python), it merely adjusts the existing
1863indentation to be correct in context.
1864
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001865Warning: This function really has no idea what to do with
1866non-indenting comment lines, and shifts them as if they were indenting
1867comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001868
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001869Special cases: whitespace is deleted from blank lines; continuation
1870lines are shifted by the same amount their initial line was shifted,
1871in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001872initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001873 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001874 (save-excursion
1875 (goto-char end) (beginning-of-line) (setq end (point-marker))
1876 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001877 (let ((py-indent-offset (prefix-numeric-value
1878 (or indent-offset py-indent-offset)))
1879 (indents '(-1)) ; stack of active indent levels
1880 (target-column 0) ; column to which to indent
1881 (base-shifted-by 0) ; amount last base line was shifted
1882 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001883 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001884 0))
1885 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001886 (while (< (point) end)
1887 (setq ci (current-indentation))
1888 ;; figure out appropriate target column
1889 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001890 ((or (eq (following-char) ?#) ; comment in column 1
1891 (looking-at "[ \t]*$")) ; entirely blank
1892 (setq target-column 0))
1893 ((py-continuation-line-p) ; shift relative to base line
1894 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001895 (t ; new base line
1896 (if (> ci (car indents)) ; going deeper; push it
1897 (setq indents (cons ci indents))
1898 ;; else we should have seen this indent before
1899 (setq indents (memq ci indents)) ; pop deeper indents
1900 (if (null indents)
1901 (error "Bad indentation in region, at line %d"
1902 (save-restriction
1903 (widen)
1904 (1+ (count-lines 1 (point)))))))
1905 (setq target-column (+ indent-base
1906 (* py-indent-offset
1907 (- (length indents) 2))))
1908 (setq base-shifted-by (- target-column ci))))
1909 ;; shift as needed
1910 (if (/= ci target-column)
1911 (progn
1912 (delete-horizontal-space)
1913 (indent-to target-column)))
1914 (forward-line 1))))
1915 (set-marker end nil))
1916
Barry Warsawa7891711996-08-01 15:53:09 +00001917(defun py-comment-region (beg end &optional arg)
1918 "Like `comment-region' but uses double hash (`#') comment starter."
1919 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001920 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001921 (comment-region beg end arg)))
1922
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001923
1924;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001925(defun py-previous-statement (count)
1926 "Go to the start of previous Python statement.
1927If the statement at point is the i'th Python statement, goes to the
1928start of statement i-COUNT. If there is no such statement, goes to the
1929first statement. Returns count of statements left to move.
1930`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001931 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001932 (if (< count 0) (py-next-statement (- count))
1933 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001934 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001935 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001936 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001937 (> count 0)
1938 (zerop (forward-line -1))
1939 (py-goto-statement-at-or-above))
1940 (setq count (1- count)))
1941 (if (> count 0) (goto-char start)))
1942 count))
1943
1944(defun py-next-statement (count)
1945 "Go to the start of next Python statement.
1946If the statement at point is the i'th Python statement, goes to the
1947start of statement i+COUNT. If there is no such statement, goes to the
1948last statement. Returns count of statements left to move. `Statements'
1949do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001950 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001951 (if (< count 0) (py-previous-statement (- count))
1952 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001953 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001954 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001955 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001956 (> count 0)
1957 (py-goto-statement-below))
1958 (setq count (1- count)))
1959 (if (> count 0) (goto-char start)))
1960 count))
1961
1962(defun py-goto-block-up (&optional nomark)
1963 "Move up to start of current block.
1964Go to the statement that starts the smallest enclosing block; roughly
1965speaking, this will be the closest preceding statement that ends with a
1966colon and is indented less than the statement you started on. If
1967successful, also sets the mark to the starting point.
1968
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001969`\\[py-mark-block]' can be used afterward to mark the whole code
1970block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001971
1972If called from a program, the mark will not be set if optional argument
1973NOMARK is not nil."
1974 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001975 (let ((start (point))
1976 (found nil)
1977 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001978 (py-goto-initial-line)
1979 ;; if on blank or non-indenting comment line, use the preceding stmt
1980 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1981 (progn
1982 (py-goto-statement-at-or-above)
1983 (setq found (py-statement-opens-block-p))))
1984 ;; search back for colon line indented less
1985 (setq initial-indent (current-indentation))
1986 (if (zerop initial-indent)
1987 ;; force fast exit
1988 (goto-char (point-min)))
1989 (while (not (or found (bobp)))
1990 (setq found
1991 (and
1992 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1993 (or (py-goto-initial-line) t) ; always true -- side effect
1994 (< (current-indentation) initial-indent)
1995 (py-statement-opens-block-p))))
1996 (if found
1997 (progn
1998 (or nomark (push-mark start))
1999 (back-to-indentation))
2000 (goto-char start)
2001 (error "Enclosing block not found"))))
2002
Barry Warsawab0e86c1998-05-19 15:31:46 +00002003(defun py-beginning-of-def-or-class (&optional class count)
2004 "Move point to start of `def' or `class'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002005
2006Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsawab0e86c1998-05-19 15:31:46 +00002007arg, looks for a `class' instead. The docs below assume the `def'
2008case; just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002009
Barry Warsawab0e86c1998-05-19 15:31:46 +00002010When second optional argument is given programmatically, move to the
2011COUNTth start of `def'.
2012
2013If point is in a `def' statement already, and after the `d', simply
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002014moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002015
Barry Warsawab0e86c1998-05-19 15:31:46 +00002016Otherwise (i.e. when point is not in a `def' statement, or at or
2017before the `d' of a `def' statement), searches for the closest
2018preceding `def' statement, and leaves point at its start. If no such
2019statement can be found, leaves point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002020
Barry Warsawab0e86c1998-05-19 15:31:46 +00002021Returns t iff a `def' statement is found by these rules.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002022
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002023Note that doing this command repeatedly will take you closer to the
2024start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002025
Barry Warsawab0e86c1998-05-19 15:31:46 +00002026If you want to mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002027 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002028 (if (not count)
2029 (setq count 1))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002030 (let ((at-or-before-p (<= (current-column) (current-indentation)))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002031 (start-of-line (goto-char (py-point 'bol)))
2032 (start-of-stmt (goto-char (py-point 'bos)))
2033 (start-re (if class
2034 "^[ \t]*class\\>"
2035 "^[ \t]*def\\>"))
2036 )
2037 ;; searching backward
2038 (if (and (< 0 count)
2039 (or (/= start-of-stmt start-of-line)
2040 (not at-or-before-p)))
2041 (end-of-line))
2042 ;; search forward
2043 (if (and (> 0 count)
2044 (zerop (current-column))
2045 (looking-at start-re))
2046 (end-of-line))
2047 (re-search-backward start-re nil 'move count)
2048 (goto-char (match-beginning 0))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002049
Barry Warsawab0e86c1998-05-19 15:31:46 +00002050;; Backwards compatibility
2051(defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002052
Barry Warsawab0e86c1998-05-19 15:31:46 +00002053(defun py-end-of-def-or-class (&optional class count)
2054 "Move point beyond end of `def' or `class' body.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002055
Barry Warsawab0e86c1998-05-19 15:31:46 +00002056By default, looks for an appropriate `def'. If you supply a prefix
2057arg, looks for a `class' instead. The docs below assume the `def'
2058case; just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002059
Barry Warsawab0e86c1998-05-19 15:31:46 +00002060When second optional argument is given programmatically, move to the
2061COUNTth end of `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002062
Barry Warsawab0e86c1998-05-19 15:31:46 +00002063If point is in a `def' statement already, this is the `def' we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002064
Barry Warsawab0e86c1998-05-19 15:31:46 +00002065Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2066contains the statement you started on, that's the `def' we use.
2067
2068Otherwise, we search forward for the closest following `def', and use that.
2069
2070If a `def' can be found by these rules, point is moved to the start of
2071the line immediately following the `def' block, and the position of the
2072start of the `def' is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002073
2074Else point is moved to the end of the buffer, and nil is returned.
2075
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002076Note that doing this command repeatedly will take you closer to the
2077end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002078
Barry Warsawab0e86c1998-05-19 15:31:46 +00002079If you want to mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002080 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002081 (if (and count (/= count 1))
2082 (py-beginning-of-def-or-class (- 1 count)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002083 (let ((start (progn (py-goto-initial-line) (point)))
2084 (which (if class "class" "def"))
2085 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002086 ;; move point to start of appropriate def/class
2087 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2088 (setq state 'at-beginning)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002089 ;; else see if py-beginning-of-def-or-class hits container
2090 (if (and (py-beginning-of-def-or-class class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002091 (progn (py-goto-beyond-block)
2092 (> (point) start)))
2093 (setq state 'at-end)
2094 ;; else search forward
2095 (goto-char start)
2096 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2097 (progn (setq state 'at-beginning)
2098 (beginning-of-line)))))
2099 (cond
2100 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2101 ((eq state 'at-end) t)
2102 ((eq state 'not-found) nil)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002103 (t (error "internal error in py-end-of-def-or-class")))))
2104
2105;; Backwards compabitility
2106(defalias 'py-end-of-def-or-class 'py-end-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002107
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002108
2109;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002110(defun py-mark-block (&optional extend just-move)
2111 "Mark following block of lines. With prefix arg, mark structure.
2112Easier to use than explain. It sets the region to an `interesting'
2113block of succeeding lines. If point is on a blank line, it goes down to
2114the next non-blank line. That will be the start of the region. The end
2115of the region depends on the kind of line at the start:
2116
2117 - If a comment, the region will include all succeeding comment lines up
2118 to (but not including) the next non-comment line (if any).
2119
2120 - Else if a prefix arg is given, and the line begins one of these
2121 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002122
2123 if elif else try except finally for while def class
2124
Barry Warsaw7ae77681994-12-12 20:38:05 +00002125 the region will be set to the body of the structure, including
2126 following blocks that `belong' to it, but excluding trailing blank
2127 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002128 and all (if any) of the following `except' and `finally' blocks
2129 that belong to the `try' structure will be in the region. Ditto
2130 for if/elif/else, for/else and while/else structures, and (a bit
2131 degenerate, since they're always one-block structures) def and
2132 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002133
2134 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002135 block (see list above), and the block is not a `one-liner' (i.e.,
2136 the statement ends with a colon, not with code), the region will
2137 include all succeeding lines up to (but not including) the next
2138 code statement (if any) that's indented no more than the starting
2139 line, except that trailing blank and comment lines are excluded.
2140 E.g., if the starting line begins a multi-statement `def'
2141 structure, the region will be set to the full function definition,
2142 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002143
2144 - Else the region will include all succeeding lines up to (but not
2145 including) the next blank line, or code or indenting-comment line
2146 indented strictly less than the starting line. Trailing indenting
2147 comment lines are included in this case, but not trailing blank
2148 lines.
2149
2150A msg identifying the location of the mark is displayed in the echo
2151area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2152
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002153If called from a program, optional argument EXTEND plays the role of
2154the prefix arg, and if optional argument JUST-MOVE is not nil, just
2155moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002156 (interactive "P") ; raw prefix arg
2157 (py-goto-initial-line)
2158 ;; skip over blank lines
2159 (while (and
2160 (looking-at "[ \t]*$") ; while blank line
2161 (not (eobp))) ; & somewhere to go
2162 (forward-line 1))
2163 (if (eobp)
2164 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002165 (let ((initial-pos (point))
2166 (initial-indent (current-indentation))
2167 last-pos ; position of last stmt in region
2168 (followers
2169 '((if elif else) (elif elif else) (else)
2170 (try except finally) (except except) (finally)
2171 (for else) (while else)
2172 (def) (class) ) )
2173 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002174
2175 (cond
2176 ;; if comment line, suck up the following comment lines
2177 ((looking-at "[ \t]*#")
2178 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2179 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2180 (setq last-pos (point)))
2181
2182 ;; else if line is a block line and EXTEND given, suck up
2183 ;; the whole structure
2184 ((and extend
2185 (setq first-symbol (py-suck-up-first-keyword) )
2186 (assq first-symbol followers))
2187 (while (and
2188 (or (py-goto-beyond-block) t) ; side effect
2189 (forward-line -1) ; side effect
2190 (setq last-pos (point)) ; side effect
2191 (py-goto-statement-below)
2192 (= (current-indentation) initial-indent)
2193 (setq next-symbol (py-suck-up-first-keyword))
2194 (memq next-symbol (cdr (assq first-symbol followers))))
2195 (setq first-symbol next-symbol)))
2196
2197 ;; else if line *opens* a block, search for next stmt indented <=
2198 ((py-statement-opens-block-p)
2199 (while (and
2200 (setq last-pos (point)) ; always true -- side effect
2201 (py-goto-statement-below)
2202 (> (current-indentation) initial-indent))
2203 nil))
2204
2205 ;; else plain code line; stop at next blank line, or stmt or
2206 ;; indenting comment line indented <
2207 (t
2208 (while (and
2209 (setq last-pos (point)) ; always true -- side effect
2210 (or (py-goto-beyond-final-line) t)
2211 (not (looking-at "[ \t]*$")) ; stop at blank line
2212 (or
2213 (>= (current-indentation) initial-indent)
2214 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2215 nil)))
2216
2217 ;; skip to end of last stmt
2218 (goto-char last-pos)
2219 (py-goto-beyond-final-line)
2220
2221 ;; set mark & display
2222 (if just-move
2223 () ; just return
2224 (push-mark (point) 'no-msg)
2225 (forward-line -1)
2226 (message "Mark set after: %s" (py-suck-up-leading-text))
2227 (goto-char initial-pos))))
2228
Barry Warsaw2518c671997-11-05 00:51:08 +00002229(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002230 "Set region to body of def (or class, with prefix arg) enclosing point.
2231Pushes the current mark, then point, on the mark ring (all language
2232modes do this, but although it's handy it's never documented ...).
2233
2234In most Emacs language modes, this function bears at least a
Barry Warsawab0e86c1998-05-19 15:31:46 +00002235hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2236`\\[py-beginning-of-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002237
2238And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002239Turned out that was more confusing than useful: the `goto start' and
2240`goto end' commands are usually used to search through a file, and
2241people expect them to act a lot like `search backward' and `search
2242forward' string-search commands. But because Python `def' and `class'
2243can nest to arbitrary levels, finding the smallest def containing
2244point cannot be done via a simple backward search: the def containing
2245point may not be the closest preceding def, or even the closest
2246preceding def that's indented less. The fancy algorithm required is
2247appropriate for the usual uses of this `mark' command, but not for the
2248`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002249
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002250So the def marked by this command may not be the one either of the
2251`goto' commands find: If point is on a blank or non-indenting comment
2252line, moves back to start of the closest preceding code statement or
2253indenting comment line. If this is a `def' statement, that's the def
2254we use. Else searches for the smallest enclosing `def' block and uses
2255that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002256
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002257When an enclosing def is found: The mark is left immediately beyond
2258the last line of the def block. Point is left at the start of the
2259def, except that: if the def is preceded by a number of comment lines
2260followed by (at most) one optional blank line, point is left at the
2261start of the comments; else if the def is preceded by a blank line,
2262point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002263
2264The intent is to mark the containing def/class and its associated
2265documentation, to make moving and duplicating functions and classes
2266pleasant."
2267 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002268 (let ((start (point))
2269 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002270 (push-mark start)
2271 (if (not (py-go-up-tree-to-keyword which))
2272 (progn (goto-char start)
2273 (error "Enclosing %s not found" which))
2274 ;; else enclosing def/class found
2275 (setq start (point))
2276 (py-goto-beyond-block)
2277 (push-mark (point))
2278 (goto-char start)
2279 (if (zerop (forward-line -1)) ; if there is a preceding line
2280 (progn
2281 (if (looking-at "[ \t]*$") ; it's blank
2282 (setq start (point)) ; so reset start point
2283 (goto-char start)) ; else try again
2284 (if (zerop (forward-line -1))
2285 (if (looking-at "[ \t]*#") ; a comment
2286 ;; look back for non-comment line
2287 ;; tricky: note that the regexp matches a blank
2288 ;; line, cuz \n is in the 2nd character class
2289 (and
2290 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2291 (forward-line 1))
2292 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002293 (goto-char start)))))))
2294 (exchange-point-and-mark)
2295 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002296
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002297;; ripped from cc-mode
2298(defun py-forward-into-nomenclature (&optional arg)
2299 "Move forward to end of a nomenclature section or word.
2300With arg, to it arg times.
2301
2302A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2303 (interactive "p")
2304 (let ((case-fold-search nil))
2305 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002306 (re-search-forward
2307 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2308 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002309 (while (and (< arg 0)
2310 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002311 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002312 (point-min) 0))
2313 (forward-char 1)
2314 (setq arg (1+ arg)))))
2315 (py-keep-region-active))
2316
2317(defun py-backward-into-nomenclature (&optional arg)
2318 "Move backward to beginning of a nomenclature section or word.
2319With optional ARG, move that many times. If ARG is negative, move
2320forward.
2321
2322A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2323 (interactive "p")
2324 (py-forward-into-nomenclature (- arg))
2325 (py-keep-region-active))
2326
2327
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002328
2329;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002330
2331;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002332;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2333;; out of the right places, along with the keys they're on & current
2334;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002335(defun py-dump-help-string (str)
2336 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002337 (let ((locals (buffer-local-variables))
2338 funckind funcname func funcdoc
2339 (start 0) mstart end
2340 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002341 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2342 (setq mstart (match-beginning 0) end (match-end 0)
2343 funckind (substring str (match-beginning 1) (match-end 1))
2344 funcname (substring str (match-beginning 2) (match-end 2))
2345 func (intern funcname))
2346 (princ (substitute-command-keys (substring str start mstart)))
2347 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002348 ((equal funckind "c") ; command
2349 (setq funcdoc (documentation func)
2350 keys (concat
2351 "Key(s): "
2352 (mapconcat 'key-description
2353 (where-is-internal func py-mode-map)
2354 ", "))))
2355 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002356 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002357 keys (if (assq func locals)
2358 (concat
2359 "Local/Global values: "
2360 (prin1-to-string (symbol-value func))
2361 " / "
2362 (prin1-to-string (default-value func)))
2363 (concat
2364 "Value: "
2365 (prin1-to-string (symbol-value func))))))
2366 (t ; unexpected
2367 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002368 (princ (format "\n-> %s:\t%s\t%s\n\n"
2369 (if (equal funckind "c") "Command" "Variable")
2370 funcname keys))
2371 (princ funcdoc)
2372 (terpri)
2373 (setq start end))
2374 (princ (substitute-command-keys (substring str start))))
2375 (print-help-return-message)))
2376
2377(defun py-describe-mode ()
2378 "Dump long form of Python-mode docs."
2379 (interactive)
2380 (py-dump-help-string "Major mode for editing Python files.
2381Knows about Python indentation, tokens, comments and continuation lines.
2382Paragraphs are separated by blank lines only.
2383
2384Major sections below begin with the string `@'; specific function and
2385variable docs begin with `->'.
2386
2387@EXECUTING PYTHON CODE
2388
2389\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2390\\[py-execute-region]\tsends the current region
2391\\[py-shell]\tstarts a Python interpreter window; this will be used by
2392\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2393%c:py-execute-buffer
2394%c:py-execute-region
2395%c:py-shell
2396
2397@VARIABLES
2398
2399py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002400py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002401
2402py-python-command\tshell command to invoke Python interpreter
2403py-scroll-process-buffer\talways scroll Python process buffer
2404py-temp-directory\tdirectory used for temp files (if needed)
2405
2406py-beep-if-tab-change\tring the bell if tab-width is changed
2407%v:py-indent-offset
2408%v:py-block-comment-prefix
2409%v:py-python-command
2410%v:py-scroll-process-buffer
2411%v:py-temp-directory
2412%v:py-beep-if-tab-change
2413
2414@KINDS OF LINES
2415
2416Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002417preceding line ends with a backslash that's not part of a comment, or
2418the paren/bracket/brace nesting level at the start of the line is
2419non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002420
2421An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002422possibly blanks or tabs), a `comment line' (leftmost non-blank
2423character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002424
2425Comment Lines
2426
2427Although all comment lines are treated alike by Python, Python mode
2428recognizes two kinds that act differently with respect to indentation.
2429
2430An `indenting comment line' is a comment line with a blank, tab or
2431nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002432treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002433indenting comment line will be indented like the comment line. All
2434other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002435following the initial `#') are `non-indenting comment lines', and
2436their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002437
2438Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002439whenever possible. Non-indenting comment lines are useful in cases
2440like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002441
2442\ta = b # a very wordy single-line comment that ends up being
2443\t #... continued onto another line
2444
2445\tif a == b:
2446##\t\tprint 'panic!' # old code we've `commented out'
2447\t\treturn a
2448
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002449Since the `#...' and `##' comment lines have a non-whitespace
2450character following the initial `#', Python mode ignores them when
2451computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002452
2453Continuation Lines and Statements
2454
2455The Python-mode commands generally work on statements instead of on
2456individual lines, where a `statement' is a comment or blank line, or a
2457code line and all of its following continuation lines (if any)
2458considered as a single logical unit. The commands in this mode
2459generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002460statement containing point, even if point happens to be in the middle
2461of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002462
2463
2464@INDENTATION
2465
2466Primarily for entering new code:
2467\t\\[indent-for-tab-command]\t indent line appropriately
2468\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002469\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002470
2471Primarily for reindenting existing code:
2472\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2473\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2474
2475\t\\[py-indent-region]\t reindent region to match its context
2476\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2477\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2478
2479Unlike most programming languages, Python uses indentation, and only
2480indentation, to specify block structure. Hence the indentation supplied
2481automatically by Python-mode is just an educated guess: only you know
2482the block structure you intend, so only you can supply correct
2483indentation.
2484
2485The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2486the indentation of preceding statements. E.g., assuming
2487py-indent-offset is 4, after you enter
2488\tif a > 0: \\[py-newline-and-indent]
2489the cursor will be moved to the position of the `_' (_ is not a
2490character in the file, it's just used here to indicate the location of
2491the cursor):
2492\tif a > 0:
2493\t _
2494If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2495to
2496\tif a > 0:
2497\t c = d
2498\t _
2499Python-mode cannot know whether that's what you intended, or whether
2500\tif a > 0:
2501\t c = d
2502\t_
2503was your intent. In general, Python-mode either reproduces the
2504indentation of the (closest code or indenting-comment) preceding
2505statement, or adds an extra py-indent-offset blanks if the preceding
2506statement has `:' as its last significant (non-whitespace and non-
2507comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002508\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002509
2510Continuation lines are given extra indentation. If you don't like the
2511suggested indentation, change it to something you do like, and Python-
2512mode will strive to indent later lines of the statement in the same way.
2513
2514If a line is a continuation line by virtue of being in an unclosed
2515paren/bracket/brace structure (`list', for short), the suggested
2516indentation depends on whether the current line contains the first item
2517in the list. If it does, it's indented py-indent-offset columns beyond
2518the indentation of the line containing the open bracket. If you don't
2519like that, change it by hand. The remaining items in the list will mimic
2520whatever indentation you give to the first item.
2521
2522If a line is a continuation line because the line preceding it ends with
2523a backslash, the third and following lines of the statement inherit their
2524indentation from the line preceding them. The indentation of the second
2525line in the statement depends on the form of the first (base) line: if
2526the base line is an assignment statement with anything more interesting
2527than the backslash following the leftmost assigning `=', the second line
2528is indented two columns beyond that `='. Else it's indented to two
2529columns beyond the leftmost solid chunk of non-whitespace characters on
2530the base line.
2531
2532Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2533repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2534structure you intend.
2535%c:indent-for-tab-command
2536%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002537%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002538
2539
2540The next function may be handy when editing code you didn't write:
2541%c:py-guess-indent-offset
2542
2543
2544The remaining `indent' functions apply to a region of Python code. They
2545assume the block structure (equals indentation, in Python) of the region
2546is correct, and alter the indentation in various ways while preserving
2547the block structure:
2548%c:py-indent-region
2549%c:py-shift-region-left
2550%c:py-shift-region-right
2551
2552@MARKING & MANIPULATING REGIONS OF CODE
2553
2554\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002555\\[py-mark-def-or-class]\t mark smallest enclosing def
2556\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002557\\[comment-region]\t comment out region of code
2558\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002559%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002560%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002561%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002562
2563@MOVING POINT
2564
2565\\[py-previous-statement]\t move to statement preceding point
2566\\[py-next-statement]\t move to statement following point
2567\\[py-goto-block-up]\t move up to start of current block
Barry Warsawab0e86c1998-05-19 15:31:46 +00002568\\[py-beginning-of-def-or-class]\t move to start of def
2569\\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
2570\\[py-end-of-def-or-class]\t move to end of def
2571\\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002572
2573The first two move to one statement beyond the statement that contains
2574point. A numeric prefix argument tells them to move that many
2575statements instead. Blank lines, comment lines, and continuation lines
2576do not count as `statements' for these commands. So, e.g., you can go
2577to the first code statement in a file by entering
2578\t\\[beginning-of-buffer]\t to move to the top of the file
2579\t\\[py-next-statement]\t to skip over initial comments and blank lines
2580Or do `\\[py-previous-statement]' with a huge prefix argument.
2581%c:py-previous-statement
2582%c:py-next-statement
2583%c:py-goto-block-up
Barry Warsawab0e86c1998-05-19 15:31:46 +00002584%c:py-beginning-of-def-or-class
2585%c:py-end-of-def-or-class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002586
2587@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2588
2589`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2590
2591`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2592overall class and def structure of a module.
2593
2594`\\[back-to-indentation]' moves point to a line's first non-blank character.
2595
2596`\\[indent-relative]' is handy for creating odd indentation.
2597
2598@OTHER EMACS HINTS
2599
2600If you don't like the default value of a variable, change its value to
2601whatever you do like by putting a `setq' line in your .emacs file.
2602E.g., to set the indentation increment to 4, put this line in your
2603.emacs:
2604\t(setq py-indent-offset 4)
2605To see the value of a variable, do `\\[describe-variable]' and enter the variable
2606name at the prompt.
2607
2608When entering a key sequence like `C-c C-n', it is not necessary to
2609release the CONTROL key after doing the `C-c' part -- it suffices to
2610press the CONTROL key, press and release `c' (while still holding down
2611CONTROL), press and release `n' (while still holding down CONTROL), &
2612then release CONTROL.
2613
2614Entering Python mode calls with no arguments the value of the variable
2615`python-mode-hook', if that value exists and is not nil; for backward
2616compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2617the Elisp manual for details.
2618
2619Obscure: When python-mode is first loaded, it looks for all bindings
2620to newline-and-indent in the global keymap, and shadows them with
2621local bindings to py-newline-and-indent."))
2622
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002623
2624;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002625(defvar py-parse-state-re
2626 (concat
2627 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2628 "\\|"
2629 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002630
Barry Warsaw7ae77681994-12-12 20:38:05 +00002631;; returns the parse state at point (see parse-partial-sexp docs)
2632(defun py-parse-state ()
2633 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002634 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002635 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002636 (while (not done)
2637 ;; back up to the first preceding line (if any; else start of
2638 ;; buffer) that begins with a popular Python keyword, or a
2639 ;; non- whitespace and non-comment character. These are good
2640 ;; places to start parsing to see whether where we started is
2641 ;; at a non-zero nesting level. It may be slow for people who
2642 ;; write huge code blocks or huge lists ... tough beans.
2643 (re-search-backward py-parse-state-re nil 'move)
2644 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002645 ;; In XEmacs, we have a much better way to test for whether
2646 ;; we're in a triple-quoted string or not. Emacs does not
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002647 ;; have this built-in function, which is its loss because
Barry Warsawf64b4051998-02-12 16:52:14 +00002648 ;; without scanning from the beginning of the buffer, there's
2649 ;; no accurate way to determine this otherwise.
2650 (if (not (fboundp 'buffer-syntactic-context))
2651 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002652 (progn
2653 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002654 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002655 (setq done (or (not (nth 3 pps))
2656 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002657 ;; XEmacs
2658 (setq done (or (not (buffer-syntactic-context))
2659 (bobp)))
2660 (when done
2661 (setq pps (parse-partial-sexp (point) here)))
2662 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002663 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002664
2665;; if point is at a non-zero nesting level, returns the number of the
2666;; character that opens the smallest enclosing unclosed list; else
2667;; returns nil.
2668(defun py-nesting-level ()
Barry Warsawf64b4051998-02-12 16:52:14 +00002669 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002670 (if (zerop (car status))
2671 nil ; not in a nest
2672 (car (cdr status))))) ; char# of open bracket
2673
2674;; t iff preceding line ends with backslash that's not in a comment
2675(defun py-backslash-continuation-line-p ()
2676 (save-excursion
2677 (beginning-of-line)
2678 (and
2679 ;; use a cheap test first to avoid the regexp if possible
2680 ;; use 'eq' because char-after may return nil
2681 (eq (char-after (- (point) 2)) ?\\ )
2682 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002683 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002684 (looking-at py-continued-re))))
2685
2686;; t iff current line is a continuation line
2687(defun py-continuation-line-p ()
2688 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002689 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002690 (or (py-backslash-continuation-line-p)
2691 (py-nesting-level))))
2692
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002693;; go to initial line of current statement; usually this is the line
2694;; we're on, but if we're on the 2nd or following lines of a
2695;; continuation block, we need to go up to the first line of the
2696;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002697;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002698;; Tricky: We want to avoid quadratic-time behavior for long continued
2699;; blocks, whether of the backslash or open-bracket varieties, or a
2700;; mix of the two. The following manages to do that in the usual
2701;; cases.
Barry Warsawc210e691998-01-20 22:52:56 +00002702;;
2703;; Also, if we're sitting inside a triple quoted string, this will
2704;; drop us at the line that begins the string.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002705(defun py-goto-initial-line ()
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002706 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002707 (while (py-continuation-line-p)
2708 (beginning-of-line)
2709 (if (py-backslash-continuation-line-p)
2710 (while (py-backslash-continuation-line-p)
2711 (forward-line -1))
2712 ;; else zip out of nested brackets/braces/parens
2713 (while (setq open-bracket-pos (py-nesting-level))
2714 (goto-char open-bracket-pos)))))
2715 (beginning-of-line))
2716
2717;; go to point right beyond final line of current statement; usually
2718;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002719;; statement we need to skip over the continuation lines. Tricky:
2720;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002721(defun py-goto-beyond-final-line ()
2722 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002723 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002724 (while (and (py-continuation-line-p)
2725 (not (eobp)))
2726 ;; skip over the backslash flavor
2727 (while (and (py-backslash-continuation-line-p)
2728 (not (eobp)))
2729 (forward-line 1))
2730 ;; if in nest, zip to the end of the nest
2731 (setq state (py-parse-state))
2732 (if (and (not (zerop (car state)))
2733 (not (eobp)))
2734 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002735 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002736 (forward-line 1))))))
2737
2738;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002739;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002740(defun py-statement-opens-block-p ()
2741 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002742 (let ((start (point))
2743 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2744 (searching t)
2745 (answer nil)
2746 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002747 (goto-char start)
2748 (while searching
2749 ;; look for a colon with nothing after it except whitespace, and
2750 ;; maybe a comment
2751 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2752 finish t)
2753 (if (eq (point) finish) ; note: no `else' clause; just
2754 ; keep searching if we're not at
2755 ; the end yet
2756 ;; sure looks like it opens a block -- but it might
2757 ;; be in a comment
2758 (progn
2759 (setq searching nil) ; search is done either way
2760 (setq state (parse-partial-sexp start
2761 (match-beginning 0)))
2762 (setq answer (not (nth 4 state)))))
2763 ;; search failed: couldn't find another interesting colon
2764 (setq searching nil)))
2765 answer)))
2766
Barry Warsawf831d811996-07-31 20:42:59 +00002767(defun py-statement-closes-block-p ()
2768 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002769 ;; starts with `return', `raise', `break', `continue', and `pass'.
2770 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002771 (let ((here (point)))
2772 (back-to-indentation)
2773 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002774 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002775 (goto-char here))))
2776
Barry Warsaw7ae77681994-12-12 20:38:05 +00002777;; go to point right beyond final line of block begun by the current
2778;; line. This is the same as where py-goto-beyond-final-line goes
2779;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002780;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002781(defun py-goto-beyond-block ()
2782 (if (py-statement-opens-block-p)
2783 (py-mark-block nil 'just-move)
2784 (py-goto-beyond-final-line)))
2785
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002786;; Go to start of first statement (not blank or comment or
2787;; continuation line) at or preceding point. Returns t if there is
2788;; one, else nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002789(defun py-goto-statement-at-or-above ()
2790 (py-goto-initial-line)
2791 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002792 ;; skip back over blank & comment lines
2793 ;; note: will skip a blank or comment line that happens to be
2794 ;; a continuation line too
2795 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2796 (progn (py-goto-initial-line) t)
2797 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002798 t))
2799
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002800;; Go to start of first statement (not blank or comment or
2801;; continuation line) following the statement containing point.
2802;; Returns t if there is one, else nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002803(defun py-goto-statement-below ()
2804 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002805 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002806 (py-goto-beyond-final-line)
2807 (while (and
2808 (looking-at py-blank-or-comment-re)
2809 (not (eobp)))
2810 (forward-line 1))
2811 (if (eobp)
2812 (progn (goto-char start) nil)
2813 t)))
2814
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002815;; Go to start of statement, at or preceding point, starting with
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002816;; keyword KEY. Skips blank lines and non-indenting comments upward
2817;; first. If that statement starts with KEY, done, else go back to
2818;; first enclosing block starting with KEY. If successful, leaves
2819;; point at the start of the KEY line & returns t. Else leaves point
2820;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002821(defun py-go-up-tree-to-keyword (key)
2822 ;; skip blanks and non-indenting #
2823 (py-goto-initial-line)
2824 (while (and
2825 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2826 (zerop (forward-line -1))) ; go back
2827 nil)
2828 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002829 (let* ((re (concat "[ \t]*" key "\\b"))
2830 (case-fold-search nil) ; let* so looking-at sees this
2831 (found (looking-at re))
2832 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002833 (while (not (or found dead))
2834 (condition-case nil ; in case no enclosing block
2835 (py-goto-block-up 'no-mark)
2836 (error (setq dead t)))
2837 (or dead (setq found (looking-at re))))
2838 (beginning-of-line)
2839 found))
2840
2841;; return string in buffer from start of indentation to end of line;
2842;; prefix "..." if leading whitespace was skipped
2843(defun py-suck-up-leading-text ()
2844 (save-excursion
2845 (back-to-indentation)
2846 (concat
2847 (if (bolp) "" "...")
2848 (buffer-substring (point) (progn (end-of-line) (point))))))
2849
2850;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2851;; as a Lisp symbol; return nil if none
2852(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002853 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002854 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2855 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2856 nil)))
2857
Barry Warsawb3e81d51996-09-04 15:12:42 +00002858(defun py-current-defun ()
2859 ;; tell add-log.el how to find the current function/method/variable
2860 (save-excursion
2861 (if (re-search-backward py-defun-start-re nil t)
2862 (or (match-string 3)
2863 (let ((method (match-string 2)))
2864 (if (and (not (zerop (length (match-string 1))))
2865 (re-search-backward py-class-start-re nil t))
2866 (concat (match-string 1) "." method)
2867 method)))
2868 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002869
2870
Barry Warsawfec75d61995-07-05 23:26:15 +00002871(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002872 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002873
Barry Warsaw850437a1995-03-08 21:50:28 +00002874(defun py-version ()
2875 "Echo the current version of `python-mode' in the minibuffer."
2876 (interactive)
2877 (message "Using `python-mode' version %s" py-version)
2878 (py-keep-region-active))
2879
2880;; only works under Emacs 19
2881;(eval-when-compile
2882; (require 'reporter))
2883
2884(defun py-submit-bug-report (enhancement-p)
2885 "Submit via mail a bug report on `python-mode'.
2886With \\[universal-argument] just submit an enhancement request."
2887 (interactive
2888 (list (not (y-or-n-p
2889 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002890 (let ((reporter-prompt-for-summary-p (if enhancement-p
2891 "(Very) brief summary: "
2892 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002893 (require 'reporter)
2894 (reporter-submit-bug-report
2895 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002896 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002897 ;; varlist
2898 (if enhancement-p nil
2899 '(py-python-command
2900 py-indent-offset
2901 py-block-comment-prefix
2902 py-scroll-process-buffer
2903 py-temp-directory
2904 py-beep-if-tab-change))
2905 nil ;pre-hooks
2906 nil ;post-hooks
2907 "Dear Barry,") ;salutation
2908 (if enhancement-p nil
2909 (set-mark (point))
2910 (insert
2911"Please replace this text with a sufficiently large code sample\n\
2912and an exact recipe so that I can reproduce your problem. Failure\n\
2913to do so may mean a greater delay in fixing your bug.\n\n")
2914 (exchange-point-and-mark)
2915 (py-keep-region-active))))
2916
2917
Barry Warsaw47384781997-11-26 05:27:45 +00002918(defun py-kill-emacs-hook ()
2919 (mapcar #'(lambda (filename)
2920 (py-safe (delete-file filename)))
2921 py-file-queue))
2922
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002923;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002924(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002925
2926
2927
2928(provide 'python-mode)
2929;;; python-mode.el ends here