blob: fe177b71a04a2363a008af3168f3eeac86cc39f0 [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
Barry Warsaw3bfed5b1998-05-19 16:25:04 +0000310source code of the innermost frame."
311 :type 'boolean
312 :group 'python)
313
314(defcustom py-ask-about-save t
315 "If not nil, ask about which buffers to save before executing some code.
316Otherwise, all modified buffers are saved without asking."
317 :type 'boolean
318 :group 'python)
Barry Warsaw9981d221997-12-03 05:25:48 +0000319
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000320(defcustom py-backspace-function 'backward-delete-char-untabify
321 "*Function called by `py-electric-backspace' when deleting backwards."
322 :type 'function
323 :group 'python)
324
325(defcustom py-delete-function 'delete-char
326 "*Function called by `py-electric-delete' when deleting forwards."
327 :type 'function
328 :group 'python)
329
Barry Warsawc0ecb531998-01-20 21:43:34 +0000330;; Not customizable
331(defvar py-master-file nil
332 "If non-nil, execute the named file instead of the buffer's file.
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000333The intent is to allow you to set this variable in the file's local
Barry Warsawc0ecb531998-01-20 21:43:34 +0000334variable section, e.g.:
335
336 # Local Variables:
337 # py-master-file: \"master.py\"
338 # End:
339
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000340so that typing \\[py-execute-buffer] in that buffer executes the
Barry Warsawc0ecb531998-01-20 21:43:34 +0000341named master file instead of the buffer's file. Note that if the file
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000342name has a relative path, the `default-directory' for the buffer is
343prepended to come up with a file name.")
Barry Warsawc0ecb531998-01-20 21:43:34 +0000344(make-variable-buffer-local 'py-master-file)
345
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000346
Barry Warsawc72c11c1997-08-09 06:42:08 +0000347
348;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
349;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
350
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000351(defconst py-emacs-features
352 (let (features)
353 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
354 ;; the same string.
355 (let ((tmp1 (make-temp-name ""))
356 (tmp2 (make-temp-name "")))
357 (if (string-equal tmp1 tmp2)
358 (push 'broken-temp-names features)))
359 ;; return the features
360 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000361 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000362There are many flavors of Emacs out there, with different levels of
363support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000364
Barry Warsawfb07f401997-02-24 03:37:22 +0000365(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000366 (let ((kw1 (mapconcat 'identity
367 '("and" "assert" "break" "class"
368 "continue" "def" "del" "elif"
369 "else" "except" "exec" "for"
370 "from" "global" "if" "import"
371 "in" "is" "lambda" "not"
372 "or" "pass" "print" "raise"
373 "return" "while"
374 )
375 "\\|"))
376 (kw2 (mapconcat 'identity
377 '("else:" "except:" "finally:" "try:")
378 "\\|"))
379 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000380 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000381 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000382 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
383 ;; block introducing keywords with immediately following colons.
384 ;; Yes "except" is in both lists.
385 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000386 ;; classes
387 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
388 1 font-lock-type-face)
389 ;; functions
390 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
391 1 font-lock-function-name-face)
392 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000393 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000394(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
395
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000396
Barry Warsaw81437461996-08-01 19:48:02 +0000397(defvar imenu-example--python-show-method-args-p nil
398 "*Controls echoing of arguments of functions & methods in the imenu buffer.
399When non-nil, arguments are printed.")
400
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000401(make-variable-buffer-local 'py-indent-offset)
402
Barry Warsawe467bfb1997-11-26 05:40:58 +0000403;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000404(defvar py-file-queue nil
405 "Queue of Python temp files awaiting execution.
406Currently-active file is at the head of the list.")
407
Barry Warsawc72c11c1997-08-09 06:42:08 +0000408
409;; Constants
410
411;; Regexp matching a Python string literal
412(defconst py-stringlit-re
413 (concat
Barry Warsaw751f4931998-05-19 16:06:21 +0000414 ;; These fail if backslash-quote ends the string (not worth
415 ;; fixing?). They precede the short versions so that the first two
416 ;; quotes don't look like an empty short string.
417 ;;
418 ;; (maybe raw), long single quoted triple quoted strings (SQTQ),
419 ;; with potential embedded single quotes
420 "[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
421 "\\|"
422 ;; (maybe raw), long double quoted triple quoted strings (DQTQ),
423 ;; with potential embedded double quotes
424 "[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
425 "\\|"
426 "[rR]?'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
Barry Warsawc72c11c1997-08-09 06:42:08 +0000427 "\\|" ; or
Barry Warsaw751f4931998-05-19 16:06:21 +0000428 "[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\"" ; double-quoted
429 ))
430
Barry Warsawc72c11c1997-08-09 06:42:08 +0000431
432;; Regexp matching Python lines that are continued via backslash.
433;; This is tricky because a trailing backslash does not mean
434;; continuation if it's in a comment
435(defconst py-continued-re
436 (concat
437 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
438 "\\\\$"))
439
440;; Regexp matching blank or comment lines.
441(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
442
443;; Regexp matching clauses to be outdented one level.
444(defconst py-outdent-re
445 (concat "\\(" (mapconcat 'identity
446 '("else:"
447 "except\\(\\s +.*\\)?:"
448 "finally:"
449 "elif\\s +.*:")
450 "\\|")
451 "\\)"))
452
453
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000454;; Regexp matching keywords which typically close a block
455(defconst py-block-closing-keywords-re
456 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
457
Barry Warsawc72c11c1997-08-09 06:42:08 +0000458;; Regexp matching lines to not outdent after.
459(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000460 (concat
461 "\\("
462 (mapconcat 'identity
463 (list "try:"
464 "except\\(\\s +.*\\)?:"
465 "while\\s +.*:"
466 "for\\s +.*:"
467 "if\\s +.*:"
468 "elif\\s +.*:"
469 (concat py-block-closing-keywords-re "[ \t\n]")
470 )
471 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000472 "\\)"))
473
474;; Regexp matching a function, method or variable assignment. If you
475;; change this, you probably have to change `py-current-defun' as
476;; well. This is only used by `py-current-defun' to find the name for
477;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000478(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000479 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
480
481;; Regexp for finding a class name. If you change this, you probably
482;; have to change `py-current-defun' as well. This is only used by
483;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000484(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
485
486;; Regexp that describes tracebacks
487(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000488 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000489
490
491
492;; Utilities
493
494(defmacro py-safe (&rest body)
495 ;; safely execute BODY, return nil if an error occurred
496 (` (condition-case nil
497 (progn (,@ body))
498 (error nil))))
499
500(defsubst py-keep-region-active ()
501 ;; Do whatever is necessary to keep the region active in XEmacs.
502 ;; Ignore byte-compiler warnings you might see. Also note that
503 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
504 ;; to take explicit action.
505 (and (boundp 'zmacs-region-stays)
506 (setq zmacs-region-stays t)))
507
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000508(defsubst py-point (position)
509 ;; Returns the value of point at certain commonly referenced POSITIONs.
510 ;; POSITION can be one of the following symbols:
511 ;;
512 ;; bol -- beginning of line
513 ;; eol -- end of line
514 ;; bod -- beginning of defun
Barry Warsawab0e86c1998-05-19 15:31:46 +0000515 ;; bob -- beginning of buffer
516 ;; eob -- end of buffer
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000517 ;; boi -- back to indentation
Barry Warsawab0e86c1998-05-19 15:31:46 +0000518 ;; bos -- beginning of statement
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000519 ;;
520 ;; This function does not modify point or mark.
521 (let ((here (point)))
522 (cond
523 ((eq position 'bol) (beginning-of-line))
524 ((eq position 'eol) (end-of-line))
Barry Warsawab0e86c1998-05-19 15:31:46 +0000525 ((eq position 'bod) (py-beginning-of-def-or-class))
526 ;; Kind of funny, I know, but useful for py-up-exception.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000527 ((eq position 'bob) (beginning-of-buffer))
528 ((eq position 'eob) (end-of-buffer))
529 ((eq position 'boi) (back-to-indentation))
Barry Warsawab0e86c1998-05-19 15:31:46 +0000530 ((eq position 'bos) (py-goto-initial-line))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000531 (t (error "unknown buffer position requested: %s" position))
532 )
533 (prog1
534 (point)
535 (goto-char here))))
536
537(defsubst py-highlight-line (from to file line)
538 (cond
539 ((fboundp 'make-extent)
540 ;; XEmacs
541 (let ((e (make-extent from to)))
542 (set-extent-property e 'mouse-face 'highlight)
543 (set-extent-property e 'py-exc-info (cons file line))
544 (set-extent-property e 'keymap py-mode-output-map)))
545 (t
546 ;; Emacs -- Please port this!
547 )
548 ))
549
Barry Warsawe908b6b1998-03-19 22:48:02 +0000550(defun py-in-literal (&optional lim)
551 ;; Determine if point is in a Python literal, defined as a comment
552 ;; or string. This is the version used for non-XEmacs, which has a
553 ;; nicer interface.
554 ;;
555 ;; WARNING: Watch out for infinite recursion.
556 (let* ((lim (or lim (c-point 'bod)))
557 (state (parse-partial-sexp lim (point))))
558 (cond
559 ((nth 3 state) 'string)
560 ((nth 4 state) 'comment)
561 (t nil))))
562
563;; XEmacs has a built-in function that should make this much quicker.
564;; In this case, lim is ignored
565(defun py-fast-in-literal (&optional lim)
566 ;; don't have to worry about context == 'block-comment
567 (buffer-syntactic-context))
568
569(if (fboundp 'buffer-syntactic-context)
570 (defalias 'c-in-literal 'c-fast-in-literal))
571
572
Barry Warsawc72c11c1997-08-09 06:42:08 +0000573
574;; Major mode boilerplate
575
Barry Warsaw7ae77681994-12-12 20:38:05 +0000576;; define a mode-specific abbrev table for those who use such things
577(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000578 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000579(define-abbrev-table 'python-mode-abbrev-table nil)
580
Barry Warsaw7ae77681994-12-12 20:38:05 +0000581(defvar python-mode-hook nil
582 "*Hook called by `python-mode'.")
583
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000584;; In previous version of python-mode.el, the hook was incorrectly
585;; called py-mode-hook, and was not defvar'd. Deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000586(and (fboundp 'make-obsolete-variable)
587 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
588
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000589(defvar py-mode-map ()
590 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000591(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000592 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000593 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000594 ;; electric keys
595 (define-key py-mode-map ":" 'py-electric-colon)
596 ;; indentation level modifiers
597 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
598 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
599 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
600 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
601 ;; subprocess commands
602 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
Barry Warsaw820273d1998-05-19 15:54:45 +0000603 (define-key py-mode-map "\C-c\C-m" 'py-execute-import-or-reload)
Barry Warsaw1d0364b1998-05-19 16:15:26 +0000604 (define-key py-mode-map "\C-c\C-s" 'py-execute-string)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000605 (define-key py-mode-map "\C-c|" 'py-execute-region)
Barry Warsaw820273d1998-05-19 15:54:45 +0000606 (define-key py-mode-map "\e\C-x" 'py-execute-def-or-class)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000607 (define-key py-mode-map "\C-c!" 'py-shell)
Barry Warsawa2398801998-04-09 23:28:20 +0000608 (define-key py-mode-map "\C-c\C-t" 'py-toggle-shells)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000609 ;; Caution! Enter here at your own risk. We are trying to support
610 ;; several behaviors and it gets disgusting. :-( This logic ripped
611 ;; largely from CC Mode.
612 ;;
613 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
614 ;; backwards deletion behavior to DEL, which both Delete and
615 ;; Backspace get translated to. There's no way to separate this
616 ;; behavior in a clean way, so deal with it! Besides, it's been
617 ;; this way since the dawn of time.
618 (if (not (boundp 'delete-key-deletes-forward))
619 (define-key py-mode-map "\177" 'py-electric-backspace)
620 ;; However, XEmacs 20 actually achieved enlightenment. It is
621 ;; possible to sanely define both backward and forward deletion
622 ;; behavior under X separately (TTYs are forever beyond hope, but
623 ;; who cares? XEmacs 20 does the right thing with these too).
624 (define-key py-mode-map [delete] 'py-electric-delete)
625 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000626 ;; Separate M-BS from C-M-h. The former should remain
627 ;; backward-kill-word.
628 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000629 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000630 ;; Miscellaneous
631 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
632 (define-key py-mode-map "\C-c\t" 'py-indent-region)
633 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
634 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
635 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000636 (define-key py-mode-map "\C-c#" 'py-comment-region)
637 (define-key py-mode-map "\C-c?" 'py-describe-mode)
638 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
Barry Warsawab0e86c1998-05-19 15:31:46 +0000639 (define-key py-mode-map "\e\C-a" 'py-beginning-of-def-or-class)
640 (define-key py-mode-map "\e\C-e" 'py-end-of-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000641 (define-key py-mode-map "\C-c-" 'py-up-exception)
642 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000643 ;; information
644 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
645 (define-key py-mode-map "\C-c\C-v" 'py-version)
646 ;; py-newline-and-indent mappings
Barry Warsaw82aecb91998-01-21 05:14:24 +0000647 (define-key py-mode-map "\n" 'py-newline-and-indent)
648 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000649 ;; shadow global bindings for newline-and-indent w/ the py- version.
650 ;; BAW - this is extremely bad form, but I'm not going to change it
651 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000652 (mapcar #'(lambda (key)
653 (define-key py-mode-map key 'py-newline-and-indent))
654 (where-is-internal 'newline-and-indent))
655 )
656
657(defvar py-mode-output-map nil
658 "Keymap used in *Python Output* buffers*")
659(if py-mode-output-map
660 nil
661 (setq py-mode-output-map (make-sparse-keymap))
662 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
663 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
664 ;; TBD: Disable all self-inserting keys. This is bogus, we should
665 ;; really implement this as *Python Output* buffer being read-only
666 (mapcar #' (lambda (key)
667 (define-key py-mode-output-map key
668 #'(lambda () (interactive) (beep))))
669 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000670 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000671
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000672(defvar py-mode-syntax-table nil
673 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000674(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000675 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000676 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000677 (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 ;; Add operator symbols misassigned in the std table
684 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
685 (modify-syntax-entry ?\% "." py-mode-syntax-table)
686 (modify-syntax-entry ?\& "." py-mode-syntax-table)
687 (modify-syntax-entry ?\* "." py-mode-syntax-table)
688 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
689 (modify-syntax-entry ?\- "." py-mode-syntax-table)
690 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
691 (modify-syntax-entry ?\< "." py-mode-syntax-table)
692 (modify-syntax-entry ?\= "." py-mode-syntax-table)
693 (modify-syntax-entry ?\> "." py-mode-syntax-table)
694 (modify-syntax-entry ?\| "." py-mode-syntax-table)
695 ;; For historical reasons, underscore is word class instead of
696 ;; symbol class. GNU conventions say it should be symbol class, but
697 ;; there's a natural conflict between what major mode authors want
698 ;; and what users expect from `forward-word' and `backward-word'.
699 ;; Guido and I have hashed this out and have decided to keep
700 ;; underscore in word class. If you're tempted to change it, try
701 ;; binding M-f and M-b to py-forward-into-nomenclature and
702 ;; py-backward-into-nomenclature instead.
703 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
704 ;; Both single quote and double quote are string delimiters
705 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
706 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
707 ;; backquote is open and close paren
708 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
709 ;; comment delimiters
710 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
711 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
712 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000713
Barry Warsawb3e81d51996-09-04 15:12:42 +0000714
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000715
Barry Warsaw42f707f1996-07-29 21:05:05 +0000716;; Menu definitions, only relevent if you have the easymenu.el package
717;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000718(defvar py-menu nil
719 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000720This menu will get created automatically if you have the `easymenu'
721package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000722
Barry Warsawc72c11c1997-08-09 06:42:08 +0000723(and (py-safe (require 'easymenu) t)
724 (easy-menu-define
725 py-menu py-mode-map "Python Mode menu"
726 '("Python"
727 ["Comment Out Region" py-comment-region (mark)]
728 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
729 "-"
730 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000731 ["Mark current def" py-mark-def-or-class t]
732 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000733 "-"
734 ["Shift region left" py-shift-region-left (mark)]
735 ["Shift region right" py-shift-region-right (mark)]
736 "-"
Barry Warsaw820273d1998-05-19 15:54:45 +0000737 ["Import/reload file" py-execute-import-or-reload t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000738 ["Execute buffer" py-execute-buffer t]
739 ["Execute region" py-execute-region (mark)]
Barry Warsaw820273d1998-05-19 15:54:45 +0000740 ["Execute def or class" py-execute-def-or-class (mark)]
Barry Warsaw1d0364b1998-05-19 16:15:26 +0000741 ["Execute string" py-execute-string t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000742 ["Start interpreter..." py-shell t]
743 "-"
744 ["Go to start of block" py-goto-block-up t]
Barry Warsawab0e86c1998-05-19 15:31:46 +0000745 ["Go to start of class" (py-beginning-of-def-or-class t) t]
746 ["Move to end of class" (py-end-of-def-or-class t) t]
747 ["Move to start of def" py-beginning-of-def-or-class t]
748 ["Move to end of def" py-end-of-def-or-class t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000749 "-"
750 ["Describe mode" py-describe-mode t]
751 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000752
Barry Warsaw81437461996-08-01 19:48:02 +0000753
754
755;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
756(defvar imenu-example--python-class-regexp
757 (concat ; <<classes>>
758 "\\(" ;
759 "^[ \t]*" ; newline and maybe whitespace
760 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
761 ; possibly multiple superclasses
Barry Warsaw3179fe01998-04-04 21:36:53 +0000762 "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
Barry Warsaw81437461996-08-01 19:48:02 +0000763 "[ \t]*:" ; and the final :
764 "\\)" ; >>classes<<
765 )
766 "Regexp for Python classes for use with the imenu package."
767 )
768
769(defvar imenu-example--python-method-regexp
770 (concat ; <<methods and functions>>
771 "\\(" ;
772 "^[ \t]*" ; new line and maybe whitespace
773 "\\(def[ \t]+" ; function definitions start with def
774 "\\([a-zA-Z0-9_]+\\)" ; name is here
775 ; function arguments...
776 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
777 "\\)" ; end of def
778 "[ \t]*:" ; and then the :
779 "\\)" ; >>methods and functions<<
780 )
781 "Regexp for Python methods/functions for use with the imenu package."
782 )
783
784(defvar imenu-example--python-method-no-arg-parens '(2 8)
785 "Indicies into groups of the Python regexp for use with imenu.
786
787Using these values will result in smaller imenu lists, as arguments to
788functions are not listed.
789
790See the variable `imenu-example--python-show-method-args-p' for more
791information.")
792
793(defvar imenu-example--python-method-arg-parens '(2 7)
794 "Indicies into groups of the Python regexp for use with imenu.
795Using these values will result in large imenu lists, as arguments to
796functions are listed.
797
798See the variable `imenu-example--python-show-method-args-p' for more
799information.")
800
801;; Note that in this format, this variable can still be used with the
802;; imenu--generic-function. Otherwise, there is no real reason to have
803;; it.
804(defvar imenu-example--generic-python-expression
805 (cons
806 (concat
807 imenu-example--python-class-regexp
808 "\\|" ; or...
809 imenu-example--python-method-regexp
810 )
811 imenu-example--python-method-no-arg-parens)
812 "Generic Python expression which may be used directly with imenu.
813Used by setting the variable `imenu-generic-expression' to this value.
814Also, see the function \\[imenu-example--create-python-index] for a
815better alternative for finding the index.")
816
817;; These next two variables are used when searching for the python
818;; class/definitions. Just saving some time in accessing the
819;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000820(defvar imenu-example--python-generic-regexp nil)
821(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000822
823
Barry Warsaw81437461996-08-01 19:48:02 +0000824(defun imenu-example--create-python-index ()
825 "Python interface function for imenu package.
826Finds all python classes and functions/methods. Calls function
827\\[imenu-example--create-python-index-engine]. See that function for
828the details of how this works."
829 (setq imenu-example--python-generic-regexp
830 (car imenu-example--generic-python-expression))
831 (setq imenu-example--python-generic-parens
832 (if imenu-example--python-show-method-args-p
833 imenu-example--python-method-arg-parens
834 imenu-example--python-method-no-arg-parens))
835 (goto-char (point-min))
836 (imenu-example--create-python-index-engine nil))
837
838(defun imenu-example--create-python-index-engine (&optional start-indent)
839 "Function for finding imenu definitions in Python.
840
841Finds all definitions (classes, methods, or functions) in a Python
842file for the imenu package.
843
844Returns a possibly nested alist of the form
845
846 (INDEX-NAME . INDEX-POSITION)
847
848The second element of the alist may be an alist, producing a nested
849list as in
850
851 (INDEX-NAME . INDEX-ALIST)
852
853This function should not be called directly, as it calls itself
854recursively and requires some setup. Rather this is the engine for
855the function \\[imenu-example--create-python-index].
856
857It works recursively by looking for all definitions at the current
858indention level. When it finds one, it adds it to the alist. If it
859finds a definition at a greater indentation level, it removes the
Barry Warsaw145ab1c1998-05-19 14:49:49 +0000860previous definition from the alist. In its place it adds all
Barry Warsaw81437461996-08-01 19:48:02 +0000861definitions found at the next indentation level. When it finds a
862definition that is less indented then the current level, it retuns the
863alist it has created thus far.
864
865The optional argument START-INDENT indicates the starting indentation
866at which to continue looking for Python classes, methods, or
867functions. If this is not supplied, the function uses the indentation
868of the first definition found."
869 (let ((index-alist '())
870 (sub-method-alist '())
871 looking-p
872 def-name prev-name
873 cur-indent def-pos
874 (class-paren (first imenu-example--python-generic-parens))
875 (def-paren (second imenu-example--python-generic-parens)))
876 (setq looking-p
877 (re-search-forward imenu-example--python-generic-regexp
878 (point-max) t))
879 (while looking-p
880 (save-excursion
881 ;; used to set def-name to this value but generic-extract-name is
882 ;; new to imenu-1.14. this way it still works with imenu-1.11
883 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
884 (let ((cur-paren (if (match-beginning class-paren)
885 class-paren def-paren)))
886 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000887 (buffer-substring-no-properties (match-beginning cur-paren)
888 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000889 (beginning-of-line)
890 (setq cur-indent (current-indentation)))
891
892 ;; HACK: want to go to the next correct definition location. we
893 ;; explicitly list them here. would be better to have them in a
894 ;; list.
895 (setq def-pos
896 (or (match-beginning class-paren)
897 (match-beginning def-paren)))
898
899 ;; if we don't have a starting indent level, take this one
900 (or start-indent
901 (setq start-indent cur-indent))
902
903 ;; if we don't have class name yet, take this one
904 (or prev-name
905 (setq prev-name def-name))
906
907 ;; what level is the next definition on? must be same, deeper
908 ;; or shallower indentation
909 (cond
910 ;; at the same indent level, add it to the list...
911 ((= start-indent cur-indent)
912
913 ;; if we don't have push, use the following...
914 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
915 (push (cons def-name def-pos) index-alist))
916
917 ;; deeper indented expression, recur...
918 ((< start-indent cur-indent)
919
920 ;; the point is currently on the expression we're supposed to
921 ;; start on, so go back to the last expression. The recursive
922 ;; call will find this place again and add it to the correct
923 ;; list
924 (re-search-backward imenu-example--python-generic-regexp
925 (point-min) 'move)
926 (setq sub-method-alist (imenu-example--create-python-index-engine
927 cur-indent))
928
929 (if sub-method-alist
930 ;; we put the last element on the index-alist on the start
931 ;; of the submethod alist so the user can still get to it.
932 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000933 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000934 (cons save-elmt sub-method-alist))
935 index-alist))))
936
937 ;; found less indented expression, we're done.
938 (t
939 (setq looking-p nil)
940 (re-search-backward imenu-example--python-generic-regexp
941 (point-min) t)))
942 (setq prev-name def-name)
943 (and looking-p
944 (setq looking-p
945 (re-search-forward imenu-example--python-generic-regexp
946 (point-max) 'move))))
947 (nreverse index-alist)))
948
Barry Warsaw42f707f1996-07-29 21:05:05 +0000949
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000950;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000951(defun python-mode ()
952 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000953To submit a problem report, enter `\\[py-submit-bug-report]' from a
954`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
955documentation. To see what version of `python-mode' you are running,
956enter `\\[py-version]'.
957
958This mode knows about Python indentation, tokens, comments and
959continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000960
961COMMANDS
962\\{py-mode-map}
963VARIABLES
964
Barry Warsaw42f707f1996-07-29 21:05:05 +0000965py-indent-offset\t\tindentation increment
966py-block-comment-prefix\t\tcomment string used by comment-region
967py-python-command\t\tshell command to invoke Python interpreter
968py-scroll-process-buffer\t\talways scroll Python process buffer
969py-temp-directory\t\tdirectory used for temp files (if needed)
970py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000971 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000972 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000973 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000974 (make-local-variable 'font-lock-defaults)
975 (make-local-variable 'paragraph-separate)
976 (make-local-variable 'paragraph-start)
977 (make-local-variable 'require-final-newline)
978 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000979 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000980 (make-local-variable 'comment-start-skip)
981 (make-local-variable 'comment-column)
Barry Warsaw003932a1998-07-07 15:11:24 +0000982 (make-local-variable 'comment-indent-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000983 (make-local-variable 'indent-region-function)
984 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000985 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000986 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000987 (set-syntax-table py-mode-syntax-table)
Barry Warsaw003932a1998-07-07 15:11:24 +0000988 (setq major-mode 'python-mode
989 mode-name "Python"
990 local-abbrev-table python-mode-abbrev-table
991 font-lock-defaults '(python-font-lock-keywords)
992 paragraph-separate "^[ \t]*$"
993 paragraph-start "^[ \t]*$"
994 require-final-newline t
995 comment-start "# "
996 comment-end ""
997 comment-start-skip "# *"
998 comment-column 40
999 comment-indent-function 'py-comment-indent-function
1000 indent-region-function 'py-indent-region
1001 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +00001002 ;; tell add-log.el how to find the current function/method/variable
1003 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +00001004 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001005 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +00001006 ;; add the menu
1007 (if py-menu
1008 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +00001009 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +00001010 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +00001011 (setq comment-multi-line nil))
Barry Warsaw742a5111998-03-13 17:29:15 +00001012 ;; Install Imenu, only works for Emacs.
1013 (when (py-safe (require 'imenu))
1014 (make-variable-buffer-local 'imenu-create-index-function)
1015 (setq imenu-create-index-function
1016 (function imenu-example--create-python-index))
1017 (setq imenu-generic-expression
1018 imenu-example--generic-python-expression)
1019 (if (fboundp 'imenu-add-to-menubar)
1020 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
1021 )
1022 ;; Run the mode hook. Note that py-mode-hook is deprecated.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001023 (if python-mode-hook
1024 (run-hooks 'python-mode-hook)
Barry Warsaw742a5111998-03-13 17:29:15 +00001025 (run-hooks 'py-mode-hook))
1026 ;; Now do the automagical guessing
1027 (if py-smart-indentation
1028 (let ((offset py-indent-offset))
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001029 ;; It's okay if this fails to guess a good value
Barry Warsaw742a5111998-03-13 17:29:15 +00001030 (if (and (py-safe (py-guess-indent-offset))
1031 (<= py-indent-offset 8)
1032 (>= py-indent-offset 2))
1033 (setq offset py-indent-offset))
1034 (setq py-indent-offset offset)
Barry Warsaw639eea61998-03-16 18:12:13 +00001035 ;; Only turn indent-tabs-mode off if tab-width !=
1036 ;; py-indent-offset. Never turn it on, because the user must
1037 ;; have explicitly turned it off.
1038 (if (/= tab-width py-indent-offset)
1039 (setq indent-tabs-mode nil))
Barry Warsaw742a5111998-03-13 17:29:15 +00001040 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001041
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001042
Barry Warsawb91b7431995-03-14 15:55:20 +00001043;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001044(defun py-outdent-p ()
1045 ;; returns non-nil if the current line should outdent one level
1046 (save-excursion
1047 (and (progn (back-to-indentation)
1048 (looking-at py-outdent-re))
Barry Warsawf06777d1998-01-21 05:36:18 +00001049 (progn (forward-line -1)
1050 (py-goto-initial-line)
1051 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001052 (while (or (looking-at py-blank-or-comment-re)
1053 (bobp))
1054 (backward-to-indentation 1))
1055 (not (looking-at py-no-outdent-re)))
1056 )))
1057
Barry Warsawb91b7431995-03-14 15:55:20 +00001058(defun py-electric-colon (arg)
1059 "Insert a colon.
1060In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001061argument is provided, that many colons are inserted non-electrically.
1062Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +00001063 (interactive "P")
1064 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001065 ;; are we in a string or comment?
1066 (if (save-excursion
1067 (let ((pps (parse-partial-sexp (save-excursion
Barry Warsawab0e86c1998-05-19 15:31:46 +00001068 (py-beginning-of-def-or-class)
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001069 (point))
1070 (point))))
1071 (not (or (nth 3 pps) (nth 4 pps)))))
1072 (save-excursion
1073 (let ((here (point))
1074 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001075 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001076 (if (and (not arg)
1077 (py-outdent-p)
1078 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +00001079 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001080 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001081 )
1082 (setq outdent py-indent-offset))
1083 ;; Don't indent, only outdent. This assumes that any lines that
1084 ;; are already outdented relative to py-compute-indentation were
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001085 ;; put there on purpose. It's highly annoying to have `:' indent
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001086 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
1087 ;; there a better way to determine this???
1088 (if (< (current-indentation) indent) nil
1089 (goto-char here)
1090 (beginning-of-line)
1091 (delete-horizontal-space)
1092 (indent-to (- indent outdent))
1093 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001094
1095
Barry Warsawa97a3f31997-11-04 18:47:06 +00001096;; Python subprocess utilities and filters
1097(defun py-execute-file (proc filename)
1098 ;; Send a properly formatted execfile('FILENAME') to the underlying
1099 ;; Python interpreter process FILENAME. Make that process's buffer
1100 ;; visible and force display. Also make comint believe the user
1101 ;; typed this string so that kill-output-from-shell does The Right
1102 ;; Thing.
1103 (let ((curbuf (current-buffer))
1104 (procbuf (process-buffer proc))
1105 (comint-scroll-to-bottom-on-output t)
1106 (msg (format "## working on region in file %s...\n" filename))
1107 (cmd (format "execfile('%s')\n" filename)))
1108 (unwind-protect
1109 (progn
1110 (set-buffer procbuf)
1111 (goto-char (point-max))
1112 (move-marker (process-mark proc) (point))
1113 (funcall (process-filter proc) proc msg))
1114 (set-buffer curbuf))
1115 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001116
1117(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001118 (let ((curbuf (current-buffer))
1119 (pbuf (process-buffer pyproc))
1120 (pmark (process-mark pyproc))
1121 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001122 ;; make sure we switch to a different buffer at least once. if we
1123 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001124 ;; window, and point is before the end, and lots of output is
1125 ;; coming at a fast pace, then (a) simple cursor-movement commands
1126 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
1127 ;; to have a visible effect (the window just doesn't get updated,
1128 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
1129 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001130 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001131 ;; #b makes no sense to me at all. #a almost makes sense: unless
1132 ;; we actually change buffers, set_buffer_internal in buffer.c
1133 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1134 ;; seems to make the Emacs command loop reluctant to update the
1135 ;; display. Perhaps the default process filter in process.c's
1136 ;; read_process_output has update_mode_lines++ for a similar
1137 ;; reason? beats me ...
1138
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001139 (unwind-protect
1140 ;; make sure current buffer is restored
1141 ;; BAW - we want to check to see if this still applies
1142 (progn
1143 ;; mysterious ugly hack
1144 (if (eq curbuf pbuf)
1145 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001146
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001147 (set-buffer pbuf)
1148 (let* ((start (point))
1149 (goback (< start pmark))
1150 (goend (and (not goback) (= start (point-max))))
1151 (buffer-read-only nil))
1152 (goto-char pmark)
1153 (insert string)
1154 (move-marker pmark (point))
1155 (setq file-finished
1156 (and py-file-queue
1157 (equal ">>> "
1158 (buffer-substring
1159 (prog2 (beginning-of-line) (point)
1160 (goto-char pmark))
1161 (point)))))
1162 (if goback (goto-char start)
1163 ;; else
1164 (if py-scroll-process-buffer
1165 (let* ((pop-up-windows t)
1166 (pwin (display-buffer pbuf)))
1167 (set-window-point pwin (point)))))
1168 (set-buffer curbuf)
1169 (if file-finished
1170 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001171 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001172 (setq py-file-queue (cdr py-file-queue))
1173 (if py-file-queue
1174 (py-execute-file pyproc (car py-file-queue)))))
1175 (and goend
1176 (progn (set-buffer pbuf)
1177 (goto-char (point-max))))
1178 ))
1179 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001180
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001181(defun py-postprocess-output-buffer (buf)
Barry Warsawf9b99f41998-03-26 16:08:59 +00001182 ;; Highlight exceptions found in BUF. If an exception occurred
1183 ;; return t, otherwise return nil. BUF must exist.
1184 (let (line file bol err-p)
Barry Warsaw9981d221997-12-03 05:25:48 +00001185 (save-excursion
1186 (set-buffer buf)
1187 (beginning-of-buffer)
1188 (while (re-search-forward py-traceback-line-re nil t)
1189 (setq file (match-string 1)
1190 line (string-to-int (match-string 2))
1191 bol (py-point 'bol))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001192 (py-highlight-line bol (py-point 'eol) file line)))
1193 (when (and py-jump-on-exception line)
1194 (beep)
1195 (py-jump-to-exception file line)
1196 (setq err-p t))
1197 err-p))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001198
Barry Warsaw9981d221997-12-03 05:25:48 +00001199
Barry Warsawa97a3f31997-11-04 18:47:06 +00001200
1201;;; Subprocess commands
1202
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001203;; only used when (memq 'broken-temp-names py-emacs-features)
1204(defvar py-serial-number 0)
1205(defvar py-exception-buffer nil)
1206(defconst py-output-buffer "*Python Output*")
Barry Warsawa2398801998-04-09 23:28:20 +00001207(make-variable-buffer-local 'py-output-buffer)
1208
1209;; for toggling between CPython and JPython
1210(defvar py-which-shell py-python-command)
1211(defvar py-which-args py-python-command-args)
1212(defvar py-which-bufname "Python")
1213(make-variable-buffer-local 'py-which-shell)
1214(make-variable-buffer-local 'py-which-args)
1215(make-variable-buffer-local 'py-which-bufname)
1216
1217(defun py-toggle-shells (arg)
1218 "Toggles between the CPython and JPython shells.
1219With positive \\[universal-argument], uses the CPython shell, with
1220negative \\[universal-argument] uses the JPython shell, and with a
1221zero argument, toggles the shell."
1222 (interactive "P")
1223 ;; default is to toggle
1224 (if (null arg)
1225 (setq arg 0))
1226 ;; toggle if zero
1227 (if (= arg 0)
1228 (if (string-equal py-which-bufname "Python")
1229 (setq arg -1)
1230 (setq arg 1)))
1231 (let (msg)
1232 (cond
1233 ((< 0 arg)
1234 ;; set to CPython
1235 (setq py-which-shell py-python-command
1236 py-which-args py-python-command-args
1237 py-which-bufname "Python"
1238 msg "CPython"
1239 mode-name "Python"))
1240 ((> 0 arg)
1241 (setq py-which-shell py-jpython-command
1242 py-which-args py-jpython-command-args
1243 py-which-bufname "JPython"
1244 msg "JPython"
1245 mode-name "JPython"))
1246 )
Barry Warsawea609c11998-04-10 16:08:26 +00001247 (message "Using the %s shell" msg)
Barry Warsawa2398801998-04-09 23:28:20 +00001248 (setq py-output-buffer (format "*%s Output*" py-which-bufname))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001249
Barry Warsawa97a3f31997-11-04 18:47:06 +00001250;;;###autoload
1251(defun py-shell ()
1252 "Start an interactive Python interpreter in another window.
1253This is like Shell mode, except that Python is running in the window
1254instead of a shell. See the `Interactive Shell' and `Shell Mode'
1255sections of the Emacs manual for details, especially for the key
1256bindings active in the `*Python*' buffer.
1257
1258See the docs for variable `py-scroll-buffer' for info on scrolling
1259behavior in the process window.
1260
Barry Warsawa2398801998-04-09 23:28:20 +00001261Note: You can toggle between using the CPython interpreter and the
1262JPython interpreter by hitting \\[py-toggle-shells]. This toggles
1263buffer local variables which control whether all your subshell
1264interactions happen to the `*JPython*' or `*Python*' buffers (the
1265latter is the name used for the CPython buffer).
1266
Barry Warsawa97a3f31997-11-04 18:47:06 +00001267Warning: Don't use an interactive Python if you change sys.ps1 or
1268sys.ps2 from their default values, or if you're running code that
1269prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1270distinguish your output from Python's output, and assumes that `>>> '
1271at the start of a line is a prompt from Python. Similarly, the Emacs
1272Shell mode code assumes that both `>>> ' and `... ' at the start of a
1273line are Python prompts. Bad things can happen if you fool either
1274mode.
1275
1276Warning: If you do any editing *in* the process buffer *while* the
1277buffer is accepting output from Python, do NOT attempt to `undo' the
1278changes. Some of the output (nowhere near the parts you changed!) may
1279be lost if you do. This appears to be an Emacs bug, an unfortunate
1280interaction between undo and process filters; the same problem exists in
1281non-Python process buffers using the default (Emacs-supplied) process
1282filter."
1283 ;; BAW - should undo be disabled in the python process buffer, if
1284 ;; this bug still exists?
1285 (interactive)
1286 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001287 (switch-to-buffer-other-window
Barry Warsawa2398801998-04-09 23:28:20 +00001288 (apply 'make-comint py-which-bufname py-which-shell nil py-which-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001289 (make-local-variable 'comint-prompt-regexp)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001290 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
Barry Warsawa97a3f31997-11-04 18:47:06 +00001291 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1292 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001293 ;; set up keybindings for this subshell
1294 (local-set-key [tab] 'self-insert-command)
1295 (local-set-key "\C-c-" 'py-up-exception)
1296 (local-set-key "\C-c=" 'py-down-exception)
1297 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001298
Barry Warsawa97a3f31997-11-04 18:47:06 +00001299(defun py-clear-queue ()
1300 "Clear the queue of temporary files waiting to execute."
1301 (interactive)
1302 (let ((n (length py-file-queue)))
1303 (mapcar 'delete-file py-file-queue)
1304 (setq py-file-queue nil)
1305 (message "%d pending files de-queued." n)))
1306
Barry Warsaw820273d1998-05-19 15:54:45 +00001307
Barry Warsawa97a3f31997-11-04 18:47:06 +00001308(defun py-execute-region (start end &optional async)
1309 "Execute the the region in a Python interpreter.
1310The region is first copied into a temporary file (in the directory
1311`py-temp-directory'). If there is no Python interpreter shell
1312running, this file is executed synchronously using
1313`shell-command-on-region'. If the program is long running, use an
1314optional \\[universal-argument] to run the command asynchronously in
1315its own buffer.
1316
1317If the Python interpreter shell is running, the region is execfile()'d
1318in that shell. If you try to execute regions too quickly,
1319`python-mode' will queue them up and execute them one at a time when
1320it sees a `>>> ' prompt from Python. Each time this happens, the
1321process buffer is popped into a window (if it's not already in some
1322window) so you can see it, and a comment of the form
1323
1324 \t## working on region in file <name>...
1325
1326is inserted at the end. See also the command `py-clear-queue'."
1327 (interactive "r\nP")
1328 (or (< start end)
1329 (error "Region is empty"))
1330 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001331 (temp (if (memq 'broken-temp-names py-emacs-features)
Barry Warsaw1b344241998-08-07 22:24:16 +00001332 (let
1333 ((sn py-serial-number)
1334 (pid (and (fboundp 'emacs-pid) (emacs-pid))))
1335 (setq py-serial-number (1+ py-serial-number))
1336 (if pid
1337 (format "python-%d-%d" sn pid)
1338 (format "python-%d" sn)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001339 (make-temp-name "python-")))
1340 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001341 (write-region start end file nil 'nomsg)
1342 (cond
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001343 ;; always run the code in its own asynchronous subprocess
Barry Warsawa97a3f31997-11-04 18:47:06 +00001344 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001345 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001346 (start-process "Python" buf py-python-command "-u" file)
1347 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001348 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001349 ))
1350 ;; if the Python interpreter shell is running, queue it up for
1351 ;; execution there.
1352 (proc
1353 ;; use the existing python shell
1354 (if (not py-file-queue)
1355 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001356 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001357 (push file py-file-queue)
1358 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001359 (t
1360 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001361 (shell-command-on-region start end py-python-command py-output-buffer)
Barry Warsaw512af041998-03-25 23:27:17 +00001362 ;; shell-command-on-region kills the output buffer if it never
1363 ;; existed and there's no output from the command
1364 (if (not (get-buffer py-output-buffer))
1365 (message "No output.")
1366 (setq py-exception-buffer (current-buffer))
Barry Warsawf9b99f41998-03-26 16:08:59 +00001367 (let ((err-p (py-postprocess-output-buffer py-output-buffer)))
1368 (pop-to-buffer py-output-buffer)
1369 (if err-p
1370 (pop-to-buffer py-exception-buffer)))
Barry Warsaw512af041998-03-25 23:27:17 +00001371 ))
1372 )))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001373
Barry Warsaw820273d1998-05-19 15:54:45 +00001374
1375;; Code execution commands
Barry Warsawa97a3f31997-11-04 18:47:06 +00001376(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001377 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001378If the file local variable `py-master-file' is non-nil, execute the
1379named file instead of the buffer's file.
1380
Barry Warsaw7ae77681994-12-12 20:38:05 +00001381If there is a *Python* process buffer it is used. If a clipping
1382restriction is in effect, only the accessible portion of the buffer is
1383sent. A trailing newline will be supplied if needed.
1384
1385See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001386 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001387 (if py-master-file
1388 (let* ((filename (expand-file-name py-master-file))
1389 (buffer (or (get-file-buffer filename)
1390 (find-file-noselect filename))))
1391 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001392 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001393
Barry Warsaw820273d1998-05-19 15:54:45 +00001394(defun py-execute-import-or-reload (&optional async)
1395 "Import the current buffer's file in a Python interpreter.
1396
1397If the file has already been imported, then do reload instead to get
Barry Warsaw7c29b231998-07-07 17:45:38 +00001398the latest version.
1399
1400If the file's name does not end in \".py\", then do execfile instead.
1401
1402If the current buffer is not visiting a file, do `py-execute-buffer'
1403instead.
1404
1405If the file local variable `py-master-file' is non-nil, import or
1406reload the named file instead of the buffer's file. The file may be
1407saved based on the value of `py-execute-import-or-reload-save-p'.
Barry Warsaw820273d1998-05-19 15:54:45 +00001408
1409See the `\\[py-execute-region]' docs for an account of some subtleties.
1410
Barry Warsaw7c29b231998-07-07 17:45:38 +00001411This may be preferable to `\\[py-execute-buffer]' because:
Barry Warsaw820273d1998-05-19 15:54:45 +00001412
1413 - Definitions stay in their module rather than appearing at top
1414 level, where they would clutter the global namespace and not affect
1415 uses of qualified names (MODULE.NAME).
1416
1417 - The Python debugger gets line number information about the functions."
1418 (interactive "P")
1419 ;; Check file local variable py-master-file
1420 (if py-master-file
1421 (let* ((filename (expand-file-name py-master-file))
1422 (buffer (or (get-file-buffer filename)
1423 (find-file-noselect filename))))
1424 (set-buffer buffer)))
1425 (let ((file (buffer-file-name (current-buffer))))
1426 (if file
1427 (progn
Barry Warsaw3bfed5b1998-05-19 16:25:04 +00001428 ;; Maybe save some buffers
1429 (save-some-buffers (not py-ask-about-save) nil)
Barry Warsaw820273d1998-05-19 15:54:45 +00001430 (py-execute-string
1431 (if (string-match "\\.py$" file)
1432 (let ((f (file-name-sans-extension
1433 (file-name-nondirectory file))))
1434 (format "if globals().has_key('%s'):\n reload(%s)\nelse:\n import %s\n"
1435 f f f))
1436 (format "execfile('%s')\n" file))
1437 async))
1438 ;; else
1439 (py-execute-buffer async))))
1440
1441
1442(defun py-execute-def-or-class (&optional async)
1443 "Send the current function or class definition to a Python interpreter.
1444
1445If there is a *Python* process buffer it is used.
1446
1447See the `\\[py-execute-region]' docs for an account of some subtleties."
1448 (interactive "P")
1449 (save-excursion
1450 (py-mark-def-or-class)
1451 ;; mark is before point
1452 (py-execute-region (mark) (point) async)))
1453
1454
1455(defun py-execute-string (string &optional async)
1456 "Send the argument string to a Python interpreter.
1457
1458If there is a *Python* process buffer it is used.
1459
1460See the `\\[py-execute-region]' docs for an account of some subtleties."
1461 (interactive "sExecute Python command: ")
1462 (save-excursion
1463 (set-buffer (get-buffer-create
1464 (generate-new-buffer-name " *Python Command*")))
1465 (insert string)
1466 (py-execute-region (point-min) (point-max) async)))
1467
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001468
1469
1470(defun py-jump-to-exception (file line)
1471 (let ((buffer (cond ((string-equal file "<stdin>")
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001472 (if (consp py-exception-buffer)
1473 (cdr py-exception-buffer)
1474 py-exception-buffer))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001475 ((and (consp py-exception-buffer)
1476 (string-equal file (car py-exception-buffer)))
1477 (cdr py-exception-buffer))
1478 ((py-safe (find-file-noselect file)))
1479 ;; could not figure out what file the exception
1480 ;; is pointing to, so prompt for it
1481 (t (find-file (read-file-name "Exception file: "
1482 nil
1483 file t))))))
1484 (pop-to-buffer buffer)
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001485 ;; Force Python mode
Barry Warsaw820273d1998-05-19 15:54:45 +00001486 (if (not (eq major-mode 'python-mode))
Barry Warsawebc7b7a1998-05-19 15:01:06 +00001487 (python-mode))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001488 (goto-line line)
1489 (message "Jumping to exception in file %s on line %d" file line)))
1490
1491(defun py-mouseto-exception (event)
1492 (interactive "e")
1493 (cond
1494 ((fboundp 'event-point)
1495 ;; XEmacs
1496 (let* ((point (event-point event))
1497 (buffer (event-buffer event))
1498 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1499 (info (and e (extent-property e 'py-exc-info))))
1500 (message "Event point: %d, info: %s" point info)
1501 (and info
1502 (py-jump-to-exception (car info) (cdr info)))
1503 ))
1504 ;; Emacs -- Please port this!
1505 ))
1506
1507(defun py-goto-exception ()
1508 "Go to the line indicated by the traceback."
1509 (interactive)
1510 (let (file line)
1511 (save-excursion
1512 (beginning-of-line)
1513 (if (looking-at py-traceback-line-re)
1514 (setq file (match-string 1)
1515 line (string-to-int (match-string 2)))))
1516 (if (not file)
1517 (error "Not on a traceback line."))
1518 (py-jump-to-exception file line)))
1519
1520(defun py-find-next-exception (start buffer searchdir errwhere)
1521 ;; Go to start position in buffer, search in the specified
1522 ;; direction, and jump to the exception found. If at the end of the
1523 ;; exception, print error message
1524 (let (file line)
1525 (save-excursion
1526 (set-buffer buffer)
1527 (goto-char (py-point start))
1528 (if (funcall searchdir py-traceback-line-re nil t)
1529 (setq file (match-string 1)
1530 line (string-to-int (match-string 2)))))
1531 (if (and file line)
1532 (py-jump-to-exception file line)
1533 (error "%s of traceback" errwhere))))
1534
1535(defun py-down-exception (&optional bottom)
1536 "Go to the next line down in the traceback.
1537With optional \\[universal-argument], jump to the bottom (innermost)
1538exception in the exception stack."
1539 (interactive "P")
1540 (let* ((proc (get-process "Python"))
1541 (buffer (if proc "*Python*" py-output-buffer)))
1542 (if bottom
1543 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1544 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1545
1546(defun py-up-exception (&optional top)
1547 "Go to the previous line up in the traceback.
1548With optional \\[universal-argument], jump to the top (outermost)
1549exception in the exception stack."
1550 (interactive "P")
1551 (let* ((proc (get-process "Python"))
1552 (buffer (if proc "*Python*" py-output-buffer)))
1553 (if top
1554 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001555 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001556
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001557
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001558;; Electric deletion
1559(defun py-electric-backspace (arg)
1560 "Deletes preceding character or levels of indentation.
1561Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001562with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001563
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001564If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001565
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001566Otherwise, if point is at the leftmost non-whitespace character of a
1567line that is neither a continuation line nor a non-indenting comment
1568line, or if point is at the end of a blank line, this command reduces
1569the indentation to match that of the line that opened the current
1570block of code. The line that opened the block is displayed in the
1571echo area to help you keep track of where you are. With numeric arg,
1572outdents that many blocks (but not past column zero).
1573
1574Otherwise the preceding character is deleted, converting a tab to
1575spaces if needed so that only a single column position is deleted.
1576Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001577 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001578 (if (or (/= (current-indentation) (current-column))
1579 (bolp)
1580 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001581 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001582 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001583 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001584 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001585 ;; force non-blank so py-goto-block-up doesn't ignore it
1586 (insert-char ?* 1)
1587 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001588 (let ((base-indent 0) ; indentation of base line
1589 (base-text "") ; and text of base line
1590 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001591 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001592 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001593 (condition-case nil ; in case no enclosing block
1594 (progn
1595 (py-goto-block-up 'no-mark)
1596 (setq base-indent (current-indentation)
1597 base-text (py-suck-up-leading-text)
1598 base-found-p t))
1599 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001600 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001601 (delete-char 1) ; toss the dummy character
1602 (delete-horizontal-space)
1603 (indent-to base-indent)
1604 (if base-found-p
1605 (message "Closes block: %s" base-text)))))
1606
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001607
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001608(defun py-electric-delete (arg)
1609 "Deletes preceding or following character or levels of whitespace.
1610
1611The behavior of this function depends on the variable
1612`delete-key-deletes-forward'. If this variable is nil (or does not
1613exist, as in older Emacsen), then this function behaves identical to
1614\\[c-electric-backspace].
1615
1616If `delete-key-deletes-forward' is non-nil and is supported in your
1617Emacs, then deletion occurs in the forward direction, by calling the
1618function in `py-delete-function'."
1619 (interactive "*p")
1620 (if (and (boundp 'delete-key-deletes-forward)
1621 delete-key-deletes-forward)
1622 (funcall py-delete-function arg)
1623 ;; else
1624 (py-electric-backspace arg)))
1625
1626;; required for pending-del and delsel modes
1627(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1628(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1629(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1630(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1631
1632
1633
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001634(defun py-indent-line (&optional arg)
1635 "Fix the indentation of the current line according to Python rules.
1636With \\[universal-argument], ignore outdenting rules for block
1637closing statements (e.g. return, raise, break, continue, pass)
1638
1639This function is normally bound to `indent-line-function' so
1640\\[indent-for-tab-command] will call it."
1641 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001642 (let* ((ci (current-indentation))
1643 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001644 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001645 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001646 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001647 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001648 (if (/= ci need)
1649 (save-excursion
1650 (beginning-of-line)
1651 (delete-horizontal-space)
1652 (indent-to need)))
1653 (if move-to-indentation-p (back-to-indentation))))
1654
1655(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001656 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001657This is just `strives to' because correct indentation can't be computed
1658from scratch for Python code. In general, deletes the whitespace before
1659point, inserts a newline, and takes an educated guess as to how you want
1660the new line indented."
1661 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001662 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001663 (if (< ci (current-column)) ; if point beyond indentation
1664 (newline-and-indent)
1665 ;; else try to act like newline-and-indent "normally" acts
1666 (beginning-of-line)
1667 (insert-char ?\n 1)
1668 (move-to-column ci))))
1669
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001670(defun py-compute-indentation (honor-block-close-p)
1671 ;; implements all the rules for indentation computation. when
1672 ;; honor-block-close-p is non-nil, statements such as return, raise,
1673 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001674 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001675 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001676 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001677 (pps (parse-partial-sexp bod (point)))
1678 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001679 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001680 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001681 ((or (and (nth 3 pps) (nth 3 boipps))
1682 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001683 (save-excursion
1684 (if (not py-align-multiline-strings-p) 0
1685 ;; skip back over blank & non-indenting comment lines
1686 ;; note: will skip a blank or non-indenting comment line
1687 ;; that happens to be a continuation line too
1688 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1689 (back-to-indentation)
1690 (current-column))))
1691 ;; are we on a continuation line?
1692 ((py-continuation-line-p)
1693 (let ((startpos (point))
1694 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001695 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001696 (if open-bracket-pos
1697 (progn
1698 ;; align with first item in list; else a normal
1699 ;; indent beyond the line with the open bracket
1700 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1701 ;; is the first list item on the same line?
1702 (skip-chars-forward " \t")
1703 (if (null (memq (following-char) '(?\n ?# ?\\)))
1704 ; yes, so line up with it
1705 (current-column)
1706 ;; first list item on another line, or doesn't exist yet
1707 (forward-line 1)
1708 (while (and (< (point) startpos)
1709 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1710 (forward-line 1))
Barry Warsaw92166d91998-04-01 21:59:41 +00001711 (if (and (< (point) startpos)
1712 (/= startpos
1713 (save-excursion
1714 (goto-char (1+ open-bracket-pos))
Barry Warsaw77d1fce1998-04-16 20:04:59 +00001715 (forward-comment (point-max))
Barry Warsaw92166d91998-04-01 21:59:41 +00001716 (point))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001717 ;; again mimic the first list item
1718 (current-indentation)
1719 ;; else they're about to enter the first item
1720 (goto-char open-bracket-pos)
1721 (+ (current-indentation) py-indent-offset))))
1722
1723 ;; else on backslash continuation line
1724 (forward-line -1)
1725 (if (py-continuation-line-p) ; on at least 3rd line in block
1726 (current-indentation) ; so just continue the pattern
1727 ;; else started on 2nd line in block, so indent more.
1728 ;; if base line is an assignment with a start on a RHS,
1729 ;; indent to 2 beyond the leftmost "="; else skip first
1730 ;; chunk of non-whitespace characters on base line, + 1 more
1731 ;; column
1732 (end-of-line)
1733 (setq endpos (point) searching t)
1734 (back-to-indentation)
1735 (setq startpos (point))
1736 ;; look at all "=" from left to right, stopping at first
1737 ;; one not nested in a list or string
1738 (while searching
1739 (skip-chars-forward "^=" endpos)
1740 (if (= (point) endpos)
1741 (setq searching nil)
1742 (forward-char 1)
1743 (setq state (parse-partial-sexp startpos (point)))
1744 (if (and (zerop (car state)) ; not in a bracket
1745 (null (nth 3 state))) ; & not in a string
1746 (progn
1747 (setq searching nil) ; done searching in any case
1748 (setq found
1749 (not (or
1750 (eq (following-char) ?=)
1751 (memq (char-after (- (point) 2))
1752 '(?< ?> ?!)))))))))
1753 (if (or (not found) ; not an assignment
1754 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1755 (progn
1756 (goto-char startpos)
1757 (skip-chars-forward "^ \t\n")))
1758 (1+ (current-column))))))
1759
1760 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001761 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001762
Barry Warsawa7891711996-08-01 15:53:09 +00001763 ;; Dfn: "Indenting comment line". A line containing only a
1764 ;; comment, but which is treated like a statement for
1765 ;; indentation calculation purposes. Such lines are only
1766 ;; treated specially by the mode; they are not treated
1767 ;; specially by the Python interpreter.
1768
1769 ;; The rules for indenting comment lines are a line where:
1770 ;; - the first non-whitespace character is `#', and
1771 ;; - the character following the `#' is whitespace, and
1772 ;; - the line is outdented with respect to (i.e. to the left
1773 ;; of) the indentation of the preceding non-blank line.
1774
1775 ;; The first non-blank line following an indenting comment
1776 ;; line is given the same amount of indentation as the
1777 ;; indenting comment line.
1778
1779 ;; All other comment-only lines are ignored for indentation
1780 ;; purposes.
1781
1782 ;; Are we looking at a comment-only line which is *not* an
Barry Warsaw145ab1c1998-05-19 14:49:49 +00001783 ;; indenting comment line? If so, we assume that it's been
Barry Warsawa7891711996-08-01 15:53:09 +00001784 ;; placed at the desired indentation, so leave it alone.
1785 ;; Indenting comment lines are aligned as statements down
1786 ;; below.
1787 ((and (looking-at "[ \t]*#[^ \t\n]")
1788 ;; NOTE: this test will not be performed in older Emacsen
1789 (fboundp 'forward-comment)
1790 (<= (current-indentation)
1791 (save-excursion
1792 (forward-comment (- (point-max)))
1793 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001794 (current-indentation))
1795
1796 ;; else indentation based on that of the statement that
1797 ;; precedes us; use the first line of that statement to
1798 ;; establish the base, in case the user forced a non-std
1799 ;; indentation for the continuation lines (if any)
1800 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001801 ;; skip back over blank & non-indenting comment lines note:
1802 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001803 ;; happens to be a continuation line too. use fast Emacs 19
1804 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001805 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001806 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001807 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001808 (let (done)
1809 (while (not done)
1810 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1811 nil 'move)
1812 (setq done (or (eq py-honor-comment-indentation t)
1813 (bobp)
1814 (/= (following-char) ?#)
1815 (not (zerop (current-column)))))
1816 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001817 ;; if we landed inside a string, go to the beginning of that
1818 ;; string. this handles triple quoted, multi-line spanning
1819 ;; strings.
Barry Warsaw585f7331998-04-01 21:13:51 +00001820 (let* ((delim (nth 3 (parse-partial-sexp bod (point))))
Barry Warsawf64b4051998-02-12 16:52:14 +00001821 (skip (and delim (make-string 1 delim))))
1822 (when skip
1823 (save-excursion
1824 (py-safe (search-backward skip))
1825 (if (and (eq (char-before) delim)
1826 (eq (char-before (1- (point))) delim))
1827 (setq skip (make-string 3 delim))))
1828 ;; we're looking at a triple-quoted string
1829 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001830 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001831 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001832 (+ (current-indentation)
1833 (if (py-statement-opens-block-p)
1834 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001835 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001836 (- py-indent-offset)
1837 0)))
1838 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001839
1840(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001841 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001842By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001843`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001844Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001845`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001846their own buffer-local copy), both those currently existing and those
1847created later in the Emacs session.
1848
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001849Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001850There's no excuse for such foolishness, but sometimes you have to deal
1851with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001852`py-indent-offset' to what it thinks it was when they created the
1853mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001854
1855Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001856looking for a line that opens a block of code. `py-indent-offset' is
1857set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001858statement following it. If the search doesn't succeed going forward,
1859it's tried again going backward."
1860 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001861 (let (new-value
1862 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001863 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001864 (found nil)
1865 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001866 (py-goto-initial-line)
1867 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001868 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1869 (not (py-in-literal restart)))
1870 (setq restart (point))
1871 (py-goto-initial-line)
1872 (if (py-statement-opens-block-p)
1873 (setq found t)
1874 (goto-char restart))))
1875 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001876 (goto-char start)
1877 (py-goto-initial-line)
1878 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001879 (setq found (and
1880 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1881 (or (py-goto-initial-line) t) ; always true -- side effect
1882 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001883 (setq colon-indent (current-indentation)
1884 found (and found (zerop (py-next-statement 1)))
1885 new-value (- (current-indentation) colon-indent))
1886 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001887 (if (not found)
1888 (error "Sorry, couldn't guess a value for py-indent-offset")
1889 (funcall (if global 'kill-local-variable 'make-local-variable)
1890 'py-indent-offset)
1891 (setq py-indent-offset new-value)
1892 (message "%s value of py-indent-offset set to %d"
1893 (if global "Global" "Local")
1894 py-indent-offset))
1895 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001896
Barry Warsaw003932a1998-07-07 15:11:24 +00001897(defun py-comment-indent-function ()
1898 ;; A better value for comment-indent-function in Python source, this
1899 ;; actually works when filladapt is turned off. Without this, in
1900 ;; that case, comments which start in column zero cascade one
1901 ;; character to the right
1902 (save-excursion
1903 (beginning-of-line)
1904 (let ((eol (py-point 'eol)))
1905 (and comment-start-skip
1906 (re-search-forward comment-start-skip eol t)
1907 (setq eol (match-beginning 0)))
1908 (goto-char eol)
1909 (skip-chars-backward " \t")
1910 (max comment-column (+ (current-column) (if (bolp) 0 1)))
1911 )))
1912
1913
Barry Warsaw7ae77681994-12-12 20:38:05 +00001914(defun py-shift-region (start end count)
1915 (save-excursion
1916 (goto-char end) (beginning-of-line) (setq end (point))
1917 (goto-char start) (beginning-of-line) (setq start (point))
1918 (indent-rigidly start end count)))
1919
1920(defun py-shift-region-left (start end &optional count)
1921 "Shift region of Python code to the left.
1922The lines from the line containing the start of the current region up
1923to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001924shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001925
1926If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001927many columns. With no active region, outdent only the current line.
1928You cannot outdent the region if any line is already at column zero."
1929 (interactive
1930 (let ((p (point))
1931 (m (mark))
1932 (arg current-prefix-arg))
1933 (if m
1934 (list (min p m) (max p m) arg)
1935 (list p (save-excursion (forward-line 1) (point)) arg))))
1936 ;; if any line is at column zero, don't shift the region
1937 (save-excursion
1938 (goto-char start)
1939 (while (< (point) end)
1940 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001941 (if (and (zerop (current-column))
1942 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001943 (error "Region is at left edge."))
1944 (forward-line 1)))
1945 (py-shift-region start end (- (prefix-numeric-value
1946 (or count py-indent-offset))))
1947 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001948
1949(defun py-shift-region-right (start end &optional count)
1950 "Shift region of Python code to the right.
1951The lines from the line containing the start of the current region up
1952to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001953shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001954
1955If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001956many columns. With no active region, indent only the current line."
1957 (interactive
1958 (let ((p (point))
1959 (m (mark))
1960 (arg current-prefix-arg))
1961 (if m
1962 (list (min p m) (max p m) arg)
1963 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001964 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001965 (or count py-indent-offset)))
1966 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001967
1968(defun py-indent-region (start end &optional indent-offset)
1969 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001970
Barry Warsaw7ae77681994-12-12 20:38:05 +00001971The lines from the line containing the start of the current region up
1972to (but not including) the line containing the end of the region are
1973reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001974character in the first column, the first line is left alone and the
1975rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001976region is reindented with respect to the (closest code or indenting
1977comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001978
1979This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001980control structures are introduced or removed, or to reformat code
1981using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001982
1983If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001984the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001985used.
1986
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001987Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001988is called! This function does not compute proper indentation from
1989scratch (that's impossible in Python), it merely adjusts the existing
1990indentation to be correct in context.
1991
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001992Warning: This function really has no idea what to do with
1993non-indenting comment lines, and shifts them as if they were indenting
1994comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001995
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001996Special cases: whitespace is deleted from blank lines; continuation
1997lines are shifted by the same amount their initial line was shifted,
1998in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001999initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002000 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002001 (save-excursion
2002 (goto-char end) (beginning-of-line) (setq end (point-marker))
2003 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002004 (let ((py-indent-offset (prefix-numeric-value
2005 (or indent-offset py-indent-offset)))
2006 (indents '(-1)) ; stack of active indent levels
2007 (target-column 0) ; column to which to indent
2008 (base-shifted-by 0) ; amount last base line was shifted
2009 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002010 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002011 0))
2012 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002013 (while (< (point) end)
2014 (setq ci (current-indentation))
2015 ;; figure out appropriate target column
2016 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002017 ((or (eq (following-char) ?#) ; comment in column 1
2018 (looking-at "[ \t]*$")) ; entirely blank
2019 (setq target-column 0))
2020 ((py-continuation-line-p) ; shift relative to base line
2021 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002022 (t ; new base line
2023 (if (> ci (car indents)) ; going deeper; push it
2024 (setq indents (cons ci indents))
2025 ;; else we should have seen this indent before
2026 (setq indents (memq ci indents)) ; pop deeper indents
2027 (if (null indents)
2028 (error "Bad indentation in region, at line %d"
2029 (save-restriction
2030 (widen)
2031 (1+ (count-lines 1 (point)))))))
2032 (setq target-column (+ indent-base
2033 (* py-indent-offset
2034 (- (length indents) 2))))
2035 (setq base-shifted-by (- target-column ci))))
2036 ;; shift as needed
2037 (if (/= ci target-column)
2038 (progn
2039 (delete-horizontal-space)
2040 (indent-to target-column)))
2041 (forward-line 1))))
2042 (set-marker end nil))
2043
Barry Warsawa7891711996-08-01 15:53:09 +00002044(defun py-comment-region (beg end &optional arg)
2045 "Like `comment-region' but uses double hash (`#') comment starter."
2046 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00002047 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00002048 (comment-region beg end arg)))
2049
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002050
2051;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00002052(defun py-previous-statement (count)
2053 "Go to the start of previous Python statement.
2054If the statement at point is the i'th Python statement, goes to the
2055start of statement i-COUNT. If there is no such statement, goes to the
2056first statement. Returns count of statements left to move.
2057`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002058 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002059 (if (< count 0) (py-next-statement (- count))
2060 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002061 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002062 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002063 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002064 (> count 0)
2065 (zerop (forward-line -1))
2066 (py-goto-statement-at-or-above))
2067 (setq count (1- count)))
2068 (if (> count 0) (goto-char start)))
2069 count))
2070
2071(defun py-next-statement (count)
2072 "Go to the start of next Python statement.
2073If the statement at point is the i'th Python statement, goes to the
2074start of statement i+COUNT. If there is no such statement, goes to the
2075last statement. Returns count of statements left to move. `Statements'
2076do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002077 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00002078 (if (< count 0) (py-previous-statement (- count))
2079 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002080 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002081 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002082 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002083 (> count 0)
2084 (py-goto-statement-below))
2085 (setq count (1- count)))
2086 (if (> count 0) (goto-char start)))
2087 count))
2088
2089(defun py-goto-block-up (&optional nomark)
2090 "Move up to start of current block.
2091Go to the statement that starts the smallest enclosing block; roughly
2092speaking, this will be the closest preceding statement that ends with a
2093colon and is indented less than the statement you started on. If
2094successful, also sets the mark to the starting point.
2095
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002096`\\[py-mark-block]' can be used afterward to mark the whole code
2097block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002098
2099If called from a program, the mark will not be set if optional argument
2100NOMARK is not nil."
2101 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002102 (let ((start (point))
2103 (found nil)
2104 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002105 (py-goto-initial-line)
2106 ;; if on blank or non-indenting comment line, use the preceding stmt
2107 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2108 (progn
2109 (py-goto-statement-at-or-above)
2110 (setq found (py-statement-opens-block-p))))
2111 ;; search back for colon line indented less
2112 (setq initial-indent (current-indentation))
2113 (if (zerop initial-indent)
2114 ;; force fast exit
2115 (goto-char (point-min)))
2116 (while (not (or found (bobp)))
2117 (setq found
2118 (and
2119 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
2120 (or (py-goto-initial-line) t) ; always true -- side effect
2121 (< (current-indentation) initial-indent)
2122 (py-statement-opens-block-p))))
2123 (if found
2124 (progn
2125 (or nomark (push-mark start))
2126 (back-to-indentation))
2127 (goto-char start)
2128 (error "Enclosing block not found"))))
2129
Barry Warsawab0e86c1998-05-19 15:31:46 +00002130(defun py-beginning-of-def-or-class (&optional class count)
2131 "Move point to start of `def' or `class'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002132
2133Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsawab0e86c1998-05-19 15:31:46 +00002134arg, looks for a `class' instead. The docs below assume the `def'
2135case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002136Programmatically, if CLASS is `either', then moves to either `class'
2137or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002138
Barry Warsawab0e86c1998-05-19 15:31:46 +00002139When second optional argument is given programmatically, move to the
2140COUNTth start of `def'.
2141
2142If point is in a `def' statement already, and after the `d', simply
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002143moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002144
Barry Warsawab0e86c1998-05-19 15:31:46 +00002145Otherwise (i.e. when point is not in a `def' statement, or at or
2146before the `d' of a `def' statement), searches for the closest
2147preceding `def' statement, and leaves point at its start. If no such
2148statement can be found, leaves point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002149
Barry Warsawab0e86c1998-05-19 15:31:46 +00002150Returns t iff a `def' statement is found by these rules.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002151
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002152Note that doing this command repeatedly will take you closer to the
2153start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002154
Barry Warsaw7c29b231998-07-07 17:45:38 +00002155To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002156 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002157 (if (not count)
2158 (setq count 1))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002159 (let ((at-or-before-p (<= (current-column) (current-indentation)))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002160 (start-of-line (goto-char (py-point 'bol)))
2161 (start-of-stmt (goto-char (py-point 'bos)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002162 (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
2163 (class "^[ \t]*class\\>")
2164 (t "^[ \t]*def\\>")))
Barry Warsawab0e86c1998-05-19 15:31:46 +00002165 )
2166 ;; searching backward
2167 (if (and (< 0 count)
2168 (or (/= start-of-stmt start-of-line)
2169 (not at-or-before-p)))
2170 (end-of-line))
2171 ;; search forward
2172 (if (and (> 0 count)
2173 (zerop (current-column))
2174 (looking-at start-re))
2175 (end-of-line))
2176 (re-search-backward start-re nil 'move count)
2177 (goto-char (match-beginning 0))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002178
Barry Warsawab0e86c1998-05-19 15:31:46 +00002179;; Backwards compatibility
2180(defalias 'beginning-of-python-def-or-class 'py-beginning-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002181
Barry Warsawab0e86c1998-05-19 15:31:46 +00002182(defun py-end-of-def-or-class (&optional class count)
2183 "Move point beyond end of `def' or `class' body.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002184
Barry Warsawab0e86c1998-05-19 15:31:46 +00002185By default, looks for an appropriate `def'. If you supply a prefix
2186arg, looks for a `class' instead. The docs below assume the `def'
2187case; just substitute `class' for `def' for the other case.
Barry Warsaw7c29b231998-07-07 17:45:38 +00002188Programmatically, if CLASS is `either', then moves to either `class'
2189or `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002190
Barry Warsawab0e86c1998-05-19 15:31:46 +00002191When second optional argument is given programmatically, move to the
2192COUNTth end of `def'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002193
Barry Warsawab0e86c1998-05-19 15:31:46 +00002194If point is in a `def' statement already, this is the `def' we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002195
Barry Warsawab0e86c1998-05-19 15:31:46 +00002196Else, if the `def' found by `\\[py-beginning-of-def-or-class]'
2197contains the statement you started on, that's the `def' we use.
2198
2199Otherwise, we search forward for the closest following `def', and use that.
2200
2201If a `def' can be found by these rules, point is moved to the start of
2202the line immediately following the `def' block, and the position of the
2203start of the `def' is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002204
2205Else point is moved to the end of the buffer, and nil is returned.
2206
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002207Note that doing this command repeatedly will take you closer to the
2208end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002209
Barry Warsaw7c29b231998-07-07 17:45:38 +00002210To mark the current `def', see `\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002211 (interactive "P") ; raw prefix arg
Barry Warsawab0e86c1998-05-19 15:31:46 +00002212 (if (and count (/= count 1))
2213 (py-beginning-of-def-or-class (- 1 count)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002214 (let ((start (progn (py-goto-initial-line) (point)))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002215 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2216 (class "class")
2217 (t "def")))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002218 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002219 ;; move point to start of appropriate def/class
2220 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2221 (setq state 'at-beginning)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002222 ;; else see if py-beginning-of-def-or-class hits container
2223 (if (and (py-beginning-of-def-or-class class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002224 (progn (py-goto-beyond-block)
2225 (> (point) start)))
2226 (setq state 'at-end)
2227 ;; else search forward
2228 (goto-char start)
2229 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2230 (progn (setq state 'at-beginning)
2231 (beginning-of-line)))))
2232 (cond
2233 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2234 ((eq state 'at-end) t)
2235 ((eq state 'not-found) nil)
Barry Warsawab0e86c1998-05-19 15:31:46 +00002236 (t (error "internal error in py-end-of-def-or-class")))))
2237
2238;; Backwards compabitility
Barry Warsaw820273d1998-05-19 15:54:45 +00002239(defalias 'end-of-python-def-or-class 'py-end-of-def-or-class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002240
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002241
2242;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002243(defun py-mark-block (&optional extend just-move)
2244 "Mark following block of lines. With prefix arg, mark structure.
2245Easier to use than explain. It sets the region to an `interesting'
2246block of succeeding lines. If point is on a blank line, it goes down to
2247the next non-blank line. That will be the start of the region. The end
2248of the region depends on the kind of line at the start:
2249
2250 - If a comment, the region will include all succeeding comment lines up
2251 to (but not including) the next non-comment line (if any).
2252
2253 - Else if a prefix arg is given, and the line begins one of these
2254 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002255
2256 if elif else try except finally for while def class
2257
Barry Warsaw7ae77681994-12-12 20:38:05 +00002258 the region will be set to the body of the structure, including
2259 following blocks that `belong' to it, but excluding trailing blank
2260 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002261 and all (if any) of the following `except' and `finally' blocks
2262 that belong to the `try' structure will be in the region. Ditto
2263 for if/elif/else, for/else and while/else structures, and (a bit
2264 degenerate, since they're always one-block structures) def and
2265 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002266
2267 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002268 block (see list above), and the block is not a `one-liner' (i.e.,
2269 the statement ends with a colon, not with code), the region will
2270 include all succeeding lines up to (but not including) the next
2271 code statement (if any) that's indented no more than the starting
2272 line, except that trailing blank and comment lines are excluded.
2273 E.g., if the starting line begins a multi-statement `def'
2274 structure, the region will be set to the full function definition,
2275 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002276
2277 - Else the region will include all succeeding lines up to (but not
2278 including) the next blank line, or code or indenting-comment line
2279 indented strictly less than the starting line. Trailing indenting
2280 comment lines are included in this case, but not trailing blank
2281 lines.
2282
2283A msg identifying the location of the mark is displayed in the echo
2284area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2285
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002286If called from a program, optional argument EXTEND plays the role of
2287the prefix arg, and if optional argument JUST-MOVE is not nil, just
2288moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002289 (interactive "P") ; raw prefix arg
2290 (py-goto-initial-line)
2291 ;; skip over blank lines
2292 (while (and
2293 (looking-at "[ \t]*$") ; while blank line
2294 (not (eobp))) ; & somewhere to go
2295 (forward-line 1))
2296 (if (eobp)
2297 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002298 (let ((initial-pos (point))
2299 (initial-indent (current-indentation))
2300 last-pos ; position of last stmt in region
2301 (followers
2302 '((if elif else) (elif elif else) (else)
2303 (try except finally) (except except) (finally)
2304 (for else) (while else)
2305 (def) (class) ) )
2306 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002307
2308 (cond
2309 ;; if comment line, suck up the following comment lines
2310 ((looking-at "[ \t]*#")
2311 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2312 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2313 (setq last-pos (point)))
2314
2315 ;; else if line is a block line and EXTEND given, suck up
2316 ;; the whole structure
2317 ((and extend
2318 (setq first-symbol (py-suck-up-first-keyword) )
2319 (assq first-symbol followers))
2320 (while (and
2321 (or (py-goto-beyond-block) t) ; side effect
2322 (forward-line -1) ; side effect
2323 (setq last-pos (point)) ; side effect
2324 (py-goto-statement-below)
2325 (= (current-indentation) initial-indent)
2326 (setq next-symbol (py-suck-up-first-keyword))
2327 (memq next-symbol (cdr (assq first-symbol followers))))
2328 (setq first-symbol next-symbol)))
2329
2330 ;; else if line *opens* a block, search for next stmt indented <=
2331 ((py-statement-opens-block-p)
2332 (while (and
2333 (setq last-pos (point)) ; always true -- side effect
2334 (py-goto-statement-below)
2335 (> (current-indentation) initial-indent))
2336 nil))
2337
2338 ;; else plain code line; stop at next blank line, or stmt or
2339 ;; indenting comment line indented <
2340 (t
2341 (while (and
2342 (setq last-pos (point)) ; always true -- side effect
2343 (or (py-goto-beyond-final-line) t)
2344 (not (looking-at "[ \t]*$")) ; stop at blank line
2345 (or
2346 (>= (current-indentation) initial-indent)
2347 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2348 nil)))
2349
2350 ;; skip to end of last stmt
2351 (goto-char last-pos)
2352 (py-goto-beyond-final-line)
2353
2354 ;; set mark & display
2355 (if just-move
2356 () ; just return
2357 (push-mark (point) 'no-msg)
2358 (forward-line -1)
2359 (message "Mark set after: %s" (py-suck-up-leading-text))
2360 (goto-char initial-pos))))
2361
Barry Warsaw2518c671997-11-05 00:51:08 +00002362(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002363 "Set region to body of def (or class, with prefix arg) enclosing point.
2364Pushes the current mark, then point, on the mark ring (all language
2365modes do this, but although it's handy it's never documented ...).
2366
2367In most Emacs language modes, this function bears at least a
Barry Warsawab0e86c1998-05-19 15:31:46 +00002368hallucinogenic resemblance to `\\[py-end-of-def-or-class]' and
2369`\\[py-beginning-of-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002370
2371And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002372Turned out that was more confusing than useful: the `goto start' and
2373`goto end' commands are usually used to search through a file, and
2374people expect them to act a lot like `search backward' and `search
2375forward' string-search commands. But because Python `def' and `class'
2376can nest to arbitrary levels, finding the smallest def containing
2377point cannot be done via a simple backward search: the def containing
2378point may not be the closest preceding def, or even the closest
2379preceding def that's indented less. The fancy algorithm required is
2380appropriate for the usual uses of this `mark' command, but not for the
2381`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002382
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002383So the def marked by this command may not be the one either of the
2384`goto' commands find: If point is on a blank or non-indenting comment
2385line, moves back to start of the closest preceding code statement or
2386indenting comment line. If this is a `def' statement, that's the def
2387we use. Else searches for the smallest enclosing `def' block and uses
2388that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002389
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002390When an enclosing def is found: The mark is left immediately beyond
2391the last line of the def block. Point is left at the start of the
2392def, except that: if the def is preceded by a number of comment lines
2393followed by (at most) one optional blank line, point is left at the
2394start of the comments; else if the def is preceded by a blank line,
2395point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002396
2397The intent is to mark the containing def/class and its associated
2398documentation, to make moving and duplicating functions and classes
2399pleasant."
2400 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002401 (let ((start (point))
Barry Warsaw7c29b231998-07-07 17:45:38 +00002402 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2403 (class "class")
2404 (t "def"))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002405 (push-mark start)
2406 (if (not (py-go-up-tree-to-keyword which))
2407 (progn (goto-char start)
Barry Warsaw7c29b231998-07-07 17:45:38 +00002408 (error "Enclosing %s not found"
2409 (if (eq class 'either)
2410 "def or class"
2411 which)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002412 ;; else enclosing def/class found
2413 (setq start (point))
2414 (py-goto-beyond-block)
2415 (push-mark (point))
2416 (goto-char start)
2417 (if (zerop (forward-line -1)) ; if there is a preceding line
2418 (progn
2419 (if (looking-at "[ \t]*$") ; it's blank
2420 (setq start (point)) ; so reset start point
2421 (goto-char start)) ; else try again
2422 (if (zerop (forward-line -1))
2423 (if (looking-at "[ \t]*#") ; a comment
2424 ;; look back for non-comment line
2425 ;; tricky: note that the regexp matches a blank
2426 ;; line, cuz \n is in the 2nd character class
2427 (and
2428 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2429 (forward-line 1))
2430 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002431 (goto-char start)))))))
2432 (exchange-point-and-mark)
2433 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002434
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002435;; ripped from cc-mode
2436(defun py-forward-into-nomenclature (&optional arg)
2437 "Move forward to end of a nomenclature section or word.
2438With arg, to it arg times.
2439
2440A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2441 (interactive "p")
2442 (let ((case-fold-search nil))
2443 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002444 (re-search-forward
2445 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2446 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002447 (while (and (< arg 0)
2448 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002449 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002450 (point-min) 0))
2451 (forward-char 1)
2452 (setq arg (1+ arg)))))
2453 (py-keep-region-active))
2454
2455(defun py-backward-into-nomenclature (&optional arg)
2456 "Move backward to beginning of a nomenclature section or word.
2457With optional ARG, move that many times. If ARG is negative, move
2458forward.
2459
2460A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2461 (interactive "p")
2462 (py-forward-into-nomenclature (- arg))
2463 (py-keep-region-active))
2464
2465
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002466
2467;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002468
2469;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002470;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2471;; out of the right places, along with the keys they're on & current
2472;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002473(defun py-dump-help-string (str)
2474 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002475 (let ((locals (buffer-local-variables))
2476 funckind funcname func funcdoc
2477 (start 0) mstart end
2478 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002479 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2480 (setq mstart (match-beginning 0) end (match-end 0)
2481 funckind (substring str (match-beginning 1) (match-end 1))
2482 funcname (substring str (match-beginning 2) (match-end 2))
2483 func (intern funcname))
2484 (princ (substitute-command-keys (substring str start mstart)))
2485 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002486 ((equal funckind "c") ; command
2487 (setq funcdoc (documentation func)
2488 keys (concat
2489 "Key(s): "
2490 (mapconcat 'key-description
2491 (where-is-internal func py-mode-map)
2492 ", "))))
2493 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002494 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002495 keys (if (assq func locals)
2496 (concat
2497 "Local/Global values: "
2498 (prin1-to-string (symbol-value func))
2499 " / "
2500 (prin1-to-string (default-value func)))
2501 (concat
2502 "Value: "
2503 (prin1-to-string (symbol-value func))))))
2504 (t ; unexpected
2505 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002506 (princ (format "\n-> %s:\t%s\t%s\n\n"
2507 (if (equal funckind "c") "Command" "Variable")
2508 funcname keys))
2509 (princ funcdoc)
2510 (terpri)
2511 (setq start end))
2512 (princ (substitute-command-keys (substring str start))))
2513 (print-help-return-message)))
2514
2515(defun py-describe-mode ()
2516 "Dump long form of Python-mode docs."
2517 (interactive)
2518 (py-dump-help-string "Major mode for editing Python files.
2519Knows about Python indentation, tokens, comments and continuation lines.
2520Paragraphs are separated by blank lines only.
2521
2522Major sections below begin with the string `@'; specific function and
2523variable docs begin with `->'.
2524
2525@EXECUTING PYTHON CODE
2526
Barry Warsaw820273d1998-05-19 15:54:45 +00002527\\[py-execute-import-or-reload]\timports or reloads the file in the Python interpreter
Barry Warsaw7ae77681994-12-12 20:38:05 +00002528\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2529\\[py-execute-region]\tsends the current region
Barry Warsaw820273d1998-05-19 15:54:45 +00002530\\[py-execute-def-or-class]\tsends the current function or class definition
2531\\[py-execute-string]\tsends an arbitrary string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002532\\[py-shell]\tstarts a Python interpreter window; this will be used by
Barry Warsaw820273d1998-05-19 15:54:45 +00002533\tsubsequent Python execution commands
2534%c:py-execute-import-or-reload
Barry Warsaw7ae77681994-12-12 20:38:05 +00002535%c:py-execute-buffer
2536%c:py-execute-region
Barry Warsaw820273d1998-05-19 15:54:45 +00002537%c:py-execute-def-or-class
2538%c:py-execute-string
Barry Warsaw7ae77681994-12-12 20:38:05 +00002539%c:py-shell
2540
2541@VARIABLES
2542
2543py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002544py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002545
2546py-python-command\tshell command to invoke Python interpreter
2547py-scroll-process-buffer\talways scroll Python process buffer
2548py-temp-directory\tdirectory used for temp files (if needed)
2549
2550py-beep-if-tab-change\tring the bell if tab-width is changed
2551%v:py-indent-offset
2552%v:py-block-comment-prefix
2553%v:py-python-command
2554%v:py-scroll-process-buffer
2555%v:py-temp-directory
2556%v:py-beep-if-tab-change
2557
2558@KINDS OF LINES
2559
2560Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002561preceding line ends with a backslash that's not part of a comment, or
2562the paren/bracket/brace nesting level at the start of the line is
2563non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002564
2565An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002566possibly blanks or tabs), a `comment line' (leftmost non-blank
2567character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002568
2569Comment Lines
2570
2571Although all comment lines are treated alike by Python, Python mode
2572recognizes two kinds that act differently with respect to indentation.
2573
2574An `indenting comment line' is a comment line with a blank, tab or
2575nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002576treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002577indenting comment line will be indented like the comment line. All
2578other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002579following the initial `#') are `non-indenting comment lines', and
2580their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002581
2582Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002583whenever possible. Non-indenting comment lines are useful in cases
2584like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002585
2586\ta = b # a very wordy single-line comment that ends up being
2587\t #... continued onto another line
2588
2589\tif a == b:
2590##\t\tprint 'panic!' # old code we've `commented out'
2591\t\treturn a
2592
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002593Since the `#...' and `##' comment lines have a non-whitespace
2594character following the initial `#', Python mode ignores them when
2595computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002596
2597Continuation Lines and Statements
2598
2599The Python-mode commands generally work on statements instead of on
2600individual lines, where a `statement' is a comment or blank line, or a
2601code line and all of its following continuation lines (if any)
2602considered as a single logical unit. The commands in this mode
2603generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002604statement containing point, even if point happens to be in the middle
2605of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002606
2607
2608@INDENTATION
2609
2610Primarily for entering new code:
2611\t\\[indent-for-tab-command]\t indent line appropriately
2612\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002613\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002614
2615Primarily for reindenting existing code:
2616\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2617\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2618
2619\t\\[py-indent-region]\t reindent region to match its context
2620\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2621\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2622
2623Unlike most programming languages, Python uses indentation, and only
2624indentation, to specify block structure. Hence the indentation supplied
2625automatically by Python-mode is just an educated guess: only you know
2626the block structure you intend, so only you can supply correct
2627indentation.
2628
2629The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2630the indentation of preceding statements. E.g., assuming
2631py-indent-offset is 4, after you enter
2632\tif a > 0: \\[py-newline-and-indent]
2633the cursor will be moved to the position of the `_' (_ is not a
2634character in the file, it's just used here to indicate the location of
2635the cursor):
2636\tif a > 0:
2637\t _
2638If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2639to
2640\tif a > 0:
2641\t c = d
2642\t _
2643Python-mode cannot know whether that's what you intended, or whether
2644\tif a > 0:
2645\t c = d
2646\t_
2647was your intent. In general, Python-mode either reproduces the
2648indentation of the (closest code or indenting-comment) preceding
2649statement, or adds an extra py-indent-offset blanks if the preceding
2650statement has `:' as its last significant (non-whitespace and non-
2651comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002652\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002653
2654Continuation lines are given extra indentation. If you don't like the
2655suggested indentation, change it to something you do like, and Python-
2656mode will strive to indent later lines of the statement in the same way.
2657
2658If a line is a continuation line by virtue of being in an unclosed
2659paren/bracket/brace structure (`list', for short), the suggested
2660indentation depends on whether the current line contains the first item
2661in the list. If it does, it's indented py-indent-offset columns beyond
2662the indentation of the line containing the open bracket. If you don't
2663like that, change it by hand. The remaining items in the list will mimic
2664whatever indentation you give to the first item.
2665
2666If a line is a continuation line because the line preceding it ends with
2667a backslash, the third and following lines of the statement inherit their
2668indentation from the line preceding them. The indentation of the second
2669line in the statement depends on the form of the first (base) line: if
2670the base line is an assignment statement with anything more interesting
2671than the backslash following the leftmost assigning `=', the second line
2672is indented two columns beyond that `='. Else it's indented to two
2673columns beyond the leftmost solid chunk of non-whitespace characters on
2674the base line.
2675
2676Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2677repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2678structure you intend.
2679%c:indent-for-tab-command
2680%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002681%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002682
2683
2684The next function may be handy when editing code you didn't write:
2685%c:py-guess-indent-offset
2686
2687
2688The remaining `indent' functions apply to a region of Python code. They
2689assume the block structure (equals indentation, in Python) of the region
2690is correct, and alter the indentation in various ways while preserving
2691the block structure:
2692%c:py-indent-region
2693%c:py-shift-region-left
2694%c:py-shift-region-right
2695
2696@MARKING & MANIPULATING REGIONS OF CODE
2697
2698\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002699\\[py-mark-def-or-class]\t mark smallest enclosing def
2700\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002701\\[comment-region]\t comment out region of code
2702\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002703%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002704%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002705%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002706
2707@MOVING POINT
2708
2709\\[py-previous-statement]\t move to statement preceding point
2710\\[py-next-statement]\t move to statement following point
2711\\[py-goto-block-up]\t move up to start of current block
Barry Warsawab0e86c1998-05-19 15:31:46 +00002712\\[py-beginning-of-def-or-class]\t move to start of def
2713\\[universal-argument] \\[py-beginning-of-def-or-class]\t move to start of class
2714\\[py-end-of-def-or-class]\t move to end of def
2715\\[universal-argument] \\[py-end-of-def-or-class]\t move to end of class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002716
2717The first two move to one statement beyond the statement that contains
2718point. A numeric prefix argument tells them to move that many
2719statements instead. Blank lines, comment lines, and continuation lines
2720do not count as `statements' for these commands. So, e.g., you can go
2721to the first code statement in a file by entering
2722\t\\[beginning-of-buffer]\t to move to the top of the file
2723\t\\[py-next-statement]\t to skip over initial comments and blank lines
2724Or do `\\[py-previous-statement]' with a huge prefix argument.
2725%c:py-previous-statement
2726%c:py-next-statement
2727%c:py-goto-block-up
Barry Warsawab0e86c1998-05-19 15:31:46 +00002728%c:py-beginning-of-def-or-class
2729%c:py-end-of-def-or-class
Barry Warsaw7ae77681994-12-12 20:38:05 +00002730
2731@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2732
2733`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2734
2735`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2736overall class and def structure of a module.
2737
2738`\\[back-to-indentation]' moves point to a line's first non-blank character.
2739
2740`\\[indent-relative]' is handy for creating odd indentation.
2741
2742@OTHER EMACS HINTS
2743
2744If you don't like the default value of a variable, change its value to
2745whatever you do like by putting a `setq' line in your .emacs file.
2746E.g., to set the indentation increment to 4, put this line in your
2747.emacs:
2748\t(setq py-indent-offset 4)
2749To see the value of a variable, do `\\[describe-variable]' and enter the variable
2750name at the prompt.
2751
2752When entering a key sequence like `C-c C-n', it is not necessary to
2753release the CONTROL key after doing the `C-c' part -- it suffices to
2754press the CONTROL key, press and release `c' (while still holding down
2755CONTROL), press and release `n' (while still holding down CONTROL), &
2756then release CONTROL.
2757
2758Entering Python mode calls with no arguments the value of the variable
2759`python-mode-hook', if that value exists and is not nil; for backward
2760compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2761the Elisp manual for details.
2762
2763Obscure: When python-mode is first loaded, it looks for all bindings
2764to newline-and-indent in the global keymap, and shadows them with
2765local bindings to py-newline-and-indent."))
2766
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002767
2768;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002769(defvar py-parse-state-re
2770 (concat
2771 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2772 "\\|"
2773 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002774
Barry Warsaw7ae77681994-12-12 20:38:05 +00002775;; returns the parse state at point (see parse-partial-sexp docs)
2776(defun py-parse-state ()
2777 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002778 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002779 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002780 (while (not done)
2781 ;; back up to the first preceding line (if any; else start of
2782 ;; buffer) that begins with a popular Python keyword, or a
2783 ;; non- whitespace and non-comment character. These are good
2784 ;; places to start parsing to see whether where we started is
2785 ;; at a non-zero nesting level. It may be slow for people who
2786 ;; write huge code blocks or huge lists ... tough beans.
2787 (re-search-backward py-parse-state-re nil 'move)
2788 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002789 ;; In XEmacs, we have a much better way to test for whether
2790 ;; we're in a triple-quoted string or not. Emacs does not
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002791 ;; have this built-in function, which is its loss because
Barry Warsawf64b4051998-02-12 16:52:14 +00002792 ;; without scanning from the beginning of the buffer, there's
2793 ;; no accurate way to determine this otherwise.
2794 (if (not (fboundp 'buffer-syntactic-context))
2795 ;; Emacs
Barry Warsaw585f7331998-04-01 21:13:51 +00002796 (progn
2797 (save-excursion (setq pps (parse-partial-sexp (point) here)))
Barry Warsawf64b4051998-02-12 16:52:14 +00002798 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002799 (setq done (or (not (nth 3 pps))
2800 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002801 ;; XEmacs
2802 (setq done (or (not (buffer-syntactic-context))
2803 (bobp)))
2804 (when done
2805 (setq pps (parse-partial-sexp (point) here)))
2806 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002807 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002808
2809;; if point is at a non-zero nesting level, returns the number of the
2810;; character that opens the smallest enclosing unclosed list; else
2811;; returns nil.
2812(defun py-nesting-level ()
Barry Warsawf64b4051998-02-12 16:52:14 +00002813 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002814 (if (zerop (car status))
2815 nil ; not in a nest
2816 (car (cdr status))))) ; char# of open bracket
2817
2818;; t iff preceding line ends with backslash that's not in a comment
2819(defun py-backslash-continuation-line-p ()
2820 (save-excursion
2821 (beginning-of-line)
2822 (and
2823 ;; use a cheap test first to avoid the regexp if possible
2824 ;; use 'eq' because char-after may return nil
2825 (eq (char-after (- (point) 2)) ?\\ )
2826 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002827 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002828 (looking-at py-continued-re))))
2829
2830;; t iff current line is a continuation line
2831(defun py-continuation-line-p ()
2832 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002833 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002834 (or (py-backslash-continuation-line-p)
2835 (py-nesting-level))))
2836
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002837;; go to initial line of current statement; usually this is the line
2838;; we're on, but if we're on the 2nd or following lines of a
2839;; continuation block, we need to go up to the first line of the
2840;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002841;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002842;; Tricky: We want to avoid quadratic-time behavior for long continued
2843;; blocks, whether of the backslash or open-bracket varieties, or a
2844;; mix of the two. The following manages to do that in the usual
2845;; cases.
Barry Warsawc210e691998-01-20 22:52:56 +00002846;;
2847;; Also, if we're sitting inside a triple quoted string, this will
2848;; drop us at the line that begins the string.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002849(defun py-goto-initial-line ()
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002850 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002851 (while (py-continuation-line-p)
2852 (beginning-of-line)
2853 (if (py-backslash-continuation-line-p)
2854 (while (py-backslash-continuation-line-p)
2855 (forward-line -1))
2856 ;; else zip out of nested brackets/braces/parens
2857 (while (setq open-bracket-pos (py-nesting-level))
2858 (goto-char open-bracket-pos)))))
2859 (beginning-of-line))
2860
2861;; go to point right beyond final line of current statement; usually
2862;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002863;; statement we need to skip over the continuation lines. Tricky:
2864;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002865(defun py-goto-beyond-final-line ()
Barry Warsaw7c29b231998-07-07 17:45:38 +00002866 ;; Not quite the right solution, but deals with multiline doc strings
Barry Warsaw751f4931998-05-19 16:06:21 +00002867 (if (looking-at (concat "[ \t]*\\(" py-stringlit-re "\\)"))
2868 (goto-char (match-end 0)))
2869 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +00002870 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002871 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002872 (while (and (py-continuation-line-p)
2873 (not (eobp)))
2874 ;; skip over the backslash flavor
2875 (while (and (py-backslash-continuation-line-p)
2876 (not (eobp)))
2877 (forward-line 1))
2878 ;; if in nest, zip to the end of the nest
2879 (setq state (py-parse-state))
2880 (if (and (not (zerop (car state)))
2881 (not (eobp)))
2882 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002883 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002884 (forward-line 1))))))
2885
2886;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002887;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002888(defun py-statement-opens-block-p ()
2889 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002890 (let ((start (point))
2891 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2892 (searching t)
2893 (answer nil)
2894 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002895 (goto-char start)
2896 (while searching
2897 ;; look for a colon with nothing after it except whitespace, and
2898 ;; maybe a comment
2899 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2900 finish t)
2901 (if (eq (point) finish) ; note: no `else' clause; just
2902 ; keep searching if we're not at
2903 ; the end yet
2904 ;; sure looks like it opens a block -- but it might
2905 ;; be in a comment
2906 (progn
2907 (setq searching nil) ; search is done either way
2908 (setq state (parse-partial-sexp start
2909 (match-beginning 0)))
2910 (setq answer (not (nth 4 state)))))
2911 ;; search failed: couldn't find another interesting colon
2912 (setq searching nil)))
2913 answer)))
2914
Barry Warsawf831d811996-07-31 20:42:59 +00002915(defun py-statement-closes-block-p ()
2916 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002917 ;; starts with `return', `raise', `break', `continue', and `pass'.
2918 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002919 (let ((here (point)))
2920 (back-to-indentation)
2921 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002922 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002923 (goto-char here))))
2924
Barry Warsaw7ae77681994-12-12 20:38:05 +00002925;; go to point right beyond final line of block begun by the current
2926;; line. This is the same as where py-goto-beyond-final-line goes
2927;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002928;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002929(defun py-goto-beyond-block ()
2930 (if (py-statement-opens-block-p)
2931 (py-mark-block nil 'just-move)
2932 (py-goto-beyond-final-line)))
2933
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002934;; Go to start of first statement (not blank or comment or
2935;; continuation line) at or preceding point. Returns t if there is
2936;; one, else nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002937(defun py-goto-statement-at-or-above ()
2938 (py-goto-initial-line)
2939 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002940 ;; skip back over blank & comment lines
2941 ;; note: will skip a blank or comment line that happens to be
2942 ;; a continuation line too
2943 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2944 (progn (py-goto-initial-line) t)
2945 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002946 t))
2947
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002948;; Go to start of first statement (not blank or comment or
2949;; continuation line) following the statement containing point.
2950;; Returns t if there is one, else nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002951(defun py-goto-statement-below ()
2952 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002953 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002954 (py-goto-beyond-final-line)
2955 (while (and
2956 (looking-at py-blank-or-comment-re)
2957 (not (eobp)))
2958 (forward-line 1))
2959 (if (eobp)
2960 (progn (goto-char start) nil)
2961 t)))
2962
Barry Warsaw145ab1c1998-05-19 14:49:49 +00002963;; Go to start of statement, at or preceding point, starting with
Barry Warsaw7c29b231998-07-07 17:45:38 +00002964;; keyword (regular expression) KEY. Skips blank lines and
2965;; non-indenting comments upward first. If that statement starts with
2966;; KEY, then stop. Otherwise go back to first enclosing block
2967;; starting with KEY. If successful, leaves point at the start of the
2968;; KEY line & returns t. Else leaves point at an undefined place &
2969;; returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002970(defun py-go-up-tree-to-keyword (key)
2971 ;; skip blanks and non-indenting #
2972 (py-goto-initial-line)
2973 (while (and
2974 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2975 (zerop (forward-line -1))) ; go back
2976 nil)
2977 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002978 (let* ((re (concat "[ \t]*" key "\\b"))
2979 (case-fold-search nil) ; let* so looking-at sees this
2980 (found (looking-at re))
2981 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002982 (while (not (or found dead))
2983 (condition-case nil ; in case no enclosing block
2984 (py-goto-block-up 'no-mark)
2985 (error (setq dead t)))
2986 (or dead (setq found (looking-at re))))
2987 (beginning-of-line)
2988 found))
2989
2990;; return string in buffer from start of indentation to end of line;
2991;; prefix "..." if leading whitespace was skipped
2992(defun py-suck-up-leading-text ()
2993 (save-excursion
2994 (back-to-indentation)
2995 (concat
2996 (if (bolp) "" "...")
2997 (buffer-substring (point) (progn (end-of-line) (point))))))
2998
2999;; assuming point at bolp, return first keyword ([a-z]+) on the line,
3000;; as a Lisp symbol; return nil if none
3001(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003002 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00003003 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
3004 (intern (buffer-substring (match-beginning 1) (match-end 1)))
3005 nil)))
3006
Barry Warsawb3e81d51996-09-04 15:12:42 +00003007(defun py-current-defun ()
3008 ;; tell add-log.el how to find the current function/method/variable
3009 (save-excursion
3010 (if (re-search-backward py-defun-start-re nil t)
3011 (or (match-string 3)
3012 (let ((method (match-string 2)))
3013 (if (and (not (zerop (length (match-string 1))))
3014 (re-search-backward py-class-start-re nil t))
3015 (concat (match-string 1) "." method)
3016 method)))
3017 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003018
3019
Barry Warsawfec75d61995-07-05 23:26:15 +00003020(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00003021 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003022
Barry Warsaw850437a1995-03-08 21:50:28 +00003023(defun py-version ()
3024 "Echo the current version of `python-mode' in the minibuffer."
3025 (interactive)
3026 (message "Using `python-mode' version %s" py-version)
3027 (py-keep-region-active))
3028
3029;; only works under Emacs 19
3030;(eval-when-compile
3031; (require 'reporter))
3032
3033(defun py-submit-bug-report (enhancement-p)
3034 "Submit via mail a bug report on `python-mode'.
3035With \\[universal-argument] just submit an enhancement request."
3036 (interactive
3037 (list (not (y-or-n-p
3038 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00003039 (let ((reporter-prompt-for-summary-p (if enhancement-p
3040 "(Very) brief summary: "
3041 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00003042 (require 'reporter)
3043 (reporter-submit-bug-report
3044 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00003045 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00003046 ;; varlist
3047 (if enhancement-p nil
3048 '(py-python-command
3049 py-indent-offset
3050 py-block-comment-prefix
3051 py-scroll-process-buffer
3052 py-temp-directory
3053 py-beep-if-tab-change))
3054 nil ;pre-hooks
3055 nil ;post-hooks
3056 "Dear Barry,") ;salutation
3057 (if enhancement-p nil
3058 (set-mark (point))
3059 (insert
3060"Please replace this text with a sufficiently large code sample\n\
3061and an exact recipe so that I can reproduce your problem. Failure\n\
3062to do so may mean a greater delay in fixing your bug.\n\n")
3063 (exchange-point-and-mark)
3064 (py-keep-region-active))))
3065
3066
Barry Warsaw47384781997-11-26 05:27:45 +00003067(defun py-kill-emacs-hook ()
3068 (mapcar #'(lambda (filename)
3069 (py-safe (delete-file filename)))
3070 py-file-queue))
3071
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003072;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00003073(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00003074
3075
3076
3077(provide 'python-mode)
3078;;; python-mode.el ends here