blob: bc7e53fee4ab1a8d1f8439f22b493d756a49cd7f [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 Warsaw2ccda501997-01-30 19:50:39 +00005;; Author: 1995-1997 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 Warsaw5e21cb01997-11-05 18:41:11 +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
67;; Please see <http://www.python.org/ftp/emacs/pmdetails.html> for the
68;; 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)
111 (require 'custom)
112 ;; Stock Emacs 19.34 has a broken/old Custom library that does more
113 ;; harm than good
114 (or (fboundp 'defcustom)
115 (error "STOP! STOP! STOP! STOP!
116
117The Custom library was not found or is out of date. A more current
118version is required. Please download and install the latest version
119of the Custom library from:
120
121 <http://www.dina.kvl.dk/~abraham/custom/>
122
123See the Python Mode home page for details:
124
125 <http://www.python.org/ftp/emacs/>
126")))
127
Barry Warsawc72c11c1997-08-09 06:42:08 +0000128
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000129
130;; user definable variables
131;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000132
Barry Warsawc72c11c1997-08-09 06:42:08 +0000133(defgroup python nil
134 "Support for the Python programming language, <http://www.python.org/>"
135 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000136
Barry Warsawc72c11c1997-08-09 06:42:08 +0000137(defcustom py-python-command "python"
138 "*Shell command used to start Python interpreter."
139 :type 'string
140 :group 'python)
141
142(defcustom py-indent-offset 4
143 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000144Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +0000145when you're editing someone else's Python code."
146 :type 'integer
147 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000148
Barry Warsawc72c11c1997-08-09 06:42:08 +0000149(defcustom py-align-multiline-strings-p t
150 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000151When this flag is non-nil, continuation lines are lined up under the
152preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000153lines are aligned to column zero."
154 :type '(choice (const :tag "Align under preceding line" t)
155 (const :tag "Align to column zero" nil))
156 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000157
Barry Warsawc72c11c1997-08-09 06:42:08 +0000158(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000159 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000160This should follow the convention for non-indenting comment lines so
161that the indentation commands won't get confused (i.e., the string
162should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000163`...' is arbitrary)."
164 :type 'string
165 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000166
Barry Warsawc72c11c1997-08-09 06:42:08 +0000167(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000168 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000169
Barry Warsaw6d627751996-03-06 18:41:38 +0000170When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000171if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000172
173When t, lines that begin with a single `#' are a hint to subsequent
174line indentation. If the previous line is such a comment line (as
175opposed to one that starts with `py-block-comment-prefix'), then it's
176indentation is used as a hint for this line's indentation. Lines that
177begin with `py-block-comment-prefix' are ignored for indentation
178purposes.
179
180When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000181indentation hints, unless the comment character is in column zero."
182 :type '(choice
183 (const :tag "Skip all comment lines (fast)" nil)
184 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000185 (const :tag "Single # `sets' indentation except at column zero"
186 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000187 )
188 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000189
Barry Warsawc72c11c1997-08-09 06:42:08 +0000190(defcustom py-scroll-process-buffer t
Barry Warsaw7ae77681994-12-12 20:38:05 +0000191 "*Scroll Python process buffer as output arrives.
192If nil, the Python process buffer acts, with respect to scrolling, like
193Shell-mode buffers normally act. This is surprisingly complicated and
194so won't be explained here; in fact, you can't get the whole story
195without studying the Emacs C code.
196
197If non-nil, the behavior is different in two respects (which are
198slightly inaccurate in the interest of brevity):
199
200 - If the buffer is in a window, and you left point at its end, the
201 window will scroll as new output arrives, and point will move to the
202 buffer's end, even if the window is not the selected window (that
203 being the one the cursor is in). The usual behavior for shell-mode
204 windows is not to scroll, and to leave point where it was, if the
205 buffer is in a window other than the selected window.
206
207 - If the buffer is not visible in any window, and you left point at
208 its end, the buffer will be popped into a window as soon as more
209 output arrives. This is handy if you have a long-running
210 computation and don't want to tie up screen area waiting for the
211 output. The usual behavior for a shell-mode buffer is to stay
212 invisible until you explicitly visit it.
213
214Note the `and if you left point at its end' clauses in both of the
215above: you can `turn off' the special behaviors while output is in
216progress, by visiting the Python buffer and moving point to anywhere
217besides the end. Then the buffer won't scroll, point will remain where
218you leave it, and if you hide the buffer it will stay hidden until you
219visit it again. You can enable and disable the special behaviors as
220often as you like, while output is in progress, by (respectively) moving
221point to, or away from, the end of the buffer.
222
223Warning: If you expect a large amount of output, you'll probably be
224happier setting this option to nil.
225
226Obscure: `End of buffer' above should really say `at or beyond the
227process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000228told <grin>."
229 :type 'boolean
230 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000231
Barry Warsaw516b6201997-08-09 06:43:20 +0000232(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000233 (let ((ok '(lambda (x)
234 (and x
235 (setq x (expand-file-name x)) ; always true
236 (file-directory-p x)
237 (file-writable-p x)
238 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000239 (or (funcall ok (getenv "TMPDIR"))
240 (funcall ok "/usr/tmp")
241 (funcall ok "/tmp")
242 (funcall ok ".")
243 (error
244 "Couldn't find a usable temp directory -- set py-temp-directory")))
245 "*Directory used for temp files created by a *Python* process.
246By default, the first directory from this list that exists and that you
247can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000248/usr/tmp, /tmp, or the current directory."
249 :type 'string
250 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000251
Barry Warsaw516b6201997-08-09 06:43:20 +0000252(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000253 "*Ring the bell if tab-width is changed.
254If a comment of the form
255
256 \t# vi:set tabsize=<number>:
257
258is found before the first code line when the file is entered, and the
259current value of (the general Emacs variable) `tab-width' does not
260equal <number>, `tab-width' is set to <number>, a message saying so is
261displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000262the Emacs bell is also rung as a warning."
263 :type 'boolean
264 :group 'python)
265
Barry Warsaw9981d221997-12-03 05:25:48 +0000266(defcustom py-jump-on-exception t
267 "*Jump to innermost exception frame in *Python Output* buffer.
268When this variable is non-nil and ane exception occurs when running
269Python code synchronously in a subprocess, jump immediately to the
270source code of the innermost frame.")
271
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000272(defcustom py-backspace-function 'backward-delete-char-untabify
273 "*Function called by `py-electric-backspace' when deleting backwards."
274 :type 'function
275 :group 'python)
276
277(defcustom py-delete-function 'delete-char
278 "*Function called by `py-electric-delete' when deleting forwards."
279 :type 'function
280 :group 'python)
281
282
Barry Warsawc72c11c1997-08-09 06:42:08 +0000283
284;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
285;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
286
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000287(defconst py-emacs-features
288 (let (features)
289 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
290 ;; the same string.
291 (let ((tmp1 (make-temp-name ""))
292 (tmp2 (make-temp-name "")))
293 (if (string-equal tmp1 tmp2)
294 (push 'broken-temp-names features)))
295 ;; return the features
296 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000297 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000298There are many flavors of Emacs out there, with different levels of
299support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000300
Barry Warsawfb07f401997-02-24 03:37:22 +0000301(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000302 (let ((kw1 (mapconcat 'identity
303 '("and" "assert" "break" "class"
304 "continue" "def" "del" "elif"
305 "else" "except" "exec" "for"
306 "from" "global" "if" "import"
307 "in" "is" "lambda" "not"
308 "or" "pass" "print" "raise"
309 "return" "while"
310 )
311 "\\|"))
312 (kw2 (mapconcat 'identity
313 '("else:" "except:" "finally:" "try:")
314 "\\|"))
315 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000316 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000317 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000318 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
319 ;; block introducing keywords with immediately following colons.
320 ;; Yes "except" is in both lists.
321 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000322 ;; classes
323 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
324 1 font-lock-type-face)
325 ;; functions
326 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
327 1 font-lock-function-name-face)
328 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000329 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000330(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
331
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000332
Barry Warsaw81437461996-08-01 19:48:02 +0000333(defvar imenu-example--python-show-method-args-p nil
334 "*Controls echoing of arguments of functions & methods in the imenu buffer.
335When non-nil, arguments are printed.")
336
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000337(make-variable-buffer-local 'py-indent-offset)
338
Barry Warsawe467bfb1997-11-26 05:40:58 +0000339;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000340(defvar py-file-queue nil
341 "Queue of Python temp files awaiting execution.
342Currently-active file is at the head of the list.")
343
Barry Warsawc72c11c1997-08-09 06:42:08 +0000344
345;; Constants
346
347;; Regexp matching a Python string literal
348(defconst py-stringlit-re
349 (concat
350 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
351 "\\|" ; or
352 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
353
354;; Regexp matching Python lines that are continued via backslash.
355;; This is tricky because a trailing backslash does not mean
356;; continuation if it's in a comment
357(defconst py-continued-re
358 (concat
359 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
360 "\\\\$"))
361
362;; Regexp matching blank or comment lines.
363(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
364
365;; Regexp matching clauses to be outdented one level.
366(defconst py-outdent-re
367 (concat "\\(" (mapconcat 'identity
368 '("else:"
369 "except\\(\\s +.*\\)?:"
370 "finally:"
371 "elif\\s +.*:")
372 "\\|")
373 "\\)"))
374
375
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000376;; Regexp matching keywords which typically close a block
377(defconst py-block-closing-keywords-re
378 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
379
Barry Warsawc72c11c1997-08-09 06:42:08 +0000380;; Regexp matching lines to not outdent after.
381(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000382 (concat
383 "\\("
384 (mapconcat 'identity
385 (list "try:"
386 "except\\(\\s +.*\\)?:"
387 "while\\s +.*:"
388 "for\\s +.*:"
389 "if\\s +.*:"
390 "elif\\s +.*:"
391 (concat py-block-closing-keywords-re "[ \t\n]")
392 )
393 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000394 "\\)"))
395
396;; Regexp matching a function, method or variable assignment. If you
397;; change this, you probably have to change `py-current-defun' as
398;; well. This is only used by `py-current-defun' to find the name for
399;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000400(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000401 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
402
403;; Regexp for finding a class name. If you change this, you probably
404;; have to change `py-current-defun' as well. This is only used by
405;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000406(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
407
408;; Regexp that describes tracebacks
409(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000410 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000411
412
413
414;; Utilities
415
416(defmacro py-safe (&rest body)
417 ;; safely execute BODY, return nil if an error occurred
418 (` (condition-case nil
419 (progn (,@ body))
420 (error nil))))
421
422(defsubst py-keep-region-active ()
423 ;; Do whatever is necessary to keep the region active in XEmacs.
424 ;; Ignore byte-compiler warnings you might see. Also note that
425 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
426 ;; to take explicit action.
427 (and (boundp 'zmacs-region-stays)
428 (setq zmacs-region-stays t)))
429
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000430(defsubst py-point (position)
431 ;; Returns the value of point at certain commonly referenced POSITIONs.
432 ;; POSITION can be one of the following symbols:
433 ;;
434 ;; bol -- beginning of line
435 ;; eol -- end of line
436 ;; bod -- beginning of defun
437 ;; boi -- back to indentation
438 ;;
439 ;; This function does not modify point or mark.
440 (let ((here (point)))
441 (cond
442 ((eq position 'bol) (beginning-of-line))
443 ((eq position 'eol) (end-of-line))
444 ((eq position 'bod) (beginning-of-python-def-or-class))
445 ((eq position 'bob) (beginning-of-buffer))
446 ((eq position 'eob) (end-of-buffer))
447 ((eq position 'boi) (back-to-indentation))
448 (t (error "unknown buffer position requested: %s" position))
449 )
450 (prog1
451 (point)
452 (goto-char here))))
453
454(defsubst py-highlight-line (from to file line)
455 (cond
456 ((fboundp 'make-extent)
457 ;; XEmacs
458 (let ((e (make-extent from to)))
459 (set-extent-property e 'mouse-face 'highlight)
460 (set-extent-property e 'py-exc-info (cons file line))
461 (set-extent-property e 'keymap py-mode-output-map)))
462 (t
463 ;; Emacs -- Please port this!
464 )
465 ))
466
Barry Warsawc72c11c1997-08-09 06:42:08 +0000467
468;; Major mode boilerplate
469
Barry Warsaw7ae77681994-12-12 20:38:05 +0000470;; define a mode-specific abbrev table for those who use such things
471(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000472 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000473(define-abbrev-table 'python-mode-abbrev-table nil)
474
Barry Warsaw7ae77681994-12-12 20:38:05 +0000475(defvar python-mode-hook nil
476 "*Hook called by `python-mode'.")
477
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000478;; in previous version of python-mode.el, the hook was incorrectly
479;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000480(and (fboundp 'make-obsolete-variable)
481 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
482
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000483(defvar py-mode-map ()
484 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000485(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000486 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000487 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000488 ;; electric keys
489 (define-key py-mode-map ":" 'py-electric-colon)
490 ;; indentation level modifiers
491 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
492 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
493 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
494 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
495 ;; subprocess commands
496 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
497 (define-key py-mode-map "\C-c|" 'py-execute-region)
498 (define-key py-mode-map "\C-c!" 'py-shell)
499 ;; Caution! Enter here at your own risk. We are trying to support
500 ;; several behaviors and it gets disgusting. :-( This logic ripped
501 ;; largely from CC Mode.
502 ;;
503 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
504 ;; backwards deletion behavior to DEL, which both Delete and
505 ;; Backspace get translated to. There's no way to separate this
506 ;; behavior in a clean way, so deal with it! Besides, it's been
507 ;; this way since the dawn of time.
508 (if (not (boundp 'delete-key-deletes-forward))
509 (define-key py-mode-map "\177" 'py-electric-backspace)
510 ;; However, XEmacs 20 actually achieved enlightenment. It is
511 ;; possible to sanely define both backward and forward deletion
512 ;; behavior under X separately (TTYs are forever beyond hope, but
513 ;; who cares? XEmacs 20 does the right thing with these too).
514 (define-key py-mode-map [delete] 'py-electric-delete)
515 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000516 ;; Separate M-BS from C-M-h. The former should remain
517 ;; backward-kill-word.
518 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000519 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000520 ;; Miscellaneous
521 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
522 (define-key py-mode-map "\C-c\t" 'py-indent-region)
523 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
524 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
525 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000526 (define-key py-mode-map "\C-c#" 'py-comment-region)
527 (define-key py-mode-map "\C-c?" 'py-describe-mode)
528 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
529 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
530 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000531 (define-key py-mode-map "\C-c-" 'py-up-exception)
532 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000533 ;; information
534 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
535 (define-key py-mode-map "\C-c\C-v" 'py-version)
536 ;; py-newline-and-indent mappings
537 (define-key py-mode-map "\n" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000538 ;; shadow global bindings for newline-and-indent w/ the py- version.
539 ;; BAW - this is extremely bad form, but I'm not going to change it
540 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000541 (mapcar #'(lambda (key)
542 (define-key py-mode-map key 'py-newline-and-indent))
543 (where-is-internal 'newline-and-indent))
544 )
545
546(defvar py-mode-output-map nil
547 "Keymap used in *Python Output* buffers*")
548(if py-mode-output-map
549 nil
550 (setq py-mode-output-map (make-sparse-keymap))
551 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
552 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
553 ;; TBD: Disable all self-inserting keys. This is bogus, we should
554 ;; really implement this as *Python Output* buffer being read-only
555 (mapcar #' (lambda (key)
556 (define-key py-mode-output-map key
557 #'(lambda () (interactive) (beep))))
558 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000559 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000560
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000561(defvar py-mode-syntax-table nil
562 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000563(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000564 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000565 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000566 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
567 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
568 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
569 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
570 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
571 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
572 ;; Add operator symbols misassigned in the std table
573 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
574 (modify-syntax-entry ?\% "." py-mode-syntax-table)
575 (modify-syntax-entry ?\& "." py-mode-syntax-table)
576 (modify-syntax-entry ?\* "." py-mode-syntax-table)
577 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
578 (modify-syntax-entry ?\- "." py-mode-syntax-table)
579 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
580 (modify-syntax-entry ?\< "." py-mode-syntax-table)
581 (modify-syntax-entry ?\= "." py-mode-syntax-table)
582 (modify-syntax-entry ?\> "." py-mode-syntax-table)
583 (modify-syntax-entry ?\| "." py-mode-syntax-table)
584 ;; For historical reasons, underscore is word class instead of
585 ;; symbol class. GNU conventions say it should be symbol class, but
586 ;; there's a natural conflict between what major mode authors want
587 ;; and what users expect from `forward-word' and `backward-word'.
588 ;; Guido and I have hashed this out and have decided to keep
589 ;; underscore in word class. If you're tempted to change it, try
590 ;; binding M-f and M-b to py-forward-into-nomenclature and
591 ;; py-backward-into-nomenclature instead.
592 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
593 ;; Both single quote and double quote are string delimiters
594 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
595 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
596 ;; backquote is open and close paren
597 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
598 ;; comment delimiters
599 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
600 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
601 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000602
Barry Warsawb3e81d51996-09-04 15:12:42 +0000603
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000604
Barry Warsaw42f707f1996-07-29 21:05:05 +0000605;; Menu definitions, only relevent if you have the easymenu.el package
606;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000607(defvar py-menu nil
608 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000609This menu will get created automatically if you have the `easymenu'
610package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000611
Barry Warsawc72c11c1997-08-09 06:42:08 +0000612(and (py-safe (require 'easymenu) t)
613 (easy-menu-define
614 py-menu py-mode-map "Python Mode menu"
615 '("Python"
616 ["Comment Out Region" py-comment-region (mark)]
617 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
618 "-"
619 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000620 ["Mark current def" py-mark-def-or-class t]
621 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000622 "-"
623 ["Shift region left" py-shift-region-left (mark)]
624 ["Shift region right" py-shift-region-right (mark)]
625 "-"
626 ["Execute buffer" py-execute-buffer t]
627 ["Execute region" py-execute-region (mark)]
628 ["Start interpreter..." py-shell t]
629 "-"
630 ["Go to start of block" py-goto-block-up t]
631 ["Go to start of class" (beginning-of-python-def-or-class t) t]
632 ["Move to end of class" (end-of-python-def-or-class t) t]
633 ["Move to start of def" beginning-of-python-def-or-class t]
634 ["Move to end of def" end-of-python-def-or-class t]
635 "-"
636 ["Describe mode" py-describe-mode t]
637 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000638
Barry Warsaw81437461996-08-01 19:48:02 +0000639
640
641;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
642(defvar imenu-example--python-class-regexp
643 (concat ; <<classes>>
644 "\\(" ;
645 "^[ \t]*" ; newline and maybe whitespace
646 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
647 ; possibly multiple superclasses
648 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
649 "[ \t]*:" ; and the final :
650 "\\)" ; >>classes<<
651 )
652 "Regexp for Python classes for use with the imenu package."
653 )
654
655(defvar imenu-example--python-method-regexp
656 (concat ; <<methods and functions>>
657 "\\(" ;
658 "^[ \t]*" ; new line and maybe whitespace
659 "\\(def[ \t]+" ; function definitions start with def
660 "\\([a-zA-Z0-9_]+\\)" ; name is here
661 ; function arguments...
662 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
663 "\\)" ; end of def
664 "[ \t]*:" ; and then the :
665 "\\)" ; >>methods and functions<<
666 )
667 "Regexp for Python methods/functions for use with the imenu package."
668 )
669
670(defvar imenu-example--python-method-no-arg-parens '(2 8)
671 "Indicies into groups of the Python regexp for use with imenu.
672
673Using these values will result in smaller imenu lists, as arguments to
674functions are not listed.
675
676See the variable `imenu-example--python-show-method-args-p' for more
677information.")
678
679(defvar imenu-example--python-method-arg-parens '(2 7)
680 "Indicies into groups of the Python regexp for use with imenu.
681Using these values will result in large imenu lists, as arguments to
682functions are listed.
683
684See the variable `imenu-example--python-show-method-args-p' for more
685information.")
686
687;; Note that in this format, this variable can still be used with the
688;; imenu--generic-function. Otherwise, there is no real reason to have
689;; it.
690(defvar imenu-example--generic-python-expression
691 (cons
692 (concat
693 imenu-example--python-class-regexp
694 "\\|" ; or...
695 imenu-example--python-method-regexp
696 )
697 imenu-example--python-method-no-arg-parens)
698 "Generic Python expression which may be used directly with imenu.
699Used by setting the variable `imenu-generic-expression' to this value.
700Also, see the function \\[imenu-example--create-python-index] for a
701better alternative for finding the index.")
702
703;; These next two variables are used when searching for the python
704;; class/definitions. Just saving some time in accessing the
705;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000706(defvar imenu-example--python-generic-regexp nil)
707(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000708
709
Barry Warsaw81437461996-08-01 19:48:02 +0000710(defun imenu-example--create-python-index ()
711 "Python interface function for imenu package.
712Finds all python classes and functions/methods. Calls function
713\\[imenu-example--create-python-index-engine]. See that function for
714the details of how this works."
715 (setq imenu-example--python-generic-regexp
716 (car imenu-example--generic-python-expression))
717 (setq imenu-example--python-generic-parens
718 (if imenu-example--python-show-method-args-p
719 imenu-example--python-method-arg-parens
720 imenu-example--python-method-no-arg-parens))
721 (goto-char (point-min))
722 (imenu-example--create-python-index-engine nil))
723
724(defun imenu-example--create-python-index-engine (&optional start-indent)
725 "Function for finding imenu definitions in Python.
726
727Finds all definitions (classes, methods, or functions) in a Python
728file for the imenu package.
729
730Returns a possibly nested alist of the form
731
732 (INDEX-NAME . INDEX-POSITION)
733
734The second element of the alist may be an alist, producing a nested
735list as in
736
737 (INDEX-NAME . INDEX-ALIST)
738
739This function should not be called directly, as it calls itself
740recursively and requires some setup. Rather this is the engine for
741the function \\[imenu-example--create-python-index].
742
743It works recursively by looking for all definitions at the current
744indention level. When it finds one, it adds it to the alist. If it
745finds a definition at a greater indentation level, it removes the
746previous definition from the alist. In it's place it adds all
747definitions found at the next indentation level. When it finds a
748definition that is less indented then the current level, it retuns the
749alist it has created thus far.
750
751The optional argument START-INDENT indicates the starting indentation
752at which to continue looking for Python classes, methods, or
753functions. If this is not supplied, the function uses the indentation
754of the first definition found."
755 (let ((index-alist '())
756 (sub-method-alist '())
757 looking-p
758 def-name prev-name
759 cur-indent def-pos
760 (class-paren (first imenu-example--python-generic-parens))
761 (def-paren (second imenu-example--python-generic-parens)))
762 (setq looking-p
763 (re-search-forward imenu-example--python-generic-regexp
764 (point-max) t))
765 (while looking-p
766 (save-excursion
767 ;; used to set def-name to this value but generic-extract-name is
768 ;; new to imenu-1.14. this way it still works with imenu-1.11
769 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
770 (let ((cur-paren (if (match-beginning class-paren)
771 class-paren def-paren)))
772 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000773 (buffer-substring-no-properties (match-beginning cur-paren)
774 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000775 (beginning-of-line)
776 (setq cur-indent (current-indentation)))
777
778 ;; HACK: want to go to the next correct definition location. we
779 ;; explicitly list them here. would be better to have them in a
780 ;; list.
781 (setq def-pos
782 (or (match-beginning class-paren)
783 (match-beginning def-paren)))
784
785 ;; if we don't have a starting indent level, take this one
786 (or start-indent
787 (setq start-indent cur-indent))
788
789 ;; if we don't have class name yet, take this one
790 (or prev-name
791 (setq prev-name def-name))
792
793 ;; what level is the next definition on? must be same, deeper
794 ;; or shallower indentation
795 (cond
796 ;; at the same indent level, add it to the list...
797 ((= start-indent cur-indent)
798
799 ;; if we don't have push, use the following...
800 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
801 (push (cons def-name def-pos) index-alist))
802
803 ;; deeper indented expression, recur...
804 ((< start-indent cur-indent)
805
806 ;; the point is currently on the expression we're supposed to
807 ;; start on, so go back to the last expression. The recursive
808 ;; call will find this place again and add it to the correct
809 ;; list
810 (re-search-backward imenu-example--python-generic-regexp
811 (point-min) 'move)
812 (setq sub-method-alist (imenu-example--create-python-index-engine
813 cur-indent))
814
815 (if sub-method-alist
816 ;; we put the last element on the index-alist on the start
817 ;; of the submethod alist so the user can still get to it.
818 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000819 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000820 (cons save-elmt sub-method-alist))
821 index-alist))))
822
823 ;; found less indented expression, we're done.
824 (t
825 (setq looking-p nil)
826 (re-search-backward imenu-example--python-generic-regexp
827 (point-min) t)))
828 (setq prev-name def-name)
829 (and looking-p
830 (setq looking-p
831 (re-search-forward imenu-example--python-generic-regexp
832 (point-max) 'move))))
833 (nreverse index-alist)))
834
Barry Warsaw42f707f1996-07-29 21:05:05 +0000835
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000836;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000837(defun python-mode ()
838 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000839To submit a problem report, enter `\\[py-submit-bug-report]' from a
840`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
841documentation. To see what version of `python-mode' you are running,
842enter `\\[py-version]'.
843
844This mode knows about Python indentation, tokens, comments and
845continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000846
847COMMANDS
848\\{py-mode-map}
849VARIABLES
850
Barry Warsaw42f707f1996-07-29 21:05:05 +0000851py-indent-offset\t\tindentation increment
852py-block-comment-prefix\t\tcomment string used by comment-region
853py-python-command\t\tshell command to invoke Python interpreter
854py-scroll-process-buffer\t\talways scroll Python process buffer
855py-temp-directory\t\tdirectory used for temp files (if needed)
856py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000857 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000858 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000859 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000860 (make-local-variable 'font-lock-defaults)
861 (make-local-variable 'paragraph-separate)
862 (make-local-variable 'paragraph-start)
863 (make-local-variable 'require-final-newline)
864 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000865 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000866 (make-local-variable 'comment-start-skip)
867 (make-local-variable 'comment-column)
868 (make-local-variable 'indent-region-function)
869 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000870 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000871 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000872 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000873 (setq major-mode 'python-mode
874 mode-name "Python"
875 local-abbrev-table python-mode-abbrev-table
Barry Warsaw5c38bf61997-12-02 22:01:04 +0000876 font-lock-defaults '(python-font-lock-keywords)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000877 paragraph-separate "^[ \t]*$"
878 paragraph-start "^[ \t]*$"
879 require-final-newline t
880 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000881 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000882 comment-start-skip "# *"
883 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000884 indent-region-function 'py-indent-region
885 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000886 ;; tell add-log.el how to find the current function/method/variable
887 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000888 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000889 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000890 ;; add the menu
891 (if py-menu
892 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000893 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000894 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000895 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000896 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000897 ;;
898 ;; not sure where the magic comment has to be; to save time
899 ;; searching for a rarity, we give up if it's not found prior to the
900 ;; first executable statement.
901 ;;
902 ;; BAW - on first glance, this seems like complete hackery. Why was
903 ;; this necessary, and is it still necessary?
904 (let ((case-fold-search nil)
905 (start (point))
906 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000907 (if (re-search-forward
908 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
909 (prog2 (py-next-statement 1) (point) (goto-char 1))
910 t)
911 (progn
912 (setq new-tab-width
913 (string-to-int
914 (buffer-substring (match-beginning 1) (match-end 1))))
915 (if (= tab-width new-tab-width)
916 nil
917 (setq tab-width new-tab-width)
918 (message "Caution: tab-width changed to %d" new-tab-width)
919 (if py-beep-if-tab-change (beep)))))
920 (goto-char start))
921
Barry Warsaw755c6711996-08-01 20:02:55 +0000922 ;; install imenu
Barry Warsaw27ee1151997-12-03 05:03:44 +0000923 (if (py-safe (require 'imenu))
924 (progn
925 (make-variable-buffer-local 'imenu-create-index-function)
926 (setq imenu-create-index-function
927 (function imenu-example--create-python-index))
928 (setq imenu-generic-expression
929 imenu-example--generic-python-expression)
930 (if (fboundp 'imenu-add-to-menubar)
931 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
932 ))
Barry Warsaw755c6711996-08-01 20:02:55 +0000933
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000934 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000935 (if python-mode-hook
936 (run-hooks 'python-mode-hook)
937 (run-hooks 'py-mode-hook)))
938
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000939
Barry Warsawb91b7431995-03-14 15:55:20 +0000940;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000941(defun py-outdent-p ()
942 ;; returns non-nil if the current line should outdent one level
943 (save-excursion
944 (and (progn (back-to-indentation)
945 (looking-at py-outdent-re))
946 (progn (backward-to-indentation 1)
947 (while (or (looking-at py-blank-or-comment-re)
948 (bobp))
949 (backward-to-indentation 1))
950 (not (looking-at py-no-outdent-re)))
951 )))
952
Barry Warsawb91b7431995-03-14 15:55:20 +0000953(defun py-electric-colon (arg)
954 "Insert a colon.
955In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000956argument is provided, that many colons are inserted non-electrically.
957Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000958 (interactive "P")
959 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000960 ;; are we in a string or comment?
961 (if (save-excursion
962 (let ((pps (parse-partial-sexp (save-excursion
963 (beginning-of-python-def-or-class)
964 (point))
965 (point))))
966 (not (or (nth 3 pps) (nth 4 pps)))))
967 (save-excursion
968 (let ((here (point))
969 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000970 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000971 (if (and (not arg)
972 (py-outdent-p)
973 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000974 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000975 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000976 )
977 (setq outdent py-indent-offset))
978 ;; Don't indent, only outdent. This assumes that any lines that
979 ;; are already outdented relative to py-compute-indentation were
980 ;; put there on purpose. Its highly annoying to have `:' indent
981 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
982 ;; there a better way to determine this???
983 (if (< (current-indentation) indent) nil
984 (goto-char here)
985 (beginning-of-line)
986 (delete-horizontal-space)
987 (indent-to (- indent outdent))
988 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +0000989
990
Barry Warsawa97a3f31997-11-04 18:47:06 +0000991;; Python subprocess utilities and filters
992(defun py-execute-file (proc filename)
993 ;; Send a properly formatted execfile('FILENAME') to the underlying
994 ;; Python interpreter process FILENAME. Make that process's buffer
995 ;; visible and force display. Also make comint believe the user
996 ;; typed this string so that kill-output-from-shell does The Right
997 ;; Thing.
998 (let ((curbuf (current-buffer))
999 (procbuf (process-buffer proc))
1000 (comint-scroll-to-bottom-on-output t)
1001 (msg (format "## working on region in file %s...\n" filename))
1002 (cmd (format "execfile('%s')\n" filename)))
1003 (unwind-protect
1004 (progn
1005 (set-buffer procbuf)
1006 (goto-char (point-max))
1007 (move-marker (process-mark proc) (point))
1008 (funcall (process-filter proc) proc msg))
1009 (set-buffer curbuf))
1010 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001011
1012(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001013 (let ((curbuf (current-buffer))
1014 (pbuf (process-buffer pyproc))
1015 (pmark (process-mark pyproc))
1016 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001017 ;; make sure we switch to a different buffer at least once. if we
1018 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001019 ;; window, and point is before the end, and lots of output is
1020 ;; coming at a fast pace, then (a) simple cursor-movement commands
1021 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
1022 ;; to have a visible effect (the window just doesn't get updated,
1023 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
1024 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001025 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001026 ;; #b makes no sense to me at all. #a almost makes sense: unless
1027 ;; we actually change buffers, set_buffer_internal in buffer.c
1028 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1029 ;; seems to make the Emacs command loop reluctant to update the
1030 ;; display. Perhaps the default process filter in process.c's
1031 ;; read_process_output has update_mode_lines++ for a similar
1032 ;; reason? beats me ...
1033
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001034 (unwind-protect
1035 ;; make sure current buffer is restored
1036 ;; BAW - we want to check to see if this still applies
1037 (progn
1038 ;; mysterious ugly hack
1039 (if (eq curbuf pbuf)
1040 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001041
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001042 (set-buffer pbuf)
1043 (let* ((start (point))
1044 (goback (< start pmark))
1045 (goend (and (not goback) (= start (point-max))))
1046 (buffer-read-only nil))
1047 (goto-char pmark)
1048 (insert string)
1049 (move-marker pmark (point))
1050 (setq file-finished
1051 (and py-file-queue
1052 (equal ">>> "
1053 (buffer-substring
1054 (prog2 (beginning-of-line) (point)
1055 (goto-char pmark))
1056 (point)))))
1057 (if goback (goto-char start)
1058 ;; else
1059 (if py-scroll-process-buffer
1060 (let* ((pop-up-windows t)
1061 (pwin (display-buffer pbuf)))
1062 (set-window-point pwin (point)))))
1063 (set-buffer curbuf)
1064 (if file-finished
1065 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001066 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001067 (setq py-file-queue (cdr py-file-queue))
1068 (if py-file-queue
1069 (py-execute-file pyproc (car py-file-queue)))))
1070 (and goend
1071 (progn (set-buffer pbuf)
1072 (goto-char (point-max))))
1073 ))
1074 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001075
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001076(defun py-postprocess-output-buffer (buf)
Barry Warsaw9981d221997-12-03 05:25:48 +00001077 (let (line file bol)
1078 (save-excursion
1079 (set-buffer buf)
1080 (beginning-of-buffer)
1081 (while (re-search-forward py-traceback-line-re nil t)
1082 (setq file (match-string 1)
1083 line (string-to-int (match-string 2))
1084 bol (py-point 'bol))
1085 (py-highlight-line bol (py-point 'eol) file line))
1086 (when (and py-jump-on-exception line)
1087 (beep)
1088 (py-jump-to-exception file line))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001089 )))
1090
Barry Warsaw9981d221997-12-03 05:25:48 +00001091
Barry Warsawa97a3f31997-11-04 18:47:06 +00001092
1093;;; Subprocess commands
1094
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001095;; only used when (memq 'broken-temp-names py-emacs-features)
1096(defvar py-serial-number 0)
1097(defvar py-exception-buffer nil)
1098(defconst py-output-buffer "*Python Output*")
1099
Barry Warsawa97a3f31997-11-04 18:47:06 +00001100;;;###autoload
1101(defun py-shell ()
1102 "Start an interactive Python interpreter in another window.
1103This is like Shell mode, except that Python is running in the window
1104instead of a shell. See the `Interactive Shell' and `Shell Mode'
1105sections of the Emacs manual for details, especially for the key
1106bindings active in the `*Python*' buffer.
1107
1108See the docs for variable `py-scroll-buffer' for info on scrolling
1109behavior in the process window.
1110
1111Warning: Don't use an interactive Python if you change sys.ps1 or
1112sys.ps2 from their default values, or if you're running code that
1113prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1114distinguish your output from Python's output, and assumes that `>>> '
1115at the start of a line is a prompt from Python. Similarly, the Emacs
1116Shell mode code assumes that both `>>> ' and `... ' at the start of a
1117line are Python prompts. Bad things can happen if you fool either
1118mode.
1119
1120Warning: If you do any editing *in* the process buffer *while* the
1121buffer is accepting output from Python, do NOT attempt to `undo' the
1122changes. Some of the output (nowhere near the parts you changed!) may
1123be lost if you do. This appears to be an Emacs bug, an unfortunate
1124interaction between undo and process filters; the same problem exists in
1125non-Python process buffers using the default (Emacs-supplied) process
1126filter."
1127 ;; BAW - should undo be disabled in the python process buffer, if
1128 ;; this bug still exists?
1129 (interactive)
1130 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001131 (switch-to-buffer-other-window
1132 (make-comint "Python" py-python-command nil "-i"))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001133 (make-local-variable 'comint-prompt-regexp)
1134 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1135 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1136 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001137 ;; set up keybindings for this subshell
1138 (local-set-key [tab] 'self-insert-command)
1139 (local-set-key "\C-c-" 'py-up-exception)
1140 (local-set-key "\C-c=" 'py-down-exception)
1141 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001142
Barry Warsawa97a3f31997-11-04 18:47:06 +00001143(defun py-clear-queue ()
1144 "Clear the queue of temporary files waiting to execute."
1145 (interactive)
1146 (let ((n (length py-file-queue)))
1147 (mapcar 'delete-file py-file-queue)
1148 (setq py-file-queue nil)
1149 (message "%d pending files de-queued." n)))
1150
1151(defun py-execute-region (start end &optional async)
1152 "Execute the the region in a Python interpreter.
1153The region is first copied into a temporary file (in the directory
1154`py-temp-directory'). If there is no Python interpreter shell
1155running, this file is executed synchronously using
1156`shell-command-on-region'. If the program is long running, use an
1157optional \\[universal-argument] to run the command asynchronously in
1158its own buffer.
1159
1160If the Python interpreter shell is running, the region is execfile()'d
1161in that shell. If you try to execute regions too quickly,
1162`python-mode' will queue them up and execute them one at a time when
1163it sees a `>>> ' prompt from Python. Each time this happens, the
1164process buffer is popped into a window (if it's not already in some
1165window) so you can see it, and a comment of the form
1166
1167 \t## working on region in file <name>...
1168
1169is inserted at the end. See also the command `py-clear-queue'."
1170 (interactive "r\nP")
1171 (or (< start end)
1172 (error "Region is empty"))
1173 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001174 (temp (if (memq 'broken-temp-names py-emacs-features)
1175 (prog1
1176 (format "python-%d" py-serial-number)
1177 (setq py-serial-number (1+ py-serial-number)))
1178 (make-temp-name "python")))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001179 (file (concat (file-name-as-directory py-temp-directory) temp)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001180 (write-region start end file nil 'nomsg)
1181 (cond
1182 ;; always run the code in it's own asynchronous subprocess
1183 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001184 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001185 (start-process "Python" buf py-python-command "-u" file)
1186 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001187 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001188 ))
1189 ;; if the Python interpreter shell is running, queue it up for
1190 ;; execution there.
1191 (proc
1192 ;; use the existing python shell
1193 (if (not py-file-queue)
1194 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001195 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001196 (push file py-file-queue)
1197 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001198 (t
1199 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001200 (shell-command-on-region start end py-python-command py-output-buffer)
1201 (setq py-exception-buffer (current-buffer))
1202 (py-postprocess-output-buffer py-output-buffer)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001203 ))))
1204
1205;; Code execution command
1206(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001207 "Send the contents of the buffer to a Python interpreter.
1208If there is a *Python* process buffer it is used. If a clipping
1209restriction is in effect, only the accessible portion of the buffer is
1210sent. A trailing newline will be supplied if needed.
1211
1212See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001213 (interactive "P")
1214 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001215
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001216
1217
1218(defun py-jump-to-exception (file line)
1219 (let ((buffer (cond ((string-equal file "<stdin>")
1220 py-exception-buffer)
1221 ((and (consp py-exception-buffer)
1222 (string-equal file (car py-exception-buffer)))
1223 (cdr py-exception-buffer))
1224 ((py-safe (find-file-noselect file)))
1225 ;; could not figure out what file the exception
1226 ;; is pointing to, so prompt for it
1227 (t (find-file (read-file-name "Exception file: "
1228 nil
1229 file t))))))
1230 (pop-to-buffer buffer)
1231 (goto-line line)
1232 (message "Jumping to exception in file %s on line %d" file line)))
1233
1234(defun py-mouseto-exception (event)
1235 (interactive "e")
1236 (cond
1237 ((fboundp 'event-point)
1238 ;; XEmacs
1239 (let* ((point (event-point event))
1240 (buffer (event-buffer event))
1241 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1242 (info (and e (extent-property e 'py-exc-info))))
1243 (message "Event point: %d, info: %s" point info)
1244 (and info
1245 (py-jump-to-exception (car info) (cdr info)))
1246 ))
1247 ;; Emacs -- Please port this!
1248 ))
1249
1250(defun py-goto-exception ()
1251 "Go to the line indicated by the traceback."
1252 (interactive)
1253 (let (file line)
1254 (save-excursion
1255 (beginning-of-line)
1256 (if (looking-at py-traceback-line-re)
1257 (setq file (match-string 1)
1258 line (string-to-int (match-string 2)))))
1259 (if (not file)
1260 (error "Not on a traceback line."))
1261 (py-jump-to-exception file line)))
1262
1263(defun py-find-next-exception (start buffer searchdir errwhere)
1264 ;; Go to start position in buffer, search in the specified
1265 ;; direction, and jump to the exception found. If at the end of the
1266 ;; exception, print error message
1267 (let (file line)
1268 (save-excursion
1269 (set-buffer buffer)
1270 (goto-char (py-point start))
1271 (if (funcall searchdir py-traceback-line-re nil t)
1272 (setq file (match-string 1)
1273 line (string-to-int (match-string 2)))))
1274 (if (and file line)
1275 (py-jump-to-exception file line)
1276 (error "%s of traceback" errwhere))))
1277
1278(defun py-down-exception (&optional bottom)
1279 "Go to the next line down in the traceback.
1280With optional \\[universal-argument], jump to the bottom (innermost)
1281exception in the exception stack."
1282 (interactive "P")
1283 (let* ((proc (get-process "Python"))
1284 (buffer (if proc "*Python*" py-output-buffer)))
1285 (if bottom
1286 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1287 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1288
1289(defun py-up-exception (&optional top)
1290 "Go to the previous line up in the traceback.
1291With optional \\[universal-argument], jump to the top (outermost)
1292exception in the exception stack."
1293 (interactive "P")
1294 (let* ((proc (get-process "Python"))
1295 (buffer (if proc "*Python*" py-output-buffer)))
1296 (if top
1297 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001298 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001299
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001300
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001301;; Electric deletion
1302(defun py-electric-backspace (arg)
1303 "Deletes preceding character or levels of indentation.
1304Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001305with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001306
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001307If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001308
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001309Otherwise, if point is at the leftmost non-whitespace character of a
1310line that is neither a continuation line nor a non-indenting comment
1311line, or if point is at the end of a blank line, this command reduces
1312the indentation to match that of the line that opened the current
1313block of code. The line that opened the block is displayed in the
1314echo area to help you keep track of where you are. With numeric arg,
1315outdents that many blocks (but not past column zero).
1316
1317Otherwise the preceding character is deleted, converting a tab to
1318spaces if needed so that only a single column position is deleted.
1319Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001320 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001321 (if (or (/= (current-indentation) (current-column))
1322 (bolp)
1323 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001324 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001325 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001326 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001327 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001328 ;; force non-blank so py-goto-block-up doesn't ignore it
1329 (insert-char ?* 1)
1330 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001331 (let ((base-indent 0) ; indentation of base line
1332 (base-text "") ; and text of base line
1333 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001334 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001335 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001336 (condition-case nil ; in case no enclosing block
1337 (progn
1338 (py-goto-block-up 'no-mark)
1339 (setq base-indent (current-indentation)
1340 base-text (py-suck-up-leading-text)
1341 base-found-p t))
1342 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001343 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001344 (delete-char 1) ; toss the dummy character
1345 (delete-horizontal-space)
1346 (indent-to base-indent)
1347 (if base-found-p
1348 (message "Closes block: %s" base-text)))))
1349
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001350
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001351(defun py-electric-delete (arg)
1352 "Deletes preceding or following character or levels of whitespace.
1353
1354The behavior of this function depends on the variable
1355`delete-key-deletes-forward'. If this variable is nil (or does not
1356exist, as in older Emacsen), then this function behaves identical to
1357\\[c-electric-backspace].
1358
1359If `delete-key-deletes-forward' is non-nil and is supported in your
1360Emacs, then deletion occurs in the forward direction, by calling the
1361function in `py-delete-function'."
1362 (interactive "*p")
1363 (if (and (boundp 'delete-key-deletes-forward)
1364 delete-key-deletes-forward)
1365 (funcall py-delete-function arg)
1366 ;; else
1367 (py-electric-backspace arg)))
1368
1369;; required for pending-del and delsel modes
1370(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1371(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1372(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1373(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1374
1375
1376
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001377(defun py-indent-line (&optional arg)
1378 "Fix the indentation of the current line according to Python rules.
1379With \\[universal-argument], ignore outdenting rules for block
1380closing statements (e.g. return, raise, break, continue, pass)
1381
1382This function is normally bound to `indent-line-function' so
1383\\[indent-for-tab-command] will call it."
1384 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001385 (let* ((ci (current-indentation))
1386 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001387 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001388 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001389 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001390 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001391 (if (/= ci need)
1392 (save-excursion
1393 (beginning-of-line)
1394 (delete-horizontal-space)
1395 (indent-to need)))
1396 (if move-to-indentation-p (back-to-indentation))))
1397
1398(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001399 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001400This is just `strives to' because correct indentation can't be computed
1401from scratch for Python code. In general, deletes the whitespace before
1402point, inserts a newline, and takes an educated guess as to how you want
1403the new line indented."
1404 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001405 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001406 (if (< ci (current-column)) ; if point beyond indentation
1407 (newline-and-indent)
1408 ;; else try to act like newline-and-indent "normally" acts
1409 (beginning-of-line)
1410 (insert-char ?\n 1)
1411 (move-to-column ci))))
1412
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001413(defun py-compute-indentation (honor-block-close-p)
1414 ;; implements all the rules for indentation computation. when
1415 ;; honor-block-close-p is non-nil, statements such as return, raise,
1416 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001417 (save-excursion
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001418 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001419 (pps (parse-partial-sexp bod (point)))
1420 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001421 (beginning-of-line)
1422 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001423 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001424 ((or (and (nth 3 pps) (nth 3 boipps))
1425 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001426 (save-excursion
1427 (if (not py-align-multiline-strings-p) 0
1428 ;; skip back over blank & non-indenting comment lines
1429 ;; note: will skip a blank or non-indenting comment line
1430 ;; that happens to be a continuation line too
1431 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1432 (back-to-indentation)
1433 (current-column))))
1434 ;; are we on a continuation line?
1435 ((py-continuation-line-p)
1436 (let ((startpos (point))
1437 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001438 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001439 (if open-bracket-pos
1440 (progn
1441 ;; align with first item in list; else a normal
1442 ;; indent beyond the line with the open bracket
1443 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1444 ;; is the first list item on the same line?
1445 (skip-chars-forward " \t")
1446 (if (null (memq (following-char) '(?\n ?# ?\\)))
1447 ; yes, so line up with it
1448 (current-column)
1449 ;; first list item on another line, or doesn't exist yet
1450 (forward-line 1)
1451 (while (and (< (point) startpos)
1452 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1453 (forward-line 1))
1454 (if (< (point) startpos)
1455 ;; again mimic the first list item
1456 (current-indentation)
1457 ;; else they're about to enter the first item
1458 (goto-char open-bracket-pos)
1459 (+ (current-indentation) py-indent-offset))))
1460
1461 ;; else on backslash continuation line
1462 (forward-line -1)
1463 (if (py-continuation-line-p) ; on at least 3rd line in block
1464 (current-indentation) ; so just continue the pattern
1465 ;; else started on 2nd line in block, so indent more.
1466 ;; if base line is an assignment with a start on a RHS,
1467 ;; indent to 2 beyond the leftmost "="; else skip first
1468 ;; chunk of non-whitespace characters on base line, + 1 more
1469 ;; column
1470 (end-of-line)
1471 (setq endpos (point) searching t)
1472 (back-to-indentation)
1473 (setq startpos (point))
1474 ;; look at all "=" from left to right, stopping at first
1475 ;; one not nested in a list or string
1476 (while searching
1477 (skip-chars-forward "^=" endpos)
1478 (if (= (point) endpos)
1479 (setq searching nil)
1480 (forward-char 1)
1481 (setq state (parse-partial-sexp startpos (point)))
1482 (if (and (zerop (car state)) ; not in a bracket
1483 (null (nth 3 state))) ; & not in a string
1484 (progn
1485 (setq searching nil) ; done searching in any case
1486 (setq found
1487 (not (or
1488 (eq (following-char) ?=)
1489 (memq (char-after (- (point) 2))
1490 '(?< ?> ?!)))))))))
1491 (if (or (not found) ; not an assignment
1492 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1493 (progn
1494 (goto-char startpos)
1495 (skip-chars-forward "^ \t\n")))
1496 (1+ (current-column))))))
1497
1498 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001499 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001500
Barry Warsawa7891711996-08-01 15:53:09 +00001501 ;; Dfn: "Indenting comment line". A line containing only a
1502 ;; comment, but which is treated like a statement for
1503 ;; indentation calculation purposes. Such lines are only
1504 ;; treated specially by the mode; they are not treated
1505 ;; specially by the Python interpreter.
1506
1507 ;; The rules for indenting comment lines are a line where:
1508 ;; - the first non-whitespace character is `#', and
1509 ;; - the character following the `#' is whitespace, and
1510 ;; - the line is outdented with respect to (i.e. to the left
1511 ;; of) the indentation of the preceding non-blank line.
1512
1513 ;; The first non-blank line following an indenting comment
1514 ;; line is given the same amount of indentation as the
1515 ;; indenting comment line.
1516
1517 ;; All other comment-only lines are ignored for indentation
1518 ;; purposes.
1519
1520 ;; Are we looking at a comment-only line which is *not* an
1521 ;; indenting comment line? If so, we assume that its been
1522 ;; placed at the desired indentation, so leave it alone.
1523 ;; Indenting comment lines are aligned as statements down
1524 ;; below.
1525 ((and (looking-at "[ \t]*#[^ \t\n]")
1526 ;; NOTE: this test will not be performed in older Emacsen
1527 (fboundp 'forward-comment)
1528 (<= (current-indentation)
1529 (save-excursion
1530 (forward-comment (- (point-max)))
1531 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001532 (current-indentation))
1533
1534 ;; else indentation based on that of the statement that
1535 ;; precedes us; use the first line of that statement to
1536 ;; establish the base, in case the user forced a non-std
1537 ;; indentation for the continuation lines (if any)
1538 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001539 ;; skip back over blank & non-indenting comment lines note:
1540 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001541 ;; happens to be a continuation line too. use fast Emacs 19
1542 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001543 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001544 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001545 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001546 (let (done)
1547 (while (not done)
1548 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1549 nil 'move)
1550 (setq done (or (eq py-honor-comment-indentation t)
1551 (bobp)
1552 (/= (following-char) ?#)
1553 (not (zerop (current-column)))))
1554 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001555 ;; if we landed inside a string, go to the beginning of that
1556 ;; string. this handles triple quoted, multi-line spanning
1557 ;; strings.
1558 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001559 (+ (current-indentation)
1560 (if (py-statement-opens-block-p)
1561 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001562 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001563 (- py-indent-offset)
1564 0)))
1565 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001566
1567(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001568 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001569By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001570`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001571Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001572`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001573their own buffer-local copy), both those currently existing and those
1574created later in the Emacs session.
1575
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001576Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001577There's no excuse for such foolishness, but sometimes you have to deal
1578with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001579`py-indent-offset' to what it thinks it was when they created the
1580mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001581
1582Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001583looking for a line that opens a block of code. `py-indent-offset' is
1584set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001585statement following it. If the search doesn't succeed going forward,
1586it's tried again going backward."
1587 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001588 (let (new-value
1589 (start (point))
1590 restart
1591 (found nil)
1592 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001593 (py-goto-initial-line)
1594 (while (not (or found (eobp)))
1595 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1596 (progn
1597 (setq restart (point))
1598 (py-goto-initial-line)
1599 (if (py-statement-opens-block-p)
1600 (setq found t)
1601 (goto-char restart)))))
1602 (if found
1603 ()
1604 (goto-char start)
1605 (py-goto-initial-line)
1606 (while (not (or found (bobp)))
1607 (setq found
1608 (and
1609 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1610 (or (py-goto-initial-line) t) ; always true -- side effect
1611 (py-statement-opens-block-p)))))
1612 (setq colon-indent (current-indentation)
1613 found (and found (zerop (py-next-statement 1)))
1614 new-value (- (current-indentation) colon-indent))
1615 (goto-char start)
1616 (if found
1617 (progn
1618 (funcall (if global 'kill-local-variable 'make-local-variable)
1619 'py-indent-offset)
1620 (setq py-indent-offset new-value)
1621 (message "%s value of py-indent-offset set to %d"
1622 (if global "Global" "Local")
1623 py-indent-offset))
1624 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1625
1626(defun py-shift-region (start end count)
1627 (save-excursion
1628 (goto-char end) (beginning-of-line) (setq end (point))
1629 (goto-char start) (beginning-of-line) (setq start (point))
1630 (indent-rigidly start end count)))
1631
1632(defun py-shift-region-left (start end &optional count)
1633 "Shift region of Python code to the left.
1634The lines from the line containing the start of the current region up
1635to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001636shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001637
1638If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001639many columns. With no active region, outdent only the current line.
1640You cannot outdent the region if any line is already at column zero."
1641 (interactive
1642 (let ((p (point))
1643 (m (mark))
1644 (arg current-prefix-arg))
1645 (if m
1646 (list (min p m) (max p m) arg)
1647 (list p (save-excursion (forward-line 1) (point)) arg))))
1648 ;; if any line is at column zero, don't shift the region
1649 (save-excursion
1650 (goto-char start)
1651 (while (< (point) end)
1652 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001653 (if (and (zerop (current-column))
1654 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001655 (error "Region is at left edge."))
1656 (forward-line 1)))
1657 (py-shift-region start end (- (prefix-numeric-value
1658 (or count py-indent-offset))))
1659 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001660
1661(defun py-shift-region-right (start end &optional count)
1662 "Shift region of Python code to the right.
1663The lines from the line containing the start of the current region up
1664to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001665shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001666
1667If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001668many columns. With no active region, indent only the current line."
1669 (interactive
1670 (let ((p (point))
1671 (m (mark))
1672 (arg current-prefix-arg))
1673 (if m
1674 (list (min p m) (max p m) arg)
1675 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001676 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001677 (or count py-indent-offset)))
1678 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001679
1680(defun py-indent-region (start end &optional indent-offset)
1681 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001682
Barry Warsaw7ae77681994-12-12 20:38:05 +00001683The lines from the line containing the start of the current region up
1684to (but not including) the line containing the end of the region are
1685reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001686character in the first column, the first line is left alone and the
1687rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001688region is reindented with respect to the (closest code or indenting
1689comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001690
1691This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001692control structures are introduced or removed, or to reformat code
1693using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001694
1695If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001696the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001697used.
1698
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001699Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001700is called! This function does not compute proper indentation from
1701scratch (that's impossible in Python), it merely adjusts the existing
1702indentation to be correct in context.
1703
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001704Warning: This function really has no idea what to do with
1705non-indenting comment lines, and shifts them as if they were indenting
1706comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001707
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001708Special cases: whitespace is deleted from blank lines; continuation
1709lines are shifted by the same amount their initial line was shifted,
1710in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001711initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001712 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001713 (save-excursion
1714 (goto-char end) (beginning-of-line) (setq end (point-marker))
1715 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001716 (let ((py-indent-offset (prefix-numeric-value
1717 (or indent-offset py-indent-offset)))
1718 (indents '(-1)) ; stack of active indent levels
1719 (target-column 0) ; column to which to indent
1720 (base-shifted-by 0) ; amount last base line was shifted
1721 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001722 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001723 0))
1724 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001725 (while (< (point) end)
1726 (setq ci (current-indentation))
1727 ;; figure out appropriate target column
1728 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001729 ((or (eq (following-char) ?#) ; comment in column 1
1730 (looking-at "[ \t]*$")) ; entirely blank
1731 (setq target-column 0))
1732 ((py-continuation-line-p) ; shift relative to base line
1733 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001734 (t ; new base line
1735 (if (> ci (car indents)) ; going deeper; push it
1736 (setq indents (cons ci indents))
1737 ;; else we should have seen this indent before
1738 (setq indents (memq ci indents)) ; pop deeper indents
1739 (if (null indents)
1740 (error "Bad indentation in region, at line %d"
1741 (save-restriction
1742 (widen)
1743 (1+ (count-lines 1 (point)))))))
1744 (setq target-column (+ indent-base
1745 (* py-indent-offset
1746 (- (length indents) 2))))
1747 (setq base-shifted-by (- target-column ci))))
1748 ;; shift as needed
1749 (if (/= ci target-column)
1750 (progn
1751 (delete-horizontal-space)
1752 (indent-to target-column)))
1753 (forward-line 1))))
1754 (set-marker end nil))
1755
Barry Warsawa7891711996-08-01 15:53:09 +00001756(defun py-comment-region (beg end &optional arg)
1757 "Like `comment-region' but uses double hash (`#') comment starter."
1758 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001759 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001760 (comment-region beg end arg)))
1761
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001762
1763;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001764(defun py-previous-statement (count)
1765 "Go to the start of previous Python statement.
1766If the statement at point is the i'th Python statement, goes to the
1767start of statement i-COUNT. If there is no such statement, goes to the
1768first statement. Returns count of statements left to move.
1769`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001770 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001771 (if (< count 0) (py-next-statement (- count))
1772 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001773 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001774 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001775 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001776 (> count 0)
1777 (zerop (forward-line -1))
1778 (py-goto-statement-at-or-above))
1779 (setq count (1- count)))
1780 (if (> count 0) (goto-char start)))
1781 count))
1782
1783(defun py-next-statement (count)
1784 "Go to the start of next Python statement.
1785If the statement at point is the i'th Python statement, goes to the
1786start of statement i+COUNT. If there is no such statement, goes to the
1787last statement. Returns count of statements left to move. `Statements'
1788do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001789 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001790 (if (< count 0) (py-previous-statement (- count))
1791 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001792 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001793 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001794 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001795 (> count 0)
1796 (py-goto-statement-below))
1797 (setq count (1- count)))
1798 (if (> count 0) (goto-char start)))
1799 count))
1800
1801(defun py-goto-block-up (&optional nomark)
1802 "Move up to start of current block.
1803Go to the statement that starts the smallest enclosing block; roughly
1804speaking, this will be the closest preceding statement that ends with a
1805colon and is indented less than the statement you started on. If
1806successful, also sets the mark to the starting point.
1807
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001808`\\[py-mark-block]' can be used afterward to mark the whole code
1809block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001810
1811If called from a program, the mark will not be set if optional argument
1812NOMARK is not nil."
1813 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001814 (let ((start (point))
1815 (found nil)
1816 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001817 (py-goto-initial-line)
1818 ;; if on blank or non-indenting comment line, use the preceding stmt
1819 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1820 (progn
1821 (py-goto-statement-at-or-above)
1822 (setq found (py-statement-opens-block-p))))
1823 ;; search back for colon line indented less
1824 (setq initial-indent (current-indentation))
1825 (if (zerop initial-indent)
1826 ;; force fast exit
1827 (goto-char (point-min)))
1828 (while (not (or found (bobp)))
1829 (setq found
1830 (and
1831 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1832 (or (py-goto-initial-line) t) ; always true -- side effect
1833 (< (current-indentation) initial-indent)
1834 (py-statement-opens-block-p))))
1835 (if found
1836 (progn
1837 (or nomark (push-mark start))
1838 (back-to-indentation))
1839 (goto-char start)
1840 (error "Enclosing block not found"))))
1841
1842(defun beginning-of-python-def-or-class (&optional class)
1843 "Move point to start of def (or class, with prefix arg).
1844
1845Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001846arg, looks for a `class' instead. The docs assume the `def' case;
1847just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001848
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001849If point is in a def statement already, and after the `d', simply
1850moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001851
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001852Else (point is not in a def statement, or at or before the `d' of a
1853def statement), searches for the closest preceding def statement, and
1854leaves point at its start. If no such statement can be found, leaves
1855point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001856
1857Returns t iff a def statement is found by these rules.
1858
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001859Note that doing this command repeatedly will take you closer to the
1860start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001861
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001862If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001863`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001864 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001865 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1866 (start-of-line (progn (beginning-of-line) (point)))
1867 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001868 (if (or (/= start-of-stmt start-of-line)
1869 (not at-or-before-p))
1870 (end-of-line)) ; OK to match on this line
1871 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001872 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001873
1874(defun end-of-python-def-or-class (&optional class)
1875 "Move point beyond end of def (or class, with prefix arg) body.
1876
1877By default, looks for an appropriate `def'. If you supply a prefix arg,
1878looks for a `class' instead. The docs assume the `def' case; just
1879substitute `class' for `def' for the other case.
1880
1881If point is in a def statement already, this is the def we use.
1882
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001883Else if the def found by `\\[beginning-of-python-def-or-class]'
1884contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001885
1886Else we search forward for the closest following def, and use that.
1887
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001888If a def can be found by these rules, point is moved to the start of
1889the line immediately following the def block, and the position of the
1890start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001891
1892Else point is moved to the end of the buffer, and nil is returned.
1893
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001894Note that doing this command repeatedly will take you closer to the
1895end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001896
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001897If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001898`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001899 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001900 (let ((start (progn (py-goto-initial-line) (point)))
1901 (which (if class "class" "def"))
1902 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001903 ;; move point to start of appropriate def/class
1904 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1905 (setq state 'at-beginning)
1906 ;; else see if beginning-of-python-def-or-class hits container
1907 (if (and (beginning-of-python-def-or-class class)
1908 (progn (py-goto-beyond-block)
1909 (> (point) start)))
1910 (setq state 'at-end)
1911 ;; else search forward
1912 (goto-char start)
1913 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1914 (progn (setq state 'at-beginning)
1915 (beginning-of-line)))))
1916 (cond
1917 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1918 ((eq state 'at-end) t)
1919 ((eq state 'not-found) nil)
1920 (t (error "internal error in end-of-python-def-or-class")))))
1921
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001922
1923;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001924(defun py-mark-block (&optional extend just-move)
1925 "Mark following block of lines. With prefix arg, mark structure.
1926Easier to use than explain. It sets the region to an `interesting'
1927block of succeeding lines. If point is on a blank line, it goes down to
1928the next non-blank line. That will be the start of the region. The end
1929of the region depends on the kind of line at the start:
1930
1931 - If a comment, the region will include all succeeding comment lines up
1932 to (but not including) the next non-comment line (if any).
1933
1934 - Else if a prefix arg is given, and the line begins one of these
1935 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001936
1937 if elif else try except finally for while def class
1938
Barry Warsaw7ae77681994-12-12 20:38:05 +00001939 the region will be set to the body of the structure, including
1940 following blocks that `belong' to it, but excluding trailing blank
1941 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001942 and all (if any) of the following `except' and `finally' blocks
1943 that belong to the `try' structure will be in the region. Ditto
1944 for if/elif/else, for/else and while/else structures, and (a bit
1945 degenerate, since they're always one-block structures) def and
1946 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001947
1948 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001949 block (see list above), and the block is not a `one-liner' (i.e.,
1950 the statement ends with a colon, not with code), the region will
1951 include all succeeding lines up to (but not including) the next
1952 code statement (if any) that's indented no more than the starting
1953 line, except that trailing blank and comment lines are excluded.
1954 E.g., if the starting line begins a multi-statement `def'
1955 structure, the region will be set to the full function definition,
1956 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001957
1958 - Else the region will include all succeeding lines up to (but not
1959 including) the next blank line, or code or indenting-comment line
1960 indented strictly less than the starting line. Trailing indenting
1961 comment lines are included in this case, but not trailing blank
1962 lines.
1963
1964A msg identifying the location of the mark is displayed in the echo
1965area; or do `\\[exchange-point-and-mark]' to flip down to the end.
1966
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001967If called from a program, optional argument EXTEND plays the role of
1968the prefix arg, and if optional argument JUST-MOVE is not nil, just
1969moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001970 (interactive "P") ; raw prefix arg
1971 (py-goto-initial-line)
1972 ;; skip over blank lines
1973 (while (and
1974 (looking-at "[ \t]*$") ; while blank line
1975 (not (eobp))) ; & somewhere to go
1976 (forward-line 1))
1977 (if (eobp)
1978 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001979 (let ((initial-pos (point))
1980 (initial-indent (current-indentation))
1981 last-pos ; position of last stmt in region
1982 (followers
1983 '((if elif else) (elif elif else) (else)
1984 (try except finally) (except except) (finally)
1985 (for else) (while else)
1986 (def) (class) ) )
1987 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001988
1989 (cond
1990 ;; if comment line, suck up the following comment lines
1991 ((looking-at "[ \t]*#")
1992 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
1993 (re-search-backward "^[ \t]*#") ; and back to last comment in block
1994 (setq last-pos (point)))
1995
1996 ;; else if line is a block line and EXTEND given, suck up
1997 ;; the whole structure
1998 ((and extend
1999 (setq first-symbol (py-suck-up-first-keyword) )
2000 (assq first-symbol followers))
2001 (while (and
2002 (or (py-goto-beyond-block) t) ; side effect
2003 (forward-line -1) ; side effect
2004 (setq last-pos (point)) ; side effect
2005 (py-goto-statement-below)
2006 (= (current-indentation) initial-indent)
2007 (setq next-symbol (py-suck-up-first-keyword))
2008 (memq next-symbol (cdr (assq first-symbol followers))))
2009 (setq first-symbol next-symbol)))
2010
2011 ;; else if line *opens* a block, search for next stmt indented <=
2012 ((py-statement-opens-block-p)
2013 (while (and
2014 (setq last-pos (point)) ; always true -- side effect
2015 (py-goto-statement-below)
2016 (> (current-indentation) initial-indent))
2017 nil))
2018
2019 ;; else plain code line; stop at next blank line, or stmt or
2020 ;; indenting comment line indented <
2021 (t
2022 (while (and
2023 (setq last-pos (point)) ; always true -- side effect
2024 (or (py-goto-beyond-final-line) t)
2025 (not (looking-at "[ \t]*$")) ; stop at blank line
2026 (or
2027 (>= (current-indentation) initial-indent)
2028 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2029 nil)))
2030
2031 ;; skip to end of last stmt
2032 (goto-char last-pos)
2033 (py-goto-beyond-final-line)
2034
2035 ;; set mark & display
2036 (if just-move
2037 () ; just return
2038 (push-mark (point) 'no-msg)
2039 (forward-line -1)
2040 (message "Mark set after: %s" (py-suck-up-leading-text))
2041 (goto-char initial-pos))))
2042
Barry Warsaw2518c671997-11-05 00:51:08 +00002043(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002044 "Set region to body of def (or class, with prefix arg) enclosing point.
2045Pushes the current mark, then point, on the mark ring (all language
2046modes do this, but although it's handy it's never documented ...).
2047
2048In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002049hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
2050`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002051
2052And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002053Turned out that was more confusing than useful: the `goto start' and
2054`goto end' commands are usually used to search through a file, and
2055people expect them to act a lot like `search backward' and `search
2056forward' string-search commands. But because Python `def' and `class'
2057can nest to arbitrary levels, finding the smallest def containing
2058point cannot be done via a simple backward search: the def containing
2059point may not be the closest preceding def, or even the closest
2060preceding def that's indented less. The fancy algorithm required is
2061appropriate for the usual uses of this `mark' command, but not for the
2062`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002063
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002064So the def marked by this command may not be the one either of the
2065`goto' commands find: If point is on a blank or non-indenting comment
2066line, moves back to start of the closest preceding code statement or
2067indenting comment line. If this is a `def' statement, that's the def
2068we use. Else searches for the smallest enclosing `def' block and uses
2069that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002070
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002071When an enclosing def is found: The mark is left immediately beyond
2072the last line of the def block. Point is left at the start of the
2073def, except that: if the def is preceded by a number of comment lines
2074followed by (at most) one optional blank line, point is left at the
2075start of the comments; else if the def is preceded by a blank line,
2076point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002077
2078The intent is to mark the containing def/class and its associated
2079documentation, to make moving and duplicating functions and classes
2080pleasant."
2081 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002082 (let ((start (point))
2083 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002084 (push-mark start)
2085 (if (not (py-go-up-tree-to-keyword which))
2086 (progn (goto-char start)
2087 (error "Enclosing %s not found" which))
2088 ;; else enclosing def/class found
2089 (setq start (point))
2090 (py-goto-beyond-block)
2091 (push-mark (point))
2092 (goto-char start)
2093 (if (zerop (forward-line -1)) ; if there is a preceding line
2094 (progn
2095 (if (looking-at "[ \t]*$") ; it's blank
2096 (setq start (point)) ; so reset start point
2097 (goto-char start)) ; else try again
2098 (if (zerop (forward-line -1))
2099 (if (looking-at "[ \t]*#") ; a comment
2100 ;; look back for non-comment line
2101 ;; tricky: note that the regexp matches a blank
2102 ;; line, cuz \n is in the 2nd character class
2103 (and
2104 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2105 (forward-line 1))
2106 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002107 (goto-char start)))))))
2108 (exchange-point-and-mark)
2109 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002110
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002111;; ripped from cc-mode
2112(defun py-forward-into-nomenclature (&optional arg)
2113 "Move forward to end of a nomenclature section or word.
2114With arg, to it arg times.
2115
2116A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2117 (interactive "p")
2118 (let ((case-fold-search nil))
2119 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002120 (re-search-forward
2121 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2122 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002123 (while (and (< arg 0)
2124 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002125 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002126 (point-min) 0))
2127 (forward-char 1)
2128 (setq arg (1+ arg)))))
2129 (py-keep-region-active))
2130
2131(defun py-backward-into-nomenclature (&optional arg)
2132 "Move backward to beginning of a nomenclature section or word.
2133With optional ARG, move that many times. If ARG is negative, move
2134forward.
2135
2136A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2137 (interactive "p")
2138 (py-forward-into-nomenclature (- arg))
2139 (py-keep-region-active))
2140
2141
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002142
2143;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002144
2145;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002146;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2147;; out of the right places, along with the keys they're on & current
2148;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002149(defun py-dump-help-string (str)
2150 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002151 (let ((locals (buffer-local-variables))
2152 funckind funcname func funcdoc
2153 (start 0) mstart end
2154 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002155 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2156 (setq mstart (match-beginning 0) end (match-end 0)
2157 funckind (substring str (match-beginning 1) (match-end 1))
2158 funcname (substring str (match-beginning 2) (match-end 2))
2159 func (intern funcname))
2160 (princ (substitute-command-keys (substring str start mstart)))
2161 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002162 ((equal funckind "c") ; command
2163 (setq funcdoc (documentation func)
2164 keys (concat
2165 "Key(s): "
2166 (mapconcat 'key-description
2167 (where-is-internal func py-mode-map)
2168 ", "))))
2169 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002170 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002171 keys (if (assq func locals)
2172 (concat
2173 "Local/Global values: "
2174 (prin1-to-string (symbol-value func))
2175 " / "
2176 (prin1-to-string (default-value func)))
2177 (concat
2178 "Value: "
2179 (prin1-to-string (symbol-value func))))))
2180 (t ; unexpected
2181 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002182 (princ (format "\n-> %s:\t%s\t%s\n\n"
2183 (if (equal funckind "c") "Command" "Variable")
2184 funcname keys))
2185 (princ funcdoc)
2186 (terpri)
2187 (setq start end))
2188 (princ (substitute-command-keys (substring str start))))
2189 (print-help-return-message)))
2190
2191(defun py-describe-mode ()
2192 "Dump long form of Python-mode docs."
2193 (interactive)
2194 (py-dump-help-string "Major mode for editing Python files.
2195Knows about Python indentation, tokens, comments and continuation lines.
2196Paragraphs are separated by blank lines only.
2197
2198Major sections below begin with the string `@'; specific function and
2199variable docs begin with `->'.
2200
2201@EXECUTING PYTHON CODE
2202
2203\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2204\\[py-execute-region]\tsends the current region
2205\\[py-shell]\tstarts a Python interpreter window; this will be used by
2206\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2207%c:py-execute-buffer
2208%c:py-execute-region
2209%c:py-shell
2210
2211@VARIABLES
2212
2213py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002214py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002215
2216py-python-command\tshell command to invoke Python interpreter
2217py-scroll-process-buffer\talways scroll Python process buffer
2218py-temp-directory\tdirectory used for temp files (if needed)
2219
2220py-beep-if-tab-change\tring the bell if tab-width is changed
2221%v:py-indent-offset
2222%v:py-block-comment-prefix
2223%v:py-python-command
2224%v:py-scroll-process-buffer
2225%v:py-temp-directory
2226%v:py-beep-if-tab-change
2227
2228@KINDS OF LINES
2229
2230Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002231preceding line ends with a backslash that's not part of a comment, or
2232the paren/bracket/brace nesting level at the start of the line is
2233non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002234
2235An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002236possibly blanks or tabs), a `comment line' (leftmost non-blank
2237character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002238
2239Comment Lines
2240
2241Although all comment lines are treated alike by Python, Python mode
2242recognizes two kinds that act differently with respect to indentation.
2243
2244An `indenting comment line' is a comment line with a blank, tab or
2245nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002246treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002247indenting comment line will be indented like the comment line. All
2248other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002249following the initial `#') are `non-indenting comment lines', and
2250their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002251
2252Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002253whenever possible. Non-indenting comment lines are useful in cases
2254like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002255
2256\ta = b # a very wordy single-line comment that ends up being
2257\t #... continued onto another line
2258
2259\tif a == b:
2260##\t\tprint 'panic!' # old code we've `commented out'
2261\t\treturn a
2262
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002263Since the `#...' and `##' comment lines have a non-whitespace
2264character following the initial `#', Python mode ignores them when
2265computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002266
2267Continuation Lines and Statements
2268
2269The Python-mode commands generally work on statements instead of on
2270individual lines, where a `statement' is a comment or blank line, or a
2271code line and all of its following continuation lines (if any)
2272considered as a single logical unit. The commands in this mode
2273generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002274statement containing point, even if point happens to be in the middle
2275of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002276
2277
2278@INDENTATION
2279
2280Primarily for entering new code:
2281\t\\[indent-for-tab-command]\t indent line appropriately
2282\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002283\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002284
2285Primarily for reindenting existing code:
2286\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2287\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2288
2289\t\\[py-indent-region]\t reindent region to match its context
2290\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2291\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2292
2293Unlike most programming languages, Python uses indentation, and only
2294indentation, to specify block structure. Hence the indentation supplied
2295automatically by Python-mode is just an educated guess: only you know
2296the block structure you intend, so only you can supply correct
2297indentation.
2298
2299The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2300the indentation of preceding statements. E.g., assuming
2301py-indent-offset is 4, after you enter
2302\tif a > 0: \\[py-newline-and-indent]
2303the cursor will be moved to the position of the `_' (_ is not a
2304character in the file, it's just used here to indicate the location of
2305the cursor):
2306\tif a > 0:
2307\t _
2308If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2309to
2310\tif a > 0:
2311\t c = d
2312\t _
2313Python-mode cannot know whether that's what you intended, or whether
2314\tif a > 0:
2315\t c = d
2316\t_
2317was your intent. In general, Python-mode either reproduces the
2318indentation of the (closest code or indenting-comment) preceding
2319statement, or adds an extra py-indent-offset blanks if the preceding
2320statement has `:' as its last significant (non-whitespace and non-
2321comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002322\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002323
2324Continuation lines are given extra indentation. If you don't like the
2325suggested indentation, change it to something you do like, and Python-
2326mode will strive to indent later lines of the statement in the same way.
2327
2328If a line is a continuation line by virtue of being in an unclosed
2329paren/bracket/brace structure (`list', for short), the suggested
2330indentation depends on whether the current line contains the first item
2331in the list. If it does, it's indented py-indent-offset columns beyond
2332the indentation of the line containing the open bracket. If you don't
2333like that, change it by hand. The remaining items in the list will mimic
2334whatever indentation you give to the first item.
2335
2336If a line is a continuation line because the line preceding it ends with
2337a backslash, the third and following lines of the statement inherit their
2338indentation from the line preceding them. The indentation of the second
2339line in the statement depends on the form of the first (base) line: if
2340the base line is an assignment statement with anything more interesting
2341than the backslash following the leftmost assigning `=', the second line
2342is indented two columns beyond that `='. Else it's indented to two
2343columns beyond the leftmost solid chunk of non-whitespace characters on
2344the base line.
2345
2346Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2347repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2348structure you intend.
2349%c:indent-for-tab-command
2350%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002351%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002352
2353
2354The next function may be handy when editing code you didn't write:
2355%c:py-guess-indent-offset
2356
2357
2358The remaining `indent' functions apply to a region of Python code. They
2359assume the block structure (equals indentation, in Python) of the region
2360is correct, and alter the indentation in various ways while preserving
2361the block structure:
2362%c:py-indent-region
2363%c:py-shift-region-left
2364%c:py-shift-region-right
2365
2366@MARKING & MANIPULATING REGIONS OF CODE
2367
2368\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002369\\[py-mark-def-or-class]\t mark smallest enclosing def
2370\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002371\\[comment-region]\t comment out region of code
2372\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002373%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002374%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002375%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002376
2377@MOVING POINT
2378
2379\\[py-previous-statement]\t move to statement preceding point
2380\\[py-next-statement]\t move to statement following point
2381\\[py-goto-block-up]\t move up to start of current block
2382\\[beginning-of-python-def-or-class]\t move to start of def
2383\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2384\\[end-of-python-def-or-class]\t move to end of def
2385\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2386
2387The first two move to one statement beyond the statement that contains
2388point. A numeric prefix argument tells them to move that many
2389statements instead. Blank lines, comment lines, and continuation lines
2390do not count as `statements' for these commands. So, e.g., you can go
2391to the first code statement in a file by entering
2392\t\\[beginning-of-buffer]\t to move to the top of the file
2393\t\\[py-next-statement]\t to skip over initial comments and blank lines
2394Or do `\\[py-previous-statement]' with a huge prefix argument.
2395%c:py-previous-statement
2396%c:py-next-statement
2397%c:py-goto-block-up
2398%c:beginning-of-python-def-or-class
2399%c:end-of-python-def-or-class
2400
2401@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2402
2403`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2404
2405`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2406overall class and def structure of a module.
2407
2408`\\[back-to-indentation]' moves point to a line's first non-blank character.
2409
2410`\\[indent-relative]' is handy for creating odd indentation.
2411
2412@OTHER EMACS HINTS
2413
2414If you don't like the default value of a variable, change its value to
2415whatever you do like by putting a `setq' line in your .emacs file.
2416E.g., to set the indentation increment to 4, put this line in your
2417.emacs:
2418\t(setq py-indent-offset 4)
2419To see the value of a variable, do `\\[describe-variable]' and enter the variable
2420name at the prompt.
2421
2422When entering a key sequence like `C-c C-n', it is not necessary to
2423release the CONTROL key after doing the `C-c' part -- it suffices to
2424press the CONTROL key, press and release `c' (while still holding down
2425CONTROL), press and release `n' (while still holding down CONTROL), &
2426then release CONTROL.
2427
2428Entering Python mode calls with no arguments the value of the variable
2429`python-mode-hook', if that value exists and is not nil; for backward
2430compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2431the Elisp manual for details.
2432
2433Obscure: When python-mode is first loaded, it looks for all bindings
2434to newline-and-indent in the global keymap, and shadows them with
2435local bindings to py-newline-and-indent."))
2436
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002437
2438;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002439(defvar py-parse-state-re
2440 (concat
2441 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2442 "\\|"
2443 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002444
Barry Warsaw7ae77681994-12-12 20:38:05 +00002445;; returns the parse state at point (see parse-partial-sexp docs)
2446(defun py-parse-state ()
2447 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002448 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002449 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002450 (while (not done)
2451 ;; back up to the first preceding line (if any; else start of
2452 ;; buffer) that begins with a popular Python keyword, or a
2453 ;; non- whitespace and non-comment character. These are good
2454 ;; places to start parsing to see whether where we started is
2455 ;; at a non-zero nesting level. It may be slow for people who
2456 ;; write huge code blocks or huge lists ... tough beans.
2457 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002458 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002459 (beginning-of-line)
2460 (save-excursion
2461 (setq pps (parse-partial-sexp (point) here)))
2462 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw170ffa71996-07-31 20:57:22 +00002463 (setq done (or (zerop ci)
2464 (not (nth 3 pps))
2465 (bobp)))
2466 )
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002467 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002468
2469;; if point is at a non-zero nesting level, returns the number of the
2470;; character that opens the smallest enclosing unclosed list; else
2471;; returns nil.
2472(defun py-nesting-level ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002473 (let ((status (py-parse-state)) )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002474 (if (zerop (car status))
2475 nil ; not in a nest
2476 (car (cdr status))))) ; char# of open bracket
2477
2478;; t iff preceding line ends with backslash that's not in a comment
2479(defun py-backslash-continuation-line-p ()
2480 (save-excursion
2481 (beginning-of-line)
2482 (and
2483 ;; use a cheap test first to avoid the regexp if possible
2484 ;; use 'eq' because char-after may return nil
2485 (eq (char-after (- (point) 2)) ?\\ )
2486 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002487 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002488 (looking-at py-continued-re))))
2489
2490;; t iff current line is a continuation line
2491(defun py-continuation-line-p ()
2492 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002493 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002494 (or (py-backslash-continuation-line-p)
2495 (py-nesting-level))))
2496
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002497;; go to initial line of current statement; usually this is the line
2498;; we're on, but if we're on the 2nd or following lines of a
2499;; continuation block, we need to go up to the first line of the
2500;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002501;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002502;; Tricky: We want to avoid quadratic-time behavior for long continued
2503;; blocks, whether of the backslash or open-bracket varieties, or a
2504;; mix of the two. The following manages to do that in the usual
2505;; cases.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002506(defun py-goto-initial-line ()
2507 (let ( open-bracket-pos )
2508 (while (py-continuation-line-p)
2509 (beginning-of-line)
2510 (if (py-backslash-continuation-line-p)
2511 (while (py-backslash-continuation-line-p)
2512 (forward-line -1))
2513 ;; else zip out of nested brackets/braces/parens
2514 (while (setq open-bracket-pos (py-nesting-level))
2515 (goto-char open-bracket-pos)))))
2516 (beginning-of-line))
2517
2518;; go to point right beyond final line of current statement; usually
2519;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002520;; statement we need to skip over the continuation lines. Tricky:
2521;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002522(defun py-goto-beyond-final-line ()
2523 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002524 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002525 (while (and (py-continuation-line-p)
2526 (not (eobp)))
2527 ;; skip over the backslash flavor
2528 (while (and (py-backslash-continuation-line-p)
2529 (not (eobp)))
2530 (forward-line 1))
2531 ;; if in nest, zip to the end of the nest
2532 (setq state (py-parse-state))
2533 (if (and (not (zerop (car state)))
2534 (not (eobp)))
2535 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002536 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002537 (forward-line 1))))))
2538
2539;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002540;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002541(defun py-statement-opens-block-p ()
2542 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002543 (let ((start (point))
2544 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2545 (searching t)
2546 (answer nil)
2547 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002548 (goto-char start)
2549 (while searching
2550 ;; look for a colon with nothing after it except whitespace, and
2551 ;; maybe a comment
2552 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2553 finish t)
2554 (if (eq (point) finish) ; note: no `else' clause; just
2555 ; keep searching if we're not at
2556 ; the end yet
2557 ;; sure looks like it opens a block -- but it might
2558 ;; be in a comment
2559 (progn
2560 (setq searching nil) ; search is done either way
2561 (setq state (parse-partial-sexp start
2562 (match-beginning 0)))
2563 (setq answer (not (nth 4 state)))))
2564 ;; search failed: couldn't find another interesting colon
2565 (setq searching nil)))
2566 answer)))
2567
Barry Warsawf831d811996-07-31 20:42:59 +00002568(defun py-statement-closes-block-p ()
2569 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002570 ;; starts with `return', `raise', `break', `continue', and `pass'.
2571 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002572 (let ((here (point)))
2573 (back-to-indentation)
2574 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002575 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002576 (goto-char here))))
2577
Barry Warsaw7ae77681994-12-12 20:38:05 +00002578;; go to point right beyond final line of block begun by the current
2579;; line. This is the same as where py-goto-beyond-final-line goes
2580;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002581;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002582(defun py-goto-beyond-block ()
2583 (if (py-statement-opens-block-p)
2584 (py-mark-block nil 'just-move)
2585 (py-goto-beyond-final-line)))
2586
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002587;; go to start of first statement (not blank or comment or
2588;; continuation line) at or preceding point. returns t if there is
2589;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002590(defun py-goto-statement-at-or-above ()
2591 (py-goto-initial-line)
2592 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002593 ;; skip back over blank & comment lines
2594 ;; note: will skip a blank or comment line that happens to be
2595 ;; a continuation line too
2596 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2597 (progn (py-goto-initial-line) t)
2598 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002599 t))
2600
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002601;; go to start of first statement (not blank or comment or
2602;; continuation line) following the statement containing point returns
2603;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002604(defun py-goto-statement-below ()
2605 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002606 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002607 (py-goto-beyond-final-line)
2608 (while (and
2609 (looking-at py-blank-or-comment-re)
2610 (not (eobp)))
2611 (forward-line 1))
2612 (if (eobp)
2613 (progn (goto-char start) nil)
2614 t)))
2615
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002616;; go to start of statement, at or preceding point, starting with
2617;; keyword KEY. Skips blank lines and non-indenting comments upward
2618;; first. If that statement starts with KEY, done, else go back to
2619;; first enclosing block starting with KEY. If successful, leaves
2620;; point at the start of the KEY line & returns t. Else leaves point
2621;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002622(defun py-go-up-tree-to-keyword (key)
2623 ;; skip blanks and non-indenting #
2624 (py-goto-initial-line)
2625 (while (and
2626 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2627 (zerop (forward-line -1))) ; go back
2628 nil)
2629 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002630 (let* ((re (concat "[ \t]*" key "\\b"))
2631 (case-fold-search nil) ; let* so looking-at sees this
2632 (found (looking-at re))
2633 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002634 (while (not (or found dead))
2635 (condition-case nil ; in case no enclosing block
2636 (py-goto-block-up 'no-mark)
2637 (error (setq dead t)))
2638 (or dead (setq found (looking-at re))))
2639 (beginning-of-line)
2640 found))
2641
2642;; return string in buffer from start of indentation to end of line;
2643;; prefix "..." if leading whitespace was skipped
2644(defun py-suck-up-leading-text ()
2645 (save-excursion
2646 (back-to-indentation)
2647 (concat
2648 (if (bolp) "" "...")
2649 (buffer-substring (point) (progn (end-of-line) (point))))))
2650
2651;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2652;; as a Lisp symbol; return nil if none
2653(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002654 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002655 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2656 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2657 nil)))
2658
Barry Warsawb3e81d51996-09-04 15:12:42 +00002659(defun py-current-defun ()
2660 ;; tell add-log.el how to find the current function/method/variable
2661 (save-excursion
2662 (if (re-search-backward py-defun-start-re nil t)
2663 (or (match-string 3)
2664 (let ((method (match-string 2)))
2665 (if (and (not (zerop (length (match-string 1))))
2666 (re-search-backward py-class-start-re nil t))
2667 (concat (match-string 1) "." method)
2668 method)))
2669 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002670
2671
Barry Warsawfec75d61995-07-05 23:26:15 +00002672(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002673 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002674
Barry Warsaw850437a1995-03-08 21:50:28 +00002675(defun py-version ()
2676 "Echo the current version of `python-mode' in the minibuffer."
2677 (interactive)
2678 (message "Using `python-mode' version %s" py-version)
2679 (py-keep-region-active))
2680
2681;; only works under Emacs 19
2682;(eval-when-compile
2683; (require 'reporter))
2684
2685(defun py-submit-bug-report (enhancement-p)
2686 "Submit via mail a bug report on `python-mode'.
2687With \\[universal-argument] just submit an enhancement request."
2688 (interactive
2689 (list (not (y-or-n-p
2690 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002691 (let ((reporter-prompt-for-summary-p (if enhancement-p
2692 "(Very) brief summary: "
2693 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002694 (require 'reporter)
2695 (reporter-submit-bug-report
2696 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002697 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002698 ;; varlist
2699 (if enhancement-p nil
2700 '(py-python-command
2701 py-indent-offset
2702 py-block-comment-prefix
2703 py-scroll-process-buffer
2704 py-temp-directory
2705 py-beep-if-tab-change))
2706 nil ;pre-hooks
2707 nil ;post-hooks
2708 "Dear Barry,") ;salutation
2709 (if enhancement-p nil
2710 (set-mark (point))
2711 (insert
2712"Please replace this text with a sufficiently large code sample\n\
2713and an exact recipe so that I can reproduce your problem. Failure\n\
2714to do so may mean a greater delay in fixing your bug.\n\n")
2715 (exchange-point-and-mark)
2716 (py-keep-region-active))))
2717
2718
Barry Warsaw47384781997-11-26 05:27:45 +00002719(defun py-kill-emacs-hook ()
2720 (mapcar #'(lambda (filename)
2721 (py-safe (delete-file filename)))
2722 py-file-queue))
2723
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002724;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002725(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002726
2727
2728
2729(provide 'python-mode)
2730;;; python-mode.el ends here