blob: 39d1f1be10694d2fb1a2d4fdb9873c0dae4598f2 [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
Barry Warsaw751f4931998-05-19 16:06:21 +0000406 ;; These fail if backslash-quote ends the string (not worth
407 ;; fixing?). They precede the short versions so that the first two
408 ;; quotes don't look like an empty short string.
409 ;;
410 ;; (maybe raw), long single quoted triple quoted strings (SQTQ),
411 ;; with potential embedded single quotes
412 "[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
413 "\\|"
414 ;; (maybe raw), long double quoted triple quoted strings (DQTQ),
415 ;; with potential embedded double quotes
416 "[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
417 "\\|"
418 "[rR]?'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
Barry Warsawc72c11c1997-08-09 06:42:08 +0000419 "\\|" ; or
Barry Warsaw751f4931998-05-19 16:06:21 +0000420 "[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\"" ; double-quoted
421 ))
422
Barry Warsawc72c11c1997-08-09 06:42:08 +0000423
424;; Regexp matching Python lines that are continued via backslash.
425;; This is tricky because a trailing backslash does not mean
426;; continuation if it's in a comment
427(defconst py-continued-re
428 (concat
429 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
430 "\\\\$"))
431
432;; Regexp matching blank or comment lines.
433(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
434
435;; Regexp matching clauses to be outdented one level.
436(defconst py-outdent-re
437 (concat "\\(" (mapconcat 'identity
438 '("else:"
439 "except\\(\\s +.*\\)?:"
440 "finally:"
441 "elif\\s +.*:")
442 "\\|")
443 "\\)"))
444
445
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000446;; Regexp matching keywords which typically close a block
447(defconst py-block-closing-keywords-re
448 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
449
Barry Warsawc72c11c1997-08-09 06:42:08 +0000450;; Regexp matching lines to not outdent after.
451(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000452 (concat
453 "\\("
454 (mapconcat 'identity
455 (list "try:"
456 "except\\(\\s +.*\\)?:"
457 "while\\s +.*:"
458 "for\\s +.*:"
459 "if\\s +.*:"
460 "elif\\s +.*:"
461 (concat py-block-closing-keywords-re "[ \t\n]")
462 )
463 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000464 "\\)"))
465
466;; Regexp matching a function, method or variable assignment. If you
467;; change this, you probably have to change `py-current-defun' as
468;; well. This is only used by `py-current-defun' to find the name for
469;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000470(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000471 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
472
473;; Regexp for finding a class name. If you change this, you probably
474;; have to change `py-current-defun' as well. This is only used by
475;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000476(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
477
478;; Regexp that describes tracebacks
479(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000480 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000481
482
483
484;; Utilities
485
486(defmacro py-safe (&rest body)
487 ;; safely execute BODY, return nil if an error occurred
488 (` (condition-case nil
489 (progn (,@ body))
490 (error nil))))
491
492(defsubst py-keep-region-active ()
493 ;; Do whatever is necessary to keep the region active in XEmacs.
494 ;; Ignore byte-compiler warnings you might see. Also note that
495 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
496 ;; to take explicit action.
497 (and (boundp 'zmacs-region-stays)
498 (setq zmacs-region-stays t)))
499
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000500(defsubst py-point (position)
501 ;; Returns the value of point at certain commonly referenced POSITIONs.
502 ;; POSITION can be one of the following symbols:
503 ;;
504 ;; bol -- beginning of line
505 ;; eol -- end of line
506 ;; bod -- beginning of defun
Barry Warsawab0e86c1998-05-19 15:31:46 +0000507 ;; bob -- beginning of buffer
508 ;; eob -- end of buffer
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000509 ;; boi -- back to indentation
Barry Warsawab0e86c1998-05-19 15:31:46 +0000510 ;; bos -- beginning of statement
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000511 ;;
512 ;; This function does not modify point or mark.
513 (let ((here (point)))
514 (cond
515 ((eq position 'bol) (beginning-of-line))
516 ((eq position 'eol) (end-of-line))
Barry Warsawab0e86c1998-05-19 15:31:46 +0000517 ((eq position 'bod) (py-beginning-of-def-or-class))
518 ;; Kind of funny, I know, but useful for py-up-exception.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000519 ((eq position 'bob) (beginning-of-buffer))
520 ((eq position 'eob) (end-of-buffer))
521 ((eq position 'boi) (back-to-indentation))
Barry Warsawab0e86c1998-05-19 15:31:46 +0000522 ((eq position 'bos) (py-goto-initial-line))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000523 (t (error "unknown buffer position requested: %s" position))
524 )
525 (prog1
526 (point)
527 (goto-char here))))
528
529(defsubst py-highlight-line (from to file line)
530 (cond
531 ((fboundp 'make-extent)
532 ;; XEmacs
533 (let ((e (make-extent from to)))
534 (set-extent-property e 'mouse-face 'highlight)
535 (set-extent-property e 'py-exc-info (cons file line))
536 (set-extent-property e 'keymap py-mode-output-map)))
537 (t
538 ;; Emacs -- Please port this!
539 )
540 ))
541
Barry Warsawe908b6b1998-03-19 22:48:02 +0000542(defun py-in-literal (&optional lim)
543 ;; Determine if point is in a Python literal, defined as a comment
544 ;; or string. This is the version used for non-XEmacs, which has a
545 ;; nicer interface.
546 ;;
547 ;; WARNING: Watch out for infinite recursion.
548 (let* ((lim (or lim (c-point 'bod)))
549 (state (parse-partial-sexp lim (point))))
550 (cond
551 ((nth 3 state) 'string)
552 ((nth 4 state) 'comment)
553 (t nil))))
554
555;; XEmacs has a built-in function that should make this much quicker.
556;; In this case, lim is ignored
557(defun py-fast-in-literal (&optional lim)
558 ;; don't have to worry about context == 'block-comment
559 (buffer-syntactic-context))
560
561(if (fboundp 'buffer-syntactic-context)
562 (defalias 'c-in-literal 'c-fast-in-literal))
563
564
Barry Warsawc72c11c1997-08-09 06:42:08 +0000565
566;; Major mode boilerplate
567
Barry Warsaw7ae77681994-12-12 20:38:05 +0000568;; define a mode-specific abbrev table for those who use such things
569(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000570 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000571(define-abbrev-table 'python-mode-abbrev-table nil)
572
Barry Warsaw7ae77681994-12-12 20:38:05 +0000573(defvar python-mode-hook nil
574 "*Hook called by `python-mode'.")
575
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000576;; In previous version of python-mode.el, the hook was incorrectly
577;; called py-mode-hook, and was not defvar'd. Deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000578(and (fboundp 'make-obsolete-variable)
579 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
580
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000581(defvar py-mode-map ()
582 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000583(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000584 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000585 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000586 ;; electric keys
587 (define-key py-mode-map ":" 'py-electric-colon)
588 ;; indentation level modifiers
589 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
590 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
591 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
592 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
593 ;; subprocess commands
594 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
Barry Warsaw820273d1998-05-19 15:54:45 +0000595 (define-key py-mode-map "\C-c\C-m" 'py-execute-import-or-reload)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000596 (define-key py-mode-map "\C-c|" 'py-execute-region)
Barry Warsaw820273d1998-05-19 15:54:45 +0000597 (define-key py-mode-map "\e\C-x" 'py-execute-def-or-class)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000598 (define-key py-mode-map "\C-c!" 'py-shell)
Barry Warsawa2398801998-04-09 23:28:20 +0000599 (define-key py-mode-map "\C-c\C-t" 'py-toggle-shells)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000600 ;; Caution! Enter here at your own risk. We are trying to support
601 ;; several behaviors and it gets disgusting. :-( This logic ripped
602 ;; largely from CC Mode.
603 ;;
604 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
605 ;; backwards deletion behavior to DEL, which both Delete and
606 ;; Backspace get translated to. There's no way to separate this
607 ;; behavior in a clean way, so deal with it! Besides, it's been
608 ;; this way since the dawn of time.
609 (if (not (boundp 'delete-key-deletes-forward))
610 (define-key py-mode-map "\177" 'py-electric-backspace)
611 ;; However, XEmacs 20 actually achieved enlightenment. It is
612 ;; possible to sanely define both backward and forward deletion
613 ;; behavior under X separately (TTYs are forever beyond hope, but
614 ;; who cares? XEmacs 20 does the right thing with these too).
615 (define-key py-mode-map [delete] 'py-electric-delete)
616 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000617 ;; Separate M-BS from C-M-h. The former should remain
618 ;; backward-kill-word.
619 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000620 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000621 ;; Miscellaneous
622 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
623 (define-key py-mode-map "\C-c\t" 'py-indent-region)
624 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
625 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
626 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000627 (define-key py-mode-map "\C-c#" 'py-comment-region)
628 (define-key py-mode-map "\C-c?" 'py-describe-mode)
629 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
Barry Warsawab0e86c1998-05-19 15:31:46 +0000630 (define-key py-mode-map "\e\C-a" 'py-beginning-of-def-or-class)
631 (define-key py-mode-map "\e\C-e" 'py-end-of-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000632 (define-key py-mode-map "\C-c-" 'py-up-exception)
633 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000634 ;; information
635 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
636 (define-key py-mode-map "\C-c\C-v" 'py-version)
637 ;; py-newline-and-indent mappings
Barry Warsaw82aecb91998-01-21 05:14:24 +0000638 (define-key py-mode-map "\n" 'py-newline-and-indent)
639 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000640 ;; shadow global bindings for newline-and-indent w/ the py- version.
641 ;; BAW - this is extremely bad form, but I'm not going to change it
642 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000643 (mapcar #'(lambda (key)
644 (define-key py-mode-map key 'py-newline-and-indent))
645 (where-is-internal 'newline-and-indent))
646 )
647
648(defvar py-mode-output-map nil
649 "Keymap used in *Python Output* buffers*")
650(if py-mode-output-map
651 nil
652 (setq py-mode-output-map (make-sparse-keymap))
653 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
654 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
655 ;; TBD: Disable all self-inserting keys. This is bogus, we should
656 ;; really implement this as *Python Output* buffer being read-only
657 (mapcar #' (lambda (key)
658 (define-key py-mode-output-map key
659 #'(lambda () (interactive) (beep))))
660 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000661 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000662
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000663(defvar py-mode-syntax-table nil
664 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000665(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000666 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000667 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000668 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
669 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
670 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
671 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
672 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
673 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
674 ;; Add operator symbols misassigned in the std table
675 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
676 (modify-syntax-entry ?\% "." py-mode-syntax-table)
677 (modify-syntax-entry ?\& "." py-mode-syntax-table)
678 (modify-syntax-entry ?\* "." py-mode-syntax-table)
679 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
680 (modify-syntax-entry ?\- "." py-mode-syntax-table)
681 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
682 (modify-syntax-entry ?\< "." py-mode-syntax-table)
683 (modify-syntax-entry ?\= "." py-mode-syntax-table)
684 (modify-syntax-entry ?\> "." py-mode-syntax-table)
685 (modify-syntax-entry ?\| "." py-mode-syntax-table)
686 ;; For historical reasons, underscore is word class instead of
687 ;; symbol class. GNU conventions say it should be symbol class, but
688 ;; there's a natural conflict between what major mode authors want
689 ;; and what users expect from `forward-word' and `backward-word'.
690 ;; Guido and I have hashed this out and have decided to keep
691 ;; underscore in word class. If you're tempted to change it, try
692 ;; binding M-f and M-b to py-forward-into-nomenclature and
693 ;; py-backward-into-nomenclature instead.
694 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
695 ;; Both single quote and double quote are string delimiters
696 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
697 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
698 ;; backquote is open and close paren
699 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
700 ;; comment delimiters
701 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
702 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
703 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000704
Barry Warsawb3e81d51996-09-04 15:12:42 +0000705
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000706
Barry Warsaw42f707f1996-07-29 21:05:05 +0000707;; Menu definitions, only relevent if you have the easymenu.el package
708;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000709(defvar py-menu nil
710 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000711This menu will get created automatically if you have the `easymenu'
712package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000713
Barry Warsawc72c11c1997-08-09 06:42:08 +0000714(and (py-safe (require 'easymenu) t)
715 (easy-menu-define
716 py-menu py-mode-map "Python Mode menu"
717 '("Python"
718 ["Comment Out Region" py-comment-region (mark)]
719 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
720 "-"
721 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000722 ["Mark current def" py-mark-def-or-class t]
723 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000724 "-"
725 ["Shift region left" py-shift-region-left (mark)]
726 ["Shift region right" py-shift-region-right (mark)]
727 "-"
Barry Warsaw820273d1998-05-19 15:54:45 +0000728 ["Import/reload file" py-execute-import-or-reload t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000729 ["Execute buffer" py-execute-buffer t]
730 ["Execute region" py-execute-region (mark)]
Barry Warsaw820273d1998-05-19 15:54:45 +0000731 ["Execute def or class" py-execute-def-or-class (mark)]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000732 ["Start interpreter..." py-shell t]
733 "-"
734 ["Go to start of block" py-goto-block-up t]
Barry Warsawab0e86c1998-05-19 15:31:46 +0000735 ["Go to start of class" (py-beginning-of-def-or-class t) t]
736 ["Move to end of class" (py-end-of-def-or-class t) t]
737 ["Move to start of def" py-beginning-of-def-or-class t]
738 ["Move to end of def" py-end-of-def-or-class t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000739 "-"
740 ["Describe mode" py-describe-mode t]
741 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000742
Barry Warsaw81437461996-08-01 19:48:02 +0000743
744
745;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
746(defvar imenu-example--python-class-regexp
747 (concat ; <<classes>>
748 "\\(" ;
749 "^[ \t]*" ; newline and maybe whitespace
750 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
751 ; possibly multiple superclasses
Barry Warsaw3179fe01998-04-04 21:36:53 +0000752 "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
Barry Warsaw81437461996-08-01 19:48:02 +0000753 "[ \t]*:" ; and the final :
754 "\\)" ; >>classes<<
755 )
756 "Regexp for Python classes for use with the imenu package."
757 )
758
759(defvar imenu-example--python-method-regexp
760 (concat ; <<methods and functions>>
761 "\\(" ;
762 "^[ \t]*" ; new line and maybe whitespace
763 "\\(def[ \t]+" ; function definitions start with def
764 "\\([a-zA-Z0-9_]+\\)" ; name is here
765 ; function arguments...
766 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
767 "\\)" ; end of def
768 "[ \t]*:" ; and then the :
769 "\\)" ; >>methods and functions<<
770 )
771 "Regexp for Python methods/functions for use with the imenu package."
772 )
773
774(defvar imenu-example--python-method-no-arg-parens '(2 8)
775 "Indicies into groups of the Python regexp for use with imenu.
776
777Using these values will result in smaller imenu lists, as arguments to
778functions are not listed.
779
780See the variable `imenu-example--python-show-method-args-p' for more
781information.")
782
783(defvar imenu-example--python-method-arg-parens '(2 7)
784 "Indicies into groups of the Python regexp for use with imenu.
785Using these values will result in large imenu lists, as arguments to
786functions are listed.
787
788See the variable `imenu-example--python-show-method-args-p' for more
789information.")
790
791;; Note that in this format, this variable can still be used with the
792;; imenu--generic-function. Otherwise, there is no real reason to have
793;; it.
794(defvar imenu-example--generic-python-expression
795 (cons
796 (concat
797 imenu-example--python-class-regexp
798 "\\|" ; or...
799 imenu-example--python-method-regexp
800 )
801 imenu-example--python-method-no-arg-parens)
802 "Generic Python expression which may be used directly with imenu.
803Used by setting the variable `imenu-generic-expression' to this value.
804Also, see the function \\[imenu-example--create-python-index] for a
805better alternative for finding the index.")
806
807;; These next two variables are used when searching for the python
808;; class/definitions. Just saving some time in accessing the
809;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000810(defvar imenu-example--python-generic-regexp nil)
811(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000812
813
Barry Warsaw81437461996-08-01 19:48:02 +0000814(defun imenu-example--create-python-index ()
815 "Python interface function for imenu package.
816Finds all python classes and functions/methods. Calls function
817\\[imenu-example--create-python-index-engine]. See that function for
818the details of how this works."
819 (setq imenu-example--python-generic-regexp
820 (car imenu-example--generic-python-expression))
821 (setq imenu-example--python-generic-parens
822 (if imenu-example--python-show-method-args-p
823 imenu-example--python-method-arg-parens
824 imenu-example--python-method-no-arg-parens))
825 (goto-char (point-min))
826 (imenu-example--create-python-index-engine nil))
827
828(defun imenu-example--create-python-index-engine (&optional start-indent)
829 "Function for finding imenu definitions in Python.
830
831Finds all definitions (classes, methods, or functions) in a Python
832file for the imenu package.
833
834Returns a possibly nested alist of the form
835
836 (INDEX-NAME . INDEX-POSITION)
837
838The second element of the alist may be an alist, producing a nested
839list as in
840
841 (INDEX-NAME . INDEX-ALIST)
842
843This function should not be called directly, as it calls itself
844recursively and requires some setup. Rather this is the engine for
845the function \\[imenu-example--create-python-index].
846
847It works recursively by looking for all definitions at the current
848indention level. When it finds one, it adds it to the alist. If it
849finds a definition at a greater indentation level, it removes the
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000850previous definition from the alist. In its place it adds all
Barry Warsaw81437461996-08-01 19:48:02 +0000851definitions found at the next indentation level. When it finds a
852definition that is less indented then the current level, it retuns the
853alist it has created thus far.
854
855The optional argument START-INDENT indicates the starting indentation
856at which to continue looking for Python classes, methods, or
857functions. If this is not supplied, the function uses the indentation
858of the first definition found."
859 (let ((index-alist '())
860 (sub-method-alist '())
861 looking-p
862 def-name prev-name
863 cur-indent def-pos
864 (class-paren (first imenu-example--python-generic-parens))
865 (def-paren (second imenu-example--python-generic-parens)))
866 (setq looking-p
867 (re-search-forward imenu-example--python-generic-regexp
868 (point-max) t))
869 (while looking-p
870 (save-excursion
871 ;; used to set def-name to this value but generic-extract-name is
872 ;; new to imenu-1.14. this way it still works with imenu-1.11
873 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
874 (let ((cur-paren (if (match-beginning class-paren)
875 class-paren def-paren)))
876 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000877 (buffer-substring-no-properties (match-beginning cur-paren)
878 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000879 (beginning-of-line)
880 (setq cur-indent (current-indentation)))
881
882 ;; HACK: want to go to the next correct definition location. we
883 ;; explicitly list them here. would be better to have them in a
884 ;; list.
885 (setq def-pos
886 (or (match-beginning class-paren)
887 (match-beginning def-paren)))
888
889 ;; if we don't have a starting indent level, take this one
890 (or start-indent
891 (setq start-indent cur-indent))
892
893 ;; if we don't have class name yet, take this one
894 (or prev-name
895 (setq prev-name def-name))
896
897 ;; what level is the next definition on? must be same, deeper
898 ;; or shallower indentation
899 (cond
900 ;; at the same indent level, add it to the list...
901 ((= start-indent cur-indent)
902
903 ;; if we don't have push, use the following...
904 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
905 (push (cons def-name def-pos) index-alist))
906
907 ;; deeper indented expression, recur...
908 ((< start-indent cur-indent)
909
910 ;; the point is currently on the expression we're supposed to
911 ;; start on, so go back to the last expression. The recursive
912 ;; call will find this place again and add it to the correct
913 ;; list
914 (re-search-backward imenu-example--python-generic-regexp
915 (point-min) 'move)
916 (setq sub-method-alist (imenu-example--create-python-index-engine
917 cur-indent))
918
919 (if sub-method-alist
920 ;; we put the last element on the index-alist on the start
921 ;; of the submethod alist so the user can still get to it.
922 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000923 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000924 (cons save-elmt sub-method-alist))
925 index-alist))))
926
927 ;; found less indented expression, we're done.
928 (t
929 (setq looking-p nil)
930 (re-search-backward imenu-example--python-generic-regexp
931 (point-min) t)))
932 (setq prev-name def-name)
933 (and looking-p
934 (setq looking-p
935 (re-search-forward imenu-example--python-generic-regexp
936 (point-max) 'move))))
937 (nreverse index-alist)))
938
Barry Warsaw42f707f1996-07-29 21:05:05 +0000939
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000940;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000941(defun python-mode ()
942 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000943To submit a problem report, enter `\\[py-submit-bug-report]' from a
944`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
945documentation. To see what version of `python-mode' you are running,
946enter `\\[py-version]'.
947
948This mode knows about Python indentation, tokens, comments and
949continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000950
951COMMANDS
952\\{py-mode-map}
953VARIABLES
954
Barry Warsaw42f707f1996-07-29 21:05:05 +0000955py-indent-offset\t\tindentation increment
956py-block-comment-prefix\t\tcomment string used by comment-region
957py-python-command\t\tshell command to invoke Python interpreter
958py-scroll-process-buffer\t\talways scroll Python process buffer
959py-temp-directory\t\tdirectory used for temp files (if needed)
960py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000961 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000962 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000963 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000964 (make-local-variable 'font-lock-defaults)
965 (make-local-variable 'paragraph-separate)
966 (make-local-variable 'paragraph-start)
967 (make-local-variable 'require-final-newline)
968 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000969 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000970 (make-local-variable 'comment-start-skip)
971 (make-local-variable 'comment-column)
972 (make-local-variable 'indent-region-function)
973 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000974 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000975 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000976 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000977 (setq major-mode 'python-mode
978 mode-name "Python"
979 local-abbrev-table python-mode-abbrev-table
Barry Warsaw5c38bf61997-12-02 22:01:04 +0000980 font-lock-defaults '(python-font-lock-keywords)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000981 paragraph-separate "^[ \t]*$"
982 paragraph-start "^[ \t]*$"
983 require-final-newline t
984 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000985 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000986 comment-start-skip "# *"
987 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000988 indent-region-function 'py-indent-region
989 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000990 ;; tell add-log.el how to find the current function/method/variable
991 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000992 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000993 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000994 ;; add the menu
995 (if py-menu
996 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000997 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000998 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000999 (setq comment-multi-line nil))
Barry Warsaw742a5111998-03-13 17:29:15 +00001000 ;; Install Imenu, only works for Emacs.
1001 (when (py-safe (require 'imenu))
1002 (make-variable-buffer-local 'imenu-create-index-function)
1003 (setq imenu-create-index-function
1004 (function imenu-example--create-python-index))
1005 (setq imenu-generic-expression
1006 imenu-example--generic-python-expression)
1007 (if (fboundp 'imenu-add-to-menubar)
1008 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
1009 )
1010 ;; Run the mode hook. Note that py-mode-hook is deprecated.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001011 (if python-mode-hook
1012 (run-hooks 'python-mode-hook)
Barry Warsaw742a5111998-03-13 17:29:15 +00001013 (run-hooks 'py-mode-hook))
1014 ;; Now do the automagical guessing
1015 (if py-smart-indentation
1016 (let ((offset py-indent-offset))
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001017 ;; It's okay if this fails to guess a good value
Barry Warsaw742a5111998-03-13 17:29:15 +00001018 (if (and (py-safe (py-guess-indent-offset))
1019 (<= py-indent-offset 8)
1020 (>= py-indent-offset 2))
1021 (setq offset py-indent-offset))
1022 (setq py-indent-offset offset)
Barry Warsaw639eea61998-03-16 18:12:13 +00001023 ;; Only turn indent-tabs-mode off if tab-width !=
1024 ;; py-indent-offset. Never turn it on, because the user must
1025 ;; have explicitly turned it off.
1026 (if (/= tab-width py-indent-offset)
1027 (setq indent-tabs-mode nil))
Barry Warsaw742a5111998-03-13 17:29:15 +00001028 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001029
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001030
Barry Warsawb91b7431995-03-14 15:55:20 +00001031;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001032(defun py-outdent-p ()
1033 ;; returns non-nil if the current line should outdent one level
1034 (save-excursion
1035 (and (progn (back-to-indentation)
1036 (looking-at py-outdent-re))
Barry Warsawf06777d1998-01-21 05:36:18 +00001037 (progn (forward-line -1)
1038 (py-goto-initial-line)
1039 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001040 (while (or (looking-at py-blank-or-comment-re)
1041 (bobp))
1042 (backward-to-indentation 1))
1043 (not (looking-at py-no-outdent-re)))
1044 )))
1045
Barry Warsawb91b7431995-03-14 15:55:20 +00001046(defun py-electric-colon (arg)
1047 "Insert a colon.
1048In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001049argument is provided, that many colons are inserted non-electrically.
1050Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +00001051 (interactive "P")
1052 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001053 ;; are we in a string or comment?
1054 (if (save-excursion
1055 (let ((pps (parse-partial-sexp (save-excursion
Barry Warsawab0e86c1998-05-19 15:31:46 +00001056 (py-beginning-of-def-or-class)
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001057 (point))
1058 (point))))
1059 (not (or (nth 3 pps) (nth 4 pps)))))
1060 (save-excursion
1061 (let ((here (point))
1062 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001063 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001064 (if (and (not arg)
1065 (py-outdent-p)
1066 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +00001067 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001068 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001069 )
1070 (setq outdent py-indent-offset))
1071 ;; Don't indent, only outdent. This assumes that any lines that
1072 ;; are already outdented relative to py-compute-indentation were
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001073 ;; put there on purpose. It's highly annoying to have `:' indent
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001074 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
1075 ;; there a better way to determine this???
1076 (if (< (current-indentation) indent) nil
1077 (goto-char here)
1078 (beginning-of-line)
1079 (delete-horizontal-space)
1080 (indent-to (- indent outdent))
1081 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001082
1083
Barry Warsawa97a3f31997-11-04 18:47:06 +00001084;; Python subprocess utilities and filters
1085(defun py-execute-file (proc filename)
1086 ;; Send a properly formatted execfile('FILENAME') to the underlying
1087 ;; Python interpreter process FILENAME. Make that process's buffer
1088 ;; visible and force display. Also make comint believe the user
1089 ;; typed this string so that kill-output-from-shell does The Right
1090 ;; Thing.
1091 (let ((curbuf (current-buffer))
1092 (procbuf (process-buffer proc))
1093 (comint-scroll-to-bottom-on-output t)
1094 (msg (format "## working on region in file %s...\n" filename))
1095 (cmd (format "execfile('%s')\n" filename)))
1096 (unwind-protect
1097 (progn
1098 (set-buffer procbuf)
1099 (goto-char (point-max))
1100 (move-marker (process-mark proc) (point))
1101 (funcall (process-filter proc) proc msg))
1102 (set-buffer curbuf))
1103 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001104
1105(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001106 (let ((curbuf (current-buffer))
1107 (pbuf (process-buffer pyproc))
1108 (pmark (process-mark pyproc))
1109 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001110 ;; make sure we switch to a different buffer at least once. if we
1111 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001112 ;; window, and point is before the end, and lots of output is
1113 ;; coming at a fast pace, then (a) simple cursor-movement commands
1114 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
1115 ;; to have a visible effect (the window just doesn't get updated,
1116 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
1117 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001118 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001119 ;; #b makes no sense to me at all. #a almost makes sense: unless
1120 ;; we actually change buffers, set_buffer_internal in buffer.c
1121 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1122 ;; seems to make the Emacs command loop reluctant to update the
1123 ;; display. Perhaps the default process filter in process.c's
1124 ;; read_process_output has update_mode_lines++ for a similar
1125 ;; reason? beats me ...
1126
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001127 (unwind-protect
1128 ;; make sure current buffer is restored
1129 ;; BAW - we want to check to see if this still applies
1130 (progn
1131 ;; mysterious ugly hack
1132 (if (eq curbuf pbuf)
1133 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001134
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001135 (set-buffer pbuf)
1136 (let* ((start (point))
1137 (goback (< start pmark))
1138 (goend (and (not goback) (= start (point-max))))
1139 (buffer-read-only nil))
1140 (goto-char pmark)
1141 (insert string)
1142 (move-marker pmark (point))
1143 (setq file-finished
1144 (and py-file-queue
1145 (equal ">>> "
1146 (buffer-substring
1147 (prog2 (beginning-of-line) (point)
1148 (goto-char pmark))
1149 (point)))))
1150 (if goback (goto-char start)
1151 ;; else
1152 (if py-scroll-process-buffer
1153 (let* ((pop-up-windows t)
1154 (pwin (display-buffer pbuf)))
1155 (set-window-point pwin (point)))))
1156 (set-buffer curbuf)
1157 (if file-finished
1158 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001159 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001160 (setq py-file-queue (cdr py-file-queue))
1161 (if py-file-queue
1162 (py-execute-file pyproc (car py-file-queue)))))
1163 (and goend
1164 (progn (set-buffer pbuf)
1165 (goto-char (point-max))))
1166 ))
1167 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001168
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001169(defun py-postprocess-output-buffer (buf)
Barry Warsawf9b99f41998-03-26 16:08:59 +00001170 ;; Highlight exceptions found in BUF. If an exception occurred
1171 ;; return t, otherwise return nil. BUF must exist.
1172 (let (line file bol err-p)
Barry Warsaw9981d221997-12-03 05:25:48 +00001173 (save-excursion
1174 (set-buffer buf)
1175 (beginning-of-buffer)
1176 (while (re-search-forward py-traceback-line-re nil t)
1177 (setq file (match-string 1)
1178 line (string-to-int (match-string 2))
1179 bol (py-point 'bol))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001180 (py-highlight-line bol (py-point 'eol) file line)))
1181 (when (and py-jump-on-exception line)
1182 (beep)
1183 (py-jump-to-exception file line)
1184 (setq err-p t))
1185 err-p))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001186
Barry Warsaw9981d221997-12-03 05:25:48 +00001187
Barry Warsawa97a3f31997-11-04 18:47:06 +00001188
1189;;; Subprocess commands
1190
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001191;; only used when (memq 'broken-temp-names py-emacs-features)
1192(defvar py-serial-number 0)
1193(defvar py-exception-buffer nil)
1194(defconst py-output-buffer "*Python Output*")
Barry Warsawa2398801998-04-09 23:28:20 +00001195(make-variable-buffer-local 'py-output-buffer)
1196
1197;; for toggling between CPython and JPython
1198(defvar py-which-shell py-python-command)
1199(defvar py-which-args py-python-command-args)
1200(defvar py-which-bufname "Python")
1201(make-variable-buffer-local 'py-which-shell)
1202(make-variable-buffer-local 'py-which-args)
1203(make-variable-buffer-local 'py-which-bufname)
1204
1205(defun py-toggle-shells (arg)
1206 "Toggles between the CPython and JPython shells.
1207With positive \\[universal-argument], uses the CPython shell, with
1208negative \\[universal-argument] uses the JPython shell, and with a
1209zero argument, toggles the shell."
1210 (interactive "P")
1211 ;; default is to toggle
1212 (if (null arg)
1213 (setq arg 0))
1214 ;; toggle if zero
1215 (if (= arg 0)
1216 (if (string-equal py-which-bufname "Python")
1217 (setq arg -1)
1218 (setq arg 1)))
1219 (let (msg)
1220 (cond
1221 ((< 0 arg)
1222 ;; set to CPython
1223 (setq py-which-shell py-python-command
1224 py-which-args py-python-command-args
1225 py-which-bufname "Python"
1226 msg "CPython"
1227 mode-name "Python"))
1228 ((> 0 arg)
1229 (setq py-which-shell py-jpython-command
1230 py-which-args py-jpython-command-args
1231 py-which-bufname "JPython"
1232 msg "JPython"
1233 mode-name "JPython"))
1234 )
Barry Warsawea609c11998-04-10 16:08:26 +00001235 (message "Using the %s shell" msg)
Barry Warsawa2398801998-04-09 23:28:20 +00001236 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001237
Barry Warsawa97a3f31997-11-04 18:47:06 +00001238;;;###autoload
1239(defun py-shell ()
1240 "Start an interactive Python interpreter in another window.
1241This is like Shell mode, except that Python is running in the window
1242instead of a shell. See the `Interactive Shell' and `Shell Mode'
1243sections of the Emacs manual for details, especially for the key
1244bindings active in the `*Python*' buffer.
1245
1246See the docs for variable `py-scroll-buffer' for info on scrolling
1247behavior in the process window.
1248
Barry Warsawa2398801998-04-09 23:28:20 +00001249Note: You can toggle between using the CPython interpreter and the
1250JPython interpreter by hitting \\[py-toggle-shells]. This toggles
1251buffer local variables which control whether all your subshell
1252interactions happen to the `*JPython*' or `*Python*' buffers (the
1253latter is the name used for the CPython buffer).
1254
Barry Warsawa97a3f31997-11-04 18:47:06 +00001255Warning: Don't use an interactive Python if you change sys.ps1 or
1256sys.ps2 from their default values, or if you're running code that
1257prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1258distinguish your output from Python's output, and assumes that `>>> '
1259at the start of a line is a prompt from Python. Similarly, the Emacs
1260Shell mode code assumes that both `>>> ' and `... ' at the start of a
1261line are Python prompts. Bad things can happen if you fool either
1262mode.
1263
1264Warning: If you do any editing *in* the process buffer *while* the
1265buffer is accepting output from Python, do NOT attempt to `undo' the
1266changes. Some of the output (nowhere near the parts you changed!) may
1267be lost if you do. This appears to be an Emacs bug, an unfortunate
1268interaction between undo and process filters; the same problem exists in
1269non-Python process buffers using the default (Emacs-supplied) process
1270filter."
1271 ;; BAW - should undo be disabled in the python process buffer, if
1272 ;; this bug still exists?
1273 (interactive)
1274 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001275 (switch-to-buffer-other-window
Barry Warsawa2398801998-04-09 23:28:20 +00001276 (apply 'make-comint py-which-bufname py-which-shell nil py-which-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001277 (make-local-variable 'comint-prompt-regexp)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001278 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
Barry Warsawa97a3f31997-11-04 18:47:06 +00001279 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1280 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001281 ;; set up keybindings for this subshell
1282 (local-set-key [tab] 'self-insert-command)
1283 (local-set-key "\C-c-" 'py-up-exception)
1284 (local-set-key "\C-c=" 'py-down-exception)
1285 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001286
Barry Warsawa97a3f31997-11-04 18:47:06 +00001287(defun py-clear-queue ()
1288 "Clear the queue of temporary files waiting to execute."
1289 (interactive)
1290 (let ((n (length py-file-queue)))
1291 (mapcar 'delete-file py-file-queue)
1292 (setq py-file-queue nil)
1293 (message "%d pending files de-queued." n)))
1294
Barry Warsaw820273d1998-05-19 15:54:45 +00001295
Barry Warsawa97a3f31997-11-04 18:47:06 +00001296(defun py-execute-region (start end &optional async)
1297 "Execute the the region in a Python interpreter.
1298The region is first copied into a temporary file (in the directory
1299`py-temp-directory'). If there is no Python interpreter shell
1300running, this file is executed synchronously using
1301`shell-command-on-region'. If the program is long running, use an
1302optional \\[universal-argument] to run the command asynchronously in
1303its own buffer.
1304
1305If the Python interpreter shell is running, the region is execfile()'d
1306in that shell. If you try to execute regions too quickly,
1307`python-mode' will queue them up and execute them one at a time when
1308it sees a `>>> ' prompt from Python. Each time this happens, the
1309process buffer is popped into a window (if it's not already in some
1310window) so you can see it, and a comment of the form
1311
1312 \t## working on region in file <name>...
1313
1314is inserted at the end. See also the command `py-clear-queue'."
1315 (interactive "r\nP")
1316 (or (< start end)
1317 (error "Region is empty"))
1318 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001319 (temp (if (memq 'broken-temp-names py-emacs-features)
1320 (prog1
1321 (format "python-%d" py-serial-number)
1322 (setq py-serial-number (1+ py-serial-number)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001323 (make-temp-name "python-")))
1324 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001325 (write-region start end file nil 'nomsg)
1326 (cond
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001327 ;; always run the code in its own asynchronous subprocess
Barry Warsawa97a3f31997-11-04 18:47:06 +00001328 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001329 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001330 (start-process "Python" buf py-python-command "-u" file)
1331 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001332 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001333 ))
1334 ;; if the Python interpreter shell is running, queue it up for
1335 ;; execution there.
1336 (proc
1337 ;; use the existing python shell
1338 (if (not py-file-queue)
1339 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001340 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001341 (push file py-file-queue)
1342 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001343 (t
1344 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001345 (shell-command-on-region start end py-python-command py-output-buffer)
Barry Warsaw512af041998-03-25 23:27:17 +00001346 ;; shell-command-on-region kills the output buffer if it never
1347 ;; existed and there's no output from the command
1348 (if (not (get-buffer py-output-buffer))
1349 (message "No output.")
1350 (setq py-exception-buffer (current-buffer))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001351 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1352 (pop-to-buffer py-output-buffer)
1353 (if err-p
1354 (pop-to-buffer py-exception-buffer)))
Barry Warsaw512af041998-03-25 23:27:17 +00001355 ))
1356 )))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001357
Barry Warsaw820273d1998-05-19 15:54:45 +00001358
1359;; Code execution commands
Barry Warsawa97a3f31997-11-04 18:47:06 +00001360(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001361 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001362If the file local variable `py-master-file' is non-nil, execute the
1363named file instead of the buffer's file.
1364
Barry Warsaw7ae77681994-12-12 20:38:05 +00001365If there is a *Python* process buffer it is used. If a clipping
1366restriction is in effect, only the accessible portion of the buffer is
1367sent. A trailing newline will be supplied if needed.
1368
1369See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001370 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001371 (if py-master-file
1372 (let* ((filename (expand-file-name py-master-file))
1373 (buffer (or (get-file-buffer filename)
1374 (find-file-noselect filename))))
1375 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001376 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001377
Barry Warsaw820273d1998-05-19 15:54:45 +00001378(defun py-execute-import-or-reload (&optional async)
1379 "Import the current buffer's file in a Python interpreter.
1380
1381If the file has already been imported, then do reload instead to get
1382the latest version. If the file's name does not end in \".py\", then
1383do execfile instead. If the current buffer is not visiting a file, do
1384`py-execute-buffer' instead. If the file local variable
1385`py-master-file' is non-nil, import or reload the named file instead
1386of the buffer's file. The file is saved if necessary.
1387
1388See the `\\[py-execute-region]' docs for an account of some subtleties.
1389
1390This is may be preferable to `\\[py-execute-buffer]' because:
1391
1392 - Definitions stay in their module rather than appearing at top
1393 level, where they would clutter the global namespace and not affect
1394 uses of qualified names (MODULE.NAME).
1395
1396 - The Python debugger gets line number information about the functions."
1397 (interactive "P")
1398 ;; Check file local variable py-master-file
1399 (if py-master-file
1400 (let* ((filename (expand-file-name py-master-file))
1401 (buffer (or (get-file-buffer filename)
1402 (find-file-noselect filename))))
1403 (set-buffer buffer)))
1404 (let ((file (buffer-file-name (current-buffer))))
1405 (if file
1406 (progn
1407; (if (buffer-modified-p)
1408; ;; avoid message if unmodified
1409; (save-buffer))
1410 (py-execute-string
1411 (if (string-match "\\.py$" file)
1412 (let ((f (file-name-sans-extension
1413 (file-name-nondirectory file))))
1414 (format "if globals().has_key('%s'):\n reload(%s)\nelse:\n import %s\n"
1415 f f f))
1416 (format "execfile('%s')\n" file))
1417 async))
1418 ;; else
1419 (py-execute-buffer async))))
1420
1421
1422(defun py-execute-def-or-class (&optional async)
1423 "Send the current function or class definition to a Python interpreter.
1424
1425If there is a *Python* process buffer it is used.
1426
1427See the `\\[py-execute-region]' docs for an account of some subtleties."
1428 (interactive "P")
1429 (save-excursion
1430 (py-mark-def-or-class)
1431 ;; mark is before point
1432 (py-execute-region (mark) (point) async)))
1433
1434
1435(defun py-execute-string (string &optional async)
1436 "Send the argument string to a Python interpreter.
1437
1438If there is a *Python* process buffer it is used.
1439
1440See the `\\[py-execute-region]' docs for an account of some subtleties."
1441 (interactive "sExecute Python command: ")
1442 (save-excursion
1443 (set-buffer (get-buffer-create
1444 (generate-new-buffer-name " *Python Command*")))
1445 (insert string)
1446 (py-execute-region (point-min) (point-max) async)))
1447
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001448
1449
1450(defun py-jump-to-exception (file line)
1451 (let ((buffer (cond ((string-equal file "<stdin>")
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001452 (if (consp py-exception-buffer)
1453 (cdr py-exception-buffer)
1454 py-exception-buffer))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001455 ((and (consp py-exception-buffer)
1456 (string-equal file (car py-exception-buffer)))
1457 (cdr py-exception-buffer))
1458 ((py-safe (find-file-noselect file)))
1459 ;; could not figure out what file the exception
1460 ;; is pointing to, so prompt for it
1461 (t (find-file (read-file-name "Exception file: "
1462 nil
1463 file t))))))
1464 (pop-to-buffer buffer)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001465 ;; Force Python mode
Barry Warsaw820273d1998-05-19 15:54:45 +00001466 (if (not (eq major-mode 'python-mode))
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001467 (python-mode))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001468 (goto-line line)
1469 (message "Jumping to exception in file %s on line %d" file line)))
1470
1471(defun py-mouseto-exception (event)
1472 (interactive "e")
1473 (cond
1474 ((fboundp 'event-point)
1475 ;; XEmacs
1476 (let* ((point (event-point event))
1477 (buffer (event-buffer event))
1478 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1479 (info (and e (extent-property e 'py-exc-info))))
1480 (message "Event point: %d, info: %s" point info)
1481 (and info
1482 (py-jump-to-exception (car info) (cdr info)))
1483 ))
1484 ;; Emacs -- Please port this!
1485 ))
1486
1487(defun py-goto-exception ()
1488 "Go to the line indicated by the traceback."
1489 (interactive)
1490 (let (file line)
1491 (save-excursion
1492 (beginning-of-line)
1493 (if (looking-at py-traceback-line-re)
1494 (setq file (match-string 1)
1495 line (string-to-int (match-string 2)))))
1496 (if (not file)
1497 (error "Not on a traceback line."))
1498 (py-jump-to-exception file line)))
1499
1500(defun py-find-next-exception (start buffer searchdir errwhere)
1501 ;; Go to start position in buffer, search in the specified
1502 ;; direction, and jump to the exception found. If at the end of the
1503 ;; exception, print error message
1504 (let (file line)
1505 (save-excursion
1506 (set-buffer buffer)
1507 (goto-char (py-point start))
1508 (if (funcall searchdir py-traceback-line-re nil t)
1509 (setq file (match-string 1)
1510 line (string-to-int (match-string 2)))))
1511 (if (and file line)
1512 (py-jump-to-exception file line)
1513 (error "%s of traceback" errwhere))))
1514
1515(defun py-down-exception (&optional bottom)
1516 "Go to the next line down in the traceback.
1517With optional \\[universal-argument], jump to the bottom (innermost)
1518exception in the exception stack."
1519 (interactive "P")
1520 (let* ((proc (get-process "Python"))
1521 (buffer (if proc "*Python*" py-output-buffer)))
1522 (if bottom
1523 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1524 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1525
1526(defun py-up-exception (&optional top)
1527 "Go to the previous line up in the traceback.
1528With optional \\[universal-argument], jump to the top (outermost)
1529exception in the exception stack."
1530 (interactive "P")
1531 (let* ((proc (get-process "Python"))
1532 (buffer (if proc "*Python*" py-output-buffer)))
1533 (if top
1534 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001535 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001536
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001537
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001538;; Electric deletion
1539(defun py-electric-backspace (arg)
1540 "Deletes preceding character or levels of indentation.
1541Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001542with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001543
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001544If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001545
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001546Otherwise, if point is at the leftmost non-whitespace character of a
1547line that is neither a continuation line nor a non-indenting comment
1548line, or if point is at the end of a blank line, this command reduces
1549the indentation to match that of the line that opened the current
1550block of code. The line that opened the block is displayed in the
1551echo area to help you keep track of where you are. With numeric arg,
1552outdents that many blocks (but not past column zero).
1553
1554Otherwise the preceding character is deleted, converting a tab to
1555spaces if needed so that only a single column position is deleted.
1556Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001557 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001558 (if (or (/= (current-indentation) (current-column))
1559 (bolp)
1560 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001561 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001562 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001563 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001564 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001565 ;; force non-blank so py-goto-block-up doesn't ignore it
1566 (insert-char ?* 1)
1567 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001568 (let ((base-indent 0) ; indentation of base line
1569 (base-text "") ; and text of base line
1570 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001571 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001572 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001573 (condition-case nil ; in case no enclosing block
1574 (progn
1575 (py-goto-block-up 'no-mark)
1576 (setq base-indent (current-indentation)
1577 base-text (py-suck-up-leading-text)
1578 base-found-p t))
1579 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001580 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001581 (delete-char 1) ; toss the dummy character
1582 (delete-horizontal-space)
1583 (indent-to base-indent)
1584 (if base-found-p
1585 (message "Closes block: %s" base-text)))))
1586
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001587
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001588(defun py-electric-delete (arg)
1589 "Deletes preceding or following character or levels of whitespace.
1590
1591The behavior of this function depends on the variable
1592`delete-key-deletes-forward'. If this variable is nil (or does not
1593exist, as in older Emacsen), then this function behaves identical to
1594\\[c-electric-backspace].
1595
1596If `delete-key-deletes-forward' is non-nil and is supported in your
1597Emacs, then deletion occurs in the forward direction, by calling the
1598function in `py-delete-function'."
1599 (interactive "*p")
1600 (if (and (boundp 'delete-key-deletes-forward)
1601 delete-key-deletes-forward)
1602 (funcall py-delete-function arg)
1603 ;; else
1604 (py-electric-backspace arg)))
1605
1606;; required for pending-del and delsel modes
1607(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1608(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1609(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1610(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1611
1612
1613
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001614(defun py-indent-line (&optional arg)
1615 "Fix the indentation of the current line according to Python rules.
1616With \\[universal-argument], ignore outdenting rules for block
1617closing statements (e.g. return, raise, break, continue, pass)
1618
1619This function is normally bound to `indent-line-function' so
1620\\[indent-for-tab-command] will call it."
1621 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001622 (let* ((ci (current-indentation))
1623 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001624 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001625 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001626 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001627 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001628 (if (/= ci need)
1629 (save-excursion
1630 (beginning-of-line)
1631 (delete-horizontal-space)
1632 (indent-to need)))
1633 (if move-to-indentation-p (back-to-indentation))))
1634
1635(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001636 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001637This is just `strives to' because correct indentation can't be computed
1638from scratch for Python code. In general, deletes the whitespace before
1639point, inserts a newline, and takes an educated guess as to how you want
1640the new line indented."
1641 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001642 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001643 (if (< ci (current-column)) ; if point beyond indentation
1644 (newline-and-indent)
1645 ;; else try to act like newline-and-indent "normally" acts
1646 (beginning-of-line)
1647 (insert-char ?\n 1)
1648 (move-to-column ci))))
1649
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001650(defun py-compute-indentation (honor-block-close-p)
1651 ;; implements all the rules for indentation computation. when
1652 ;; honor-block-close-p is non-nil, statements such as return, raise,
1653 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001654 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001655 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001656 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001657 (pps (parse-partial-sexp bod (point)))
1658 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001659 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001660 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001661 ((or (and (nth 3 pps) (nth 3 boipps))
1662 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001663 (save-excursion
1664 (if (not py-align-multiline-strings-p) 0
1665 ;; skip back over blank & non-indenting comment lines
1666 ;; note: will skip a blank or non-indenting comment line
1667 ;; that happens to be a continuation line too
1668 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1669 (back-to-indentation)
1670 (current-column))))
1671 ;; are we on a continuation line?
1672 ((py-continuation-line-p)
1673 (let ((startpos (point))
1674 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001675 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001676 (if open-bracket-pos
1677 (progn
1678 ;; align with first item in list; else a normal
1679 ;; indent beyond the line with the open bracket
1680 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1681 ;; is the first list item on the same line?
1682 (skip-chars-forward " \t")
1683 (if (null (memq (following-char) '(?\n ?# ?\\)))
1684 ; yes, so line up with it
1685 (current-column)
1686 ;; first list item on another line, or doesn't exist yet
1687 (forward-line 1)
1688 (while (and (< (point) startpos)
1689 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1690 (forward-line 1))
Barry Warsaw92166d91998-04-01 21:59:41 +00001691 (if (and (< (point) startpos)
1692 (/= startpos
1693 (save-excursion
1694 (goto-char (1+ open-bracket-pos))
Barry Warsaw77d1fce1998-04-16 20:04:59 +00001695 (forward-comment (point-max))
Barry Warsaw92166d91998-04-01 21:59:41 +00001696 (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001697 ;; again mimic the first list item
1698 (current-indentation)
1699 ;; else they're about to enter the first item
1700 (goto-char open-bracket-pos)
1701 (+ (current-indentation) py-indent-offset))))
1702
1703 ;; else on backslash continuation line
1704 (forward-line -1)
1705 (if (py-continuation-line-p) ; on at least 3rd line in block
1706 (current-indentation) ; so just continue the pattern
1707 ;; else started on 2nd line in block, so indent more.
1708 ;; if base line is an assignment with a start on a RHS,
1709 ;; indent to 2 beyond the leftmost "="; else skip first
1710 ;; chunk of non-whitespace characters on base line, + 1 more
1711 ;; column
1712 (end-of-line)
1713 (setq endpos (point) searching t)
1714 (back-to-indentation)
1715 (setq startpos (point))
1716 ;; look at all "=" from left to right, stopping at first
1717 ;; one not nested in a list or string
1718 (while searching
1719 (skip-chars-forward "^=" endpos)
1720 (if (= (point) endpos)
1721 (setq searching nil)
1722 (forward-char 1)
1723 (setq state (parse-partial-sexp startpos (point)))
1724 (if (and (zerop (car state)) ; not in a bracket
1725 (null (nth 3 state))) ; & not in a string
1726 (progn
1727 (setq searching nil) ; done searching in any case
1728 (setq found
1729 (not (or
1730 (eq (following-char) ?=)
1731 (memq (char-after (- (point) 2))
1732 '(?< ?> ?!)))))))))
1733 (if (or (not found) ; not an assignment
1734 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1735 (progn
1736 (goto-char startpos)
1737 (skip-chars-forward "^ \t\n")))
1738 (1+ (current-column))))))
1739
1740 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001741 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001742
Barry Warsawa7891711996-08-01 15:53:09 +00001743 ;; Dfn: "Indenting comment line". A line containing only a
1744 ;; comment, but which is treated like a statement for
1745 ;; indentation calculation purposes. Such lines are only
1746 ;; treated specially by the mode; they are not treated
1747 ;; specially by the Python interpreter.
1748
1749 ;; The rules for indenting comment lines are a line where:
1750 ;; - the first non-whitespace character is `#', and
1751 ;; - the character following the `#' is whitespace, and
1752 ;; - the line is outdented with respect to (i.e. to the left
1753 ;; of) the indentation of the preceding non-blank line.
1754
1755 ;; The first non-blank line following an indenting comment
1756 ;; line is given the same amount of indentation as the
1757 ;; indenting comment line.
1758
1759 ;; All other comment-only lines are ignored for indentation
1760 ;; purposes.
1761
1762 ;; Are we looking at a comment-only line which is *not* an
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001763 ;; indenting comment line? If so, we assume that it's been
Barry Warsawa7891711996-08-01 15:53:09 +00001764 ;; placed at the desired indentation, so leave it alone.
1765 ;; Indenting comment lines are aligned as statements down
1766 ;; below.
1767 ((and (looking-at "[ \t]*#[^ \t\n]")
1768 ;; NOTE: this test will not be performed in older Emacsen
1769 (fboundp 'forward-comment)
1770 (<= (current-indentation)
1771 (save-excursion
1772 (forward-comment (- (point-max)))
1773 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001774 (current-indentation))
1775
1776 ;; else indentation based on that of the statement that
1777 ;; precedes us; use the first line of that statement to
1778 ;; establish the base, in case the user forced a non-std
1779 ;; indentation for the continuation lines (if any)
1780 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001781 ;; skip back over blank & non-indenting comment lines note:
1782 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001783 ;; happens to be a continuation line too. use fast Emacs 19
1784 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001785 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001786 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001787 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001788 (let (done)
1789 (while (not done)
1790 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1791 nil 'move)
1792 (setq done (or (eq py-honor-comment-indentation t)
1793 (bobp)
1794 (/= (following-char) ?#)
1795 (not (zerop (current-column)))))
1796 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001797 ;; if we landed inside a string, go to the beginning of that
1798 ;; string. this handles triple quoted, multi-line spanning
1799 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001800 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001801 (skip (and delim (make-string 1 delim))))
1802 (when skip
1803 (save-excursion
1804 (py-safe (search-backward skip))
1805 (if (and (eq (char-before) delim)
1806 (eq (char-before (1- (point))) delim))
1807 (setq skip (make-string 3 delim))))
1808 ;; we're looking at a triple-quoted string
1809 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001810 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001811 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001812 (+ (current-indentation)
1813 (if (py-statement-opens-block-p)
1814 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001815 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001816 (- py-indent-offset)
1817 0)))
1818 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001819
1820(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001821 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001822By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001823`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001824Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001825`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001826their own buffer-local copy), both those currently existing and those
1827created later in the Emacs session.
1828
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001829Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001830There's no excuse for such foolishness, but sometimes you have to deal
1831with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001832`py-indent-offset' to what it thinks it was when they created the
1833mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001834
1835Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001836looking for a line that opens a block of code. `py-indent-offset' is
1837set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001838statement following it. If the search doesn't succeed going forward,
1839it's tried again going backward."
1840 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001841 (let (new-value
1842 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001843 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001844 (found nil)
1845 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001846 (py-goto-initial-line)
1847 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001848 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1849 (not (py-in-literal restart)))
1850 (setq restart (point))
1851 (py-goto-initial-line)
1852 (if (py-statement-opens-block-p)
1853 (setq found t)
1854 (goto-char restart))))
1855 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001856 (goto-char start)
1857 (py-goto-initial-line)
1858 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001859 (setq found (and
1860 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1861 (or (py-goto-initial-line) t) ; always true -- side effect
1862 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001863 (setq colon-indent (current-indentation)
1864 found (and found (zerop (py-next-statement 1)))
1865 new-value (- (current-indentation) colon-indent))
1866 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001867 (if (not found)
1868 (error "Sorry, couldn't guess a value for py-indent-offset")
1869 (funcall (if global 'kill-local-variable 'make-local-variable)
1870 'py-indent-offset)
1871 (setq py-indent-offset new-value)
1872 (message "%s value of py-indent-offset set to %d"
1873 (if global "Global" "Local")
1874 py-indent-offset))
1875 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001876
1877(defun py-shift-region (start end count)
1878 (save-excursion
1879 (goto-char end) (beginning-of-line) (setq end (point))
1880 (goto-char start) (beginning-of-line) (setq start (point))
1881 (indent-rigidly start end count)))
1882
1883(defun py-shift-region-left (start end &optional count)
1884 "Shift region of Python code to the left.
1885The lines from the line containing the start of the current region up
1886to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001887shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001888
1889If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001890many columns. With no active region, outdent only the current line.
1891You cannot outdent the region if any line is already at column zero."
1892 (interactive
1893 (let ((p (point))
1894 (m (mark))
1895 (arg current-prefix-arg))
1896 (if m
1897 (list (min p m) (max p m) arg)
1898 (list p (save-excursion (forward-line 1) (point)) arg))))
1899 ;; if any line is at column zero, don't shift the region
1900 (save-excursion
1901 (goto-char start)
1902 (while (< (point) end)
1903 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001904 (if (and (zerop (current-column))
1905 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001906 (error "Region is at left edge."))
1907 (forward-line 1)))
1908 (py-shift-region start end (- (prefix-numeric-value
1909 (or count py-indent-offset))))
1910 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001911
1912(defun py-shift-region-right (start end &optional count)
1913 "Shift region of Python code to the right.
1914The lines from the line containing the start of the current region up
1915to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001916shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001917
1918If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001919many columns. With no active region, indent only the current line."
1920 (interactive
1921 (let ((p (point))
1922 (m (mark))
1923 (arg current-prefix-arg))
1924 (if m
1925 (list (min p m) (max p m) arg)
1926 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001927 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001928 (or count py-indent-offset)))
1929 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001930
1931(defun py-indent-region (start end &optional indent-offset)
1932 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001933
Barry Warsaw7ae77681994-12-12 20:38:05 +00001934The lines from the line containing the start of the current region up
1935to (but not including) the line containing the end of the region are
1936reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001937character in the first column, the first line is left alone and the
1938rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001939region is reindented with respect to the (closest code or indenting
1940comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001941
1942This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001943control structures are introduced or removed, or to reformat code
1944using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001945
1946If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001947the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001948used.
1949
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001950Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001951is called! This function does not compute proper indentation from
1952scratch (that's impossible in Python), it merely adjusts the existing
1953indentation to be correct in context.
1954
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001955Warning: This function really has no idea what to do with
1956non-indenting comment lines, and shifts them as if they were indenting
1957comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001958
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001959Special cases: whitespace is deleted from blank lines; continuation
1960lines are shifted by the same amount their initial line was shifted,
1961in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001962initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001963 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001964 (save-excursion
1965 (goto-char end) (beginning-of-line) (setq end (point-marker))
1966 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001967 (let ((py-indent-offset (prefix-numeric-value
1968 (or indent-offset py-indent-offset)))
1969 (indents '(-1)) ; stack of active indent levels
1970 (target-column 0) ; column to which to indent
1971 (base-shifted-by 0) ; amount last base line was shifted
1972 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001973 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001974 0))
1975 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001976 (while (< (point) end)
1977 (setq ci (current-indentation))
1978 ;; figure out appropriate target column
1979 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001980 ((or (eq (following-char) ?#) ; comment in column 1
1981 (looking-at "[ \t]*$")) ; entirely blank
1982 (setq target-column 0))
1983 ((py-continuation-line-p) ; shift relative to base line
1984 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001985 (t ; new base line
1986 (if (> ci (car indents)) ; going deeper; push it
1987 (setq indents (cons ci indents))
1988 ;; else we should have seen this indent before
1989 (setq indents (memq ci indents)) ; pop deeper indents
1990 (if (null indents)
1991 (error "Bad indentation in region, at line %d"
1992 (save-restriction
1993 (widen)
1994 (1+ (count-lines 1 (point)))))))
1995 (setq target-column (+ indent-base
1996 (* py-indent-offset
1997 (- (length indents) 2))))
1998 (setq base-shifted-by (- target-column ci))))
1999 ;; shift as needed
2000 (if (/= ci target-column)
2001 (progn
2002 (delete-horizontal-space)
2003 (indent-to target-column)))
2004 (forward-line 1))))
2005 (set-marker end nil))
2006
Barry Warsawa7891711996-08-01 15:53:09 +00002007(defun py-comment-region (beg end &optional arg)
2008 "Like `comment-region' but uses double hash (`#') comment starter."
2009 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00002010 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00002011 (comment-region beg end arg)))
2012
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002013
2014;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00002015(defun py-previous-statement (count)
2016 "Go to the start of previous Python statement.
2017If the statement at point is the i'th Python statement, goes to the
2018start of statement i-COUNT. If there is no such statement, goes to the
2019first statement. Returns count of statements left to move.
2020`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002021 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002022 (if (< count 0) (py-next-statement (- count))
2023 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002024 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002025 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002026 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002027 (> count 0)
2028 (zerop (forward-line -1))
2029 (py-goto-statement-at-or-above))
2030 (setq count (1- count)))
2031 (if (> count 0) (goto-char start)))
2032 count))
2033
2034(defun py-next-statement (count)
2035 "Go to the start of next Python statement.
2036If the statement at point is the i'th Python statement, goes to the
2037start of statement i+COUNT. If there is no such statement, goes to the
2038last statement. Returns count of statements left to move. `Statements'
2039do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002040 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002041 (if (< count 0) (py-previous-statement (- count))
2042 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002043 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002044 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002045 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002046 (> count 0)
2047 (py-goto-statement-below))
2048 (setq count (1- count)))
2049 (if (> count 0) (goto-char start)))
2050 count))
2051
2052(defun py-goto-block-up (&optional nomark)
2053 "Move up to start of current block.
2054Go to the statement that starts the smallest enclosing block; roughly
2055speaking, this will be the closest preceding statement that ends with a
2056colon and is indented less than the statement you started on. If
2057successful, also sets the mark to the starting point.
2058
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002059`\\[py-mark-block]' can be used afterward to mark the whole code
2060block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002061
2062If called from a program, the mark will not be set if optional argument
2063NOMARK is not nil."
2064 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002065 (let ((start (point))
2066 (found nil)
2067 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002068 (py-goto-initial-line)
2069 ;; if on blank or non-indenting comment line, use the preceding stmt
2070 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2071 (progn
2072 (py-goto-statement-at-or-above)
2073 (setq found (py-statement-opens-block-p))))
2074 ;; search back for colon line indented less
2075 (setq initial-indent (current-indentation))
2076 (if (zerop initial-indent)
2077 ;; force fast exit
2078 (goto-char (point-min)))
2079 (while (not (or found (bobp)))
2080 (setq found
2081 (and
2082 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2083 (or (py-goto-initial-line) t) ; always true -- side effect
2084 (< (current-indentation) initial-indent)
2085 (py-statement-opens-block-p))))
2086 (if found
2087 (progn
2088 (or nomark (push-mark start))
2089 (back-to-indentation))
2090 (goto-char start)
2091 (error "Enclosing block not found"))))
2092
Barry Warsawab0e86c1998-05-19 15:31:46 +00002093(defun py-beginning-of-def-or-class (&optional class count)
2094 "Move point to start of `def' or `class'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002095
2096Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsawab0e86c1998-05-19 15:31:46 +00002097arg, looks for a `class' instead. The docs below assume the `def'
2098case; just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002099
Barry Warsawab0e86c1998-05-19 15:31:46 +00002100When second optional argument is given programmatically, move to the
2101COUNTth start of `def'.
2102
2103If point is in a `def' statement already, and after the `d', simply
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002104moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002105
Barry Warsawab0e86c1998-05-19 15:31:46 +00002106Otherwise (i.e. when point is not in a `def' statement, or at or
2107before the `d' of a `def' statement), searches for the closest
2108preceding `def' statement, and leaves point at its start. If no such
2109statement can be found, leaves point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002110
Barry Warsawab0e86c1998-05-19 15:31:46 +00002111Returns t iff a `def' statement is found by these rules.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002112
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002113Note that doing this command repeatedly will take you closer to the
2114start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002115
Barry Warsawab0e86c1998-05-19 15:31:46 +00002116If you want to mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002117 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002118 (if (not count)
2119 (setq count 1))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002120 (let ((at-or-before-p (<= (current-column) (current-indentation)))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002121 (start-of-line (goto-char (py-point 'bol)))
2122 (start-of-stmt (goto-char (py-point 'bos)))
2123 (start-re (if class
2124 "^[ \t]*class\\>"
2125 "^[ \t]*def\\>"))
2126 )
2127 ;; searching backward
2128 (if (and (< 0 count)
2129 (or (/= start-of-stmt start-of-line)
2130 (not at-or-before-p)))
2131 (end-of-line))
2132 ;; search forward
2133 (if (and (> 0 count)
2134 (zerop (current-column))
2135 (looking-at start-re))
2136 (end-of-line))
2137 (re-search-backward start-re nil 'move count)
2138 (goto-char (match-beginning 0))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002139
Barry Warsawab0e86c1998-05-19 15:31:46 +00002140;; Backwards compatibility
2141(defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002142
Barry Warsawab0e86c1998-05-19 15:31:46 +00002143(defun py-end-of-def-or-class (&optional class count)
2144 "Move point beyond end of `def' or `class' body.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002145
Barry Warsawab0e86c1998-05-19 15:31:46 +00002146By default, looks for an appropriate `def'. If you supply a prefix
2147arg, looks for a `class' instead. The docs below assume the `def'
2148case; just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002149
Barry Warsawab0e86c1998-05-19 15:31:46 +00002150When second optional argument is given programmatically, move to the
2151COUNTth end of `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002152
Barry Warsawab0e86c1998-05-19 15:31:46 +00002153If point is in a `def' statement already, this is the `def' we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002154
Barry Warsawab0e86c1998-05-19 15:31:46 +00002155Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2156contains the statement you started on, that's the `def' we use.
2157
2158Otherwise, we search forward for the closest following `def', and use that.
2159
2160If a `def' can be found by these rules, point is moved to the start of
2161the line immediately following the `def' block, and the position of the
2162start of the `def' is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002163
2164Else point is moved to the end of the buffer, and nil is returned.
2165
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002166Note that doing this command repeatedly will take you closer to the
2167end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002168
Barry Warsawab0e86c1998-05-19 15:31:46 +00002169If you want to mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002170 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002171 (if (and count (/= count 1))
2172 (py-beginning-of-def-or-class (- 1 count)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002173 (let ((start (progn (py-goto-initial-line) (point)))
2174 (which (if class "class" "def"))
2175 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002176 ;; move point to start of appropriate def/class
2177 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2178 (setq state 'at-beginning)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002179 ;; else see if py-beginning-of-def-or-class hits container
2180 (if (and (py-beginning-of-def-or-class class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002181 (progn (py-goto-beyond-block)
2182 (> (point) start)))
2183 (setq state 'at-end)
2184 ;; else search forward
2185 (goto-char start)
2186 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2187 (progn (setq state 'at-beginning)
2188 (beginning-of-line)))))
2189 (cond
2190 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2191 ((eq state 'at-end) t)
2192 ((eq state 'not-found) nil)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002193 (t (error "internal error in py-end-of-def-or-class")))))
2194
2195;; Backwards compabitility
Barry Warsaw820273d1998-05-19 15:54:45 +00002196(defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002197
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002198
2199;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002200(defun py-mark-block (&optional extend just-move)
2201 "Mark following block of lines. With prefix arg, mark structure.
2202Easier to use than explain. It sets the region to an `interesting'
2203block of succeeding lines. If point is on a blank line, it goes down to
2204the next non-blank line. That will be the start of the region. The end
2205of the region depends on the kind of line at the start:
2206
2207 - If a comment, the region will include all succeeding comment lines up
2208 to (but not including) the next non-comment line (if any).
2209
2210 - Else if a prefix arg is given, and the line begins one of these
2211 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002212
2213 if elif else try except finally for while def class
2214
Barry Warsaw7ae77681994-12-12 20:38:05 +00002215 the region will be set to the body of the structure, including
2216 following blocks that `belong' to it, but excluding trailing blank
2217 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002218 and all (if any) of the following `except' and `finally' blocks
2219 that belong to the `try' structure will be in the region. Ditto
2220 for if/elif/else, for/else and while/else structures, and (a bit
2221 degenerate, since they're always one-block structures) def and
2222 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002223
2224 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002225 block (see list above), and the block is not a `one-liner' (i.e.,
2226 the statement ends with a colon, not with code), the region will
2227 include all succeeding lines up to (but not including) the next
2228 code statement (if any) that's indented no more than the starting
2229 line, except that trailing blank and comment lines are excluded.
2230 E.g., if the starting line begins a multi-statement `def'
2231 structure, the region will be set to the full function definition,
2232 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002233
2234 - Else the region will include all succeeding lines up to (but not
2235 including) the next blank line, or code or indenting-comment line
2236 indented strictly less than the starting line. Trailing indenting
2237 comment lines are included in this case, but not trailing blank
2238 lines.
2239
2240A msg identifying the location of the mark is displayed in the echo
2241area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2242
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002243If called from a program, optional argument EXTEND plays the role of
2244the prefix arg, and if optional argument JUST-MOVE is not nil, just
2245moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002246 (interactive "P") ; raw prefix arg
2247 (py-goto-initial-line)
2248 ;; skip over blank lines
2249 (while (and
2250 (looking-at "[ \t]*$") ; while blank line
2251 (not (eobp))) ; & somewhere to go
2252 (forward-line 1))
2253 (if (eobp)
2254 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002255 (let ((initial-pos (point))
2256 (initial-indent (current-indentation))
2257 last-pos ; position of last stmt in region
2258 (followers
2259 '((if elif else) (elif elif else) (else)
2260 (try except finally) (except except) (finally)
2261 (for else) (while else)
2262 (def) (class) ) )
2263 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002264
2265 (cond
2266 ;; if comment line, suck up the following comment lines
2267 ((looking-at "[ \t]*#")
2268 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2269 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2270 (setq last-pos (point)))
2271
2272 ;; else if line is a block line and EXTEND given, suck up
2273 ;; the whole structure
2274 ((and extend
2275 (setq first-symbol (py-suck-up-first-keyword) )
2276 (assq first-symbol followers))
2277 (while (and
2278 (or (py-goto-beyond-block) t) ; side effect
2279 (forward-line -1) ; side effect
2280 (setq last-pos (point)) ; side effect
2281 (py-goto-statement-below)
2282 (= (current-indentation) initial-indent)
2283 (setq next-symbol (py-suck-up-first-keyword))
2284 (memq next-symbol (cdr (assq first-symbol followers))))
2285 (setq first-symbol next-symbol)))
2286
2287 ;; else if line *opens* a block, search for next stmt indented <=
2288 ((py-statement-opens-block-p)
2289 (while (and
2290 (setq last-pos (point)) ; always true -- side effect
2291 (py-goto-statement-below)
2292 (> (current-indentation) initial-indent))
2293 nil))
2294
2295 ;; else plain code line; stop at next blank line, or stmt or
2296 ;; indenting comment line indented <
2297 (t
2298 (while (and
2299 (setq last-pos (point)) ; always true -- side effect
2300 (or (py-goto-beyond-final-line) t)
2301 (not (looking-at "[ \t]*$")) ; stop at blank line
2302 (or
2303 (>= (current-indentation) initial-indent)
2304 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2305 nil)))
2306
2307 ;; skip to end of last stmt
2308 (goto-char last-pos)
2309 (py-goto-beyond-final-line)
2310
2311 ;; set mark & display
2312 (if just-move
2313 () ; just return
2314 (push-mark (point) 'no-msg)
2315 (forward-line -1)
2316 (message "Mark set after: %s" (py-suck-up-leading-text))
2317 (goto-char initial-pos))))
2318
Barry Warsaw2518c671997-11-05 00:51:08 +00002319(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002320 "Set region to body of def (or class, with prefix arg) enclosing point.
2321Pushes the current mark, then point, on the mark ring (all language
2322modes do this, but although it's handy it's never documented ...).
2323
2324In most Emacs language modes, this function bears at least a
Barry Warsawab0e86c1998-05-19 15:31:46 +00002325hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2326`\\[py-beginning-of-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002327
2328And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002329Turned out that was more confusing than useful: the `goto start' and
2330`goto end' commands are usually used to search through a file, and
2331people expect them to act a lot like `search backward' and `search
2332forward' string-search commands. But because Python `def' and `class'
2333can nest to arbitrary levels, finding the smallest def containing
2334point cannot be done via a simple backward search: the def containing
2335point may not be the closest preceding def, or even the closest
2336preceding def that's indented less. The fancy algorithm required is
2337appropriate for the usual uses of this `mark' command, but not for the
2338`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002339
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002340So the def marked by this command may not be the one either of the
2341`goto' commands find: If point is on a blank or non-indenting comment
2342line, moves back to start of the closest preceding code statement or
2343indenting comment line. If this is a `def' statement, that's the def
2344we use. Else searches for the smallest enclosing `def' block and uses
2345that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002346
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002347When an enclosing def is found: The mark is left immediately beyond
2348the last line of the def block. Point is left at the start of the
2349def, except that: if the def is preceded by a number of comment lines
2350followed by (at most) one optional blank line, point is left at the
2351start of the comments; else if the def is preceded by a blank line,
2352point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002353
2354The intent is to mark the containing def/class and its associated
2355documentation, to make moving and duplicating functions and classes
2356pleasant."
2357 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002358 (let ((start (point))
2359 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002360 (push-mark start)
2361 (if (not (py-go-up-tree-to-keyword which))
2362 (progn (goto-char start)
2363 (error "Enclosing %s not found" which))
2364 ;; else enclosing def/class found
2365 (setq start (point))
2366 (py-goto-beyond-block)
2367 (push-mark (point))
2368 (goto-char start)
2369 (if (zerop (forward-line -1)) ; if there is a preceding line
2370 (progn
2371 (if (looking-at "[ \t]*$") ; it's blank
2372 (setq start (point)) ; so reset start point
2373 (goto-char start)) ; else try again
2374 (if (zerop (forward-line -1))
2375 (if (looking-at "[ \t]*#") ; a comment
2376 ;; look back for non-comment line
2377 ;; tricky: note that the regexp matches a blank
2378 ;; line, cuz \n is in the 2nd character class
2379 (and
2380 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2381 (forward-line 1))
2382 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002383 (goto-char start)))))))
2384 (exchange-point-and-mark)
2385 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002386
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002387;; ripped from cc-mode
2388(defun py-forward-into-nomenclature (&optional arg)
2389 "Move forward to end of a nomenclature section or word.
2390With arg, to it arg times.
2391
2392A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2393 (interactive "p")
2394 (let ((case-fold-search nil))
2395 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002396 (re-search-forward
2397 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2398 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002399 (while (and (< arg 0)
2400 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002401 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002402 (point-min) 0))
2403 (forward-char 1)
2404 (setq arg (1+ arg)))))
2405 (py-keep-region-active))
2406
2407(defun py-backward-into-nomenclature (&optional arg)
2408 "Move backward to beginning of a nomenclature section or word.
2409With optional ARG, move that many times. If ARG is negative, move
2410forward.
2411
2412A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2413 (interactive "p")
2414 (py-forward-into-nomenclature (- arg))
2415 (py-keep-region-active))
2416
2417
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002418
2419;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002420
2421;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002422;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2423;; out of the right places, along with the keys they're on & current
2424;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002425(defun py-dump-help-string (str)
2426 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002427 (let ((locals (buffer-local-variables))
2428 funckind funcname func funcdoc
2429 (start 0) mstart end
2430 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002431 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2432 (setq mstart (match-beginning 0) end (match-end 0)
2433 funckind (substring str (match-beginning 1) (match-end 1))
2434 funcname (substring str (match-beginning 2) (match-end 2))
2435 func (intern funcname))
2436 (princ (substitute-command-keys (substring str start mstart)))
2437 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002438 ((equal funckind "c") ; command
2439 (setq funcdoc (documentation func)
2440 keys (concat
2441 "Key(s): "
2442 (mapconcat 'key-description
2443 (where-is-internal func py-mode-map)
2444 ", "))))
2445 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002446 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002447 keys (if (assq func locals)
2448 (concat
2449 "Local/Global values: "
2450 (prin1-to-string (symbol-value func))
2451 " / "
2452 (prin1-to-string (default-value func)))
2453 (concat
2454 "Value: "
2455 (prin1-to-string (symbol-value func))))))
2456 (t ; unexpected
2457 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002458 (princ (format "\n-> %s:\t%s\t%s\n\n"
2459 (if (equal funckind "c") "Command" "Variable")
2460 funcname keys))
2461 (princ funcdoc)
2462 (terpri)
2463 (setq start end))
2464 (princ (substitute-command-keys (substring str start))))
2465 (print-help-return-message)))
2466
2467(defun py-describe-mode ()
2468 "Dump long form of Python-mode docs."
2469 (interactive)
2470 (py-dump-help-string "Major mode for editing Python files.
2471Knows about Python indentation, tokens, comments and continuation lines.
2472Paragraphs are separated by blank lines only.
2473
2474Major sections below begin with the string `@'; specific function and
2475variable docs begin with `->'.
2476
2477@EXECUTING PYTHON CODE
2478
Barry Warsaw820273d1998-05-19 15:54:45 +00002479\\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002480\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2481\\[py-execute-region]\tsends the current region
Barry Warsaw820273d1998-05-19 15:54:45 +00002482\\[py-execute-def-or-class]\tsends the current function or class definition
2483\\[py-execute-string]\tsends an arbitrary string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002484\\[py-shell]\tstarts a Python interpreter window; this will be used by
Barry Warsaw820273d1998-05-19 15:54:45 +00002485\tsubsequent Python execution commands
2486%c:py-execute-import-or-reload
Barry Warsaw7ae77681994-12-12 20:38:05 +00002487%c:py-execute-buffer
2488%c:py-execute-region
Barry Warsaw820273d1998-05-19 15:54:45 +00002489%c:py-execute-def-or-class
2490%c:py-execute-string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002491%c:py-shell
2492
2493@VARIABLES
2494
2495py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002496py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002497
2498py-python-command\tshell command to invoke Python interpreter
2499py-scroll-process-buffer\talways scroll Python process buffer
2500py-temp-directory\tdirectory used for temp files (if needed)
2501
2502py-beep-if-tab-change\tring the bell if tab-width is changed
2503%v:py-indent-offset
2504%v:py-block-comment-prefix
2505%v:py-python-command
2506%v:py-scroll-process-buffer
2507%v:py-temp-directory
2508%v:py-beep-if-tab-change
2509
2510@KINDS OF LINES
2511
2512Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002513preceding line ends with a backslash that's not part of a comment, or
2514the paren/bracket/brace nesting level at the start of the line is
2515non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002516
2517An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002518possibly blanks or tabs), a `comment line' (leftmost non-blank
2519character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002520
2521Comment Lines
2522
2523Although all comment lines are treated alike by Python, Python mode
2524recognizes two kinds that act differently with respect to indentation.
2525
2526An `indenting comment line' is a comment line with a blank, tab or
2527nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002528treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002529indenting comment line will be indented like the comment line. All
2530other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002531following the initial `#') are `non-indenting comment lines', and
2532their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002533
2534Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002535whenever possible. Non-indenting comment lines are useful in cases
2536like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002537
2538\ta = b # a very wordy single-line comment that ends up being
2539\t #... continued onto another line
2540
2541\tif a == b:
2542##\t\tprint 'panic!' # old code we've `commented out'
2543\t\treturn a
2544
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002545Since the `#...' and `##' comment lines have a non-whitespace
2546character following the initial `#', Python mode ignores them when
2547computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002548
2549Continuation Lines and Statements
2550
2551The Python-mode commands generally work on statements instead of on
2552individual lines, where a `statement' is a comment or blank line, or a
2553code line and all of its following continuation lines (if any)
2554considered as a single logical unit. The commands in this mode
2555generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002556statement containing point, even if point happens to be in the middle
2557of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002558
2559
2560@INDENTATION
2561
2562Primarily for entering new code:
2563\t\\[indent-for-tab-command]\t indent line appropriately
2564\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002565\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002566
2567Primarily for reindenting existing code:
2568\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2569\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2570
2571\t\\[py-indent-region]\t reindent region to match its context
2572\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2573\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2574
2575Unlike most programming languages, Python uses indentation, and only
2576indentation, to specify block structure. Hence the indentation supplied
2577automatically by Python-mode is just an educated guess: only you know
2578the block structure you intend, so only you can supply correct
2579indentation.
2580
2581The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2582the indentation of preceding statements. E.g., assuming
2583py-indent-offset is 4, after you enter
2584\tif a > 0: \\[py-newline-and-indent]
2585the cursor will be moved to the position of the `_' (_ is not a
2586character in the file, it's just used here to indicate the location of
2587the cursor):
2588\tif a > 0:
2589\t _
2590If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2591to
2592\tif a > 0:
2593\t c = d
2594\t _
2595Python-mode cannot know whether that's what you intended, or whether
2596\tif a > 0:
2597\t c = d
2598\t_
2599was your intent. In general, Python-mode either reproduces the
2600indentation of the (closest code or indenting-comment) preceding
2601statement, or adds an extra py-indent-offset blanks if the preceding
2602statement has `:' as its last significant (non-whitespace and non-
2603comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002604\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002605
2606Continuation lines are given extra indentation. If you don't like the
2607suggested indentation, change it to something you do like, and Python-
2608mode will strive to indent later lines of the statement in the same way.
2609
2610If a line is a continuation line by virtue of being in an unclosed
2611paren/bracket/brace structure (`list', for short), the suggested
2612indentation depends on whether the current line contains the first item
2613in the list. If it does, it's indented py-indent-offset columns beyond
2614the indentation of the line containing the open bracket. If you don't
2615like that, change it by hand. The remaining items in the list will mimic
2616whatever indentation you give to the first item.
2617
2618If a line is a continuation line because the line preceding it ends with
2619a backslash, the third and following lines of the statement inherit their
2620indentation from the line preceding them. The indentation of the second
2621line in the statement depends on the form of the first (base) line: if
2622the base line is an assignment statement with anything more interesting
2623than the backslash following the leftmost assigning `=', the second line
2624is indented two columns beyond that `='. Else it's indented to two
2625columns beyond the leftmost solid chunk of non-whitespace characters on
2626the base line.
2627
2628Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2629repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2630structure you intend.
2631%c:indent-for-tab-command
2632%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002633%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002634
2635
2636The next function may be handy when editing code you didn't write:
2637%c:py-guess-indent-offset
2638
2639
2640The remaining `indent' functions apply to a region of Python code. They
2641assume the block structure (equals indentation, in Python) of the region
2642is correct, and alter the indentation in various ways while preserving
2643the block structure:
2644%c:py-indent-region
2645%c:py-shift-region-left
2646%c:py-shift-region-right
2647
2648@MARKING & MANIPULATING REGIONS OF CODE
2649
2650\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002651\\[py-mark-def-or-class]\t mark smallest enclosing def
2652\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002653\\[comment-region]\t comment out region of code
2654\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002655%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002656%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002657%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002658
2659@MOVING POINT
2660
2661\\[py-previous-statement]\t move to statement preceding point
2662\\[py-next-statement]\t move to statement following point
2663\\[py-goto-block-up]\t move up to start of current block
Barry Warsawab0e86c1998-05-19 15:31:46 +00002664\\[py-beginning-of-def-or-class]\t move to start of def
2665\\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
2666\\[py-end-of-def-or-class]\t move to end of def
2667\\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002668
2669The first two move to one statement beyond the statement that contains
2670point. A numeric prefix argument tells them to move that many
2671statements instead. Blank lines, comment lines, and continuation lines
2672do not count as `statements' for these commands. So, e.g., you can go
2673to the first code statement in a file by entering
2674\t\\[beginning-of-buffer]\t to move to the top of the file
2675\t\\[py-next-statement]\t to skip over initial comments and blank lines
2676Or do `\\[py-previous-statement]' with a huge prefix argument.
2677%c:py-previous-statement
2678%c:py-next-statement
2679%c:py-goto-block-up
Barry Warsawab0e86c1998-05-19 15:31:46 +00002680%c:py-beginning-of-def-or-class
2681%c:py-end-of-def-or-class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002682
2683@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2684
2685`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2686
2687`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2688overall class and def structure of a module.
2689
2690`\\[back-to-indentation]' moves point to a line's first non-blank character.
2691
2692`\\[indent-relative]' is handy for creating odd indentation.
2693
2694@OTHER EMACS HINTS
2695
2696If you don't like the default value of a variable, change its value to
2697whatever you do like by putting a `setq' line in your .emacs file.
2698E.g., to set the indentation increment to 4, put this line in your
2699.emacs:
2700\t(setq py-indent-offset 4)
2701To see the value of a variable, do `\\[describe-variable]' and enter the variable
2702name at the prompt.
2703
2704When entering a key sequence like `C-c C-n', it is not necessary to
2705release the CONTROL key after doing the `C-c' part -- it suffices to
2706press the CONTROL key, press and release `c' (while still holding down
2707CONTROL), press and release `n' (while still holding down CONTROL), &
2708then release CONTROL.
2709
2710Entering Python mode calls with no arguments the value of the variable
2711`python-mode-hook', if that value exists and is not nil; for backward
2712compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2713the Elisp manual for details.
2714
2715Obscure: When python-mode is first loaded, it looks for all bindings
2716to newline-and-indent in the global keymap, and shadows them with
2717local bindings to py-newline-and-indent."))
2718
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002719
2720;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002721(defvar py-parse-state-re
2722 (concat
2723 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2724 "\\|"
2725 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002726
Barry Warsaw7ae77681994-12-12 20:38:05 +00002727;; returns the parse state at point (see parse-partial-sexp docs)
2728(defun py-parse-state ()
2729 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002730 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002731 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002732 (while (not done)
2733 ;; back up to the first preceding line (if any; else start of
2734 ;; buffer) that begins with a popular Python keyword, or a
2735 ;; non- whitespace and non-comment character. These are good
2736 ;; places to start parsing to see whether where we started is
2737 ;; at a non-zero nesting level. It may be slow for people who
2738 ;; write huge code blocks or huge lists ... tough beans.
2739 (re-search-backward py-parse-state-re nil 'move)
2740 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002741 ;; In XEmacs, we have a much better way to test for whether
2742 ;; we're in a triple-quoted string or not. Emacs does not
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002743 ;; have this built-in function, which is its loss because
Barry Warsawf64b4051998-02-12 16:52:14 +00002744 ;; without scanning from the beginning of the buffer, there's
2745 ;; no accurate way to determine this otherwise.
2746 (if (not (fboundp 'buffer-syntactic-context))
2747 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002748 (progn
2749 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002750 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002751 (setq done (or (not (nth 3 pps))
2752 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002753 ;; XEmacs
2754 (setq done (or (not (buffer-syntactic-context))
2755 (bobp)))
2756 (when done
2757 (setq pps (parse-partial-sexp (point) here)))
2758 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002759 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002760
2761;; if point is at a non-zero nesting level, returns the number of the
2762;; character that opens the smallest enclosing unclosed list; else
2763;; returns nil.
2764(defun py-nesting-level ()
Barry Warsawf64b4051998-02-12 16:52:14 +00002765 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002766 (if (zerop (car status))
2767 nil ; not in a nest
2768 (car (cdr status))))) ; char# of open bracket
2769
2770;; t iff preceding line ends with backslash that's not in a comment
2771(defun py-backslash-continuation-line-p ()
2772 (save-excursion
2773 (beginning-of-line)
2774 (and
2775 ;; use a cheap test first to avoid the regexp if possible
2776 ;; use 'eq' because char-after may return nil
2777 (eq (char-after (- (point) 2)) ?\\ )
2778 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002779 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002780 (looking-at py-continued-re))))
2781
2782;; t iff current line is a continuation line
2783(defun py-continuation-line-p ()
2784 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002785 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002786 (or (py-backslash-continuation-line-p)
2787 (py-nesting-level))))
2788
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002789;; go to initial line of current statement; usually this is the line
2790;; we're on, but if we're on the 2nd or following lines of a
2791;; continuation block, we need to go up to the first line of the
2792;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002793;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002794;; Tricky: We want to avoid quadratic-time behavior for long continued
2795;; blocks, whether of the backslash or open-bracket varieties, or a
2796;; mix of the two. The following manages to do that in the usual
2797;; cases.
Barry Warsawc210e691998-01-20 22:52:56 +00002798;;
2799;; Also, if we're sitting inside a triple quoted string, this will
2800;; drop us at the line that begins the string.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002801(defun py-goto-initial-line ()
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002802 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002803 (while (py-continuation-line-p)
2804 (beginning-of-line)
2805 (if (py-backslash-continuation-line-p)
2806 (while (py-backslash-continuation-line-p)
2807 (forward-line -1))
2808 ;; else zip out of nested brackets/braces/parens
2809 (while (setq open-bracket-pos (py-nesting-level))
2810 (goto-char open-bracket-pos)))))
2811 (beginning-of-line))
2812
2813;; go to point right beyond final line of current statement; usually
2814;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002815;; statement we need to skip over the continuation lines. Tricky:
2816;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002817(defun py-goto-beyond-final-line ()
Barry Warsaw751f4931998-05-19 16:06:21 +00002818 ;; TEST ADDED BY MDE; not quite the right solution
2819 (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
2820 (goto-char (match-end 0)))
2821 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +00002822 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002823 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002824 (while (and (py-continuation-line-p)
2825 (not (eobp)))
2826 ;; skip over the backslash flavor
2827 (while (and (py-backslash-continuation-line-p)
2828 (not (eobp)))
2829 (forward-line 1))
2830 ;; if in nest, zip to the end of the nest
2831 (setq state (py-parse-state))
2832 (if (and (not (zerop (car state)))
2833 (not (eobp)))
2834 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002835 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002836 (forward-line 1))))))
2837
2838;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002839;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002840(defun py-statement-opens-block-p ()
2841 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002842 (let ((start (point))
2843 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2844 (searching t)
2845 (answer nil)
2846 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002847 (goto-char start)
2848 (while searching
2849 ;; look for a colon with nothing after it except whitespace, and
2850 ;; maybe a comment
2851 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2852 finish t)
2853 (if (eq (point) finish) ; note: no `else' clause; just
2854 ; keep searching if we're not at
2855 ; the end yet
2856 ;; sure looks like it opens a block -- but it might
2857 ;; be in a comment
2858 (progn
2859 (setq searching nil) ; search is done either way
2860 (setq state (parse-partial-sexp start
2861 (match-beginning 0)))
2862 (setq answer (not (nth 4 state)))))
2863 ;; search failed: couldn't find another interesting colon
2864 (setq searching nil)))
2865 answer)))
2866
Barry Warsawf831d811996-07-31 20:42:59 +00002867(defun py-statement-closes-block-p ()
2868 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002869 ;; starts with `return', `raise', `break', `continue', and `pass'.
2870 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002871 (let ((here (point)))
2872 (back-to-indentation)
2873 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002874 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002875 (goto-char here))))
2876
Barry Warsaw7ae77681994-12-12 20:38:05 +00002877;; go to point right beyond final line of block begun by the current
2878;; line. This is the same as where py-goto-beyond-final-line goes
2879;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002880;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002881(defun py-goto-beyond-block ()
2882 (if (py-statement-opens-block-p)
2883 (py-mark-block nil 'just-move)
2884 (py-goto-beyond-final-line)))
2885
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002886;; Go to start of first statement (not blank or comment or
2887;; continuation line) at or preceding point. Returns t if there is
2888;; one, else nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002889(defun py-goto-statement-at-or-above ()
2890 (py-goto-initial-line)
2891 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002892 ;; skip back over blank & comment lines
2893 ;; note: will skip a blank or comment line that happens to be
2894 ;; a continuation line too
2895 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2896 (progn (py-goto-initial-line) t)
2897 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002898 t))
2899
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002900;; Go to start of first statement (not blank or comment or
2901;; continuation line) following the statement containing point.
2902;; Returns t if there is one, else nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002903(defun py-goto-statement-below ()
2904 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002905 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002906 (py-goto-beyond-final-line)
2907 (while (and
2908 (looking-at py-blank-or-comment-re)
2909 (not (eobp)))
2910 (forward-line 1))
2911 (if (eobp)
2912 (progn (goto-char start) nil)
2913 t)))
2914
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002915;; Go to start of statement, at or preceding point, starting with
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002916;; keyword KEY. Skips blank lines and non-indenting comments upward
2917;; first. If that statement starts with KEY, done, else go back to
2918;; first enclosing block starting with KEY. If successful, leaves
2919;; point at the start of the KEY line & returns t. Else leaves point
2920;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002921(defun py-go-up-tree-to-keyword (key)
2922 ;; skip blanks and non-indenting #
2923 (py-goto-initial-line)
2924 (while (and
2925 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2926 (zerop (forward-line -1))) ; go back
2927 nil)
2928 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002929 (let* ((re (concat "[ \t]*" key "\\b"))
2930 (case-fold-search nil) ; let* so looking-at sees this
2931 (found (looking-at re))
2932 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002933 (while (not (or found dead))
2934 (condition-case nil ; in case no enclosing block
2935 (py-goto-block-up 'no-mark)
2936 (error (setq dead t)))
2937 (or dead (setq found (looking-at re))))
2938 (beginning-of-line)
2939 found))
2940
2941;; return string in buffer from start of indentation to end of line;
2942;; prefix "..." if leading whitespace was skipped
2943(defun py-suck-up-leading-text ()
2944 (save-excursion
2945 (back-to-indentation)
2946 (concat
2947 (if (bolp) "" "...")
2948 (buffer-substring (point) (progn (end-of-line) (point))))))
2949
2950;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2951;; as a Lisp symbol; return nil if none
2952(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002953 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002954 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2955 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2956 nil)))
2957
Barry Warsawb3e81d51996-09-04 15:12:42 +00002958(defun py-current-defun ()
2959 ;; tell add-log.el how to find the current function/method/variable
2960 (save-excursion
2961 (if (re-search-backward py-defun-start-re nil t)
2962 (or (match-string 3)
2963 (let ((method (match-string 2)))
2964 (if (and (not (zerop (length (match-string 1))))
2965 (re-search-backward py-class-start-re nil t))
2966 (concat (match-string 1) "." method)
2967 method)))
2968 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002969
2970
Barry Warsawfec75d61995-07-05 23:26:15 +00002971(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002972 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002973
Barry Warsaw850437a1995-03-08 21:50:28 +00002974(defun py-version ()
2975 "Echo the current version of `python-mode' in the minibuffer."
2976 (interactive)
2977 (message "Using `python-mode' version %s" py-version)
2978 (py-keep-region-active))
2979
2980;; only works under Emacs 19
2981;(eval-when-compile
2982; (require 'reporter))
2983
2984(defun py-submit-bug-report (enhancement-p)
2985 "Submit via mail a bug report on `python-mode'.
2986With \\[universal-argument] just submit an enhancement request."
2987 (interactive
2988 (list (not (y-or-n-p
2989 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002990 (let ((reporter-prompt-for-summary-p (if enhancement-p
2991 "(Very) brief summary: "
2992 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002993 (require 'reporter)
2994 (reporter-submit-bug-report
2995 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002996 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002997 ;; varlist
2998 (if enhancement-p nil
2999 '(py-python-command
3000 py-indent-offset
3001 py-block-comment-prefix
3002 py-scroll-process-buffer
3003 py-temp-directory
3004 py-beep-if-tab-change))
3005 nil ;pre-hooks
3006 nil ;post-hooks
3007 "Dear Barry,") ;salutation
3008 (if enhancement-p nil
3009 (set-mark (point))
3010 (insert
3011"Please replace this text with a sufficiently large code sample\n\
3012and an exact recipe so that I can reproduce your problem. Failure\n\
3013to do so may mean a greater delay in fixing your bug.\n\n")
3014 (exchange-point-and-mark)
3015 (py-keep-region-active))))
3016
3017
Barry Warsaw47384781997-11-26 05:27:45 +00003018(defun py-kill-emacs-hook ()
3019 (mapcar #'(lambda (filename)
3020 (py-safe (delete-file filename)))
3021 py-file-queue))
3022
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003023;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00003024(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003025
3026
3027
3028(provide 'python-mode)
3029;;; python-mode.el ends here