blob: e4d3dd07ae6b5ab5ca24c5ab204d12b7fc18e4d4 [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 Warsaw1d0364b1998-05-19 16:15:26 +0000596 (define-key py-mode-map "\C-c\C-s" 'py-execute-string)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000597 (define-key py-mode-map "\C-c|" 'py-execute-region)
Barry Warsaw820273d1998-05-19 15:54:45 +0000598 (define-key py-mode-map "\e\C-x" 'py-execute-def-or-class)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000599 (define-key py-mode-map "\C-c!" 'py-shell)
Barry Warsawa2398801998-04-09 23:28:20 +0000600 (define-key py-mode-map "\C-c\C-t" 'py-toggle-shells)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000601 ;; Caution! Enter here at your own risk. We are trying to support
602 ;; several behaviors and it gets disgusting. :-( This logic ripped
603 ;; largely from CC Mode.
604 ;;
605 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
606 ;; backwards deletion behavior to DEL, which both Delete and
607 ;; Backspace get translated to. There's no way to separate this
608 ;; behavior in a clean way, so deal with it! Besides, it's been
609 ;; this way since the dawn of time.
610 (if (not (boundp 'delete-key-deletes-forward))
611 (define-key py-mode-map "\177" 'py-electric-backspace)
612 ;; However, XEmacs 20 actually achieved enlightenment. It is
613 ;; possible to sanely define both backward and forward deletion
614 ;; behavior under X separately (TTYs are forever beyond hope, but
615 ;; who cares? XEmacs 20 does the right thing with these too).
616 (define-key py-mode-map [delete] 'py-electric-delete)
617 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000618 ;; Separate M-BS from C-M-h. The former should remain
619 ;; backward-kill-word.
620 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000621 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000622 ;; Miscellaneous
623 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
624 (define-key py-mode-map "\C-c\t" 'py-indent-region)
625 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
626 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
627 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000628 (define-key py-mode-map "\C-c#" 'py-comment-region)
629 (define-key py-mode-map "\C-c?" 'py-describe-mode)
630 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
Barry Warsawab0e86c1998-05-19 15:31:46 +0000631 (define-key py-mode-map "\e\C-a" 'py-beginning-of-def-or-class)
632 (define-key py-mode-map "\e\C-e" 'py-end-of-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000633 (define-key py-mode-map "\C-c-" 'py-up-exception)
634 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000635 ;; information
636 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
637 (define-key py-mode-map "\C-c\C-v" 'py-version)
638 ;; py-newline-and-indent mappings
Barry Warsaw82aecb91998-01-21 05:14:24 +0000639 (define-key py-mode-map "\n" 'py-newline-and-indent)
640 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000641 ;; shadow global bindings for newline-and-indent w/ the py- version.
642 ;; BAW - this is extremely bad form, but I'm not going to change it
643 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000644 (mapcar #'(lambda (key)
645 (define-key py-mode-map key 'py-newline-and-indent))
646 (where-is-internal 'newline-and-indent))
647 )
648
649(defvar py-mode-output-map nil
650 "Keymap used in *Python Output* buffers*")
651(if py-mode-output-map
652 nil
653 (setq py-mode-output-map (make-sparse-keymap))
654 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
655 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
656 ;; TBD: Disable all self-inserting keys. This is bogus, we should
657 ;; really implement this as *Python Output* buffer being read-only
658 (mapcar #' (lambda (key)
659 (define-key py-mode-output-map key
660 #'(lambda () (interactive) (beep))))
661 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000662 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000663
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000664(defvar py-mode-syntax-table nil
665 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000666(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000667 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000668 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000669 (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 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
675 ;; Add operator symbols misassigned in the std 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 (modify-syntax-entry ?\| "." py-mode-syntax-table)
687 ;; For historical reasons, underscore is word class instead of
688 ;; symbol class. GNU conventions say it should be symbol class, but
689 ;; there's a natural conflict between what major mode authors want
690 ;; and what users expect from `forward-word' and `backward-word'.
691 ;; Guido and I have hashed this out and have decided to keep
692 ;; underscore in word class. If you're tempted to change it, try
693 ;; binding M-f and M-b to py-forward-into-nomenclature and
694 ;; py-backward-into-nomenclature instead.
695 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
696 ;; Both single quote and double quote are string delimiters
697 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
698 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
699 ;; backquote is open and close paren
700 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
701 ;; comment delimiters
702 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
703 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
704 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000705
Barry Warsawb3e81d51996-09-04 15:12:42 +0000706
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000707
Barry Warsaw42f707f1996-07-29 21:05:05 +0000708;; Menu definitions, only relevent if you have the easymenu.el package
709;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000710(defvar py-menu nil
711 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000712This menu will get created automatically if you have the `easymenu'
713package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000714
Barry Warsawc72c11c1997-08-09 06:42:08 +0000715(and (py-safe (require 'easymenu) t)
716 (easy-menu-define
717 py-menu py-mode-map "Python Mode menu"
718 '("Python"
719 ["Comment Out Region" py-comment-region (mark)]
720 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
721 "-"
722 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000723 ["Mark current def" py-mark-def-or-class t]
724 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000725 "-"
726 ["Shift region left" py-shift-region-left (mark)]
727 ["Shift region right" py-shift-region-right (mark)]
728 "-"
Barry Warsaw820273d1998-05-19 15:54:45 +0000729 ["Import/reload file" py-execute-import-or-reload t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000730 ["Execute buffer" py-execute-buffer t]
731 ["Execute region" py-execute-region (mark)]
Barry Warsaw820273d1998-05-19 15:54:45 +0000732 ["Execute def or class" py-execute-def-or-class (mark)]
Barry Warsaw1d0364b1998-05-19 16:15:26 +0000733 ["Execute string" py-execute-string t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000734 ["Start interpreter..." py-shell t]
735 "-"
736 ["Go to start of block" py-goto-block-up t]
Barry Warsawab0e86c1998-05-19 15:31:46 +0000737 ["Go to start of class" (py-beginning-of-def-or-class t) t]
738 ["Move to end of class" (py-end-of-def-or-class t) t]
739 ["Move to start of def" py-beginning-of-def-or-class t]
740 ["Move to end of def" py-end-of-def-or-class t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000741 "-"
742 ["Describe mode" py-describe-mode t]
743 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000744
Barry Warsaw81437461996-08-01 19:48:02 +0000745
746
747;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
748(defvar imenu-example--python-class-regexp
749 (concat ; <<classes>>
750 "\\(" ;
751 "^[ \t]*" ; newline and maybe whitespace
752 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
753 ; possibly multiple superclasses
Barry Warsaw3179fe01998-04-04 21:36:53 +0000754 "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
Barry Warsaw81437461996-08-01 19:48:02 +0000755 "[ \t]*:" ; and the final :
756 "\\)" ; >>classes<<
757 )
758 "Regexp for Python classes for use with the imenu package."
759 )
760
761(defvar imenu-example--python-method-regexp
762 (concat ; <<methods and functions>>
763 "\\(" ;
764 "^[ \t]*" ; new line and maybe whitespace
765 "\\(def[ \t]+" ; function definitions start with def
766 "\\([a-zA-Z0-9_]+\\)" ; name is here
767 ; function arguments...
768 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
769 "\\)" ; end of def
770 "[ \t]*:" ; and then the :
771 "\\)" ; >>methods and functions<<
772 )
773 "Regexp for Python methods/functions for use with the imenu package."
774 )
775
776(defvar imenu-example--python-method-no-arg-parens '(2 8)
777 "Indicies into groups of the Python regexp for use with imenu.
778
779Using these values will result in smaller imenu lists, as arguments to
780functions are not listed.
781
782See the variable `imenu-example--python-show-method-args-p' for more
783information.")
784
785(defvar imenu-example--python-method-arg-parens '(2 7)
786 "Indicies into groups of the Python regexp for use with imenu.
787Using these values will result in large imenu lists, as arguments to
788functions are listed.
789
790See the variable `imenu-example--python-show-method-args-p' for more
791information.")
792
793;; Note that in this format, this variable can still be used with the
794;; imenu--generic-function. Otherwise, there is no real reason to have
795;; it.
796(defvar imenu-example--generic-python-expression
797 (cons
798 (concat
799 imenu-example--python-class-regexp
800 "\\|" ; or...
801 imenu-example--python-method-regexp
802 )
803 imenu-example--python-method-no-arg-parens)
804 "Generic Python expression which may be used directly with imenu.
805Used by setting the variable `imenu-generic-expression' to this value.
806Also, see the function \\[imenu-example--create-python-index] for a
807better alternative for finding the index.")
808
809;; These next two variables are used when searching for the python
810;; class/definitions. Just saving some time in accessing the
811;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000812(defvar imenu-example--python-generic-regexp nil)
813(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000814
815
Barry Warsaw81437461996-08-01 19:48:02 +0000816(defun imenu-example--create-python-index ()
817 "Python interface function for imenu package.
818Finds all python classes and functions/methods. Calls function
819\\[imenu-example--create-python-index-engine]. See that function for
820the details of how this works."
821 (setq imenu-example--python-generic-regexp
822 (car imenu-example--generic-python-expression))
823 (setq imenu-example--python-generic-parens
824 (if imenu-example--python-show-method-args-p
825 imenu-example--python-method-arg-parens
826 imenu-example--python-method-no-arg-parens))
827 (goto-char (point-min))
828 (imenu-example--create-python-index-engine nil))
829
830(defun imenu-example--create-python-index-engine (&optional start-indent)
831 "Function for finding imenu definitions in Python.
832
833Finds all definitions (classes, methods, or functions) in a Python
834file for the imenu package.
835
836Returns a possibly nested alist of the form
837
838 (INDEX-NAME . INDEX-POSITION)
839
840The second element of the alist may be an alist, producing a nested
841list as in
842
843 (INDEX-NAME . INDEX-ALIST)
844
845This function should not be called directly, as it calls itself
846recursively and requires some setup. Rather this is the engine for
847the function \\[imenu-example--create-python-index].
848
849It works recursively by looking for all definitions at the current
850indention level. When it finds one, it adds it to the alist. If it
851finds a definition at a greater indentation level, it removes the
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000852previous definition from the alist. In its place it adds all
Barry Warsaw81437461996-08-01 19:48:02 +0000853definitions found at the next indentation level. When it finds a
854definition that is less indented then the current level, it retuns the
855alist it has created thus far.
856
857The optional argument START-INDENT indicates the starting indentation
858at which to continue looking for Python classes, methods, or
859functions. If this is not supplied, the function uses the indentation
860of the first definition found."
861 (let ((index-alist '())
862 (sub-method-alist '())
863 looking-p
864 def-name prev-name
865 cur-indent def-pos
866 (class-paren (first imenu-example--python-generic-parens))
867 (def-paren (second imenu-example--python-generic-parens)))
868 (setq looking-p
869 (re-search-forward imenu-example--python-generic-regexp
870 (point-max) t))
871 (while looking-p
872 (save-excursion
873 ;; used to set def-name to this value but generic-extract-name is
874 ;; new to imenu-1.14. this way it still works with imenu-1.11
875 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
876 (let ((cur-paren (if (match-beginning class-paren)
877 class-paren def-paren)))
878 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000879 (buffer-substring-no-properties (match-beginning cur-paren)
880 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000881 (beginning-of-line)
882 (setq cur-indent (current-indentation)))
883
884 ;; HACK: want to go to the next correct definition location. we
885 ;; explicitly list them here. would be better to have them in a
886 ;; list.
887 (setq def-pos
888 (or (match-beginning class-paren)
889 (match-beginning def-paren)))
890
891 ;; if we don't have a starting indent level, take this one
892 (or start-indent
893 (setq start-indent cur-indent))
894
895 ;; if we don't have class name yet, take this one
896 (or prev-name
897 (setq prev-name def-name))
898
899 ;; what level is the next definition on? must be same, deeper
900 ;; or shallower indentation
901 (cond
902 ;; at the same indent level, add it to the list...
903 ((= start-indent cur-indent)
904
905 ;; if we don't have push, use the following...
906 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
907 (push (cons def-name def-pos) index-alist))
908
909 ;; deeper indented expression, recur...
910 ((< start-indent cur-indent)
911
912 ;; the point is currently on the expression we're supposed to
913 ;; start on, so go back to the last expression. The recursive
914 ;; call will find this place again and add it to the correct
915 ;; list
916 (re-search-backward imenu-example--python-generic-regexp
917 (point-min) 'move)
918 (setq sub-method-alist (imenu-example--create-python-index-engine
919 cur-indent))
920
921 (if sub-method-alist
922 ;; we put the last element on the index-alist on the start
923 ;; of the submethod alist so the user can still get to it.
924 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000925 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000926 (cons save-elmt sub-method-alist))
927 index-alist))))
928
929 ;; found less indented expression, we're done.
930 (t
931 (setq looking-p nil)
932 (re-search-backward imenu-example--python-generic-regexp
933 (point-min) t)))
934 (setq prev-name def-name)
935 (and looking-p
936 (setq looking-p
937 (re-search-forward imenu-example--python-generic-regexp
938 (point-max) 'move))))
939 (nreverse index-alist)))
940
Barry Warsaw42f707f1996-07-29 21:05:05 +0000941
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000942;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000943(defun python-mode ()
944 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000945To submit a problem report, enter `\\[py-submit-bug-report]' from a
946`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
947documentation. To see what version of `python-mode' you are running,
948enter `\\[py-version]'.
949
950This mode knows about Python indentation, tokens, comments and
951continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000952
953COMMANDS
954\\{py-mode-map}
955VARIABLES
956
Barry Warsaw42f707f1996-07-29 21:05:05 +0000957py-indent-offset\t\tindentation increment
958py-block-comment-prefix\t\tcomment string used by comment-region
959py-python-command\t\tshell command to invoke Python interpreter
960py-scroll-process-buffer\t\talways scroll Python process buffer
961py-temp-directory\t\tdirectory used for temp files (if needed)
962py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000963 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000964 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000965 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000966 (make-local-variable 'font-lock-defaults)
967 (make-local-variable 'paragraph-separate)
968 (make-local-variable 'paragraph-start)
969 (make-local-variable 'require-final-newline)
970 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000971 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000972 (make-local-variable 'comment-start-skip)
973 (make-local-variable 'comment-column)
974 (make-local-variable 'indent-region-function)
975 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000976 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000977 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000978 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000979 (setq major-mode 'python-mode
980 mode-name "Python"
981 local-abbrev-table python-mode-abbrev-table
Barry Warsaw5c38bf61997-12-02 22:01:04 +0000982 font-lock-defaults '(python-font-lock-keywords)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000983 paragraph-separate "^[ \t]*$"
984 paragraph-start "^[ \t]*$"
985 require-final-newline t
986 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000987 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000988 comment-start-skip "# *"
989 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000990 indent-region-function 'py-indent-region
991 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000992 ;; tell add-log.el how to find the current function/method/variable
993 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000994 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000995 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000996 ;; add the menu
997 (if py-menu
998 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000999 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +00001000 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +00001001 (setq comment-multi-line nil))
Barry Warsaw742a5111998-03-13 17:29:15 +00001002 ;; Install Imenu, only works for Emacs.
1003 (when (py-safe (require 'imenu))
1004 (make-variable-buffer-local 'imenu-create-index-function)
1005 (setq imenu-create-index-function
1006 (function imenu-example--create-python-index))
1007 (setq imenu-generic-expression
1008 imenu-example--generic-python-expression)
1009 (if (fboundp 'imenu-add-to-menubar)
1010 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
1011 )
1012 ;; Run the mode hook. Note that py-mode-hook is deprecated.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001013 (if python-mode-hook
1014 (run-hooks 'python-mode-hook)
Barry Warsaw742a5111998-03-13 17:29:15 +00001015 (run-hooks 'py-mode-hook))
1016 ;; Now do the automagical guessing
1017 (if py-smart-indentation
1018 (let ((offset py-indent-offset))
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001019 ;; It's okay if this fails to guess a good value
Barry Warsaw742a5111998-03-13 17:29:15 +00001020 (if (and (py-safe (py-guess-indent-offset))
1021 (<= py-indent-offset 8)
1022 (>= py-indent-offset 2))
1023 (setq offset py-indent-offset))
1024 (setq py-indent-offset offset)
Barry Warsaw639eea61998-03-16 18:12:13 +00001025 ;; Only turn indent-tabs-mode off if tab-width !=
1026 ;; py-indent-offset. Never turn it on, because the user must
1027 ;; have explicitly turned it off.
1028 (if (/= tab-width py-indent-offset)
1029 (setq indent-tabs-mode nil))
Barry Warsaw742a5111998-03-13 17:29:15 +00001030 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001031
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001032
Barry Warsawb91b7431995-03-14 15:55:20 +00001033;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001034(defun py-outdent-p ()
1035 ;; returns non-nil if the current line should outdent one level
1036 (save-excursion
1037 (and (progn (back-to-indentation)
1038 (looking-at py-outdent-re))
Barry Warsawf06777d1998-01-21 05:36:18 +00001039 (progn (forward-line -1)
1040 (py-goto-initial-line)
1041 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001042 (while (or (looking-at py-blank-or-comment-re)
1043 (bobp))
1044 (backward-to-indentation 1))
1045 (not (looking-at py-no-outdent-re)))
1046 )))
1047
Barry Warsawb91b7431995-03-14 15:55:20 +00001048(defun py-electric-colon (arg)
1049 "Insert a colon.
1050In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001051argument is provided, that many colons are inserted non-electrically.
1052Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +00001053 (interactive "P")
1054 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001055 ;; are we in a string or comment?
1056 (if (save-excursion
1057 (let ((pps (parse-partial-sexp (save-excursion
Barry Warsawab0e86c1998-05-19 15:31:46 +00001058 (py-beginning-of-def-or-class)
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001059 (point))
1060 (point))))
1061 (not (or (nth 3 pps) (nth 4 pps)))))
1062 (save-excursion
1063 (let ((here (point))
1064 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001065 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001066 (if (and (not arg)
1067 (py-outdent-p)
1068 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +00001069 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001070 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001071 )
1072 (setq outdent py-indent-offset))
1073 ;; Don't indent, only outdent. This assumes that any lines that
1074 ;; are already outdented relative to py-compute-indentation were
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001075 ;; put there on purpose. It's highly annoying to have `:' indent
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001076 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
1077 ;; there a better way to determine this???
1078 (if (< (current-indentation) indent) nil
1079 (goto-char here)
1080 (beginning-of-line)
1081 (delete-horizontal-space)
1082 (indent-to (- indent outdent))
1083 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001084
1085
Barry Warsawa97a3f31997-11-04 18:47:06 +00001086;; Python subprocess utilities and filters
1087(defun py-execute-file (proc filename)
1088 ;; Send a properly formatted execfile('FILENAME') to the underlying
1089 ;; Python interpreter process FILENAME. Make that process's buffer
1090 ;; visible and force display. Also make comint believe the user
1091 ;; typed this string so that kill-output-from-shell does The Right
1092 ;; Thing.
1093 (let ((curbuf (current-buffer))
1094 (procbuf (process-buffer proc))
1095 (comint-scroll-to-bottom-on-output t)
1096 (msg (format "## working on region in file %s...\n" filename))
1097 (cmd (format "execfile('%s')\n" filename)))
1098 (unwind-protect
1099 (progn
1100 (set-buffer procbuf)
1101 (goto-char (point-max))
1102 (move-marker (process-mark proc) (point))
1103 (funcall (process-filter proc) proc msg))
1104 (set-buffer curbuf))
1105 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001106
1107(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001108 (let ((curbuf (current-buffer))
1109 (pbuf (process-buffer pyproc))
1110 (pmark (process-mark pyproc))
1111 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001112 ;; make sure we switch to a different buffer at least once. if we
1113 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001114 ;; window, and point is before the end, and lots of output is
1115 ;; coming at a fast pace, then (a) simple cursor-movement commands
1116 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
1117 ;; to have a visible effect (the window just doesn't get updated,
1118 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
1119 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001120 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001121 ;; #b makes no sense to me at all. #a almost makes sense: unless
1122 ;; we actually change buffers, set_buffer_internal in buffer.c
1123 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1124 ;; seems to make the Emacs command loop reluctant to update the
1125 ;; display. Perhaps the default process filter in process.c's
1126 ;; read_process_output has update_mode_lines++ for a similar
1127 ;; reason? beats me ...
1128
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001129 (unwind-protect
1130 ;; make sure current buffer is restored
1131 ;; BAW - we want to check to see if this still applies
1132 (progn
1133 ;; mysterious ugly hack
1134 (if (eq curbuf pbuf)
1135 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001136
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001137 (set-buffer pbuf)
1138 (let* ((start (point))
1139 (goback (< start pmark))
1140 (goend (and (not goback) (= start (point-max))))
1141 (buffer-read-only nil))
1142 (goto-char pmark)
1143 (insert string)
1144 (move-marker pmark (point))
1145 (setq file-finished
1146 (and py-file-queue
1147 (equal ">>> "
1148 (buffer-substring
1149 (prog2 (beginning-of-line) (point)
1150 (goto-char pmark))
1151 (point)))))
1152 (if goback (goto-char start)
1153 ;; else
1154 (if py-scroll-process-buffer
1155 (let* ((pop-up-windows t)
1156 (pwin (display-buffer pbuf)))
1157 (set-window-point pwin (point)))))
1158 (set-buffer curbuf)
1159 (if file-finished
1160 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001161 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001162 (setq py-file-queue (cdr py-file-queue))
1163 (if py-file-queue
1164 (py-execute-file pyproc (car py-file-queue)))))
1165 (and goend
1166 (progn (set-buffer pbuf)
1167 (goto-char (point-max))))
1168 ))
1169 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001170
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001171(defun py-postprocess-output-buffer (buf)
Barry Warsawf9b99f41998-03-26 16:08:59 +00001172 ;; Highlight exceptions found in BUF. If an exception occurred
1173 ;; return t, otherwise return nil. BUF must exist.
1174 (let (line file bol err-p)
Barry Warsaw9981d221997-12-03 05:25:48 +00001175 (save-excursion
1176 (set-buffer buf)
1177 (beginning-of-buffer)
1178 (while (re-search-forward py-traceback-line-re nil t)
1179 (setq file (match-string 1)
1180 line (string-to-int (match-string 2))
1181 bol (py-point 'bol))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001182 (py-highlight-line bol (py-point 'eol) file line)))
1183 (when (and py-jump-on-exception line)
1184 (beep)
1185 (py-jump-to-exception file line)
1186 (setq err-p t))
1187 err-p))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001188
Barry Warsaw9981d221997-12-03 05:25:48 +00001189
Barry Warsawa97a3f31997-11-04 18:47:06 +00001190
1191;;; Subprocess commands
1192
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001193;; only used when (memq 'broken-temp-names py-emacs-features)
1194(defvar py-serial-number 0)
1195(defvar py-exception-buffer nil)
1196(defconst py-output-buffer "*Python Output*")
Barry Warsawa2398801998-04-09 23:28:20 +00001197(make-variable-buffer-local 'py-output-buffer)
1198
1199;; for toggling between CPython and JPython
1200(defvar py-which-shell py-python-command)
1201(defvar py-which-args py-python-command-args)
1202(defvar py-which-bufname "Python")
1203(make-variable-buffer-local 'py-which-shell)
1204(make-variable-buffer-local 'py-which-args)
1205(make-variable-buffer-local 'py-which-bufname)
1206
1207(defun py-toggle-shells (arg)
1208 "Toggles between the CPython and JPython shells.
1209With positive \\[universal-argument], uses the CPython shell, with
1210negative \\[universal-argument] uses the JPython shell, and with a
1211zero argument, toggles the shell."
1212 (interactive "P")
1213 ;; default is to toggle
1214 (if (null arg)
1215 (setq arg 0))
1216 ;; toggle if zero
1217 (if (= arg 0)
1218 (if (string-equal py-which-bufname "Python")
1219 (setq arg -1)
1220 (setq arg 1)))
1221 (let (msg)
1222 (cond
1223 ((< 0 arg)
1224 ;; set to CPython
1225 (setq py-which-shell py-python-command
1226 py-which-args py-python-command-args
1227 py-which-bufname "Python"
1228 msg "CPython"
1229 mode-name "Python"))
1230 ((> 0 arg)
1231 (setq py-which-shell py-jpython-command
1232 py-which-args py-jpython-command-args
1233 py-which-bufname "JPython"
1234 msg "JPython"
1235 mode-name "JPython"))
1236 )
Barry Warsawea609c11998-04-10 16:08:26 +00001237 (message "Using the %s shell" msg)
Barry Warsawa2398801998-04-09 23:28:20 +00001238 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001239
Barry Warsawa97a3f31997-11-04 18:47:06 +00001240;;;###autoload
1241(defun py-shell ()
1242 "Start an interactive Python interpreter in another window.
1243This is like Shell mode, except that Python is running in the window
1244instead of a shell. See the `Interactive Shell' and `Shell Mode'
1245sections of the Emacs manual for details, especially for the key
1246bindings active in the `*Python*' buffer.
1247
1248See the docs for variable `py-scroll-buffer' for info on scrolling
1249behavior in the process window.
1250
Barry Warsawa2398801998-04-09 23:28:20 +00001251Note: You can toggle between using the CPython interpreter and the
1252JPython interpreter by hitting \\[py-toggle-shells]. This toggles
1253buffer local variables which control whether all your subshell
1254interactions happen to the `*JPython*' or `*Python*' buffers (the
1255latter is the name used for the CPython buffer).
1256
Barry Warsawa97a3f31997-11-04 18:47:06 +00001257Warning: Don't use an interactive Python if you change sys.ps1 or
1258sys.ps2 from their default values, or if you're running code that
1259prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1260distinguish your output from Python's output, and assumes that `>>> '
1261at the start of a line is a prompt from Python. Similarly, the Emacs
1262Shell mode code assumes that both `>>> ' and `... ' at the start of a
1263line are Python prompts. Bad things can happen if you fool either
1264mode.
1265
1266Warning: If you do any editing *in* the process buffer *while* the
1267buffer is accepting output from Python, do NOT attempt to `undo' the
1268changes. Some of the output (nowhere near the parts you changed!) may
1269be lost if you do. This appears to be an Emacs bug, an unfortunate
1270interaction between undo and process filters; the same problem exists in
1271non-Python process buffers using the default (Emacs-supplied) process
1272filter."
1273 ;; BAW - should undo be disabled in the python process buffer, if
1274 ;; this bug still exists?
1275 (interactive)
1276 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001277 (switch-to-buffer-other-window
Barry Warsawa2398801998-04-09 23:28:20 +00001278 (apply 'make-comint py-which-bufname py-which-shell nil py-which-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001279 (make-local-variable 'comint-prompt-regexp)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001280 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
Barry Warsawa97a3f31997-11-04 18:47:06 +00001281 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1282 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001283 ;; set up keybindings for this subshell
1284 (local-set-key [tab] 'self-insert-command)
1285 (local-set-key "\C-c-" 'py-up-exception)
1286 (local-set-key "\C-c=" 'py-down-exception)
1287 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001288
Barry Warsawa97a3f31997-11-04 18:47:06 +00001289(defun py-clear-queue ()
1290 "Clear the queue of temporary files waiting to execute."
1291 (interactive)
1292 (let ((n (length py-file-queue)))
1293 (mapcar 'delete-file py-file-queue)
1294 (setq py-file-queue nil)
1295 (message "%d pending files de-queued." n)))
1296
Barry Warsaw820273d1998-05-19 15:54:45 +00001297
Barry Warsawa97a3f31997-11-04 18:47:06 +00001298(defun py-execute-region (start end &optional async)
1299 "Execute the the region in a Python interpreter.
1300The region is first copied into a temporary file (in the directory
1301`py-temp-directory'). If there is no Python interpreter shell
1302running, this file is executed synchronously using
1303`shell-command-on-region'. If the program is long running, use an
1304optional \\[universal-argument] to run the command asynchronously in
1305its own buffer.
1306
1307If the Python interpreter shell is running, the region is execfile()'d
1308in that shell. If you try to execute regions too quickly,
1309`python-mode' will queue them up and execute them one at a time when
1310it sees a `>>> ' prompt from Python. Each time this happens, the
1311process buffer is popped into a window (if it's not already in some
1312window) so you can see it, and a comment of the form
1313
1314 \t## working on region in file <name>...
1315
1316is inserted at the end. See also the command `py-clear-queue'."
1317 (interactive "r\nP")
1318 (or (< start end)
1319 (error "Region is empty"))
1320 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001321 (temp (if (memq 'broken-temp-names py-emacs-features)
1322 (prog1
1323 (format "python-%d" py-serial-number)
1324 (setq py-serial-number (1+ py-serial-number)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001325 (make-temp-name "python-")))
1326 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001327 (write-region start end file nil 'nomsg)
1328 (cond
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001329 ;; always run the code in its own asynchronous subprocess
Barry Warsawa97a3f31997-11-04 18:47:06 +00001330 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001331 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001332 (start-process "Python" buf py-python-command "-u" file)
1333 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001334 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001335 ))
1336 ;; if the Python interpreter shell is running, queue it up for
1337 ;; execution there.
1338 (proc
1339 ;; use the existing python shell
1340 (if (not py-file-queue)
1341 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001342 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001343 (push file py-file-queue)
1344 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001345 (t
1346 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001347 (shell-command-on-region start end py-python-command py-output-buffer)
Barry Warsaw512af041998-03-25 23:27:17 +00001348 ;; shell-command-on-region kills the output buffer if it never
1349 ;; existed and there's no output from the command
1350 (if (not (get-buffer py-output-buffer))
1351 (message "No output.")
1352 (setq py-exception-buffer (current-buffer))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001353 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1354 (pop-to-buffer py-output-buffer)
1355 (if err-p
1356 (pop-to-buffer py-exception-buffer)))
Barry Warsaw512af041998-03-25 23:27:17 +00001357 ))
1358 )))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001359
Barry Warsaw820273d1998-05-19 15:54:45 +00001360
1361;; Code execution commands
Barry Warsawa97a3f31997-11-04 18:47:06 +00001362(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001363 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001364If the file local variable `py-master-file' is non-nil, execute the
1365named file instead of the buffer's file.
1366
Barry Warsaw7ae77681994-12-12 20:38:05 +00001367If there is a *Python* process buffer it is used. If a clipping
1368restriction is in effect, only the accessible portion of the buffer is
1369sent. A trailing newline will be supplied if needed.
1370
1371See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001372 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001373 (if py-master-file
1374 (let* ((filename (expand-file-name py-master-file))
1375 (buffer (or (get-file-buffer filename)
1376 (find-file-noselect filename))))
1377 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001378 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001379
Barry Warsaw820273d1998-05-19 15:54:45 +00001380(defun py-execute-import-or-reload (&optional async)
1381 "Import the current buffer's file in a Python interpreter.
1382
1383If the file has already been imported, then do reload instead to get
1384the latest version. If the file's name does not end in \".py\", then
1385do execfile instead. If the current buffer is not visiting a file, do
1386`py-execute-buffer' instead. If the file local variable
1387`py-master-file' is non-nil, import or reload the named file instead
1388of the buffer's file. The file is saved if necessary.
1389
1390See the `\\[py-execute-region]' docs for an account of some subtleties.
1391
1392This is may be preferable to `\\[py-execute-buffer]' because:
1393
1394 - Definitions stay in their module rather than appearing at top
1395 level, where they would clutter the global namespace and not affect
1396 uses of qualified names (MODULE.NAME).
1397
1398 - The Python debugger gets line number information about the functions."
1399 (interactive "P")
1400 ;; Check file local variable py-master-file
1401 (if py-master-file
1402 (let* ((filename (expand-file-name py-master-file))
1403 (buffer (or (get-file-buffer filename)
1404 (find-file-noselect filename))))
1405 (set-buffer buffer)))
1406 (let ((file (buffer-file-name (current-buffer))))
1407 (if file
1408 (progn
1409; (if (buffer-modified-p)
1410; ;; avoid message if unmodified
1411; (save-buffer))
1412 (py-execute-string
1413 (if (string-match "\\.py$" file)
1414 (let ((f (file-name-sans-extension
1415 (file-name-nondirectory file))))
1416 (format "if globals().has_key('%s'):\n reload(%s)\nelse:\n import %s\n"
1417 f f f))
1418 (format "execfile('%s')\n" file))
1419 async))
1420 ;; else
1421 (py-execute-buffer async))))
1422
1423
1424(defun py-execute-def-or-class (&optional async)
1425 "Send the current function or class definition to a Python interpreter.
1426
1427If there is a *Python* process buffer it is used.
1428
1429See the `\\[py-execute-region]' docs for an account of some subtleties."
1430 (interactive "P")
1431 (save-excursion
1432 (py-mark-def-or-class)
1433 ;; mark is before point
1434 (py-execute-region (mark) (point) async)))
1435
1436
1437(defun py-execute-string (string &optional async)
1438 "Send the argument string to a Python interpreter.
1439
1440If there is a *Python* process buffer it is used.
1441
1442See the `\\[py-execute-region]' docs for an account of some subtleties."
1443 (interactive "sExecute Python command: ")
1444 (save-excursion
1445 (set-buffer (get-buffer-create
1446 (generate-new-buffer-name " *Python Command*")))
1447 (insert string)
1448 (py-execute-region (point-min) (point-max) async)))
1449
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001450
1451
1452(defun py-jump-to-exception (file line)
1453 (let ((buffer (cond ((string-equal file "<stdin>")
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001454 (if (consp py-exception-buffer)
1455 (cdr py-exception-buffer)
1456 py-exception-buffer))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001457 ((and (consp py-exception-buffer)
1458 (string-equal file (car py-exception-buffer)))
1459 (cdr py-exception-buffer))
1460 ((py-safe (find-file-noselect file)))
1461 ;; could not figure out what file the exception
1462 ;; is pointing to, so prompt for it
1463 (t (find-file (read-file-name "Exception file: "
1464 nil
1465 file t))))))
1466 (pop-to-buffer buffer)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001467 ;; Force Python mode
Barry Warsaw820273d1998-05-19 15:54:45 +00001468 (if (not (eq major-mode 'python-mode))
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001469 (python-mode))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001470 (goto-line line)
1471 (message "Jumping to exception in file %s on line %d" file line)))
1472
1473(defun py-mouseto-exception (event)
1474 (interactive "e")
1475 (cond
1476 ((fboundp 'event-point)
1477 ;; XEmacs
1478 (let* ((point (event-point event))
1479 (buffer (event-buffer event))
1480 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1481 (info (and e (extent-property e 'py-exc-info))))
1482 (message "Event point: %d, info: %s" point info)
1483 (and info
1484 (py-jump-to-exception (car info) (cdr info)))
1485 ))
1486 ;; Emacs -- Please port this!
1487 ))
1488
1489(defun py-goto-exception ()
1490 "Go to the line indicated by the traceback."
1491 (interactive)
1492 (let (file line)
1493 (save-excursion
1494 (beginning-of-line)
1495 (if (looking-at py-traceback-line-re)
1496 (setq file (match-string 1)
1497 line (string-to-int (match-string 2)))))
1498 (if (not file)
1499 (error "Not on a traceback line."))
1500 (py-jump-to-exception file line)))
1501
1502(defun py-find-next-exception (start buffer searchdir errwhere)
1503 ;; Go to start position in buffer, search in the specified
1504 ;; direction, and jump to the exception found. If at the end of the
1505 ;; exception, print error message
1506 (let (file line)
1507 (save-excursion
1508 (set-buffer buffer)
1509 (goto-char (py-point start))
1510 (if (funcall searchdir py-traceback-line-re nil t)
1511 (setq file (match-string 1)
1512 line (string-to-int (match-string 2)))))
1513 (if (and file line)
1514 (py-jump-to-exception file line)
1515 (error "%s of traceback" errwhere))))
1516
1517(defun py-down-exception (&optional bottom)
1518 "Go to the next line down in the traceback.
1519With optional \\[universal-argument], jump to the bottom (innermost)
1520exception in the exception stack."
1521 (interactive "P")
1522 (let* ((proc (get-process "Python"))
1523 (buffer (if proc "*Python*" py-output-buffer)))
1524 (if bottom
1525 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1526 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1527
1528(defun py-up-exception (&optional top)
1529 "Go to the previous line up in the traceback.
1530With optional \\[universal-argument], jump to the top (outermost)
1531exception in the exception stack."
1532 (interactive "P")
1533 (let* ((proc (get-process "Python"))
1534 (buffer (if proc "*Python*" py-output-buffer)))
1535 (if top
1536 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001537 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001538
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001539
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001540;; Electric deletion
1541(defun py-electric-backspace (arg)
1542 "Deletes preceding character or levels of indentation.
1543Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001544with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001545
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001546If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001547
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001548Otherwise, if point is at the leftmost non-whitespace character of a
1549line that is neither a continuation line nor a non-indenting comment
1550line, or if point is at the end of a blank line, this command reduces
1551the indentation to match that of the line that opened the current
1552block of code. The line that opened the block is displayed in the
1553echo area to help you keep track of where you are. With numeric arg,
1554outdents that many blocks (but not past column zero).
1555
1556Otherwise the preceding character is deleted, converting a tab to
1557spaces if needed so that only a single column position is deleted.
1558Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001559 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001560 (if (or (/= (current-indentation) (current-column))
1561 (bolp)
1562 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001563 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001564 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001565 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001566 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001567 ;; force non-blank so py-goto-block-up doesn't ignore it
1568 (insert-char ?* 1)
1569 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001570 (let ((base-indent 0) ; indentation of base line
1571 (base-text "") ; and text of base line
1572 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001573 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001574 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001575 (condition-case nil ; in case no enclosing block
1576 (progn
1577 (py-goto-block-up 'no-mark)
1578 (setq base-indent (current-indentation)
1579 base-text (py-suck-up-leading-text)
1580 base-found-p t))
1581 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001582 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001583 (delete-char 1) ; toss the dummy character
1584 (delete-horizontal-space)
1585 (indent-to base-indent)
1586 (if base-found-p
1587 (message "Closes block: %s" base-text)))))
1588
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001589
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001590(defun py-electric-delete (arg)
1591 "Deletes preceding or following character or levels of whitespace.
1592
1593The behavior of this function depends on the variable
1594`delete-key-deletes-forward'. If this variable is nil (or does not
1595exist, as in older Emacsen), then this function behaves identical to
1596\\[c-electric-backspace].
1597
1598If `delete-key-deletes-forward' is non-nil and is supported in your
1599Emacs, then deletion occurs in the forward direction, by calling the
1600function in `py-delete-function'."
1601 (interactive "*p")
1602 (if (and (boundp 'delete-key-deletes-forward)
1603 delete-key-deletes-forward)
1604 (funcall py-delete-function arg)
1605 ;; else
1606 (py-electric-backspace arg)))
1607
1608;; required for pending-del and delsel modes
1609(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1610(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1611(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1612(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1613
1614
1615
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001616(defun py-indent-line (&optional arg)
1617 "Fix the indentation of the current line according to Python rules.
1618With \\[universal-argument], ignore outdenting rules for block
1619closing statements (e.g. return, raise, break, continue, pass)
1620
1621This function is normally bound to `indent-line-function' so
1622\\[indent-for-tab-command] will call it."
1623 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001624 (let* ((ci (current-indentation))
1625 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001626 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001627 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001628 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001629 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001630 (if (/= ci need)
1631 (save-excursion
1632 (beginning-of-line)
1633 (delete-horizontal-space)
1634 (indent-to need)))
1635 (if move-to-indentation-p (back-to-indentation))))
1636
1637(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001638 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001639This is just `strives to' because correct indentation can't be computed
1640from scratch for Python code. In general, deletes the whitespace before
1641point, inserts a newline, and takes an educated guess as to how you want
1642the new line indented."
1643 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001644 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001645 (if (< ci (current-column)) ; if point beyond indentation
1646 (newline-and-indent)
1647 ;; else try to act like newline-and-indent "normally" acts
1648 (beginning-of-line)
1649 (insert-char ?\n 1)
1650 (move-to-column ci))))
1651
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001652(defun py-compute-indentation (honor-block-close-p)
1653 ;; implements all the rules for indentation computation. when
1654 ;; honor-block-close-p is non-nil, statements such as return, raise,
1655 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001656 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001657 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001658 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001659 (pps (parse-partial-sexp bod (point)))
1660 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001661 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001662 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001663 ((or (and (nth 3 pps) (nth 3 boipps))
1664 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001665 (save-excursion
1666 (if (not py-align-multiline-strings-p) 0
1667 ;; skip back over blank & non-indenting comment lines
1668 ;; note: will skip a blank or non-indenting comment line
1669 ;; that happens to be a continuation line too
1670 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1671 (back-to-indentation)
1672 (current-column))))
1673 ;; are we on a continuation line?
1674 ((py-continuation-line-p)
1675 (let ((startpos (point))
1676 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001677 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001678 (if open-bracket-pos
1679 (progn
1680 ;; align with first item in list; else a normal
1681 ;; indent beyond the line with the open bracket
1682 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1683 ;; is the first list item on the same line?
1684 (skip-chars-forward " \t")
1685 (if (null (memq (following-char) '(?\n ?# ?\\)))
1686 ; yes, so line up with it
1687 (current-column)
1688 ;; first list item on another line, or doesn't exist yet
1689 (forward-line 1)
1690 (while (and (< (point) startpos)
1691 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1692 (forward-line 1))
Barry Warsaw92166d91998-04-01 21:59:41 +00001693 (if (and (< (point) startpos)
1694 (/= startpos
1695 (save-excursion
1696 (goto-char (1+ open-bracket-pos))
Barry Warsaw77d1fce1998-04-16 20:04:59 +00001697 (forward-comment (point-max))
Barry Warsaw92166d91998-04-01 21:59:41 +00001698 (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001699 ;; again mimic the first list item
1700 (current-indentation)
1701 ;; else they're about to enter the first item
1702 (goto-char open-bracket-pos)
1703 (+ (current-indentation) py-indent-offset))))
1704
1705 ;; else on backslash continuation line
1706 (forward-line -1)
1707 (if (py-continuation-line-p) ; on at least 3rd line in block
1708 (current-indentation) ; so just continue the pattern
1709 ;; else started on 2nd line in block, so indent more.
1710 ;; if base line is an assignment with a start on a RHS,
1711 ;; indent to 2 beyond the leftmost "="; else skip first
1712 ;; chunk of non-whitespace characters on base line, + 1 more
1713 ;; column
1714 (end-of-line)
1715 (setq endpos (point) searching t)
1716 (back-to-indentation)
1717 (setq startpos (point))
1718 ;; look at all "=" from left to right, stopping at first
1719 ;; one not nested in a list or string
1720 (while searching
1721 (skip-chars-forward "^=" endpos)
1722 (if (= (point) endpos)
1723 (setq searching nil)
1724 (forward-char 1)
1725 (setq state (parse-partial-sexp startpos (point)))
1726 (if (and (zerop (car state)) ; not in a bracket
1727 (null (nth 3 state))) ; & not in a string
1728 (progn
1729 (setq searching nil) ; done searching in any case
1730 (setq found
1731 (not (or
1732 (eq (following-char) ?=)
1733 (memq (char-after (- (point) 2))
1734 '(?< ?> ?!)))))))))
1735 (if (or (not found) ; not an assignment
1736 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1737 (progn
1738 (goto-char startpos)
1739 (skip-chars-forward "^ \t\n")))
1740 (1+ (current-column))))))
1741
1742 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001743 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001744
Barry Warsawa7891711996-08-01 15:53:09 +00001745 ;; Dfn: "Indenting comment line". A line containing only a
1746 ;; comment, but which is treated like a statement for
1747 ;; indentation calculation purposes. Such lines are only
1748 ;; treated specially by the mode; they are not treated
1749 ;; specially by the Python interpreter.
1750
1751 ;; The rules for indenting comment lines are a line where:
1752 ;; - the first non-whitespace character is `#', and
1753 ;; - the character following the `#' is whitespace, and
1754 ;; - the line is outdented with respect to (i.e. to the left
1755 ;; of) the indentation of the preceding non-blank line.
1756
1757 ;; The first non-blank line following an indenting comment
1758 ;; line is given the same amount of indentation as the
1759 ;; indenting comment line.
1760
1761 ;; All other comment-only lines are ignored for indentation
1762 ;; purposes.
1763
1764 ;; Are we looking at a comment-only line which is *not* an
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001765 ;; indenting comment line? If so, we assume that it's been
Barry Warsawa7891711996-08-01 15:53:09 +00001766 ;; placed at the desired indentation, so leave it alone.
1767 ;; Indenting comment lines are aligned as statements down
1768 ;; below.
1769 ((and (looking-at "[ \t]*#[^ \t\n]")
1770 ;; NOTE: this test will not be performed in older Emacsen
1771 (fboundp 'forward-comment)
1772 (<= (current-indentation)
1773 (save-excursion
1774 (forward-comment (- (point-max)))
1775 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001776 (current-indentation))
1777
1778 ;; else indentation based on that of the statement that
1779 ;; precedes us; use the first line of that statement to
1780 ;; establish the base, in case the user forced a non-std
1781 ;; indentation for the continuation lines (if any)
1782 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001783 ;; skip back over blank & non-indenting comment lines note:
1784 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001785 ;; happens to be a continuation line too. use fast Emacs 19
1786 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001787 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001788 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001789 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001790 (let (done)
1791 (while (not done)
1792 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1793 nil 'move)
1794 (setq done (or (eq py-honor-comment-indentation t)
1795 (bobp)
1796 (/= (following-char) ?#)
1797 (not (zerop (current-column)))))
1798 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001799 ;; if we landed inside a string, go to the beginning of that
1800 ;; string. this handles triple quoted, multi-line spanning
1801 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001802 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001803 (skip (and delim (make-string 1 delim))))
1804 (when skip
1805 (save-excursion
1806 (py-safe (search-backward skip))
1807 (if (and (eq (char-before) delim)
1808 (eq (char-before (1- (point))) delim))
1809 (setq skip (make-string 3 delim))))
1810 ;; we're looking at a triple-quoted string
1811 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001812 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001813 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001814 (+ (current-indentation)
1815 (if (py-statement-opens-block-p)
1816 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001817 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001818 (- py-indent-offset)
1819 0)))
1820 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001821
1822(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001823 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001824By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001825`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001826Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001827`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001828their own buffer-local copy), both those currently existing and those
1829created later in the Emacs session.
1830
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001831Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001832There's no excuse for such foolishness, but sometimes you have to deal
1833with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001834`py-indent-offset' to what it thinks it was when they created the
1835mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001836
1837Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001838looking for a line that opens a block of code. `py-indent-offset' is
1839set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001840statement following it. If the search doesn't succeed going forward,
1841it's tried again going backward."
1842 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001843 (let (new-value
1844 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001845 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001846 (found nil)
1847 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001848 (py-goto-initial-line)
1849 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001850 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1851 (not (py-in-literal restart)))
1852 (setq restart (point))
1853 (py-goto-initial-line)
1854 (if (py-statement-opens-block-p)
1855 (setq found t)
1856 (goto-char restart))))
1857 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001858 (goto-char start)
1859 (py-goto-initial-line)
1860 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001861 (setq found (and
1862 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1863 (or (py-goto-initial-line) t) ; always true -- side effect
1864 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001865 (setq colon-indent (current-indentation)
1866 found (and found (zerop (py-next-statement 1)))
1867 new-value (- (current-indentation) colon-indent))
1868 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001869 (if (not found)
1870 (error "Sorry, couldn't guess a value for py-indent-offset")
1871 (funcall (if global 'kill-local-variable 'make-local-variable)
1872 'py-indent-offset)
1873 (setq py-indent-offset new-value)
1874 (message "%s value of py-indent-offset set to %d"
1875 (if global "Global" "Local")
1876 py-indent-offset))
1877 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001878
1879(defun py-shift-region (start end count)
1880 (save-excursion
1881 (goto-char end) (beginning-of-line) (setq end (point))
1882 (goto-char start) (beginning-of-line) (setq start (point))
1883 (indent-rigidly start end count)))
1884
1885(defun py-shift-region-left (start end &optional count)
1886 "Shift region of Python code to the left.
1887The lines from the line containing the start of the current region up
1888to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001889shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001890
1891If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001892many columns. With no active region, outdent only the current line.
1893You cannot outdent the region if any line is already at column zero."
1894 (interactive
1895 (let ((p (point))
1896 (m (mark))
1897 (arg current-prefix-arg))
1898 (if m
1899 (list (min p m) (max p m) arg)
1900 (list p (save-excursion (forward-line 1) (point)) arg))))
1901 ;; if any line is at column zero, don't shift the region
1902 (save-excursion
1903 (goto-char start)
1904 (while (< (point) end)
1905 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001906 (if (and (zerop (current-column))
1907 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001908 (error "Region is at left edge."))
1909 (forward-line 1)))
1910 (py-shift-region start end (- (prefix-numeric-value
1911 (or count py-indent-offset))))
1912 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001913
1914(defun py-shift-region-right (start end &optional count)
1915 "Shift region of Python code to the right.
1916The lines from the line containing the start of the current region up
1917to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001918shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001919
1920If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001921many columns. With no active region, indent only the current line."
1922 (interactive
1923 (let ((p (point))
1924 (m (mark))
1925 (arg current-prefix-arg))
1926 (if m
1927 (list (min p m) (max p m) arg)
1928 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001929 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001930 (or count py-indent-offset)))
1931 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001932
1933(defun py-indent-region (start end &optional indent-offset)
1934 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001935
Barry Warsaw7ae77681994-12-12 20:38:05 +00001936The lines from the line containing the start of the current region up
1937to (but not including) the line containing the end of the region are
1938reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001939character in the first column, the first line is left alone and the
1940rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001941region is reindented with respect to the (closest code or indenting
1942comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001943
1944This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001945control structures are introduced or removed, or to reformat code
1946using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001947
1948If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001949the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001950used.
1951
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001952Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001953is called! This function does not compute proper indentation from
1954scratch (that's impossible in Python), it merely adjusts the existing
1955indentation to be correct in context.
1956
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001957Warning: This function really has no idea what to do with
1958non-indenting comment lines, and shifts them as if they were indenting
1959comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001960
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001961Special cases: whitespace is deleted from blank lines; continuation
1962lines are shifted by the same amount their initial line was shifted,
1963in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001964initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001965 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001966 (save-excursion
1967 (goto-char end) (beginning-of-line) (setq end (point-marker))
1968 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001969 (let ((py-indent-offset (prefix-numeric-value
1970 (or indent-offset py-indent-offset)))
1971 (indents '(-1)) ; stack of active indent levels
1972 (target-column 0) ; column to which to indent
1973 (base-shifted-by 0) ; amount last base line was shifted
1974 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001975 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001976 0))
1977 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001978 (while (< (point) end)
1979 (setq ci (current-indentation))
1980 ;; figure out appropriate target column
1981 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001982 ((or (eq (following-char) ?#) ; comment in column 1
1983 (looking-at "[ \t]*$")) ; entirely blank
1984 (setq target-column 0))
1985 ((py-continuation-line-p) ; shift relative to base line
1986 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001987 (t ; new base line
1988 (if (> ci (car indents)) ; going deeper; push it
1989 (setq indents (cons ci indents))
1990 ;; else we should have seen this indent before
1991 (setq indents (memq ci indents)) ; pop deeper indents
1992 (if (null indents)
1993 (error "Bad indentation in region, at line %d"
1994 (save-restriction
1995 (widen)
1996 (1+ (count-lines 1 (point)))))))
1997 (setq target-column (+ indent-base
1998 (* py-indent-offset
1999 (- (length indents) 2))))
2000 (setq base-shifted-by (- target-column ci))))
2001 ;; shift as needed
2002 (if (/= ci target-column)
2003 (progn
2004 (delete-horizontal-space)
2005 (indent-to target-column)))
2006 (forward-line 1))))
2007 (set-marker end nil))
2008
Barry Warsawa7891711996-08-01 15:53:09 +00002009(defun py-comment-region (beg end &optional arg)
2010 "Like `comment-region' but uses double hash (`#') comment starter."
2011 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00002012 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00002013 (comment-region beg end arg)))
2014
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002015
2016;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00002017(defun py-previous-statement (count)
2018 "Go to the start of previous Python statement.
2019If the statement at point is the i'th Python statement, goes to the
2020start of statement i-COUNT. If there is no such statement, goes to the
2021first statement. Returns count of statements left to move.
2022`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002023 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002024 (if (< count 0) (py-next-statement (- count))
2025 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002026 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002027 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002028 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002029 (> count 0)
2030 (zerop (forward-line -1))
2031 (py-goto-statement-at-or-above))
2032 (setq count (1- count)))
2033 (if (> count 0) (goto-char start)))
2034 count))
2035
2036(defun py-next-statement (count)
2037 "Go to the start of next Python statement.
2038If the statement at point is the i'th Python statement, goes to the
2039start of statement i+COUNT. If there is no such statement, goes to the
2040last statement. Returns count of statements left to move. `Statements'
2041do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002042 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002043 (if (< count 0) (py-previous-statement (- count))
2044 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002045 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002046 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002047 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002048 (> count 0)
2049 (py-goto-statement-below))
2050 (setq count (1- count)))
2051 (if (> count 0) (goto-char start)))
2052 count))
2053
2054(defun py-goto-block-up (&optional nomark)
2055 "Move up to start of current block.
2056Go to the statement that starts the smallest enclosing block; roughly
2057speaking, this will be the closest preceding statement that ends with a
2058colon and is indented less than the statement you started on. If
2059successful, also sets the mark to the starting point.
2060
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002061`\\[py-mark-block]' can be used afterward to mark the whole code
2062block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002063
2064If called from a program, the mark will not be set if optional argument
2065NOMARK is not nil."
2066 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002067 (let ((start (point))
2068 (found nil)
2069 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002070 (py-goto-initial-line)
2071 ;; if on blank or non-indenting comment line, use the preceding stmt
2072 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2073 (progn
2074 (py-goto-statement-at-or-above)
2075 (setq found (py-statement-opens-block-p))))
2076 ;; search back for colon line indented less
2077 (setq initial-indent (current-indentation))
2078 (if (zerop initial-indent)
2079 ;; force fast exit
2080 (goto-char (point-min)))
2081 (while (not (or found (bobp)))
2082 (setq found
2083 (and
2084 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2085 (or (py-goto-initial-line) t) ; always true -- side effect
2086 (< (current-indentation) initial-indent)
2087 (py-statement-opens-block-p))))
2088 (if found
2089 (progn
2090 (or nomark (push-mark start))
2091 (back-to-indentation))
2092 (goto-char start)
2093 (error "Enclosing block not found"))))
2094
Barry Warsawab0e86c1998-05-19 15:31:46 +00002095(defun py-beginning-of-def-or-class (&optional class count)
2096 "Move point to start of `def' or `class'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002097
2098Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsawab0e86c1998-05-19 15:31:46 +00002099arg, looks for a `class' instead. The docs below assume the `def'
2100case; just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002101
Barry Warsawab0e86c1998-05-19 15:31:46 +00002102When second optional argument is given programmatically, move to the
2103COUNTth start of `def'.
2104
2105If point is in a `def' statement already, and after the `d', simply
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002106moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002107
Barry Warsawab0e86c1998-05-19 15:31:46 +00002108Otherwise (i.e. when point is not in a `def' statement, or at or
2109before the `d' of a `def' statement), searches for the closest
2110preceding `def' statement, and leaves point at its start. If no such
2111statement can be found, leaves point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002112
Barry Warsawab0e86c1998-05-19 15:31:46 +00002113Returns t iff a `def' statement is found by these rules.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002114
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002115Note that doing this command repeatedly will take you closer to the
2116start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002117
Barry Warsawab0e86c1998-05-19 15:31:46 +00002118If you want to mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002119 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002120 (if (not count)
2121 (setq count 1))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002122 (let ((at-or-before-p (<= (current-column) (current-indentation)))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002123 (start-of-line (goto-char (py-point 'bol)))
2124 (start-of-stmt (goto-char (py-point 'bos)))
2125 (start-re (if class
2126 "^[ \t]*class\\>"
2127 "^[ \t]*def\\>"))
2128 )
2129 ;; searching backward
2130 (if (and (< 0 count)
2131 (or (/= start-of-stmt start-of-line)
2132 (not at-or-before-p)))
2133 (end-of-line))
2134 ;; search forward
2135 (if (and (> 0 count)
2136 (zerop (current-column))
2137 (looking-at start-re))
2138 (end-of-line))
2139 (re-search-backward start-re nil 'move count)
2140 (goto-char (match-beginning 0))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002141
Barry Warsawab0e86c1998-05-19 15:31:46 +00002142;; Backwards compatibility
2143(defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002144
Barry Warsawab0e86c1998-05-19 15:31:46 +00002145(defun py-end-of-def-or-class (&optional class count)
2146 "Move point beyond end of `def' or `class' body.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002147
Barry Warsawab0e86c1998-05-19 15:31:46 +00002148By default, looks for an appropriate `def'. If you supply a prefix
2149arg, looks for a `class' instead. The docs below assume the `def'
2150case; just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002151
Barry Warsawab0e86c1998-05-19 15:31:46 +00002152When second optional argument is given programmatically, move to the
2153COUNTth end of `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002154
Barry Warsawab0e86c1998-05-19 15:31:46 +00002155If point is in a `def' statement already, this is the `def' we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002156
Barry Warsawab0e86c1998-05-19 15:31:46 +00002157Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2158contains the statement you started on, that's the `def' we use.
2159
2160Otherwise, we search forward for the closest following `def', and use that.
2161
2162If a `def' can be found by these rules, point is moved to the start of
2163the line immediately following the `def' block, and the position of the
2164start of the `def' is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002165
2166Else point is moved to the end of the buffer, and nil is returned.
2167
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002168Note that doing this command repeatedly will take you closer to the
2169end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002170
Barry Warsawab0e86c1998-05-19 15:31:46 +00002171If you want to mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002172 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002173 (if (and count (/= count 1))
2174 (py-beginning-of-def-or-class (- 1 count)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002175 (let ((start (progn (py-goto-initial-line) (point)))
2176 (which (if class "class" "def"))
2177 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002178 ;; move point to start of appropriate def/class
2179 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2180 (setq state 'at-beginning)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002181 ;; else see if py-beginning-of-def-or-class hits container
2182 (if (and (py-beginning-of-def-or-class class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002183 (progn (py-goto-beyond-block)
2184 (> (point) start)))
2185 (setq state 'at-end)
2186 ;; else search forward
2187 (goto-char start)
2188 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2189 (progn (setq state 'at-beginning)
2190 (beginning-of-line)))))
2191 (cond
2192 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2193 ((eq state 'at-end) t)
2194 ((eq state 'not-found) nil)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002195 (t (error "internal error in py-end-of-def-or-class")))))
2196
2197;; Backwards compabitility
Barry Warsaw820273d1998-05-19 15:54:45 +00002198(defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002199
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002200
2201;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002202(defun py-mark-block (&optional extend just-move)
2203 "Mark following block of lines. With prefix arg, mark structure.
2204Easier to use than explain. It sets the region to an `interesting'
2205block of succeeding lines. If point is on a blank line, it goes down to
2206the next non-blank line. That will be the start of the region. The end
2207of the region depends on the kind of line at the start:
2208
2209 - If a comment, the region will include all succeeding comment lines up
2210 to (but not including) the next non-comment line (if any).
2211
2212 - Else if a prefix arg is given, and the line begins one of these
2213 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002214
2215 if elif else try except finally for while def class
2216
Barry Warsaw7ae77681994-12-12 20:38:05 +00002217 the region will be set to the body of the structure, including
2218 following blocks that `belong' to it, but excluding trailing blank
2219 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002220 and all (if any) of the following `except' and `finally' blocks
2221 that belong to the `try' structure will be in the region. Ditto
2222 for if/elif/else, for/else and while/else structures, and (a bit
2223 degenerate, since they're always one-block structures) def and
2224 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002225
2226 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002227 block (see list above), and the block is not a `one-liner' (i.e.,
2228 the statement ends with a colon, not with code), the region will
2229 include all succeeding lines up to (but not including) the next
2230 code statement (if any) that's indented no more than the starting
2231 line, except that trailing blank and comment lines are excluded.
2232 E.g., if the starting line begins a multi-statement `def'
2233 structure, the region will be set to the full function definition,
2234 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002235
2236 - Else the region will include all succeeding lines up to (but not
2237 including) the next blank line, or code or indenting-comment line
2238 indented strictly less than the starting line. Trailing indenting
2239 comment lines are included in this case, but not trailing blank
2240 lines.
2241
2242A msg identifying the location of the mark is displayed in the echo
2243area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2244
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002245If called from a program, optional argument EXTEND plays the role of
2246the prefix arg, and if optional argument JUST-MOVE is not nil, just
2247moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002248 (interactive "P") ; raw prefix arg
2249 (py-goto-initial-line)
2250 ;; skip over blank lines
2251 (while (and
2252 (looking-at "[ \t]*$") ; while blank line
2253 (not (eobp))) ; & somewhere to go
2254 (forward-line 1))
2255 (if (eobp)
2256 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002257 (let ((initial-pos (point))
2258 (initial-indent (current-indentation))
2259 last-pos ; position of last stmt in region
2260 (followers
2261 '((if elif else) (elif elif else) (else)
2262 (try except finally) (except except) (finally)
2263 (for else) (while else)
2264 (def) (class) ) )
2265 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002266
2267 (cond
2268 ;; if comment line, suck up the following comment lines
2269 ((looking-at "[ \t]*#")
2270 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2271 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2272 (setq last-pos (point)))
2273
2274 ;; else if line is a block line and EXTEND given, suck up
2275 ;; the whole structure
2276 ((and extend
2277 (setq first-symbol (py-suck-up-first-keyword) )
2278 (assq first-symbol followers))
2279 (while (and
2280 (or (py-goto-beyond-block) t) ; side effect
2281 (forward-line -1) ; side effect
2282 (setq last-pos (point)) ; side effect
2283 (py-goto-statement-below)
2284 (= (current-indentation) initial-indent)
2285 (setq next-symbol (py-suck-up-first-keyword))
2286 (memq next-symbol (cdr (assq first-symbol followers))))
2287 (setq first-symbol next-symbol)))
2288
2289 ;; else if line *opens* a block, search for next stmt indented <=
2290 ((py-statement-opens-block-p)
2291 (while (and
2292 (setq last-pos (point)) ; always true -- side effect
2293 (py-goto-statement-below)
2294 (> (current-indentation) initial-indent))
2295 nil))
2296
2297 ;; else plain code line; stop at next blank line, or stmt or
2298 ;; indenting comment line indented <
2299 (t
2300 (while (and
2301 (setq last-pos (point)) ; always true -- side effect
2302 (or (py-goto-beyond-final-line) t)
2303 (not (looking-at "[ \t]*$")) ; stop at blank line
2304 (or
2305 (>= (current-indentation) initial-indent)
2306 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2307 nil)))
2308
2309 ;; skip to end of last stmt
2310 (goto-char last-pos)
2311 (py-goto-beyond-final-line)
2312
2313 ;; set mark & display
2314 (if just-move
2315 () ; just return
2316 (push-mark (point) 'no-msg)
2317 (forward-line -1)
2318 (message "Mark set after: %s" (py-suck-up-leading-text))
2319 (goto-char initial-pos))))
2320
Barry Warsaw2518c671997-11-05 00:51:08 +00002321(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002322 "Set region to body of def (or class, with prefix arg) enclosing point.
2323Pushes the current mark, then point, on the mark ring (all language
2324modes do this, but although it's handy it's never documented ...).
2325
2326In most Emacs language modes, this function bears at least a
Barry Warsawab0e86c1998-05-19 15:31:46 +00002327hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2328`\\[py-beginning-of-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002329
2330And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002331Turned out that was more confusing than useful: the `goto start' and
2332`goto end' commands are usually used to search through a file, and
2333people expect them to act a lot like `search backward' and `search
2334forward' string-search commands. But because Python `def' and `class'
2335can nest to arbitrary levels, finding the smallest def containing
2336point cannot be done via a simple backward search: the def containing
2337point may not be the closest preceding def, or even the closest
2338preceding def that's indented less. The fancy algorithm required is
2339appropriate for the usual uses of this `mark' command, but not for the
2340`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002341
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002342So the def marked by this command may not be the one either of the
2343`goto' commands find: If point is on a blank or non-indenting comment
2344line, moves back to start of the closest preceding code statement or
2345indenting comment line. If this is a `def' statement, that's the def
2346we use. Else searches for the smallest enclosing `def' block and uses
2347that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002348
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002349When an enclosing def is found: The mark is left immediately beyond
2350the last line of the def block. Point is left at the start of the
2351def, except that: if the def is preceded by a number of comment lines
2352followed by (at most) one optional blank line, point is left at the
2353start of the comments; else if the def is preceded by a blank line,
2354point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002355
2356The intent is to mark the containing def/class and its associated
2357documentation, to make moving and duplicating functions and classes
2358pleasant."
2359 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002360 (let ((start (point))
2361 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002362 (push-mark start)
2363 (if (not (py-go-up-tree-to-keyword which))
2364 (progn (goto-char start)
2365 (error "Enclosing %s not found" which))
2366 ;; else enclosing def/class found
2367 (setq start (point))
2368 (py-goto-beyond-block)
2369 (push-mark (point))
2370 (goto-char start)
2371 (if (zerop (forward-line -1)) ; if there is a preceding line
2372 (progn
2373 (if (looking-at "[ \t]*$") ; it's blank
2374 (setq start (point)) ; so reset start point
2375 (goto-char start)) ; else try again
2376 (if (zerop (forward-line -1))
2377 (if (looking-at "[ \t]*#") ; a comment
2378 ;; look back for non-comment line
2379 ;; tricky: note that the regexp matches a blank
2380 ;; line, cuz \n is in the 2nd character class
2381 (and
2382 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2383 (forward-line 1))
2384 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002385 (goto-char start)))))))
2386 (exchange-point-and-mark)
2387 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002388
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002389;; ripped from cc-mode
2390(defun py-forward-into-nomenclature (&optional arg)
2391 "Move forward to end of a nomenclature section or word.
2392With arg, to it arg times.
2393
2394A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2395 (interactive "p")
2396 (let ((case-fold-search nil))
2397 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002398 (re-search-forward
2399 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2400 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002401 (while (and (< arg 0)
2402 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002403 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002404 (point-min) 0))
2405 (forward-char 1)
2406 (setq arg (1+ arg)))))
2407 (py-keep-region-active))
2408
2409(defun py-backward-into-nomenclature (&optional arg)
2410 "Move backward to beginning of a nomenclature section or word.
2411With optional ARG, move that many times. If ARG is negative, move
2412forward.
2413
2414A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2415 (interactive "p")
2416 (py-forward-into-nomenclature (- arg))
2417 (py-keep-region-active))
2418
2419
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002420
2421;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002422
2423;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002424;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2425;; out of the right places, along with the keys they're on & current
2426;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002427(defun py-dump-help-string (str)
2428 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002429 (let ((locals (buffer-local-variables))
2430 funckind funcname func funcdoc
2431 (start 0) mstart end
2432 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002433 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2434 (setq mstart (match-beginning 0) end (match-end 0)
2435 funckind (substring str (match-beginning 1) (match-end 1))
2436 funcname (substring str (match-beginning 2) (match-end 2))
2437 func (intern funcname))
2438 (princ (substitute-command-keys (substring str start mstart)))
2439 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002440 ((equal funckind "c") ; command
2441 (setq funcdoc (documentation func)
2442 keys (concat
2443 "Key(s): "
2444 (mapconcat 'key-description
2445 (where-is-internal func py-mode-map)
2446 ", "))))
2447 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002448 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002449 keys (if (assq func locals)
2450 (concat
2451 "Local/Global values: "
2452 (prin1-to-string (symbol-value func))
2453 " / "
2454 (prin1-to-string (default-value func)))
2455 (concat
2456 "Value: "
2457 (prin1-to-string (symbol-value func))))))
2458 (t ; unexpected
2459 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002460 (princ (format "\n-> %s:\t%s\t%s\n\n"
2461 (if (equal funckind "c") "Command" "Variable")
2462 funcname keys))
2463 (princ funcdoc)
2464 (terpri)
2465 (setq start end))
2466 (princ (substitute-command-keys (substring str start))))
2467 (print-help-return-message)))
2468
2469(defun py-describe-mode ()
2470 "Dump long form of Python-mode docs."
2471 (interactive)
2472 (py-dump-help-string "Major mode for editing Python files.
2473Knows about Python indentation, tokens, comments and continuation lines.
2474Paragraphs are separated by blank lines only.
2475
2476Major sections below begin with the string `@'; specific function and
2477variable docs begin with `->'.
2478
2479@EXECUTING PYTHON CODE
2480
Barry Warsaw820273d1998-05-19 15:54:45 +00002481\\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002482\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2483\\[py-execute-region]\tsends the current region
Barry Warsaw820273d1998-05-19 15:54:45 +00002484\\[py-execute-def-or-class]\tsends the current function or class definition
2485\\[py-execute-string]\tsends an arbitrary string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002486\\[py-shell]\tstarts a Python interpreter window; this will be used by
Barry Warsaw820273d1998-05-19 15:54:45 +00002487\tsubsequent Python execution commands
2488%c:py-execute-import-or-reload
Barry Warsaw7ae77681994-12-12 20:38:05 +00002489%c:py-execute-buffer
2490%c:py-execute-region
Barry Warsaw820273d1998-05-19 15:54:45 +00002491%c:py-execute-def-or-class
2492%c:py-execute-string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002493%c:py-shell
2494
2495@VARIABLES
2496
2497py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002498py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002499
2500py-python-command\tshell command to invoke Python interpreter
2501py-scroll-process-buffer\talways scroll Python process buffer
2502py-temp-directory\tdirectory used for temp files (if needed)
2503
2504py-beep-if-tab-change\tring the bell if tab-width is changed
2505%v:py-indent-offset
2506%v:py-block-comment-prefix
2507%v:py-python-command
2508%v:py-scroll-process-buffer
2509%v:py-temp-directory
2510%v:py-beep-if-tab-change
2511
2512@KINDS OF LINES
2513
2514Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002515preceding line ends with a backslash that's not part of a comment, or
2516the paren/bracket/brace nesting level at the start of the line is
2517non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002518
2519An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002520possibly blanks or tabs), a `comment line' (leftmost non-blank
2521character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002522
2523Comment Lines
2524
2525Although all comment lines are treated alike by Python, Python mode
2526recognizes two kinds that act differently with respect to indentation.
2527
2528An `indenting comment line' is a comment line with a blank, tab or
2529nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002530treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002531indenting comment line will be indented like the comment line. All
2532other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002533following the initial `#') are `non-indenting comment lines', and
2534their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002535
2536Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002537whenever possible. Non-indenting comment lines are useful in cases
2538like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002539
2540\ta = b # a very wordy single-line comment that ends up being
2541\t #... continued onto another line
2542
2543\tif a == b:
2544##\t\tprint 'panic!' # old code we've `commented out'
2545\t\treturn a
2546
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002547Since the `#...' and `##' comment lines have a non-whitespace
2548character following the initial `#', Python mode ignores them when
2549computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002550
2551Continuation Lines and Statements
2552
2553The Python-mode commands generally work on statements instead of on
2554individual lines, where a `statement' is a comment or blank line, or a
2555code line and all of its following continuation lines (if any)
2556considered as a single logical unit. The commands in this mode
2557generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002558statement containing point, even if point happens to be in the middle
2559of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002560
2561
2562@INDENTATION
2563
2564Primarily for entering new code:
2565\t\\[indent-for-tab-command]\t indent line appropriately
2566\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002567\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002568
2569Primarily for reindenting existing code:
2570\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2571\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2572
2573\t\\[py-indent-region]\t reindent region to match its context
2574\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2575\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2576
2577Unlike most programming languages, Python uses indentation, and only
2578indentation, to specify block structure. Hence the indentation supplied
2579automatically by Python-mode is just an educated guess: only you know
2580the block structure you intend, so only you can supply correct
2581indentation.
2582
2583The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2584the indentation of preceding statements. E.g., assuming
2585py-indent-offset is 4, after you enter
2586\tif a > 0: \\[py-newline-and-indent]
2587the cursor will be moved to the position of the `_' (_ is not a
2588character in the file, it's just used here to indicate the location of
2589the cursor):
2590\tif a > 0:
2591\t _
2592If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2593to
2594\tif a > 0:
2595\t c = d
2596\t _
2597Python-mode cannot know whether that's what you intended, or whether
2598\tif a > 0:
2599\t c = d
2600\t_
2601was your intent. In general, Python-mode either reproduces the
2602indentation of the (closest code or indenting-comment) preceding
2603statement, or adds an extra py-indent-offset blanks if the preceding
2604statement has `:' as its last significant (non-whitespace and non-
2605comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002606\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002607
2608Continuation lines are given extra indentation. If you don't like the
2609suggested indentation, change it to something you do like, and Python-
2610mode will strive to indent later lines of the statement in the same way.
2611
2612If a line is a continuation line by virtue of being in an unclosed
2613paren/bracket/brace structure (`list', for short), the suggested
2614indentation depends on whether the current line contains the first item
2615in the list. If it does, it's indented py-indent-offset columns beyond
2616the indentation of the line containing the open bracket. If you don't
2617like that, change it by hand. The remaining items in the list will mimic
2618whatever indentation you give to the first item.
2619
2620If a line is a continuation line because the line preceding it ends with
2621a backslash, the third and following lines of the statement inherit their
2622indentation from the line preceding them. The indentation of the second
2623line in the statement depends on the form of the first (base) line: if
2624the base line is an assignment statement with anything more interesting
2625than the backslash following the leftmost assigning `=', the second line
2626is indented two columns beyond that `='. Else it's indented to two
2627columns beyond the leftmost solid chunk of non-whitespace characters on
2628the base line.
2629
2630Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2631repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2632structure you intend.
2633%c:indent-for-tab-command
2634%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002635%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002636
2637
2638The next function may be handy when editing code you didn't write:
2639%c:py-guess-indent-offset
2640
2641
2642The remaining `indent' functions apply to a region of Python code. They
2643assume the block structure (equals indentation, in Python) of the region
2644is correct, and alter the indentation in various ways while preserving
2645the block structure:
2646%c:py-indent-region
2647%c:py-shift-region-left
2648%c:py-shift-region-right
2649
2650@MARKING & MANIPULATING REGIONS OF CODE
2651
2652\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002653\\[py-mark-def-or-class]\t mark smallest enclosing def
2654\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002655\\[comment-region]\t comment out region of code
2656\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002657%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002658%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002659%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002660
2661@MOVING POINT
2662
2663\\[py-previous-statement]\t move to statement preceding point
2664\\[py-next-statement]\t move to statement following point
2665\\[py-goto-block-up]\t move up to start of current block
Barry Warsawab0e86c1998-05-19 15:31:46 +00002666\\[py-beginning-of-def-or-class]\t move to start of def
2667\\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
2668\\[py-end-of-def-or-class]\t move to end of def
2669\\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002670
2671The first two move to one statement beyond the statement that contains
2672point. A numeric prefix argument tells them to move that many
2673statements instead. Blank lines, comment lines, and continuation lines
2674do not count as `statements' for these commands. So, e.g., you can go
2675to the first code statement in a file by entering
2676\t\\[beginning-of-buffer]\t to move to the top of the file
2677\t\\[py-next-statement]\t to skip over initial comments and blank lines
2678Or do `\\[py-previous-statement]' with a huge prefix argument.
2679%c:py-previous-statement
2680%c:py-next-statement
2681%c:py-goto-block-up
Barry Warsawab0e86c1998-05-19 15:31:46 +00002682%c:py-beginning-of-def-or-class
2683%c:py-end-of-def-or-class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002684
2685@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2686
2687`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2688
2689`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2690overall class and def structure of a module.
2691
2692`\\[back-to-indentation]' moves point to a line's first non-blank character.
2693
2694`\\[indent-relative]' is handy for creating odd indentation.
2695
2696@OTHER EMACS HINTS
2697
2698If you don't like the default value of a variable, change its value to
2699whatever you do like by putting a `setq' line in your .emacs file.
2700E.g., to set the indentation increment to 4, put this line in your
2701.emacs:
2702\t(setq py-indent-offset 4)
2703To see the value of a variable, do `\\[describe-variable]' and enter the variable
2704name at the prompt.
2705
2706When entering a key sequence like `C-c C-n', it is not necessary to
2707release the CONTROL key after doing the `C-c' part -- it suffices to
2708press the CONTROL key, press and release `c' (while still holding down
2709CONTROL), press and release `n' (while still holding down CONTROL), &
2710then release CONTROL.
2711
2712Entering Python mode calls with no arguments the value of the variable
2713`python-mode-hook', if that value exists and is not nil; for backward
2714compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2715the Elisp manual for details.
2716
2717Obscure: When python-mode is first loaded, it looks for all bindings
2718to newline-and-indent in the global keymap, and shadows them with
2719local bindings to py-newline-and-indent."))
2720
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002721
2722;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002723(defvar py-parse-state-re
2724 (concat
2725 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2726 "\\|"
2727 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002728
Barry Warsaw7ae77681994-12-12 20:38:05 +00002729;; returns the parse state at point (see parse-partial-sexp docs)
2730(defun py-parse-state ()
2731 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002732 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002733 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002734 (while (not done)
2735 ;; back up to the first preceding line (if any; else start of
2736 ;; buffer) that begins with a popular Python keyword, or a
2737 ;; non- whitespace and non-comment character. These are good
2738 ;; places to start parsing to see whether where we started is
2739 ;; at a non-zero nesting level. It may be slow for people who
2740 ;; write huge code blocks or huge lists ... tough beans.
2741 (re-search-backward py-parse-state-re nil 'move)
2742 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002743 ;; In XEmacs, we have a much better way to test for whether
2744 ;; we're in a triple-quoted string or not. Emacs does not
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002745 ;; have this built-in function, which is its loss because
Barry Warsawf64b4051998-02-12 16:52:14 +00002746 ;; without scanning from the beginning of the buffer, there's
2747 ;; no accurate way to determine this otherwise.
2748 (if (not (fboundp 'buffer-syntactic-context))
2749 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002750 (progn
2751 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002752 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002753 (setq done (or (not (nth 3 pps))
2754 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002755 ;; XEmacs
2756 (setq done (or (not (buffer-syntactic-context))
2757 (bobp)))
2758 (when done
2759 (setq pps (parse-partial-sexp (point) here)))
2760 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002761 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002762
2763;; if point is at a non-zero nesting level, returns the number of the
2764;; character that opens the smallest enclosing unclosed list; else
2765;; returns nil.
2766(defun py-nesting-level ()
Barry Warsawf64b4051998-02-12 16:52:14 +00002767 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002768 (if (zerop (car status))
2769 nil ; not in a nest
2770 (car (cdr status))))) ; char# of open bracket
2771
2772;; t iff preceding line ends with backslash that's not in a comment
2773(defun py-backslash-continuation-line-p ()
2774 (save-excursion
2775 (beginning-of-line)
2776 (and
2777 ;; use a cheap test first to avoid the regexp if possible
2778 ;; use 'eq' because char-after may return nil
2779 (eq (char-after (- (point) 2)) ?\\ )
2780 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002781 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002782 (looking-at py-continued-re))))
2783
2784;; t iff current line is a continuation line
2785(defun py-continuation-line-p ()
2786 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002787 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002788 (or (py-backslash-continuation-line-p)
2789 (py-nesting-level))))
2790
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002791;; go to initial line of current statement; usually this is the line
2792;; we're on, but if we're on the 2nd or following lines of a
2793;; continuation block, we need to go up to the first line of the
2794;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002795;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002796;; Tricky: We want to avoid quadratic-time behavior for long continued
2797;; blocks, whether of the backslash or open-bracket varieties, or a
2798;; mix of the two. The following manages to do that in the usual
2799;; cases.
Barry Warsawc210e691998-01-20 22:52:56 +00002800;;
2801;; Also, if we're sitting inside a triple quoted string, this will
2802;; drop us at the line that begins the string.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002803(defun py-goto-initial-line ()
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002804 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002805 (while (py-continuation-line-p)
2806 (beginning-of-line)
2807 (if (py-backslash-continuation-line-p)
2808 (while (py-backslash-continuation-line-p)
2809 (forward-line -1))
2810 ;; else zip out of nested brackets/braces/parens
2811 (while (setq open-bracket-pos (py-nesting-level))
2812 (goto-char open-bracket-pos)))))
2813 (beginning-of-line))
2814
2815;; go to point right beyond final line of current statement; usually
2816;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002817;; statement we need to skip over the continuation lines. Tricky:
2818;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002819(defun py-goto-beyond-final-line ()
Barry Warsaw751f4931998-05-19 16:06:21 +00002820 ;; TEST ADDED BY MDE; not quite the right solution
2821 (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
2822 (goto-char (match-end 0)))
2823 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +00002824 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002825 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002826 (while (and (py-continuation-line-p)
2827 (not (eobp)))
2828 ;; skip over the backslash flavor
2829 (while (and (py-backslash-continuation-line-p)
2830 (not (eobp)))
2831 (forward-line 1))
2832 ;; if in nest, zip to the end of the nest
2833 (setq state (py-parse-state))
2834 (if (and (not (zerop (car state)))
2835 (not (eobp)))
2836 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002837 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002838 (forward-line 1))))))
2839
2840;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002841;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002842(defun py-statement-opens-block-p ()
2843 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002844 (let ((start (point))
2845 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2846 (searching t)
2847 (answer nil)
2848 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002849 (goto-char start)
2850 (while searching
2851 ;; look for a colon with nothing after it except whitespace, and
2852 ;; maybe a comment
2853 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2854 finish t)
2855 (if (eq (point) finish) ; note: no `else' clause; just
2856 ; keep searching if we're not at
2857 ; the end yet
2858 ;; sure looks like it opens a block -- but it might
2859 ;; be in a comment
2860 (progn
2861 (setq searching nil) ; search is done either way
2862 (setq state (parse-partial-sexp start
2863 (match-beginning 0)))
2864 (setq answer (not (nth 4 state)))))
2865 ;; search failed: couldn't find another interesting colon
2866 (setq searching nil)))
2867 answer)))
2868
Barry Warsawf831d811996-07-31 20:42:59 +00002869(defun py-statement-closes-block-p ()
2870 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002871 ;; starts with `return', `raise', `break', `continue', and `pass'.
2872 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002873 (let ((here (point)))
2874 (back-to-indentation)
2875 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002876 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002877 (goto-char here))))
2878
Barry Warsaw7ae77681994-12-12 20:38:05 +00002879;; go to point right beyond final line of block begun by the current
2880;; line. This is the same as where py-goto-beyond-final-line goes
2881;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002882;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002883(defun py-goto-beyond-block ()
2884 (if (py-statement-opens-block-p)
2885 (py-mark-block nil 'just-move)
2886 (py-goto-beyond-final-line)))
2887
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002888;; Go to start of first statement (not blank or comment or
2889;; continuation line) at or preceding point. Returns t if there is
2890;; one, else nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002891(defun py-goto-statement-at-or-above ()
2892 (py-goto-initial-line)
2893 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002894 ;; skip back over blank & comment lines
2895 ;; note: will skip a blank or comment line that happens to be
2896 ;; a continuation line too
2897 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2898 (progn (py-goto-initial-line) t)
2899 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002900 t))
2901
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002902;; Go to start of first statement (not blank or comment or
2903;; continuation line) following the statement containing point.
2904;; Returns t if there is one, else nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002905(defun py-goto-statement-below ()
2906 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002907 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002908 (py-goto-beyond-final-line)
2909 (while (and
2910 (looking-at py-blank-or-comment-re)
2911 (not (eobp)))
2912 (forward-line 1))
2913 (if (eobp)
2914 (progn (goto-char start) nil)
2915 t)))
2916
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002917;; Go to start of statement, at or preceding point, starting with
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002918;; keyword KEY. Skips blank lines and non-indenting comments upward
2919;; first. If that statement starts with KEY, done, else go back to
2920;; first enclosing block starting with KEY. If successful, leaves
2921;; point at the start of the KEY line & returns t. Else leaves point
2922;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002923(defun py-go-up-tree-to-keyword (key)
2924 ;; skip blanks and non-indenting #
2925 (py-goto-initial-line)
2926 (while (and
2927 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2928 (zerop (forward-line -1))) ; go back
2929 nil)
2930 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002931 (let* ((re (concat "[ \t]*" key "\\b"))
2932 (case-fold-search nil) ; let* so looking-at sees this
2933 (found (looking-at re))
2934 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002935 (while (not (or found dead))
2936 (condition-case nil ; in case no enclosing block
2937 (py-goto-block-up 'no-mark)
2938 (error (setq dead t)))
2939 (or dead (setq found (looking-at re))))
2940 (beginning-of-line)
2941 found))
2942
2943;; return string in buffer from start of indentation to end of line;
2944;; prefix "..." if leading whitespace was skipped
2945(defun py-suck-up-leading-text ()
2946 (save-excursion
2947 (back-to-indentation)
2948 (concat
2949 (if (bolp) "" "...")
2950 (buffer-substring (point) (progn (end-of-line) (point))))))
2951
2952;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2953;; as a Lisp symbol; return nil if none
2954(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002955 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002956 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2957 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2958 nil)))
2959
Barry Warsawb3e81d51996-09-04 15:12:42 +00002960(defun py-current-defun ()
2961 ;; tell add-log.el how to find the current function/method/variable
2962 (save-excursion
2963 (if (re-search-backward py-defun-start-re nil t)
2964 (or (match-string 3)
2965 (let ((method (match-string 2)))
2966 (if (and (not (zerop (length (match-string 1))))
2967 (re-search-backward py-class-start-re nil t))
2968 (concat (match-string 1) "." method)
2969 method)))
2970 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002971
2972
Barry Warsawfec75d61995-07-05 23:26:15 +00002973(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002974 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002975
Barry Warsaw850437a1995-03-08 21:50:28 +00002976(defun py-version ()
2977 "Echo the current version of `python-mode' in the minibuffer."
2978 (interactive)
2979 (message "Using `python-mode' version %s" py-version)
2980 (py-keep-region-active))
2981
2982;; only works under Emacs 19
2983;(eval-when-compile
2984; (require 'reporter))
2985
2986(defun py-submit-bug-report (enhancement-p)
2987 "Submit via mail a bug report on `python-mode'.
2988With \\[universal-argument] just submit an enhancement request."
2989 (interactive
2990 (list (not (y-or-n-p
2991 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002992 (let ((reporter-prompt-for-summary-p (if enhancement-p
2993 "(Very) brief summary: "
2994 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002995 (require 'reporter)
2996 (reporter-submit-bug-report
2997 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002998 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002999 ;; varlist
3000 (if enhancement-p nil
3001 '(py-python-command
3002 py-indent-offset
3003 py-block-comment-prefix
3004 py-scroll-process-buffer
3005 py-temp-directory
3006 py-beep-if-tab-change))
3007 nil ;pre-hooks
3008 nil ;post-hooks
3009 "Dear Barry,") ;salutation
3010 (if enhancement-p nil
3011 (set-mark (point))
3012 (insert
3013"Please replace this text with a sufficiently large code sample\n\
3014and an exact recipe so that I can reproduce your problem. Failure\n\
3015to do so may mean a greater delay in fixing your bug.\n\n")
3016 (exchange-point-and-mark)
3017 (py-keep-region-active))))
3018
3019
Barry Warsaw47384781997-11-26 05:27:45 +00003020(defun py-kill-emacs-hook ()
3021 (mapcar #'(lambda (filename)
3022 (py-safe (delete-file filename)))
3023 py-file-queue))
3024
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003025;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00003026(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003027
3028
3029
3030(provide 'python-mode)
3031;;; python-mode.el ends here