blob: 9a622055207108cd06383fa12bc7d5f004bf3655 [file] [log] [blame]
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001;;; python-mode.el --- Major mode for editing Python programs
2
3;; Copyright (C) 1992,1993,1994 Tim Peters
4
Barry Warsawf64b4051998-02-12 16:52:14 +00005;; Author: 1995-1998 Barry A. Warsaw
Barry Warsawfec75d61995-07-05 23:26:15 +00006;; 1992-1994 Tim Peters
Barry Warsawa97a3f31997-11-04 18:47:06 +00007;; Maintainer: python-mode@python.org
8;; Created: Feb 1992
9;; Keywords: python languages oop
Barry Warsaw7b0f5681995-03-08 21:33:04 +000010
Barry 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
Barry Warsaw8f972b71998-02-05 20:45:49 +0000142(defcustom py-python-command-args '("-i")
143 "*List of string arguments to be used when starting a Python shell."
144 :type '(repeat string)
145 :group 'python)
146
Barry Warsawc72c11c1997-08-09 06:42:08 +0000147(defcustom py-indent-offset 4
148 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000149Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +0000150when you're editing someone else's Python code."
151 :type 'integer
152 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000153
Barry Warsawc72c11c1997-08-09 06:42:08 +0000154(defcustom py-align-multiline-strings-p t
155 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000156When this flag is non-nil, continuation lines are lined up under the
157preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000158lines are aligned to column zero."
159 :type '(choice (const :tag "Align under preceding line" t)
160 (const :tag "Align to column zero" nil))
161 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000162
Barry Warsawc72c11c1997-08-09 06:42:08 +0000163(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000164 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000165This should follow the convention for non-indenting comment lines so
166that the indentation commands won't get confused (i.e., the string
167should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000168`...' is arbitrary)."
169 :type 'string
170 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000171
Barry Warsawc72c11c1997-08-09 06:42:08 +0000172(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000173 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000174
Barry Warsaw6d627751996-03-06 18:41:38 +0000175When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000176if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000177
178When t, lines that begin with a single `#' are a hint to subsequent
179line indentation. If the previous line is such a comment line (as
180opposed to one that starts with `py-block-comment-prefix'), then it's
181indentation is used as a hint for this line's indentation. Lines that
182begin with `py-block-comment-prefix' are ignored for indentation
183purposes.
184
185When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000186indentation hints, unless the comment character is in column zero."
187 :type '(choice
188 (const :tag "Skip all comment lines (fast)" nil)
189 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000190 (const :tag "Single # `sets' indentation except at column zero"
191 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000192 )
193 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000194
Barry Warsaw8ee4a601998-02-06 16:01:52 +0000195(defcustom py-scroll-process-buffer nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000196 "*Scroll Python process buffer as output arrives.
197If nil, the Python process buffer acts, with respect to scrolling, like
198Shell-mode buffers normally act. This is surprisingly complicated and
199so won't be explained here; in fact, you can't get the whole story
200without studying the Emacs C code.
201
202If non-nil, the behavior is different in two respects (which are
203slightly inaccurate in the interest of brevity):
204
205 - If the buffer is in a window, and you left point at its end, the
206 window will scroll as new output arrives, and point will move to the
207 buffer's end, even if the window is not the selected window (that
208 being the one the cursor is in). The usual behavior for shell-mode
209 windows is not to scroll, and to leave point where it was, if the
210 buffer is in a window other than the selected window.
211
212 - If the buffer is not visible in any window, and you left point at
213 its end, the buffer will be popped into a window as soon as more
214 output arrives. This is handy if you have a long-running
215 computation and don't want to tie up screen area waiting for the
216 output. The usual behavior for a shell-mode buffer is to stay
217 invisible until you explicitly visit it.
218
219Note the `and if you left point at its end' clauses in both of the
220above: you can `turn off' the special behaviors while output is in
221progress, by visiting the Python buffer and moving point to anywhere
222besides the end. Then the buffer won't scroll, point will remain where
223you leave it, and if you hide the buffer it will stay hidden until you
224visit it again. You can enable and disable the special behaviors as
225often as you like, while output is in progress, by (respectively) moving
226point to, or away from, the end of the buffer.
227
228Warning: If you expect a large amount of output, you'll probably be
229happier setting this option to nil.
230
231Obscure: `End of buffer' above should really say `at or beyond the
232process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000233told <grin>."
234 :type 'boolean
235 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000236
Barry Warsaw516b6201997-08-09 06:43:20 +0000237(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000238 (let ((ok '(lambda (x)
239 (and x
240 (setq x (expand-file-name x)) ; always true
241 (file-directory-p x)
242 (file-writable-p x)
243 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000244 (or (funcall ok (getenv "TMPDIR"))
245 (funcall ok "/usr/tmp")
246 (funcall ok "/tmp")
247 (funcall ok ".")
248 (error
249 "Couldn't find a usable temp directory -- set py-temp-directory")))
250 "*Directory used for temp files created by a *Python* process.
251By default, the first directory from this list that exists and that you
252can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000253/usr/tmp, /tmp, or the current directory."
254 :type 'string
255 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000256
Barry Warsaw516b6201997-08-09 06:43:20 +0000257(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000258 "*Ring the bell if tab-width is changed.
259If a comment of the form
260
261 \t# vi:set tabsize=<number>:
262
263is found before the first code line when the file is entered, and the
264current value of (the general Emacs variable) `tab-width' does not
265equal <number>, `tab-width' is set to <number>, a message saying so is
266displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000267the Emacs bell is also rung as a warning."
268 :type 'boolean
269 :group 'python)
270
Barry Warsaw9981d221997-12-03 05:25:48 +0000271(defcustom py-jump-on-exception t
272 "*Jump to innermost exception frame in *Python Output* buffer.
273When this variable is non-nil and ane exception occurs when running
274Python code synchronously in a subprocess, jump immediately to the
275source code of the innermost frame.")
276
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000277(defcustom py-backspace-function 'backward-delete-char-untabify
278 "*Function called by `py-electric-backspace' when deleting backwards."
279 :type 'function
280 :group 'python)
281
282(defcustom py-delete-function 'delete-char
283 "*Function called by `py-electric-delete' when deleting forwards."
284 :type 'function
285 :group 'python)
286
Barry Warsawc0ecb531998-01-20 21:43:34 +0000287;; Not customizable
288(defvar py-master-file nil
289 "If non-nil, execute the named file instead of the buffer's file.
290The intent is to allow someone to set this variable file local
291variable section, e.g.:
292
293 # Local Variables:
294 # py-master-file: \"master.py\"
295 # End:
296
297so that hitting \\[py-execute-buffer] in that buffer executes the
298named master file instead of the buffer's file. Note that if the file
299name has a relative path, the `default-directory' for the file is
300prepended to come up with a buffer name.")
301(make-variable-buffer-local 'py-master-file)
302
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000303
Barry Warsawc72c11c1997-08-09 06:42:08 +0000304
305;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
306;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
307
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000308(defconst py-emacs-features
309 (let (features)
310 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
311 ;; the same string.
312 (let ((tmp1 (make-temp-name ""))
313 (tmp2 (make-temp-name "")))
314 (if (string-equal tmp1 tmp2)
315 (push 'broken-temp-names features)))
316 ;; return the features
317 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000318 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000319There are many flavors of Emacs out there, with different levels of
320support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000321
Barry Warsawfb07f401997-02-24 03:37:22 +0000322(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000323 (let ((kw1 (mapconcat 'identity
324 '("and" "assert" "break" "class"
325 "continue" "def" "del" "elif"
326 "else" "except" "exec" "for"
327 "from" "global" "if" "import"
328 "in" "is" "lambda" "not"
329 "or" "pass" "print" "raise"
330 "return" "while"
331 )
332 "\\|"))
333 (kw2 (mapconcat 'identity
334 '("else:" "except:" "finally:" "try:")
335 "\\|"))
336 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000337 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000338 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000339 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
340 ;; block introducing keywords with immediately following colons.
341 ;; Yes "except" is in both lists.
342 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000343 ;; classes
344 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
345 1 font-lock-type-face)
346 ;; functions
347 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
348 1 font-lock-function-name-face)
349 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000350 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000351(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
352
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000353
Barry Warsaw81437461996-08-01 19:48:02 +0000354(defvar imenu-example--python-show-method-args-p nil
355 "*Controls echoing of arguments of functions & methods in the imenu buffer.
356When non-nil, arguments are printed.")
357
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000358(make-variable-buffer-local 'py-indent-offset)
359
Barry Warsawe467bfb1997-11-26 05:40:58 +0000360;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000361(defvar py-file-queue nil
362 "Queue of Python temp files awaiting execution.
363Currently-active file is at the head of the list.")
364
Barry Warsawc72c11c1997-08-09 06:42:08 +0000365
366;; Constants
367
368;; Regexp matching a Python string literal
369(defconst py-stringlit-re
370 (concat
371 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
372 "\\|" ; or
373 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
374
375;; Regexp matching Python lines that are continued via backslash.
376;; This is tricky because a trailing backslash does not mean
377;; continuation if it's in a comment
378(defconst py-continued-re
379 (concat
380 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
381 "\\\\$"))
382
383;; Regexp matching blank or comment lines.
384(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
385
386;; Regexp matching clauses to be outdented one level.
387(defconst py-outdent-re
388 (concat "\\(" (mapconcat 'identity
389 '("else:"
390 "except\\(\\s +.*\\)?:"
391 "finally:"
392 "elif\\s +.*:")
393 "\\|")
394 "\\)"))
395
396
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000397;; Regexp matching keywords which typically close a block
398(defconst py-block-closing-keywords-re
399 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
400
Barry Warsawc72c11c1997-08-09 06:42:08 +0000401;; Regexp matching lines to not outdent after.
402(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000403 (concat
404 "\\("
405 (mapconcat 'identity
406 (list "try:"
407 "except\\(\\s +.*\\)?:"
408 "while\\s +.*:"
409 "for\\s +.*:"
410 "if\\s +.*:"
411 "elif\\s +.*:"
412 (concat py-block-closing-keywords-re "[ \t\n]")
413 )
414 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000415 "\\)"))
416
417;; Regexp matching a function, method or variable assignment. If you
418;; change this, you probably have to change `py-current-defun' as
419;; well. This is only used by `py-current-defun' to find the name for
420;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000421(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000422 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
423
424;; Regexp for finding a class name. If you change this, you probably
425;; have to change `py-current-defun' as well. This is only used by
426;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000427(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
428
429;; Regexp that describes tracebacks
430(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000431 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000432
433
434
435;; Utilities
436
437(defmacro py-safe (&rest body)
438 ;; safely execute BODY, return nil if an error occurred
439 (` (condition-case nil
440 (progn (,@ body))
441 (error nil))))
442
443(defsubst py-keep-region-active ()
444 ;; Do whatever is necessary to keep the region active in XEmacs.
445 ;; Ignore byte-compiler warnings you might see. Also note that
446 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
447 ;; to take explicit action.
448 (and (boundp 'zmacs-region-stays)
449 (setq zmacs-region-stays t)))
450
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000451(defsubst py-point (position)
452 ;; Returns the value of point at certain commonly referenced POSITIONs.
453 ;; POSITION can be one of the following symbols:
454 ;;
455 ;; bol -- beginning of line
456 ;; eol -- end of line
457 ;; bod -- beginning of defun
458 ;; boi -- back to indentation
459 ;;
460 ;; This function does not modify point or mark.
461 (let ((here (point)))
462 (cond
463 ((eq position 'bol) (beginning-of-line))
464 ((eq position 'eol) (end-of-line))
465 ((eq position 'bod) (beginning-of-python-def-or-class))
466 ((eq position 'bob) (beginning-of-buffer))
467 ((eq position 'eob) (end-of-buffer))
468 ((eq position 'boi) (back-to-indentation))
469 (t (error "unknown buffer position requested: %s" position))
470 )
471 (prog1
472 (point)
473 (goto-char here))))
474
475(defsubst py-highlight-line (from to file line)
476 (cond
477 ((fboundp 'make-extent)
478 ;; XEmacs
479 (let ((e (make-extent from to)))
480 (set-extent-property e 'mouse-face 'highlight)
481 (set-extent-property e 'py-exc-info (cons file line))
482 (set-extent-property e 'keymap py-mode-output-map)))
483 (t
484 ;; Emacs -- Please port this!
485 )
486 ))
487
Barry Warsawc72c11c1997-08-09 06:42:08 +0000488
489;; Major mode boilerplate
490
Barry Warsaw7ae77681994-12-12 20:38:05 +0000491;; define a mode-specific abbrev table for those who use such things
492(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000493 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000494(define-abbrev-table 'python-mode-abbrev-table nil)
495
Barry Warsaw7ae77681994-12-12 20:38:05 +0000496(defvar python-mode-hook nil
497 "*Hook called by `python-mode'.")
498
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000499;; in previous version of python-mode.el, the hook was incorrectly
500;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000501(and (fboundp 'make-obsolete-variable)
502 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
503
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000504(defvar py-mode-map ()
505 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000506(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000507 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000508 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000509 ;; electric keys
510 (define-key py-mode-map ":" 'py-electric-colon)
511 ;; indentation level modifiers
512 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
513 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
514 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
515 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
516 ;; subprocess commands
517 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
518 (define-key py-mode-map "\C-c|" 'py-execute-region)
519 (define-key py-mode-map "\C-c!" 'py-shell)
520 ;; Caution! Enter here at your own risk. We are trying to support
521 ;; several behaviors and it gets disgusting. :-( This logic ripped
522 ;; largely from CC Mode.
523 ;;
524 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
525 ;; backwards deletion behavior to DEL, which both Delete and
526 ;; Backspace get translated to. There's no way to separate this
527 ;; behavior in a clean way, so deal with it! Besides, it's been
528 ;; this way since the dawn of time.
529 (if (not (boundp 'delete-key-deletes-forward))
530 (define-key py-mode-map "\177" 'py-electric-backspace)
531 ;; However, XEmacs 20 actually achieved enlightenment. It is
532 ;; possible to sanely define both backward and forward deletion
533 ;; behavior under X separately (TTYs are forever beyond hope, but
534 ;; who cares? XEmacs 20 does the right thing with these too).
535 (define-key py-mode-map [delete] 'py-electric-delete)
536 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000537 ;; Separate M-BS from C-M-h. The former should remain
538 ;; backward-kill-word.
539 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000540 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000541 ;; Miscellaneous
542 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
543 (define-key py-mode-map "\C-c\t" 'py-indent-region)
544 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
545 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
546 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000547 (define-key py-mode-map "\C-c#" 'py-comment-region)
548 (define-key py-mode-map "\C-c?" 'py-describe-mode)
549 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
550 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
551 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000552 (define-key py-mode-map "\C-c-" 'py-up-exception)
553 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000554 ;; information
555 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
556 (define-key py-mode-map "\C-c\C-v" 'py-version)
557 ;; py-newline-and-indent mappings
Barry Warsaw82aecb91998-01-21 05:14:24 +0000558 (define-key py-mode-map "\n" 'py-newline-and-indent)
559 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000560 ;; shadow global bindings for newline-and-indent w/ the py- version.
561 ;; BAW - this is extremely bad form, but I'm not going to change it
562 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000563 (mapcar #'(lambda (key)
564 (define-key py-mode-map key 'py-newline-and-indent))
565 (where-is-internal 'newline-and-indent))
566 )
567
568(defvar py-mode-output-map nil
569 "Keymap used in *Python Output* buffers*")
570(if py-mode-output-map
571 nil
572 (setq py-mode-output-map (make-sparse-keymap))
573 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
574 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
575 ;; TBD: Disable all self-inserting keys. This is bogus, we should
576 ;; really implement this as *Python Output* buffer being read-only
577 (mapcar #' (lambda (key)
578 (define-key py-mode-output-map key
579 #'(lambda () (interactive) (beep))))
580 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000581 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000582
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000583(defvar py-mode-syntax-table nil
584 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000585(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000586 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000587 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000588 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
589 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
590 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
591 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
592 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
593 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
594 ;; Add operator symbols misassigned in the std table
595 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
596 (modify-syntax-entry ?\% "." py-mode-syntax-table)
597 (modify-syntax-entry ?\& "." py-mode-syntax-table)
598 (modify-syntax-entry ?\* "." py-mode-syntax-table)
599 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
600 (modify-syntax-entry ?\- "." py-mode-syntax-table)
601 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
602 (modify-syntax-entry ?\< "." py-mode-syntax-table)
603 (modify-syntax-entry ?\= "." py-mode-syntax-table)
604 (modify-syntax-entry ?\> "." py-mode-syntax-table)
605 (modify-syntax-entry ?\| "." py-mode-syntax-table)
606 ;; For historical reasons, underscore is word class instead of
607 ;; symbol class. GNU conventions say it should be symbol class, but
608 ;; there's a natural conflict between what major mode authors want
609 ;; and what users expect from `forward-word' and `backward-word'.
610 ;; Guido and I have hashed this out and have decided to keep
611 ;; underscore in word class. If you're tempted to change it, try
612 ;; binding M-f and M-b to py-forward-into-nomenclature and
613 ;; py-backward-into-nomenclature instead.
614 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
615 ;; Both single quote and double quote are string delimiters
616 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
617 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
618 ;; backquote is open and close paren
619 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
620 ;; comment delimiters
621 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
622 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
623 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000624
Barry Warsawb3e81d51996-09-04 15:12:42 +0000625
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000626
Barry Warsaw42f707f1996-07-29 21:05:05 +0000627;; Menu definitions, only relevent if you have the easymenu.el package
628;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000629(defvar py-menu nil
630 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000631This menu will get created automatically if you have the `easymenu'
632package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000633
Barry Warsawc72c11c1997-08-09 06:42:08 +0000634(and (py-safe (require 'easymenu) t)
635 (easy-menu-define
636 py-menu py-mode-map "Python Mode menu"
637 '("Python"
638 ["Comment Out Region" py-comment-region (mark)]
639 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
640 "-"
641 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000642 ["Mark current def" py-mark-def-or-class t]
643 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000644 "-"
645 ["Shift region left" py-shift-region-left (mark)]
646 ["Shift region right" py-shift-region-right (mark)]
647 "-"
648 ["Execute buffer" py-execute-buffer t]
649 ["Execute region" py-execute-region (mark)]
650 ["Start interpreter..." py-shell t]
651 "-"
652 ["Go to start of block" py-goto-block-up t]
653 ["Go to start of class" (beginning-of-python-def-or-class t) t]
654 ["Move to end of class" (end-of-python-def-or-class t) t]
655 ["Move to start of def" beginning-of-python-def-or-class t]
656 ["Move to end of def" end-of-python-def-or-class t]
657 "-"
658 ["Describe mode" py-describe-mode t]
659 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000660
Barry Warsaw81437461996-08-01 19:48:02 +0000661
662
663;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
664(defvar imenu-example--python-class-regexp
665 (concat ; <<classes>>
666 "\\(" ;
667 "^[ \t]*" ; newline and maybe whitespace
668 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
669 ; possibly multiple superclasses
670 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
671 "[ \t]*:" ; and the final :
672 "\\)" ; >>classes<<
673 )
674 "Regexp for Python classes for use with the imenu package."
675 )
676
677(defvar imenu-example--python-method-regexp
678 (concat ; <<methods and functions>>
679 "\\(" ;
680 "^[ \t]*" ; new line and maybe whitespace
681 "\\(def[ \t]+" ; function definitions start with def
682 "\\([a-zA-Z0-9_]+\\)" ; name is here
683 ; function arguments...
684 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
685 "\\)" ; end of def
686 "[ \t]*:" ; and then the :
687 "\\)" ; >>methods and functions<<
688 )
689 "Regexp for Python methods/functions for use with the imenu package."
690 )
691
692(defvar imenu-example--python-method-no-arg-parens '(2 8)
693 "Indicies into groups of the Python regexp for use with imenu.
694
695Using these values will result in smaller imenu lists, as arguments to
696functions are not listed.
697
698See the variable `imenu-example--python-show-method-args-p' for more
699information.")
700
701(defvar imenu-example--python-method-arg-parens '(2 7)
702 "Indicies into groups of the Python regexp for use with imenu.
703Using these values will result in large imenu lists, as arguments to
704functions are listed.
705
706See the variable `imenu-example--python-show-method-args-p' for more
707information.")
708
709;; Note that in this format, this variable can still be used with the
710;; imenu--generic-function. Otherwise, there is no real reason to have
711;; it.
712(defvar imenu-example--generic-python-expression
713 (cons
714 (concat
715 imenu-example--python-class-regexp
716 "\\|" ; or...
717 imenu-example--python-method-regexp
718 )
719 imenu-example--python-method-no-arg-parens)
720 "Generic Python expression which may be used directly with imenu.
721Used by setting the variable `imenu-generic-expression' to this value.
722Also, see the function \\[imenu-example--create-python-index] for a
723better alternative for finding the index.")
724
725;; These next two variables are used when searching for the python
726;; class/definitions. Just saving some time in accessing the
727;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000728(defvar imenu-example--python-generic-regexp nil)
729(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000730
731
Barry Warsaw81437461996-08-01 19:48:02 +0000732(defun imenu-example--create-python-index ()
733 "Python interface function for imenu package.
734Finds all python classes and functions/methods. Calls function
735\\[imenu-example--create-python-index-engine]. See that function for
736the details of how this works."
737 (setq imenu-example--python-generic-regexp
738 (car imenu-example--generic-python-expression))
739 (setq imenu-example--python-generic-parens
740 (if imenu-example--python-show-method-args-p
741 imenu-example--python-method-arg-parens
742 imenu-example--python-method-no-arg-parens))
743 (goto-char (point-min))
744 (imenu-example--create-python-index-engine nil))
745
746(defun imenu-example--create-python-index-engine (&optional start-indent)
747 "Function for finding imenu definitions in Python.
748
749Finds all definitions (classes, methods, or functions) in a Python
750file for the imenu package.
751
752Returns a possibly nested alist of the form
753
754 (INDEX-NAME . INDEX-POSITION)
755
756The second element of the alist may be an alist, producing a nested
757list as in
758
759 (INDEX-NAME . INDEX-ALIST)
760
761This function should not be called directly, as it calls itself
762recursively and requires some setup. Rather this is the engine for
763the function \\[imenu-example--create-python-index].
764
765It works recursively by looking for all definitions at the current
766indention level. When it finds one, it adds it to the alist. If it
767finds a definition at a greater indentation level, it removes the
768previous definition from the alist. In it's place it adds all
769definitions found at the next indentation level. When it finds a
770definition that is less indented then the current level, it retuns the
771alist it has created thus far.
772
773The optional argument START-INDENT indicates the starting indentation
774at which to continue looking for Python classes, methods, or
775functions. If this is not supplied, the function uses the indentation
776of the first definition found."
777 (let ((index-alist '())
778 (sub-method-alist '())
779 looking-p
780 def-name prev-name
781 cur-indent def-pos
782 (class-paren (first imenu-example--python-generic-parens))
783 (def-paren (second imenu-example--python-generic-parens)))
784 (setq looking-p
785 (re-search-forward imenu-example--python-generic-regexp
786 (point-max) t))
787 (while looking-p
788 (save-excursion
789 ;; used to set def-name to this value but generic-extract-name is
790 ;; new to imenu-1.14. this way it still works with imenu-1.11
791 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
792 (let ((cur-paren (if (match-beginning class-paren)
793 class-paren def-paren)))
794 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000795 (buffer-substring-no-properties (match-beginning cur-paren)
796 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000797 (beginning-of-line)
798 (setq cur-indent (current-indentation)))
799
800 ;; HACK: want to go to the next correct definition location. we
801 ;; explicitly list them here. would be better to have them in a
802 ;; list.
803 (setq def-pos
804 (or (match-beginning class-paren)
805 (match-beginning def-paren)))
806
807 ;; if we don't have a starting indent level, take this one
808 (or start-indent
809 (setq start-indent cur-indent))
810
811 ;; if we don't have class name yet, take this one
812 (or prev-name
813 (setq prev-name def-name))
814
815 ;; what level is the next definition on? must be same, deeper
816 ;; or shallower indentation
817 (cond
818 ;; at the same indent level, add it to the list...
819 ((= start-indent cur-indent)
820
821 ;; if we don't have push, use the following...
822 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
823 (push (cons def-name def-pos) index-alist))
824
825 ;; deeper indented expression, recur...
826 ((< start-indent cur-indent)
827
828 ;; the point is currently on the expression we're supposed to
829 ;; start on, so go back to the last expression. The recursive
830 ;; call will find this place again and add it to the correct
831 ;; list
832 (re-search-backward imenu-example--python-generic-regexp
833 (point-min) 'move)
834 (setq sub-method-alist (imenu-example--create-python-index-engine
835 cur-indent))
836
837 (if sub-method-alist
838 ;; we put the last element on the index-alist on the start
839 ;; of the submethod alist so the user can still get to it.
840 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000841 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000842 (cons save-elmt sub-method-alist))
843 index-alist))))
844
845 ;; found less indented expression, we're done.
846 (t
847 (setq looking-p nil)
848 (re-search-backward imenu-example--python-generic-regexp
849 (point-min) t)))
850 (setq prev-name def-name)
851 (and looking-p
852 (setq looking-p
853 (re-search-forward imenu-example--python-generic-regexp
854 (point-max) 'move))))
855 (nreverse index-alist)))
856
Barry Warsaw42f707f1996-07-29 21:05:05 +0000857
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000858;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000859(defun python-mode ()
860 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000861To submit a problem report, enter `\\[py-submit-bug-report]' from a
862`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
863documentation. To see what version of `python-mode' you are running,
864enter `\\[py-version]'.
865
866This mode knows about Python indentation, tokens, comments and
867continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000868
869COMMANDS
870\\{py-mode-map}
871VARIABLES
872
Barry Warsaw42f707f1996-07-29 21:05:05 +0000873py-indent-offset\t\tindentation increment
874py-block-comment-prefix\t\tcomment string used by comment-region
875py-python-command\t\tshell command to invoke Python interpreter
876py-scroll-process-buffer\t\talways scroll Python process buffer
877py-temp-directory\t\tdirectory used for temp files (if needed)
878py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000879 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000880 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000881 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000882 (make-local-variable 'font-lock-defaults)
883 (make-local-variable 'paragraph-separate)
884 (make-local-variable 'paragraph-start)
885 (make-local-variable 'require-final-newline)
886 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000887 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000888 (make-local-variable 'comment-start-skip)
889 (make-local-variable 'comment-column)
890 (make-local-variable 'indent-region-function)
891 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000892 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000893 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000894 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000895 (setq major-mode 'python-mode
896 mode-name "Python"
897 local-abbrev-table python-mode-abbrev-table
Barry Warsaw5c38bf61997-12-02 22:01:04 +0000898 font-lock-defaults '(python-font-lock-keywords)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000899 paragraph-separate "^[ \t]*$"
900 paragraph-start "^[ \t]*$"
901 require-final-newline t
902 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000903 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000904 comment-start-skip "# *"
905 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000906 indent-region-function 'py-indent-region
907 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000908 ;; tell add-log.el how to find the current function/method/variable
909 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000910 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000911 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000912 ;; add the menu
913 (if py-menu
914 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000915 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000916 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000917 (setq comment-multi-line nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000918 ;; hack to allow overriding the tabsize in the file (see tokenizer.c)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000919 ;;
920 ;; not sure where the magic comment has to be; to save time
921 ;; searching for a rarity, we give up if it's not found prior to the
922 ;; first executable statement.
923 ;;
924 ;; BAW - on first glance, this seems like complete hackery. Why was
925 ;; this necessary, and is it still necessary?
926 (let ((case-fold-search nil)
927 (start (point))
928 new-tab-width)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000929 (if (re-search-forward
930 "^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
931 (prog2 (py-next-statement 1) (point) (goto-char 1))
932 t)
933 (progn
934 (setq new-tab-width
935 (string-to-int
936 (buffer-substring (match-beginning 1) (match-end 1))))
937 (if (= tab-width new-tab-width)
938 nil
939 (setq tab-width new-tab-width)
940 (message "Caution: tab-width changed to %d" new-tab-width)
941 (if py-beep-if-tab-change (beep)))))
942 (goto-char start))
943
Barry Warsaw755c6711996-08-01 20:02:55 +0000944 ;; install imenu
Barry Warsaw27ee1151997-12-03 05:03:44 +0000945 (if (py-safe (require 'imenu))
946 (progn
947 (make-variable-buffer-local 'imenu-create-index-function)
948 (setq imenu-create-index-function
949 (function imenu-example--create-python-index))
950 (setq imenu-generic-expression
951 imenu-example--generic-python-expression)
952 (if (fboundp 'imenu-add-to-menubar)
953 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
954 ))
Barry Warsaw755c6711996-08-01 20:02:55 +0000955
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000956 ;; run the mode hook. py-mode-hook use is deprecated
Barry Warsaw7ae77681994-12-12 20:38:05 +0000957 (if python-mode-hook
958 (run-hooks 'python-mode-hook)
959 (run-hooks 'py-mode-hook)))
960
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000961
Barry Warsawb91b7431995-03-14 15:55:20 +0000962;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000963(defun py-outdent-p ()
964 ;; returns non-nil if the current line should outdent one level
965 (save-excursion
966 (and (progn (back-to-indentation)
967 (looking-at py-outdent-re))
Barry Warsawf06777d1998-01-21 05:36:18 +0000968 (progn (forward-line -1)
969 (py-goto-initial-line)
970 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000971 (while (or (looking-at py-blank-or-comment-re)
972 (bobp))
973 (backward-to-indentation 1))
974 (not (looking-at py-no-outdent-re)))
975 )))
976
Barry Warsawb91b7431995-03-14 15:55:20 +0000977(defun py-electric-colon (arg)
978 "Insert a colon.
979In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000980argument is provided, that many colons are inserted non-electrically.
981Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +0000982 (interactive "P")
983 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000984 ;; are we in a string or comment?
985 (if (save-excursion
986 (let ((pps (parse-partial-sexp (save-excursion
987 (beginning-of-python-def-or-class)
988 (point))
989 (point))))
990 (not (or (nth 3 pps) (nth 4 pps)))))
991 (save-excursion
992 (let ((here (point))
993 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000994 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +0000995 (if (and (not arg)
996 (py-outdent-p)
997 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +0000998 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +0000999 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001000 )
1001 (setq outdent py-indent-offset))
1002 ;; Don't indent, only outdent. This assumes that any lines that
1003 ;; are already outdented relative to py-compute-indentation were
1004 ;; put there on purpose. Its highly annoying to have `:' indent
1005 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
1006 ;; there a better way to determine this???
1007 (if (< (current-indentation) indent) nil
1008 (goto-char here)
1009 (beginning-of-line)
1010 (delete-horizontal-space)
1011 (indent-to (- indent outdent))
1012 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001013
1014
Barry Warsawa97a3f31997-11-04 18:47:06 +00001015;; Python subprocess utilities and filters
1016(defun py-execute-file (proc filename)
1017 ;; Send a properly formatted execfile('FILENAME') to the underlying
1018 ;; Python interpreter process FILENAME. Make that process's buffer
1019 ;; visible and force display. Also make comint believe the user
1020 ;; typed this string so that kill-output-from-shell does The Right
1021 ;; Thing.
1022 (let ((curbuf (current-buffer))
1023 (procbuf (process-buffer proc))
1024 (comint-scroll-to-bottom-on-output t)
1025 (msg (format "## working on region in file %s...\n" filename))
1026 (cmd (format "execfile('%s')\n" filename)))
1027 (unwind-protect
1028 (progn
1029 (set-buffer procbuf)
1030 (goto-char (point-max))
1031 (move-marker (process-mark proc) (point))
1032 (funcall (process-filter proc) proc msg))
1033 (set-buffer curbuf))
1034 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001035
1036(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001037 (let ((curbuf (current-buffer))
1038 (pbuf (process-buffer pyproc))
1039 (pmark (process-mark pyproc))
1040 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001041 ;; make sure we switch to a different buffer at least once. if we
1042 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001043 ;; window, and point is before the end, and lots of output is
1044 ;; coming at a fast pace, then (a) simple cursor-movement commands
1045 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
1046 ;; to have a visible effect (the window just doesn't get updated,
1047 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
1048 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001049 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001050 ;; #b makes no sense to me at all. #a almost makes sense: unless
1051 ;; we actually change buffers, set_buffer_internal in buffer.c
1052 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1053 ;; seems to make the Emacs command loop reluctant to update the
1054 ;; display. Perhaps the default process filter in process.c's
1055 ;; read_process_output has update_mode_lines++ for a similar
1056 ;; reason? beats me ...
1057
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001058 (unwind-protect
1059 ;; make sure current buffer is restored
1060 ;; BAW - we want to check to see if this still applies
1061 (progn
1062 ;; mysterious ugly hack
1063 (if (eq curbuf pbuf)
1064 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001065
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001066 (set-buffer pbuf)
1067 (let* ((start (point))
1068 (goback (< start pmark))
1069 (goend (and (not goback) (= start (point-max))))
1070 (buffer-read-only nil))
1071 (goto-char pmark)
1072 (insert string)
1073 (move-marker pmark (point))
1074 (setq file-finished
1075 (and py-file-queue
1076 (equal ">>> "
1077 (buffer-substring
1078 (prog2 (beginning-of-line) (point)
1079 (goto-char pmark))
1080 (point)))))
1081 (if goback (goto-char start)
1082 ;; else
1083 (if py-scroll-process-buffer
1084 (let* ((pop-up-windows t)
1085 (pwin (display-buffer pbuf)))
1086 (set-window-point pwin (point)))))
1087 (set-buffer curbuf)
1088 (if file-finished
1089 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001090 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001091 (setq py-file-queue (cdr py-file-queue))
1092 (if py-file-queue
1093 (py-execute-file pyproc (car py-file-queue)))))
1094 (and goend
1095 (progn (set-buffer pbuf)
1096 (goto-char (point-max))))
1097 ))
1098 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001099
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001100(defun py-postprocess-output-buffer (buf)
Barry Warsaw9981d221997-12-03 05:25:48 +00001101 (let (line file bol)
1102 (save-excursion
1103 (set-buffer buf)
1104 (beginning-of-buffer)
1105 (while (re-search-forward py-traceback-line-re nil t)
1106 (setq file (match-string 1)
1107 line (string-to-int (match-string 2))
1108 bol (py-point 'bol))
1109 (py-highlight-line bol (py-point 'eol) file line))
1110 (when (and py-jump-on-exception line)
1111 (beep)
1112 (py-jump-to-exception file line))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001113 )))
1114
Barry Warsaw9981d221997-12-03 05:25:48 +00001115
Barry Warsawa97a3f31997-11-04 18:47:06 +00001116
1117;;; Subprocess commands
1118
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001119;; only used when (memq 'broken-temp-names py-emacs-features)
1120(defvar py-serial-number 0)
1121(defvar py-exception-buffer nil)
1122(defconst py-output-buffer "*Python Output*")
1123
Barry Warsawa97a3f31997-11-04 18:47:06 +00001124;;;###autoload
1125(defun py-shell ()
1126 "Start an interactive Python interpreter in another window.
1127This is like Shell mode, except that Python is running in the window
1128instead of a shell. See the `Interactive Shell' and `Shell Mode'
1129sections of the Emacs manual for details, especially for the key
1130bindings active in the `*Python*' buffer.
1131
1132See the docs for variable `py-scroll-buffer' for info on scrolling
1133behavior in the process window.
1134
1135Warning: Don't use an interactive Python if you change sys.ps1 or
1136sys.ps2 from their default values, or if you're running code that
1137prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1138distinguish your output from Python's output, and assumes that `>>> '
1139at the start of a line is a prompt from Python. Similarly, the Emacs
1140Shell mode code assumes that both `>>> ' and `... ' at the start of a
1141line are Python prompts. Bad things can happen if you fool either
1142mode.
1143
1144Warning: If you do any editing *in* the process buffer *while* the
1145buffer is accepting output from Python, do NOT attempt to `undo' the
1146changes. Some of the output (nowhere near the parts you changed!) may
1147be lost if you do. This appears to be an Emacs bug, an unfortunate
1148interaction between undo and process filters; the same problem exists in
1149non-Python process buffers using the default (Emacs-supplied) process
1150filter."
1151 ;; BAW - should undo be disabled in the python process buffer, if
1152 ;; this bug still exists?
1153 (interactive)
1154 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001155 (switch-to-buffer-other-window
Barry Warsaw8f972b71998-02-05 20:45:49 +00001156 (apply 'make-comint "Python" py-python-command nil py-python-command-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001157 (make-local-variable 'comint-prompt-regexp)
1158 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1159 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1160 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001161 ;; set up keybindings for this subshell
1162 (local-set-key [tab] 'self-insert-command)
1163 (local-set-key "\C-c-" 'py-up-exception)
1164 (local-set-key "\C-c=" 'py-down-exception)
1165 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001166
Barry Warsawa97a3f31997-11-04 18:47:06 +00001167(defun py-clear-queue ()
1168 "Clear the queue of temporary files waiting to execute."
1169 (interactive)
1170 (let ((n (length py-file-queue)))
1171 (mapcar 'delete-file py-file-queue)
1172 (setq py-file-queue nil)
1173 (message "%d pending files de-queued." n)))
1174
1175(defun py-execute-region (start end &optional async)
1176 "Execute the the region in a Python interpreter.
1177The region is first copied into a temporary file (in the directory
1178`py-temp-directory'). If there is no Python interpreter shell
1179running, this file is executed synchronously using
1180`shell-command-on-region'. If the program is long running, use an
1181optional \\[universal-argument] to run the command asynchronously in
1182its own buffer.
1183
1184If the Python interpreter shell is running, the region is execfile()'d
1185in that shell. If you try to execute regions too quickly,
1186`python-mode' will queue them up and execute them one at a time when
1187it sees a `>>> ' prompt from Python. Each time this happens, the
1188process buffer is popped into a window (if it's not already in some
1189window) so you can see it, and a comment of the form
1190
1191 \t## working on region in file <name>...
1192
1193is inserted at the end. See also the command `py-clear-queue'."
1194 (interactive "r\nP")
1195 (or (< start end)
1196 (error "Region is empty"))
1197 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001198 (temp (if (memq 'broken-temp-names py-emacs-features)
1199 (prog1
1200 (format "python-%d" py-serial-number)
1201 (setq py-serial-number (1+ py-serial-number)))
1202 (make-temp-name "python")))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001203 (file (concat (file-name-as-directory py-temp-directory) temp)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001204 (write-region start end file nil 'nomsg)
1205 (cond
1206 ;; always run the code in it's own asynchronous subprocess
1207 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001208 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001209 (start-process "Python" buf py-python-command "-u" file)
1210 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001211 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001212 ))
1213 ;; if the Python interpreter shell is running, queue it up for
1214 ;; execution there.
1215 (proc
1216 ;; use the existing python shell
1217 (if (not py-file-queue)
1218 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001219 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001220 (push file py-file-queue)
1221 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001222 (t
1223 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001224 (shell-command-on-region start end py-python-command py-output-buffer)
1225 (setq py-exception-buffer (current-buffer))
1226 (py-postprocess-output-buffer py-output-buffer)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001227 ))))
1228
1229;; Code execution command
1230(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001231 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001232If the file local variable `py-master-file' is non-nil, execute the
1233named file instead of the buffer's file.
1234
Barry Warsaw7ae77681994-12-12 20:38:05 +00001235If there is a *Python* process buffer it is used. If a clipping
1236restriction is in effect, only the accessible portion of the buffer is
1237sent. A trailing newline will be supplied if needed.
1238
1239See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001240 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001241 (if py-master-file
1242 (let* ((filename (expand-file-name py-master-file))
1243 (buffer (or (get-file-buffer filename)
1244 (find-file-noselect filename))))
1245 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001246 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001247
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001248
1249
1250(defun py-jump-to-exception (file line)
1251 (let ((buffer (cond ((string-equal file "<stdin>")
1252 py-exception-buffer)
1253 ((and (consp py-exception-buffer)
1254 (string-equal file (car py-exception-buffer)))
1255 (cdr py-exception-buffer))
1256 ((py-safe (find-file-noselect file)))
1257 ;; could not figure out what file the exception
1258 ;; is pointing to, so prompt for it
1259 (t (find-file (read-file-name "Exception file: "
1260 nil
1261 file t))))))
1262 (pop-to-buffer buffer)
1263 (goto-line line)
1264 (message "Jumping to exception in file %s on line %d" file line)))
1265
1266(defun py-mouseto-exception (event)
1267 (interactive "e")
1268 (cond
1269 ((fboundp 'event-point)
1270 ;; XEmacs
1271 (let* ((point (event-point event))
1272 (buffer (event-buffer event))
1273 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1274 (info (and e (extent-property e 'py-exc-info))))
1275 (message "Event point: %d, info: %s" point info)
1276 (and info
1277 (py-jump-to-exception (car info) (cdr info)))
1278 ))
1279 ;; Emacs -- Please port this!
1280 ))
1281
1282(defun py-goto-exception ()
1283 "Go to the line indicated by the traceback."
1284 (interactive)
1285 (let (file line)
1286 (save-excursion
1287 (beginning-of-line)
1288 (if (looking-at py-traceback-line-re)
1289 (setq file (match-string 1)
1290 line (string-to-int (match-string 2)))))
1291 (if (not file)
1292 (error "Not on a traceback line."))
1293 (py-jump-to-exception file line)))
1294
1295(defun py-find-next-exception (start buffer searchdir errwhere)
1296 ;; Go to start position in buffer, search in the specified
1297 ;; direction, and jump to the exception found. If at the end of the
1298 ;; exception, print error message
1299 (let (file line)
1300 (save-excursion
1301 (set-buffer buffer)
1302 (goto-char (py-point start))
1303 (if (funcall searchdir py-traceback-line-re nil t)
1304 (setq file (match-string 1)
1305 line (string-to-int (match-string 2)))))
1306 (if (and file line)
1307 (py-jump-to-exception file line)
1308 (error "%s of traceback" errwhere))))
1309
1310(defun py-down-exception (&optional bottom)
1311 "Go to the next line down in the traceback.
1312With optional \\[universal-argument], jump to the bottom (innermost)
1313exception in the exception stack."
1314 (interactive "P")
1315 (let* ((proc (get-process "Python"))
1316 (buffer (if proc "*Python*" py-output-buffer)))
1317 (if bottom
1318 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1319 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1320
1321(defun py-up-exception (&optional top)
1322 "Go to the previous line up in the traceback.
1323With optional \\[universal-argument], jump to the top (outermost)
1324exception in the exception stack."
1325 (interactive "P")
1326 (let* ((proc (get-process "Python"))
1327 (buffer (if proc "*Python*" py-output-buffer)))
1328 (if top
1329 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001330 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001331
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001332
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001333;; Electric deletion
1334(defun py-electric-backspace (arg)
1335 "Deletes preceding character or levels of indentation.
1336Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001337with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001338
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001339If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001340
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001341Otherwise, if point is at the leftmost non-whitespace character of a
1342line that is neither a continuation line nor a non-indenting comment
1343line, or if point is at the end of a blank line, this command reduces
1344the indentation to match that of the line that opened the current
1345block of code. The line that opened the block is displayed in the
1346echo area to help you keep track of where you are. With numeric arg,
1347outdents that many blocks (but not past column zero).
1348
1349Otherwise the preceding character is deleted, converting a tab to
1350spaces if needed so that only a single column position is deleted.
1351Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001352 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001353 (if (or (/= (current-indentation) (current-column))
1354 (bolp)
1355 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001356 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001357 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001358 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001359 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001360 ;; force non-blank so py-goto-block-up doesn't ignore it
1361 (insert-char ?* 1)
1362 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001363 (let ((base-indent 0) ; indentation of base line
1364 (base-text "") ; and text of base line
1365 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001366 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001367 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001368 (condition-case nil ; in case no enclosing block
1369 (progn
1370 (py-goto-block-up 'no-mark)
1371 (setq base-indent (current-indentation)
1372 base-text (py-suck-up-leading-text)
1373 base-found-p t))
1374 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001375 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001376 (delete-char 1) ; toss the dummy character
1377 (delete-horizontal-space)
1378 (indent-to base-indent)
1379 (if base-found-p
1380 (message "Closes block: %s" base-text)))))
1381
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001382
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001383(defun py-electric-delete (arg)
1384 "Deletes preceding or following character or levels of whitespace.
1385
1386The behavior of this function depends on the variable
1387`delete-key-deletes-forward'. If this variable is nil (or does not
1388exist, as in older Emacsen), then this function behaves identical to
1389\\[c-electric-backspace].
1390
1391If `delete-key-deletes-forward' is non-nil and is supported in your
1392Emacs, then deletion occurs in the forward direction, by calling the
1393function in `py-delete-function'."
1394 (interactive "*p")
1395 (if (and (boundp 'delete-key-deletes-forward)
1396 delete-key-deletes-forward)
1397 (funcall py-delete-function arg)
1398 ;; else
1399 (py-electric-backspace arg)))
1400
1401;; required for pending-del and delsel modes
1402(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1403(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1404(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1405(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1406
1407
1408
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001409(defun py-indent-line (&optional arg)
1410 "Fix the indentation of the current line according to Python rules.
1411With \\[universal-argument], ignore outdenting rules for block
1412closing statements (e.g. return, raise, break, continue, pass)
1413
1414This function is normally bound to `indent-line-function' so
1415\\[indent-for-tab-command] will call it."
1416 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001417 (let* ((ci (current-indentation))
1418 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001419 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001420 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001421 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001422 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001423 (if (/= ci need)
1424 (save-excursion
1425 (beginning-of-line)
1426 (delete-horizontal-space)
1427 (indent-to need)))
1428 (if move-to-indentation-p (back-to-indentation))))
1429
1430(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001431 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001432This is just `strives to' because correct indentation can't be computed
1433from scratch for Python code. In general, deletes the whitespace before
1434point, inserts a newline, and takes an educated guess as to how you want
1435the new line indented."
1436 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001437 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001438 (if (< ci (current-column)) ; if point beyond indentation
1439 (newline-and-indent)
1440 ;; else try to act like newline-and-indent "normally" acts
1441 (beginning-of-line)
1442 (insert-char ?\n 1)
1443 (move-to-column ci))))
1444
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001445(defun py-compute-indentation (honor-block-close-p)
1446 ;; implements all the rules for indentation computation. when
1447 ;; honor-block-close-p is non-nil, statements such as return, raise,
1448 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001449 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001450 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001451 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001452 (pps (parse-partial-sexp bod (point)))
1453 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001454 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001455 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001456 ((or (and (nth 3 pps) (nth 3 boipps))
1457 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001458 (save-excursion
1459 (if (not py-align-multiline-strings-p) 0
1460 ;; skip back over blank & non-indenting comment lines
1461 ;; note: will skip a blank or non-indenting comment line
1462 ;; that happens to be a continuation line too
1463 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1464 (back-to-indentation)
1465 (current-column))))
1466 ;; are we on a continuation line?
1467 ((py-continuation-line-p)
1468 (let ((startpos (point))
1469 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001470 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001471 (if open-bracket-pos
1472 (progn
1473 ;; align with first item in list; else a normal
1474 ;; indent beyond the line with the open bracket
1475 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1476 ;; is the first list item on the same line?
1477 (skip-chars-forward " \t")
1478 (if (null (memq (following-char) '(?\n ?# ?\\)))
1479 ; yes, so line up with it
1480 (current-column)
1481 ;; first list item on another line, or doesn't exist yet
1482 (forward-line 1)
1483 (while (and (< (point) startpos)
1484 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1485 (forward-line 1))
1486 (if (< (point) startpos)
1487 ;; again mimic the first list item
1488 (current-indentation)
1489 ;; else they're about to enter the first item
1490 (goto-char open-bracket-pos)
1491 (+ (current-indentation) py-indent-offset))))
1492
1493 ;; else on backslash continuation line
1494 (forward-line -1)
1495 (if (py-continuation-line-p) ; on at least 3rd line in block
1496 (current-indentation) ; so just continue the pattern
1497 ;; else started on 2nd line in block, so indent more.
1498 ;; if base line is an assignment with a start on a RHS,
1499 ;; indent to 2 beyond the leftmost "="; else skip first
1500 ;; chunk of non-whitespace characters on base line, + 1 more
1501 ;; column
1502 (end-of-line)
1503 (setq endpos (point) searching t)
1504 (back-to-indentation)
1505 (setq startpos (point))
1506 ;; look at all "=" from left to right, stopping at first
1507 ;; one not nested in a list or string
1508 (while searching
1509 (skip-chars-forward "^=" endpos)
1510 (if (= (point) endpos)
1511 (setq searching nil)
1512 (forward-char 1)
1513 (setq state (parse-partial-sexp startpos (point)))
1514 (if (and (zerop (car state)) ; not in a bracket
1515 (null (nth 3 state))) ; & not in a string
1516 (progn
1517 (setq searching nil) ; done searching in any case
1518 (setq found
1519 (not (or
1520 (eq (following-char) ?=)
1521 (memq (char-after (- (point) 2))
1522 '(?< ?> ?!)))))))))
1523 (if (or (not found) ; not an assignment
1524 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1525 (progn
1526 (goto-char startpos)
1527 (skip-chars-forward "^ \t\n")))
1528 (1+ (current-column))))))
1529
1530 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001531 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001532
Barry Warsawa7891711996-08-01 15:53:09 +00001533 ;; Dfn: "Indenting comment line". A line containing only a
1534 ;; comment, but which is treated like a statement for
1535 ;; indentation calculation purposes. Such lines are only
1536 ;; treated specially by the mode; they are not treated
1537 ;; specially by the Python interpreter.
1538
1539 ;; The rules for indenting comment lines are a line where:
1540 ;; - the first non-whitespace character is `#', and
1541 ;; - the character following the `#' is whitespace, and
1542 ;; - the line is outdented with respect to (i.e. to the left
1543 ;; of) the indentation of the preceding non-blank line.
1544
1545 ;; The first non-blank line following an indenting comment
1546 ;; line is given the same amount of indentation as the
1547 ;; indenting comment line.
1548
1549 ;; All other comment-only lines are ignored for indentation
1550 ;; purposes.
1551
1552 ;; Are we looking at a comment-only line which is *not* an
1553 ;; indenting comment line? If so, we assume that its been
1554 ;; placed at the desired indentation, so leave it alone.
1555 ;; Indenting comment lines are aligned as statements down
1556 ;; below.
1557 ((and (looking-at "[ \t]*#[^ \t\n]")
1558 ;; NOTE: this test will not be performed in older Emacsen
1559 (fboundp 'forward-comment)
1560 (<= (current-indentation)
1561 (save-excursion
1562 (forward-comment (- (point-max)))
1563 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001564 (current-indentation))
1565
1566 ;; else indentation based on that of the statement that
1567 ;; precedes us; use the first line of that statement to
1568 ;; establish the base, in case the user forced a non-std
1569 ;; indentation for the continuation lines (if any)
1570 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001571 ;; skip back over blank & non-indenting comment lines note:
1572 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001573 ;; happens to be a continuation line too. use fast Emacs 19
1574 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001575 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001576 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001577 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001578 (let (done)
1579 (while (not done)
1580 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1581 nil 'move)
1582 (setq done (or (eq py-honor-comment-indentation t)
1583 (bobp)
1584 (/= (following-char) ?#)
1585 (not (zerop (current-column)))))
1586 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001587 ;; if we landed inside a string, go to the beginning of that
1588 ;; string. this handles triple quoted, multi-line spanning
1589 ;; strings.
Barry Warsawf64b4051998-02-12 16:52:14 +00001590 (let* ((pps3 (nth 3 (parse-partial-sexp bod (point))))
1591 (delim (and pps3 (int-to-char pps3)))
1592 (skip (and delim (make-string 1 delim))))
1593 (when skip
1594 (save-excursion
1595 (py-safe (search-backward skip))
1596 (if (and (eq (char-before) delim)
1597 (eq (char-before (1- (point))) delim))
1598 (setq skip (make-string 3 delim))))
1599 ;; we're looking at a triple-quoted string
1600 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001601 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001602 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001603 (+ (current-indentation)
1604 (if (py-statement-opens-block-p)
1605 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001606 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001607 (- py-indent-offset)
1608 0)))
1609 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001610
1611(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001612 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001613By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001614`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001615Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001616`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001617their own buffer-local copy), both those currently existing and those
1618created later in the Emacs session.
1619
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001620Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001621There's no excuse for such foolishness, but sometimes you have to deal
1622with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001623`py-indent-offset' to what it thinks it was when they created the
1624mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001625
1626Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001627looking for a line that opens a block of code. `py-indent-offset' is
1628set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001629statement following it. If the search doesn't succeed going forward,
1630it's tried again going backward."
1631 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001632 (let (new-value
1633 (start (point))
1634 restart
1635 (found nil)
1636 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001637 (py-goto-initial-line)
1638 (while (not (or found (eobp)))
1639 (if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1640 (progn
1641 (setq restart (point))
1642 (py-goto-initial-line)
1643 (if (py-statement-opens-block-p)
1644 (setq found t)
1645 (goto-char restart)))))
1646 (if found
1647 ()
1648 (goto-char start)
1649 (py-goto-initial-line)
1650 (while (not (or found (bobp)))
1651 (setq found
1652 (and
1653 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1654 (or (py-goto-initial-line) t) ; always true -- side effect
1655 (py-statement-opens-block-p)))))
1656 (setq colon-indent (current-indentation)
1657 found (and found (zerop (py-next-statement 1)))
1658 new-value (- (current-indentation) colon-indent))
1659 (goto-char start)
1660 (if found
1661 (progn
1662 (funcall (if global 'kill-local-variable 'make-local-variable)
1663 'py-indent-offset)
1664 (setq py-indent-offset new-value)
1665 (message "%s value of py-indent-offset set to %d"
1666 (if global "Global" "Local")
1667 py-indent-offset))
1668 (error "Sorry, couldn't guess a value for py-indent-offset"))))
1669
1670(defun py-shift-region (start end count)
1671 (save-excursion
1672 (goto-char end) (beginning-of-line) (setq end (point))
1673 (goto-char start) (beginning-of-line) (setq start (point))
1674 (indent-rigidly start end count)))
1675
1676(defun py-shift-region-left (start end &optional count)
1677 "Shift region of Python code to the left.
1678The lines from the line containing the start of the current region up
1679to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001680shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001681
1682If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001683many columns. With no active region, outdent only the current line.
1684You cannot outdent the region if any line is already at column zero."
1685 (interactive
1686 (let ((p (point))
1687 (m (mark))
1688 (arg current-prefix-arg))
1689 (if m
1690 (list (min p m) (max p m) arg)
1691 (list p (save-excursion (forward-line 1) (point)) arg))))
1692 ;; if any line is at column zero, don't shift the region
1693 (save-excursion
1694 (goto-char start)
1695 (while (< (point) end)
1696 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001697 (if (and (zerop (current-column))
1698 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001699 (error "Region is at left edge."))
1700 (forward-line 1)))
1701 (py-shift-region start end (- (prefix-numeric-value
1702 (or count py-indent-offset))))
1703 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001704
1705(defun py-shift-region-right (start end &optional count)
1706 "Shift region of Python code to the right.
1707The lines from the line containing the start of the current region up
1708to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001709shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001710
1711If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001712many columns. With no active region, indent only the current line."
1713 (interactive
1714 (let ((p (point))
1715 (m (mark))
1716 (arg current-prefix-arg))
1717 (if m
1718 (list (min p m) (max p m) arg)
1719 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001720 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001721 (or count py-indent-offset)))
1722 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001723
1724(defun py-indent-region (start end &optional indent-offset)
1725 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001726
Barry Warsaw7ae77681994-12-12 20:38:05 +00001727The lines from the line containing the start of the current region up
1728to (but not including) the line containing the end of the region are
1729reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001730character in the first column, the first line is left alone and the
1731rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001732region is reindented with respect to the (closest code or indenting
1733comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001734
1735This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001736control structures are introduced or removed, or to reformat code
1737using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001738
1739If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001740the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001741used.
1742
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001743Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001744is called! This function does not compute proper indentation from
1745scratch (that's impossible in Python), it merely adjusts the existing
1746indentation to be correct in context.
1747
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001748Warning: This function really has no idea what to do with
1749non-indenting comment lines, and shifts them as if they were indenting
1750comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001751
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001752Special cases: whitespace is deleted from blank lines; continuation
1753lines are shifted by the same amount their initial line was shifted,
1754in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001755initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001756 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001757 (save-excursion
1758 (goto-char end) (beginning-of-line) (setq end (point-marker))
1759 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001760 (let ((py-indent-offset (prefix-numeric-value
1761 (or indent-offset py-indent-offset)))
1762 (indents '(-1)) ; stack of active indent levels
1763 (target-column 0) ; column to which to indent
1764 (base-shifted-by 0) ; amount last base line was shifted
1765 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001766 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001767 0))
1768 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001769 (while (< (point) end)
1770 (setq ci (current-indentation))
1771 ;; figure out appropriate target column
1772 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001773 ((or (eq (following-char) ?#) ; comment in column 1
1774 (looking-at "[ \t]*$")) ; entirely blank
1775 (setq target-column 0))
1776 ((py-continuation-line-p) ; shift relative to base line
1777 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001778 (t ; new base line
1779 (if (> ci (car indents)) ; going deeper; push it
1780 (setq indents (cons ci indents))
1781 ;; else we should have seen this indent before
1782 (setq indents (memq ci indents)) ; pop deeper indents
1783 (if (null indents)
1784 (error "Bad indentation in region, at line %d"
1785 (save-restriction
1786 (widen)
1787 (1+ (count-lines 1 (point)))))))
1788 (setq target-column (+ indent-base
1789 (* py-indent-offset
1790 (- (length indents) 2))))
1791 (setq base-shifted-by (- target-column ci))))
1792 ;; shift as needed
1793 (if (/= ci target-column)
1794 (progn
1795 (delete-horizontal-space)
1796 (indent-to target-column)))
1797 (forward-line 1))))
1798 (set-marker end nil))
1799
Barry Warsawa7891711996-08-01 15:53:09 +00001800(defun py-comment-region (beg end &optional arg)
1801 "Like `comment-region' but uses double hash (`#') comment starter."
1802 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001803 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001804 (comment-region beg end arg)))
1805
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001806
1807;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001808(defun py-previous-statement (count)
1809 "Go to the start of previous Python statement.
1810If the statement at point is the i'th Python statement, goes to the
1811start of statement i-COUNT. If there is no such statement, goes to the
1812first statement. Returns count of statements left to move.
1813`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001814 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001815 (if (< count 0) (py-next-statement (- count))
1816 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001817 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001818 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001819 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001820 (> count 0)
1821 (zerop (forward-line -1))
1822 (py-goto-statement-at-or-above))
1823 (setq count (1- count)))
1824 (if (> count 0) (goto-char start)))
1825 count))
1826
1827(defun py-next-statement (count)
1828 "Go to the start of next Python statement.
1829If the statement at point is the i'th Python statement, goes to the
1830start of statement i+COUNT. If there is no such statement, goes to the
1831last statement. Returns count of statements left to move. `Statements'
1832do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001833 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001834 (if (< count 0) (py-previous-statement (- count))
1835 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001836 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001837 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001838 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001839 (> count 0)
1840 (py-goto-statement-below))
1841 (setq count (1- count)))
1842 (if (> count 0) (goto-char start)))
1843 count))
1844
1845(defun py-goto-block-up (&optional nomark)
1846 "Move up to start of current block.
1847Go to the statement that starts the smallest enclosing block; roughly
1848speaking, this will be the closest preceding statement that ends with a
1849colon and is indented less than the statement you started on. If
1850successful, also sets the mark to the starting point.
1851
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001852`\\[py-mark-block]' can be used afterward to mark the whole code
1853block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001854
1855If called from a program, the mark will not be set if optional argument
1856NOMARK is not nil."
1857 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001858 (let ((start (point))
1859 (found nil)
1860 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001861 (py-goto-initial-line)
1862 ;; if on blank or non-indenting comment line, use the preceding stmt
1863 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1864 (progn
1865 (py-goto-statement-at-or-above)
1866 (setq found (py-statement-opens-block-p))))
1867 ;; search back for colon line indented less
1868 (setq initial-indent (current-indentation))
1869 (if (zerop initial-indent)
1870 ;; force fast exit
1871 (goto-char (point-min)))
1872 (while (not (or found (bobp)))
1873 (setq found
1874 (and
1875 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1876 (or (py-goto-initial-line) t) ; always true -- side effect
1877 (< (current-indentation) initial-indent)
1878 (py-statement-opens-block-p))))
1879 (if found
1880 (progn
1881 (or nomark (push-mark start))
1882 (back-to-indentation))
1883 (goto-char start)
1884 (error "Enclosing block not found"))))
1885
1886(defun beginning-of-python-def-or-class (&optional class)
1887 "Move point to start of def (or class, with prefix arg).
1888
1889Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001890arg, looks for a `class' instead. The docs assume the `def' case;
1891just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001892
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001893If point is in a def statement already, and after the `d', simply
1894moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001895
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001896Else (point is not in a def statement, or at or before the `d' of a
1897def statement), searches for the closest preceding def statement, and
1898leaves point at its start. If no such statement can be found, leaves
1899point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001900
1901Returns t iff a def statement is found by these rules.
1902
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001903Note that doing this command repeatedly will take you closer to the
1904start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001905
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001906If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001907`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001908 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001909 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1910 (start-of-line (progn (beginning-of-line) (point)))
1911 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001912 (if (or (/= start-of-stmt start-of-line)
1913 (not at-or-before-p))
1914 (end-of-line)) ; OK to match on this line
1915 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001916 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001917
1918(defun end-of-python-def-or-class (&optional class)
1919 "Move point beyond end of def (or class, with prefix arg) body.
1920
1921By default, looks for an appropriate `def'. If you supply a prefix arg,
1922looks for a `class' instead. The docs assume the `def' case; just
1923substitute `class' for `def' for the other case.
1924
1925If point is in a def statement already, this is the def we use.
1926
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001927Else if the def found by `\\[beginning-of-python-def-or-class]'
1928contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001929
1930Else we search forward for the closest following def, and use that.
1931
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001932If a def can be found by these rules, point is moved to the start of
1933the line immediately following the def block, and the position of the
1934start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001935
1936Else point is moved to the end of the buffer, and nil is returned.
1937
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001938Note that doing this command repeatedly will take you closer to the
1939end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001940
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001941If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001942`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001943 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001944 (let ((start (progn (py-goto-initial-line) (point)))
1945 (which (if class "class" "def"))
1946 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001947 ;; move point to start of appropriate def/class
1948 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1949 (setq state 'at-beginning)
1950 ;; else see if beginning-of-python-def-or-class hits container
1951 (if (and (beginning-of-python-def-or-class class)
1952 (progn (py-goto-beyond-block)
1953 (> (point) start)))
1954 (setq state 'at-end)
1955 ;; else search forward
1956 (goto-char start)
1957 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1958 (progn (setq state 'at-beginning)
1959 (beginning-of-line)))))
1960 (cond
1961 ((eq state 'at-beginning) (py-goto-beyond-block) t)
1962 ((eq state 'at-end) t)
1963 ((eq state 'not-found) nil)
1964 (t (error "internal error in end-of-python-def-or-class")))))
1965
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001966
1967;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00001968(defun py-mark-block (&optional extend just-move)
1969 "Mark following block of lines. With prefix arg, mark structure.
1970Easier to use than explain. It sets the region to an `interesting'
1971block of succeeding lines. If point is on a blank line, it goes down to
1972the next non-blank line. That will be the start of the region. The end
1973of the region depends on the kind of line at the start:
1974
1975 - If a comment, the region will include all succeeding comment lines up
1976 to (but not including) the next non-comment line (if any).
1977
1978 - Else if a prefix arg is given, and the line begins one of these
1979 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001980
1981 if elif else try except finally for while def class
1982
Barry Warsaw7ae77681994-12-12 20:38:05 +00001983 the region will be set to the body of the structure, including
1984 following blocks that `belong' to it, but excluding trailing blank
1985 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001986 and all (if any) of the following `except' and `finally' blocks
1987 that belong to the `try' structure will be in the region. Ditto
1988 for if/elif/else, for/else and while/else structures, and (a bit
1989 degenerate, since they're always one-block structures) def and
1990 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001991
1992 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001993 block (see list above), and the block is not a `one-liner' (i.e.,
1994 the statement ends with a colon, not with code), the region will
1995 include all succeeding lines up to (but not including) the next
1996 code statement (if any) that's indented no more than the starting
1997 line, except that trailing blank and comment lines are excluded.
1998 E.g., if the starting line begins a multi-statement `def'
1999 structure, the region will be set to the full function definition,
2000 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002001
2002 - Else the region will include all succeeding lines up to (but not
2003 including) the next blank line, or code or indenting-comment line
2004 indented strictly less than the starting line. Trailing indenting
2005 comment lines are included in this case, but not trailing blank
2006 lines.
2007
2008A msg identifying the location of the mark is displayed in the echo
2009area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2010
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002011If called from a program, optional argument EXTEND plays the role of
2012the prefix arg, and if optional argument JUST-MOVE is not nil, just
2013moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002014 (interactive "P") ; raw prefix arg
2015 (py-goto-initial-line)
2016 ;; skip over blank lines
2017 (while (and
2018 (looking-at "[ \t]*$") ; while blank line
2019 (not (eobp))) ; & somewhere to go
2020 (forward-line 1))
2021 (if (eobp)
2022 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002023 (let ((initial-pos (point))
2024 (initial-indent (current-indentation))
2025 last-pos ; position of last stmt in region
2026 (followers
2027 '((if elif else) (elif elif else) (else)
2028 (try except finally) (except except) (finally)
2029 (for else) (while else)
2030 (def) (class) ) )
2031 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002032
2033 (cond
2034 ;; if comment line, suck up the following comment lines
2035 ((looking-at "[ \t]*#")
2036 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2037 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2038 (setq last-pos (point)))
2039
2040 ;; else if line is a block line and EXTEND given, suck up
2041 ;; the whole structure
2042 ((and extend
2043 (setq first-symbol (py-suck-up-first-keyword) )
2044 (assq first-symbol followers))
2045 (while (and
2046 (or (py-goto-beyond-block) t) ; side effect
2047 (forward-line -1) ; side effect
2048 (setq last-pos (point)) ; side effect
2049 (py-goto-statement-below)
2050 (= (current-indentation) initial-indent)
2051 (setq next-symbol (py-suck-up-first-keyword))
2052 (memq next-symbol (cdr (assq first-symbol followers))))
2053 (setq first-symbol next-symbol)))
2054
2055 ;; else if line *opens* a block, search for next stmt indented <=
2056 ((py-statement-opens-block-p)
2057 (while (and
2058 (setq last-pos (point)) ; always true -- side effect
2059 (py-goto-statement-below)
2060 (> (current-indentation) initial-indent))
2061 nil))
2062
2063 ;; else plain code line; stop at next blank line, or stmt or
2064 ;; indenting comment line indented <
2065 (t
2066 (while (and
2067 (setq last-pos (point)) ; always true -- side effect
2068 (or (py-goto-beyond-final-line) t)
2069 (not (looking-at "[ \t]*$")) ; stop at blank line
2070 (or
2071 (>= (current-indentation) initial-indent)
2072 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2073 nil)))
2074
2075 ;; skip to end of last stmt
2076 (goto-char last-pos)
2077 (py-goto-beyond-final-line)
2078
2079 ;; set mark & display
2080 (if just-move
2081 () ; just return
2082 (push-mark (point) 'no-msg)
2083 (forward-line -1)
2084 (message "Mark set after: %s" (py-suck-up-leading-text))
2085 (goto-char initial-pos))))
2086
Barry Warsaw2518c671997-11-05 00:51:08 +00002087(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002088 "Set region to body of def (or class, with prefix arg) enclosing point.
2089Pushes the current mark, then point, on the mark ring (all language
2090modes do this, but although it's handy it's never documented ...).
2091
2092In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002093hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
2094`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002095
2096And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002097Turned out that was more confusing than useful: the `goto start' and
2098`goto end' commands are usually used to search through a file, and
2099people expect them to act a lot like `search backward' and `search
2100forward' string-search commands. But because Python `def' and `class'
2101can nest to arbitrary levels, finding the smallest def containing
2102point cannot be done via a simple backward search: the def containing
2103point may not be the closest preceding def, or even the closest
2104preceding def that's indented less. The fancy algorithm required is
2105appropriate for the usual uses of this `mark' command, but not for the
2106`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002107
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002108So the def marked by this command may not be the one either of the
2109`goto' commands find: If point is on a blank or non-indenting comment
2110line, moves back to start of the closest preceding code statement or
2111indenting comment line. If this is a `def' statement, that's the def
2112we use. Else searches for the smallest enclosing `def' block and uses
2113that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002114
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002115When an enclosing def is found: The mark is left immediately beyond
2116the last line of the def block. Point is left at the start of the
2117def, except that: if the def is preceded by a number of comment lines
2118followed by (at most) one optional blank line, point is left at the
2119start of the comments; else if the def is preceded by a blank line,
2120point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002121
2122The intent is to mark the containing def/class and its associated
2123documentation, to make moving and duplicating functions and classes
2124pleasant."
2125 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002126 (let ((start (point))
2127 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002128 (push-mark start)
2129 (if (not (py-go-up-tree-to-keyword which))
2130 (progn (goto-char start)
2131 (error "Enclosing %s not found" which))
2132 ;; else enclosing def/class found
2133 (setq start (point))
2134 (py-goto-beyond-block)
2135 (push-mark (point))
2136 (goto-char start)
2137 (if (zerop (forward-line -1)) ; if there is a preceding line
2138 (progn
2139 (if (looking-at "[ \t]*$") ; it's blank
2140 (setq start (point)) ; so reset start point
2141 (goto-char start)) ; else try again
2142 (if (zerop (forward-line -1))
2143 (if (looking-at "[ \t]*#") ; a comment
2144 ;; look back for non-comment line
2145 ;; tricky: note that the regexp matches a blank
2146 ;; line, cuz \n is in the 2nd character class
2147 (and
2148 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2149 (forward-line 1))
2150 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002151 (goto-char start)))))))
2152 (exchange-point-and-mark)
2153 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002154
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002155;; ripped from cc-mode
2156(defun py-forward-into-nomenclature (&optional arg)
2157 "Move forward to end of a nomenclature section or word.
2158With arg, to it arg times.
2159
2160A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2161 (interactive "p")
2162 (let ((case-fold-search nil))
2163 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002164 (re-search-forward
2165 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2166 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002167 (while (and (< arg 0)
2168 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002169 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002170 (point-min) 0))
2171 (forward-char 1)
2172 (setq arg (1+ arg)))))
2173 (py-keep-region-active))
2174
2175(defun py-backward-into-nomenclature (&optional arg)
2176 "Move backward to beginning of a nomenclature section or word.
2177With optional ARG, move that many times. If ARG is negative, move
2178forward.
2179
2180A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2181 (interactive "p")
2182 (py-forward-into-nomenclature (- arg))
2183 (py-keep-region-active))
2184
2185
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002186
2187;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002188
2189;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002190;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2191;; out of the right places, along with the keys they're on & current
2192;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002193(defun py-dump-help-string (str)
2194 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002195 (let ((locals (buffer-local-variables))
2196 funckind funcname func funcdoc
2197 (start 0) mstart end
2198 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002199 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2200 (setq mstart (match-beginning 0) end (match-end 0)
2201 funckind (substring str (match-beginning 1) (match-end 1))
2202 funcname (substring str (match-beginning 2) (match-end 2))
2203 func (intern funcname))
2204 (princ (substitute-command-keys (substring str start mstart)))
2205 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002206 ((equal funckind "c") ; command
2207 (setq funcdoc (documentation func)
2208 keys (concat
2209 "Key(s): "
2210 (mapconcat 'key-description
2211 (where-is-internal func py-mode-map)
2212 ", "))))
2213 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002214 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002215 keys (if (assq func locals)
2216 (concat
2217 "Local/Global values: "
2218 (prin1-to-string (symbol-value func))
2219 " / "
2220 (prin1-to-string (default-value func)))
2221 (concat
2222 "Value: "
2223 (prin1-to-string (symbol-value func))))))
2224 (t ; unexpected
2225 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002226 (princ (format "\n-> %s:\t%s\t%s\n\n"
2227 (if (equal funckind "c") "Command" "Variable")
2228 funcname keys))
2229 (princ funcdoc)
2230 (terpri)
2231 (setq start end))
2232 (princ (substitute-command-keys (substring str start))))
2233 (print-help-return-message)))
2234
2235(defun py-describe-mode ()
2236 "Dump long form of Python-mode docs."
2237 (interactive)
2238 (py-dump-help-string "Major mode for editing Python files.
2239Knows about Python indentation, tokens, comments and continuation lines.
2240Paragraphs are separated by blank lines only.
2241
2242Major sections below begin with the string `@'; specific function and
2243variable docs begin with `->'.
2244
2245@EXECUTING PYTHON CODE
2246
2247\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2248\\[py-execute-region]\tsends the current region
2249\\[py-shell]\tstarts a Python interpreter window; this will be used by
2250\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2251%c:py-execute-buffer
2252%c:py-execute-region
2253%c:py-shell
2254
2255@VARIABLES
2256
2257py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002258py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002259
2260py-python-command\tshell command to invoke Python interpreter
2261py-scroll-process-buffer\talways scroll Python process buffer
2262py-temp-directory\tdirectory used for temp files (if needed)
2263
2264py-beep-if-tab-change\tring the bell if tab-width is changed
2265%v:py-indent-offset
2266%v:py-block-comment-prefix
2267%v:py-python-command
2268%v:py-scroll-process-buffer
2269%v:py-temp-directory
2270%v:py-beep-if-tab-change
2271
2272@KINDS OF LINES
2273
2274Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002275preceding line ends with a backslash that's not part of a comment, or
2276the paren/bracket/brace nesting level at the start of the line is
2277non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002278
2279An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002280possibly blanks or tabs), a `comment line' (leftmost non-blank
2281character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002282
2283Comment Lines
2284
2285Although all comment lines are treated alike by Python, Python mode
2286recognizes two kinds that act differently with respect to indentation.
2287
2288An `indenting comment line' is a comment line with a blank, tab or
2289nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002290treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002291indenting comment line will be indented like the comment line. All
2292other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002293following the initial `#') are `non-indenting comment lines', and
2294their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002295
2296Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002297whenever possible. Non-indenting comment lines are useful in cases
2298like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002299
2300\ta = b # a very wordy single-line comment that ends up being
2301\t #... continued onto another line
2302
2303\tif a == b:
2304##\t\tprint 'panic!' # old code we've `commented out'
2305\t\treturn a
2306
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002307Since the `#...' and `##' comment lines have a non-whitespace
2308character following the initial `#', Python mode ignores them when
2309computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002310
2311Continuation Lines and Statements
2312
2313The Python-mode commands generally work on statements instead of on
2314individual lines, where a `statement' is a comment or blank line, or a
2315code line and all of its following continuation lines (if any)
2316considered as a single logical unit. The commands in this mode
2317generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002318statement containing point, even if point happens to be in the middle
2319of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002320
2321
2322@INDENTATION
2323
2324Primarily for entering new code:
2325\t\\[indent-for-tab-command]\t indent line appropriately
2326\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002327\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002328
2329Primarily for reindenting existing code:
2330\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2331\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2332
2333\t\\[py-indent-region]\t reindent region to match its context
2334\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2335\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2336
2337Unlike most programming languages, Python uses indentation, and only
2338indentation, to specify block structure. Hence the indentation supplied
2339automatically by Python-mode is just an educated guess: only you know
2340the block structure you intend, so only you can supply correct
2341indentation.
2342
2343The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2344the indentation of preceding statements. E.g., assuming
2345py-indent-offset is 4, after you enter
2346\tif a > 0: \\[py-newline-and-indent]
2347the cursor will be moved to the position of the `_' (_ is not a
2348character in the file, it's just used here to indicate the location of
2349the cursor):
2350\tif a > 0:
2351\t _
2352If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2353to
2354\tif a > 0:
2355\t c = d
2356\t _
2357Python-mode cannot know whether that's what you intended, or whether
2358\tif a > 0:
2359\t c = d
2360\t_
2361was your intent. In general, Python-mode either reproduces the
2362indentation of the (closest code or indenting-comment) preceding
2363statement, or adds an extra py-indent-offset blanks if the preceding
2364statement has `:' as its last significant (non-whitespace and non-
2365comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002366\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002367
2368Continuation lines are given extra indentation. If you don't like the
2369suggested indentation, change it to something you do like, and Python-
2370mode will strive to indent later lines of the statement in the same way.
2371
2372If a line is a continuation line by virtue of being in an unclosed
2373paren/bracket/brace structure (`list', for short), the suggested
2374indentation depends on whether the current line contains the first item
2375in the list. If it does, it's indented py-indent-offset columns beyond
2376the indentation of the line containing the open bracket. If you don't
2377like that, change it by hand. The remaining items in the list will mimic
2378whatever indentation you give to the first item.
2379
2380If a line is a continuation line because the line preceding it ends with
2381a backslash, the third and following lines of the statement inherit their
2382indentation from the line preceding them. The indentation of the second
2383line in the statement depends on the form of the first (base) line: if
2384the base line is an assignment statement with anything more interesting
2385than the backslash following the leftmost assigning `=', the second line
2386is indented two columns beyond that `='. Else it's indented to two
2387columns beyond the leftmost solid chunk of non-whitespace characters on
2388the base line.
2389
2390Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2391repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2392structure you intend.
2393%c:indent-for-tab-command
2394%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002395%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002396
2397
2398The next function may be handy when editing code you didn't write:
2399%c:py-guess-indent-offset
2400
2401
2402The remaining `indent' functions apply to a region of Python code. They
2403assume the block structure (equals indentation, in Python) of the region
2404is correct, and alter the indentation in various ways while preserving
2405the block structure:
2406%c:py-indent-region
2407%c:py-shift-region-left
2408%c:py-shift-region-right
2409
2410@MARKING & MANIPULATING REGIONS OF CODE
2411
2412\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002413\\[py-mark-def-or-class]\t mark smallest enclosing def
2414\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002415\\[comment-region]\t comment out region of code
2416\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002417%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002418%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002419%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002420
2421@MOVING POINT
2422
2423\\[py-previous-statement]\t move to statement preceding point
2424\\[py-next-statement]\t move to statement following point
2425\\[py-goto-block-up]\t move up to start of current block
2426\\[beginning-of-python-def-or-class]\t move to start of def
2427\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2428\\[end-of-python-def-or-class]\t move to end of def
2429\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2430
2431The first two move to one statement beyond the statement that contains
2432point. A numeric prefix argument tells them to move that many
2433statements instead. Blank lines, comment lines, and continuation lines
2434do not count as `statements' for these commands. So, e.g., you can go
2435to the first code statement in a file by entering
2436\t\\[beginning-of-buffer]\t to move to the top of the file
2437\t\\[py-next-statement]\t to skip over initial comments and blank lines
2438Or do `\\[py-previous-statement]' with a huge prefix argument.
2439%c:py-previous-statement
2440%c:py-next-statement
2441%c:py-goto-block-up
2442%c:beginning-of-python-def-or-class
2443%c:end-of-python-def-or-class
2444
2445@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2446
2447`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2448
2449`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2450overall class and def structure of a module.
2451
2452`\\[back-to-indentation]' moves point to a line's first non-blank character.
2453
2454`\\[indent-relative]' is handy for creating odd indentation.
2455
2456@OTHER EMACS HINTS
2457
2458If you don't like the default value of a variable, change its value to
2459whatever you do like by putting a `setq' line in your .emacs file.
2460E.g., to set the indentation increment to 4, put this line in your
2461.emacs:
2462\t(setq py-indent-offset 4)
2463To see the value of a variable, do `\\[describe-variable]' and enter the variable
2464name at the prompt.
2465
2466When entering a key sequence like `C-c C-n', it is not necessary to
2467release the CONTROL key after doing the `C-c' part -- it suffices to
2468press the CONTROL key, press and release `c' (while still holding down
2469CONTROL), press and release `n' (while still holding down CONTROL), &
2470then release CONTROL.
2471
2472Entering Python mode calls with no arguments the value of the variable
2473`python-mode-hook', if that value exists and is not nil; for backward
2474compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2475the Elisp manual for details.
2476
2477Obscure: When python-mode is first loaded, it looks for all bindings
2478to newline-and-indent in the global keymap, and shadows them with
2479local bindings to py-newline-and-indent."))
2480
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002481
2482;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002483(defvar py-parse-state-re
2484 (concat
2485 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2486 "\\|"
2487 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002488
Barry Warsaw7ae77681994-12-12 20:38:05 +00002489;; returns the parse state at point (see parse-partial-sexp docs)
2490(defun py-parse-state ()
2491 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002492 (let ((here (point))
Barry Warsaw170ffa71996-07-31 20:57:22 +00002493 pps done ci)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002494 (while (not done)
2495 ;; back up to the first preceding line (if any; else start of
2496 ;; buffer) that begins with a popular Python keyword, or a
2497 ;; non- whitespace and non-comment character. These are good
2498 ;; places to start parsing to see whether where we started is
2499 ;; at a non-zero nesting level. It may be slow for people who
2500 ;; write huge code blocks or huge lists ... tough beans.
2501 (re-search-backward py-parse-state-re nil 'move)
Barry Warsaw170ffa71996-07-31 20:57:22 +00002502 (setq ci (current-indentation))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002503 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002504 ;; In XEmacs, we have a much better way to test for whether
2505 ;; we're in a triple-quoted string or not. Emacs does not
2506 ;; have this built-in function, which is it's loss because
2507 ;; without scanning from the beginning of the buffer, there's
2508 ;; no accurate way to determine this otherwise.
2509 (if (not (fboundp 'buffer-syntactic-context))
2510 ;; Emacs
2511 (save-excursion
2512 (setq pps (parse-partial-sexp (point) here))
2513 ;; make sure we don't land inside a triple-quoted string
2514 (setq done (or ;(zerop ci)
2515 (not (nth 3 pps))
2516 (bobp))))
2517 ;; XEmacs
2518 (setq done (or (not (buffer-syntactic-context))
2519 (bobp)))
2520 (when done
2521 (setq pps (parse-partial-sexp (point) here)))
2522 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002523 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002524
2525;; if point is at a non-zero nesting level, returns the number of the
2526;; character that opens the smallest enclosing unclosed list; else
2527;; returns nil.
2528(defun py-nesting-level ()
Barry Warsawf64b4051998-02-12 16:52:14 +00002529 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002530 (if (zerop (car status))
2531 nil ; not in a nest
2532 (car (cdr status))))) ; char# of open bracket
2533
2534;; t iff preceding line ends with backslash that's not in a comment
2535(defun py-backslash-continuation-line-p ()
2536 (save-excursion
2537 (beginning-of-line)
2538 (and
2539 ;; use a cheap test first to avoid the regexp if possible
2540 ;; use 'eq' because char-after may return nil
2541 (eq (char-after (- (point) 2)) ?\\ )
2542 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002543 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002544 (looking-at py-continued-re))))
2545
2546;; t iff current line is a continuation line
2547(defun py-continuation-line-p ()
2548 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002549 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002550 (or (py-backslash-continuation-line-p)
2551 (py-nesting-level))))
2552
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002553;; go to initial line of current statement; usually this is the line
2554;; we're on, but if we're on the 2nd or following lines of a
2555;; continuation block, we need to go up to the first line of the
2556;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002557;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002558;; Tricky: We want to avoid quadratic-time behavior for long continued
2559;; blocks, whether of the backslash or open-bracket varieties, or a
2560;; mix of the two. The following manages to do that in the usual
2561;; cases.
Barry Warsawc210e691998-01-20 22:52:56 +00002562;;
2563;; Also, if we're sitting inside a triple quoted string, this will
2564;; drop us at the line that begins the string.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002565(defun py-goto-initial-line ()
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002566 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002567 (while (py-continuation-line-p)
2568 (beginning-of-line)
2569 (if (py-backslash-continuation-line-p)
2570 (while (py-backslash-continuation-line-p)
2571 (forward-line -1))
2572 ;; else zip out of nested brackets/braces/parens
2573 (while (setq open-bracket-pos (py-nesting-level))
2574 (goto-char open-bracket-pos)))))
2575 (beginning-of-line))
2576
2577;; go to point right beyond final line of current statement; usually
2578;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002579;; statement we need to skip over the continuation lines. Tricky:
2580;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002581(defun py-goto-beyond-final-line ()
2582 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002583 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002584 (while (and (py-continuation-line-p)
2585 (not (eobp)))
2586 ;; skip over the backslash flavor
2587 (while (and (py-backslash-continuation-line-p)
2588 (not (eobp)))
2589 (forward-line 1))
2590 ;; if in nest, zip to the end of the nest
2591 (setq state (py-parse-state))
2592 (if (and (not (zerop (car state)))
2593 (not (eobp)))
2594 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002595 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002596 (forward-line 1))))))
2597
2598;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002599;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002600(defun py-statement-opens-block-p ()
2601 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002602 (let ((start (point))
2603 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2604 (searching t)
2605 (answer nil)
2606 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002607 (goto-char start)
2608 (while searching
2609 ;; look for a colon with nothing after it except whitespace, and
2610 ;; maybe a comment
2611 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2612 finish t)
2613 (if (eq (point) finish) ; note: no `else' clause; just
2614 ; keep searching if we're not at
2615 ; the end yet
2616 ;; sure looks like it opens a block -- but it might
2617 ;; be in a comment
2618 (progn
2619 (setq searching nil) ; search is done either way
2620 (setq state (parse-partial-sexp start
2621 (match-beginning 0)))
2622 (setq answer (not (nth 4 state)))))
2623 ;; search failed: couldn't find another interesting colon
2624 (setq searching nil)))
2625 answer)))
2626
Barry Warsawf831d811996-07-31 20:42:59 +00002627(defun py-statement-closes-block-p ()
2628 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002629 ;; starts with `return', `raise', `break', `continue', and `pass'.
2630 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002631 (let ((here (point)))
2632 (back-to-indentation)
2633 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002634 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002635 (goto-char here))))
2636
Barry Warsaw7ae77681994-12-12 20:38:05 +00002637;; go to point right beyond final line of block begun by the current
2638;; line. This is the same as where py-goto-beyond-final-line goes
2639;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002640;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002641(defun py-goto-beyond-block ()
2642 (if (py-statement-opens-block-p)
2643 (py-mark-block nil 'just-move)
2644 (py-goto-beyond-final-line)))
2645
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002646;; go to start of first statement (not blank or comment or
2647;; continuation line) at or preceding point. returns t if there is
2648;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002649(defun py-goto-statement-at-or-above ()
2650 (py-goto-initial-line)
2651 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002652 ;; skip back over blank & comment lines
2653 ;; note: will skip a blank or comment line that happens to be
2654 ;; a continuation line too
2655 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2656 (progn (py-goto-initial-line) t)
2657 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002658 t))
2659
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002660;; go to start of first statement (not blank or comment or
2661;; continuation line) following the statement containing point returns
2662;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002663(defun py-goto-statement-below ()
2664 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002665 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002666 (py-goto-beyond-final-line)
2667 (while (and
2668 (looking-at py-blank-or-comment-re)
2669 (not (eobp)))
2670 (forward-line 1))
2671 (if (eobp)
2672 (progn (goto-char start) nil)
2673 t)))
2674
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002675;; go to start of statement, at or preceding point, starting with
2676;; keyword KEY. Skips blank lines and non-indenting comments upward
2677;; first. If that statement starts with KEY, done, else go back to
2678;; first enclosing block starting with KEY. If successful, leaves
2679;; point at the start of the KEY line & returns t. Else leaves point
2680;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002681(defun py-go-up-tree-to-keyword (key)
2682 ;; skip blanks and non-indenting #
2683 (py-goto-initial-line)
2684 (while (and
2685 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2686 (zerop (forward-line -1))) ; go back
2687 nil)
2688 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002689 (let* ((re (concat "[ \t]*" key "\\b"))
2690 (case-fold-search nil) ; let* so looking-at sees this
2691 (found (looking-at re))
2692 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002693 (while (not (or found dead))
2694 (condition-case nil ; in case no enclosing block
2695 (py-goto-block-up 'no-mark)
2696 (error (setq dead t)))
2697 (or dead (setq found (looking-at re))))
2698 (beginning-of-line)
2699 found))
2700
2701;; return string in buffer from start of indentation to end of line;
2702;; prefix "..." if leading whitespace was skipped
2703(defun py-suck-up-leading-text ()
2704 (save-excursion
2705 (back-to-indentation)
2706 (concat
2707 (if (bolp) "" "...")
2708 (buffer-substring (point) (progn (end-of-line) (point))))))
2709
2710;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2711;; as a Lisp symbol; return nil if none
2712(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002713 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002714 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2715 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2716 nil)))
2717
Barry Warsawb3e81d51996-09-04 15:12:42 +00002718(defun py-current-defun ()
2719 ;; tell add-log.el how to find the current function/method/variable
2720 (save-excursion
2721 (if (re-search-backward py-defun-start-re nil t)
2722 (or (match-string 3)
2723 (let ((method (match-string 2)))
2724 (if (and (not (zerop (length (match-string 1))))
2725 (re-search-backward py-class-start-re nil t))
2726 (concat (match-string 1) "." method)
2727 method)))
2728 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002729
2730
Barry Warsawfec75d61995-07-05 23:26:15 +00002731(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002732 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002733
Barry Warsaw850437a1995-03-08 21:50:28 +00002734(defun py-version ()
2735 "Echo the current version of `python-mode' in the minibuffer."
2736 (interactive)
2737 (message "Using `python-mode' version %s" py-version)
2738 (py-keep-region-active))
2739
2740;; only works under Emacs 19
2741;(eval-when-compile
2742; (require 'reporter))
2743
2744(defun py-submit-bug-report (enhancement-p)
2745 "Submit via mail a bug report on `python-mode'.
2746With \\[universal-argument] just submit an enhancement request."
2747 (interactive
2748 (list (not (y-or-n-p
2749 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002750 (let ((reporter-prompt-for-summary-p (if enhancement-p
2751 "(Very) brief summary: "
2752 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002753 (require 'reporter)
2754 (reporter-submit-bug-report
2755 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002756 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002757 ;; varlist
2758 (if enhancement-p nil
2759 '(py-python-command
2760 py-indent-offset
2761 py-block-comment-prefix
2762 py-scroll-process-buffer
2763 py-temp-directory
2764 py-beep-if-tab-change))
2765 nil ;pre-hooks
2766 nil ;post-hooks
2767 "Dear Barry,") ;salutation
2768 (if enhancement-p nil
2769 (set-mark (point))
2770 (insert
2771"Please replace this text with a sufficiently large code sample\n\
2772and an exact recipe so that I can reproduce your problem. Failure\n\
2773to do so may mean a greater delay in fixing your bug.\n\n")
2774 (exchange-point-and-mark)
2775 (py-keep-region-active))))
2776
2777
Barry Warsaw47384781997-11-26 05:27:45 +00002778(defun py-kill-emacs-hook ()
2779 (mapcar #'(lambda (filename)
2780 (py-safe (delete-file filename)))
2781 py-file-queue))
2782
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002783;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002784(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002785
2786
2787
2788(provide 'python-mode)
2789;;; python-mode.el ends here