blob: 6d10dcfbb93ffc7ac796a60b52c21e8a168b3bee [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)
Barry Warsawb6c1f1f1998-03-19 22:33:06 +0000111 (if (not (and (condition-case nil
112 (require 'custom)
113 (error nil))
114 ;; Stock Emacs 19.34 has a broken/old Custom library
115 ;; that does more harm than good. Fortunately, it is
116 ;; missing defcustom
117 (fboundp 'defcustom)))
Barry Warsaw673d05f1997-12-02 21:51:57 +0000118 (error "STOP! STOP! STOP! STOP!
119
120The Custom library was not found or is out of date. A more current
121version is required. Please download and install the latest version
122of the Custom library from:
123
124 <http://www.dina.kvl.dk/~abraham/custom/>
125
126See the Python Mode home page for details:
127
128 <http://www.python.org/ftp/emacs/>
129")))
130
Barry Warsawc72c11c1997-08-09 06:42:08 +0000131
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000132
133;; user definable variables
134;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Barry Warsaw7ae77681994-12-12 20:38:05 +0000135
Barry Warsawc72c11c1997-08-09 06:42:08 +0000136(defgroup python nil
137 "Support for the Python programming language, <http://www.python.org/>"
138 :group 'languages)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000139
Barry Warsawc72c11c1997-08-09 06:42:08 +0000140(defcustom py-python-command "python"
141 "*Shell command used to start Python interpreter."
142 :type 'string
143 :group 'python)
144
Barry Warsaw8f972b71998-02-05 20:45:49 +0000145(defcustom py-python-command-args '("-i")
146 "*List of string arguments to be used when starting a Python shell."
147 :type '(repeat string)
148 :group 'python)
149
Barry Warsawc72c11c1997-08-09 06:42:08 +0000150(defcustom py-indent-offset 4
151 "*Amount of offset per level of indentation
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000152Note that `\\[py-guess-indent-offset]' can usually guess a good value
Barry Warsawc72c11c1997-08-09 06:42:08 +0000153when you're editing someone else's Python code."
154 :type 'integer
155 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000156
Barry Warsaw742a5111998-03-13 17:29:15 +0000157(defcustom py-smart-indentation t
158 "*Should `python-mode' try to automagically set some indentation variables?
159When this variable is non-nil, two things happen when a buffer is set
160to `python-mode':
161
162 1. `py-indent-offset' is guess from existing code in the buffer.
Barry Warsaw639eea61998-03-16 18:12:13 +0000163 Only guessed values between 2 and 8 are considered. If a valid
Barry Warsaw742a5111998-03-13 17:29:15 +0000164 guess can't be made (perhaps because you are visiting a new
Barry Warsaw639eea61998-03-16 18:12:13 +0000165 file), then the value in `py-indent-offset' is used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000166
Barry Warsaw639eea61998-03-16 18:12:13 +0000167 2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
168 equal `tab-width' (`indent-tabs-mode' is never turned on by
169 Python mode). This means that for newly written code, tabs are
170 only inserted in indentation if one tab is one indentation
171 level, otherwise only spaces are used.
Barry Warsaw742a5111998-03-13 17:29:15 +0000172
Barry Warsaw8046bef1998-03-13 20:04:52 +0000173Note that both these settings occur *after* `python-mode-hook' is run,
174so if you want to defeat the automagic configuration, you must also
175set `py-smart-indentation' to nil in your `python-mode-hook'."
Barry Warsaw742a5111998-03-13 17:29:15 +0000176 :type 'boolean
177 :group 'python)
178
Barry Warsawc72c11c1997-08-09 06:42:08 +0000179(defcustom py-align-multiline-strings-p t
180 "*Flag describing how multi-line triple quoted strings are aligned.
Barry Warsaw095e9c61995-09-19 20:01:42 +0000181When this flag is non-nil, continuation lines are lined up under the
182preceding line's indentation. When this flag is nil, continuation
Barry Warsawc72c11c1997-08-09 06:42:08 +0000183lines are aligned to column zero."
184 :type '(choice (const :tag "Align under preceding line" t)
185 (const :tag "Align to column zero" nil))
186 :group 'python)
Barry Warsaw095e9c61995-09-19 20:01:42 +0000187
Barry Warsawc72c11c1997-08-09 06:42:08 +0000188(defcustom py-block-comment-prefix "## "
Barry Warsaw867a32a1996-03-07 18:30:26 +0000189 "*String used by \\[comment-region] to comment out a block of code.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000190This should follow the convention for non-indenting comment lines so
191that the indentation commands won't get confused (i.e., the string
192should be of the form `#x...' where `x' is not a blank or a tab, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000193`...' is arbitrary)."
194 :type 'string
195 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000196
Barry Warsawc72c11c1997-08-09 06:42:08 +0000197(defcustom py-honor-comment-indentation t
Barry Warsaw6d627751996-03-06 18:41:38 +0000198 "*Controls how comment lines influence subsequent indentation.
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000199
Barry Warsaw6d627751996-03-06 18:41:38 +0000200When nil, all comment lines are skipped for indentation purposes, and
Barry Warsawc72c11c1997-08-09 06:42:08 +0000201if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
Barry Warsaw6d627751996-03-06 18:41:38 +0000202
203When t, lines that begin with a single `#' are a hint to subsequent
204line indentation. If the previous line is such a comment line (as
205opposed to one that starts with `py-block-comment-prefix'), then it's
206indentation is used as a hint for this line's indentation. Lines that
207begin with `py-block-comment-prefix' are ignored for indentation
208purposes.
209
210When not nil or t, comment lines that begin with a `#' are used as
Barry Warsawc72c11c1997-08-09 06:42:08 +0000211indentation hints, unless the comment character is in column zero."
212 :type '(choice
213 (const :tag "Skip all comment lines (fast)" nil)
214 (const :tag "Single # `sets' indentation for next line" t)
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000215 (const :tag "Single # `sets' indentation except at column zero"
216 other)
Barry Warsawc72c11c1997-08-09 06:42:08 +0000217 )
218 :group 'python)
Barry Warsaw33d6ec01996-03-05 16:28:07 +0000219
Barry Warsaw8ee4a601998-02-06 16:01:52 +0000220(defcustom py-scroll-process-buffer nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000221 "*Scroll Python process buffer as output arrives.
222If nil, the Python process buffer acts, with respect to scrolling, like
223Shell-mode buffers normally act. This is surprisingly complicated and
224so won't be explained here; in fact, you can't get the whole story
225without studying the Emacs C code.
226
227If non-nil, the behavior is different in two respects (which are
228slightly inaccurate in the interest of brevity):
229
230 - If the buffer is in a window, and you left point at its end, the
231 window will scroll as new output arrives, and point will move to the
232 buffer's end, even if the window is not the selected window (that
233 being the one the cursor is in). The usual behavior for shell-mode
234 windows is not to scroll, and to leave point where it was, if the
235 buffer is in a window other than the selected window.
236
237 - If the buffer is not visible in any window, and you left point at
238 its end, the buffer will be popped into a window as soon as more
239 output arrives. This is handy if you have a long-running
240 computation and don't want to tie up screen area waiting for the
241 output. The usual behavior for a shell-mode buffer is to stay
242 invisible until you explicitly visit it.
243
244Note the `and if you left point at its end' clauses in both of the
245above: you can `turn off' the special behaviors while output is in
246progress, by visiting the Python buffer and moving point to anywhere
247besides the end. Then the buffer won't scroll, point will remain where
248you leave it, and if you hide the buffer it will stay hidden until you
249visit it again. You can enable and disable the special behaviors as
250often as you like, while output is in progress, by (respectively) moving
251point to, or away from, the end of the buffer.
252
253Warning: If you expect a large amount of output, you'll probably be
254happier setting this option to nil.
255
256Obscure: `End of buffer' above should really say `at or beyond the
257process mark', but if you know what that means you didn't need to be
Barry Warsawc72c11c1997-08-09 06:42:08 +0000258told <grin>."
259 :type 'boolean
260 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000261
Barry Warsaw516b6201997-08-09 06:43:20 +0000262(defcustom py-temp-directory
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000263 (let ((ok '(lambda (x)
264 (and x
265 (setq x (expand-file-name x)) ; always true
266 (file-directory-p x)
267 (file-writable-p x)
268 x))))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000269 (or (funcall ok (getenv "TMPDIR"))
270 (funcall ok "/usr/tmp")
271 (funcall ok "/tmp")
272 (funcall ok ".")
273 (error
Barry Warsaw6c6db0a1998-02-25 16:33:56 +0000274 "Couldn't find a usable temp directory -- set `py-temp-directory'")))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000275 "*Directory used for temp files created by a *Python* process.
276By default, the first directory from this list that exists and that you
277can write into: the value (if any) of the environment variable TMPDIR,
Barry Warsawc72c11c1997-08-09 06:42:08 +0000278/usr/tmp, /tmp, or the current directory."
279 :type 'string
280 :group 'python)
Barry Warsaw7ae77681994-12-12 20:38:05 +0000281
Barry Warsaw516b6201997-08-09 06:43:20 +0000282(defcustom py-beep-if-tab-change t
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000283 "*Ring the bell if tab-width is changed.
284If a comment of the form
285
286 \t# vi:set tabsize=<number>:
287
288is found before the first code line when the file is entered, and the
289current value of (the general Emacs variable) `tab-width' does not
290equal <number>, `tab-width' is set to <number>, a message saying so is
291displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
Barry Warsawc72c11c1997-08-09 06:42:08 +0000292the Emacs bell is also rung as a warning."
293 :type 'boolean
294 :group 'python)
295
Barry Warsaw9981d221997-12-03 05:25:48 +0000296(defcustom py-jump-on-exception t
297 "*Jump to innermost exception frame in *Python Output* buffer.
298When this variable is non-nil and ane exception occurs when running
299Python code synchronously in a subprocess, jump immediately to the
300source code of the innermost frame.")
301
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000302(defcustom py-backspace-function 'backward-delete-char-untabify
303 "*Function called by `py-electric-backspace' when deleting backwards."
304 :type 'function
305 :group 'python)
306
307(defcustom py-delete-function 'delete-char
308 "*Function called by `py-electric-delete' when deleting forwards."
309 :type 'function
310 :group 'python)
311
Barry Warsawc0ecb531998-01-20 21:43:34 +0000312;; Not customizable
313(defvar py-master-file nil
314 "If non-nil, execute the named file instead of the buffer's file.
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000315The intent is to allow you to set this variable in the file's local
Barry Warsawc0ecb531998-01-20 21:43:34 +0000316variable section, e.g.:
317
318 # Local Variables:
319 # py-master-file: \"master.py\"
320 # End:
321
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000322so that typing \\[py-execute-buffer] in that buffer executes the
Barry Warsawc0ecb531998-01-20 21:43:34 +0000323named master file instead of the buffer's file. Note that if the file
Barry Warsaw50b3eb61998-02-25 15:57:47 +0000324name has a relative path, the `default-directory' for the buffer is
325prepended to come up with a file name.")
Barry Warsawc0ecb531998-01-20 21:43:34 +0000326(make-variable-buffer-local 'py-master-file)
327
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000328
Barry Warsawc72c11c1997-08-09 06:42:08 +0000329
330;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
331;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
332
Barry Warsaw5e21cb01997-11-05 18:41:11 +0000333(defconst py-emacs-features
334 (let (features)
335 ;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
336 ;; the same string.
337 (let ((tmp1 (make-temp-name ""))
338 (tmp2 (make-temp-name "")))
339 (if (string-equal tmp1 tmp2)
340 (push 'broken-temp-names features)))
341 ;; return the features
342 features)
Barry Warsawc12c62e1997-09-04 04:18:07 +0000343 "A list of features extant in the Emacs you are using.
Barry Warsaw6ae21ad1997-11-06 14:36:49 +0000344There are many flavors of Emacs out there, with different levels of
345support for features needed by `python-mode'.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000346
Barry Warsawfb07f401997-02-24 03:37:22 +0000347(defvar python-font-lock-keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000348 (let ((kw1 (mapconcat 'identity
349 '("and" "assert" "break" "class"
350 "continue" "def" "del" "elif"
351 "else" "except" "exec" "for"
352 "from" "global" "if" "import"
353 "in" "is" "lambda" "not"
354 "or" "pass" "print" "raise"
355 "return" "while"
356 )
357 "\\|"))
358 (kw2 (mapconcat 'identity
359 '("else:" "except:" "finally:" "try:")
360 "\\|"))
361 )
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000362 (list
Barry Warsawef3c8911997-11-05 18:55:50 +0000363 ;; keywords
Barry Warsawb8f11661997-11-06 14:35:15 +0000364 (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
365 ;; block introducing keywords with immediately following colons.
366 ;; Yes "except" is in both lists.
367 (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
Barry Warsaw33ab6e41996-03-05 00:44:31 +0000368 ;; classes
369 '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
370 1 font-lock-type-face)
371 ;; functions
372 '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
373 1 font-lock-function-name-face)
374 ))
Barry Warsaw62d9d6e1996-03-06 20:32:27 +0000375 "Additional expressions to highlight in Python mode.")
Barry Warsawfb07f401997-02-24 03:37:22 +0000376(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
377
Barry Warsawb01b4fa1995-06-20 18:55:34 +0000378
Barry Warsaw81437461996-08-01 19:48:02 +0000379(defvar imenu-example--python-show-method-args-p nil
380 "*Controls echoing of arguments of functions & methods in the imenu buffer.
381When non-nil, arguments are printed.")
382
Barry Warsaw52bc17c1995-10-12 21:15:49 +0000383(make-variable-buffer-local 'py-indent-offset)
384
Barry Warsawe467bfb1997-11-26 05:40:58 +0000385;; have to bind py-file-queue before installing the kill-emacs-hook
Barry Warsaw7ae77681994-12-12 20:38:05 +0000386(defvar py-file-queue nil
387 "Queue of Python temp files awaiting execution.
388Currently-active file is at the head of the list.")
389
Barry Warsawc72c11c1997-08-09 06:42:08 +0000390
391;; Constants
392
393;; Regexp matching a Python string literal
394(defconst py-stringlit-re
395 (concat
396 "'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
397 "\\|" ; or
398 "\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
399
400;; Regexp matching Python lines that are continued via backslash.
401;; This is tricky because a trailing backslash does not mean
402;; continuation if it's in a comment
403(defconst py-continued-re
404 (concat
405 "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
406 "\\\\$"))
407
408;; Regexp matching blank or comment lines.
409(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
410
411;; Regexp matching clauses to be outdented one level.
412(defconst py-outdent-re
413 (concat "\\(" (mapconcat 'identity
414 '("else:"
415 "except\\(\\s +.*\\)?:"
416 "finally:"
417 "elif\\s +.*:")
418 "\\|")
419 "\\)"))
420
421
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000422;; Regexp matching keywords which typically close a block
423(defconst py-block-closing-keywords-re
424 "\\(return\\|raise\\|break\\|continue\\|pass\\)")
425
Barry Warsawc72c11c1997-08-09 06:42:08 +0000426;; Regexp matching lines to not outdent after.
427(defconst py-no-outdent-re
Barry Warsawaffc0ca1997-11-03 16:59:38 +0000428 (concat
429 "\\("
430 (mapconcat 'identity
431 (list "try:"
432 "except\\(\\s +.*\\)?:"
433 "while\\s +.*:"
434 "for\\s +.*:"
435 "if\\s +.*:"
436 "elif\\s +.*:"
437 (concat py-block-closing-keywords-re "[ \t\n]")
438 )
439 "\\|")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000440 "\\)"))
441
442;; Regexp matching a function, method or variable assignment. If you
443;; change this, you probably have to change `py-current-defun' as
444;; well. This is only used by `py-current-defun' to find the name for
445;; add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000446(defconst py-defun-start-re
Barry Warsawc72c11c1997-08-09 06:42:08 +0000447 "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
448
449;; Regexp for finding a class name. If you change this, you probably
450;; have to change `py-current-defun' as well. This is only used by
451;; `py-current-defun' to find the name for add-log.el.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000452(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
453
454;; Regexp that describes tracebacks
455(defconst py-traceback-line-re
Barry Warsawffbc17d1997-11-27 20:08:14 +0000456 "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
Barry Warsawc72c11c1997-08-09 06:42:08 +0000457
458
459
460;; Utilities
461
462(defmacro py-safe (&rest body)
463 ;; safely execute BODY, return nil if an error occurred
464 (` (condition-case nil
465 (progn (,@ body))
466 (error nil))))
467
468(defsubst py-keep-region-active ()
469 ;; Do whatever is necessary to keep the region active in XEmacs.
470 ;; Ignore byte-compiler warnings you might see. Also note that
471 ;; FSF's Emacs 19 does it differently; its policy doesn't require us
472 ;; to take explicit action.
473 (and (boundp 'zmacs-region-stays)
474 (setq zmacs-region-stays t)))
475
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000476(defsubst py-point (position)
477 ;; Returns the value of point at certain commonly referenced POSITIONs.
478 ;; POSITION can be one of the following symbols:
479 ;;
480 ;; bol -- beginning of line
481 ;; eol -- end of line
482 ;; bod -- beginning of defun
483 ;; boi -- back to indentation
484 ;;
485 ;; This function does not modify point or mark.
486 (let ((here (point)))
487 (cond
488 ((eq position 'bol) (beginning-of-line))
489 ((eq position 'eol) (end-of-line))
490 ((eq position 'bod) (beginning-of-python-def-or-class))
491 ((eq position 'bob) (beginning-of-buffer))
492 ((eq position 'eob) (end-of-buffer))
493 ((eq position 'boi) (back-to-indentation))
494 (t (error "unknown buffer position requested: %s" position))
495 )
496 (prog1
497 (point)
498 (goto-char here))))
499
500(defsubst py-highlight-line (from to file line)
501 (cond
502 ((fboundp 'make-extent)
503 ;; XEmacs
504 (let ((e (make-extent from to)))
505 (set-extent-property e 'mouse-face 'highlight)
506 (set-extent-property e 'py-exc-info (cons file line))
507 (set-extent-property e 'keymap py-mode-output-map)))
508 (t
509 ;; Emacs -- Please port this!
510 )
511 ))
512
Barry Warsawe908b6b1998-03-19 22:48:02 +0000513(defun py-in-literal (&optional lim)
514 ;; Determine if point is in a Python literal, defined as a comment
515 ;; or string. This is the version used for non-XEmacs, which has a
516 ;; nicer interface.
517 ;;
518 ;; WARNING: Watch out for infinite recursion.
519 (let* ((lim (or lim (c-point 'bod)))
520 (state (parse-partial-sexp lim (point))))
521 (cond
522 ((nth 3 state) 'string)
523 ((nth 4 state) 'comment)
524 (t nil))))
525
526;; XEmacs has a built-in function that should make this much quicker.
527;; In this case, lim is ignored
528(defun py-fast-in-literal (&optional lim)
529 ;; don't have to worry about context == 'block-comment
530 (buffer-syntactic-context))
531
532(if (fboundp 'buffer-syntactic-context)
533 (defalias 'c-in-literal 'c-fast-in-literal))
534
535
Barry Warsawc72c11c1997-08-09 06:42:08 +0000536
537;; Major mode boilerplate
538
Barry Warsaw7ae77681994-12-12 20:38:05 +0000539;; define a mode-specific abbrev table for those who use such things
540(defvar python-mode-abbrev-table nil
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000541 "Abbrev table in use in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000542(define-abbrev-table 'python-mode-abbrev-table nil)
543
Barry Warsaw7ae77681994-12-12 20:38:05 +0000544(defvar python-mode-hook nil
545 "*Hook called by `python-mode'.")
546
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000547;; in previous version of python-mode.el, the hook was incorrectly
548;; called py-mode-hook, and was not defvar'd. deprecate its use.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000549(and (fboundp 'make-obsolete-variable)
550 (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
551
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000552(defvar py-mode-map ()
553 "Keymap used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000554(if py-mode-map
Barry Warsawc72c11c1997-08-09 06:42:08 +0000555 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000556 (setq py-mode-map (make-sparse-keymap))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000557 ;; electric keys
558 (define-key py-mode-map ":" 'py-electric-colon)
559 ;; indentation level modifiers
560 (define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
561 (define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
562 (define-key py-mode-map "\C-c<" 'py-shift-region-left)
563 (define-key py-mode-map "\C-c>" 'py-shift-region-right)
564 ;; subprocess commands
565 (define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
566 (define-key py-mode-map "\C-c|" 'py-execute-region)
567 (define-key py-mode-map "\C-c!" 'py-shell)
568 ;; Caution! Enter here at your own risk. We are trying to support
569 ;; several behaviors and it gets disgusting. :-( This logic ripped
570 ;; largely from CC Mode.
571 ;;
572 ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
573 ;; backwards deletion behavior to DEL, which both Delete and
574 ;; Backspace get translated to. There's no way to separate this
575 ;; behavior in a clean way, so deal with it! Besides, it's been
576 ;; this way since the dawn of time.
577 (if (not (boundp 'delete-key-deletes-forward))
578 (define-key py-mode-map "\177" 'py-electric-backspace)
579 ;; However, XEmacs 20 actually achieved enlightenment. It is
580 ;; possible to sanely define both backward and forward deletion
581 ;; behavior under X separately (TTYs are forever beyond hope, but
582 ;; who cares? XEmacs 20 does the right thing with these too).
583 (define-key py-mode-map [delete] 'py-electric-delete)
584 (define-key py-mode-map [backspace] 'py-electric-backspace))
Barry Warsaw8c4a8de1997-11-26 20:30:33 +0000585 ;; Separate M-BS from C-M-h. The former should remain
586 ;; backward-kill-word.
587 (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
Barry Warsaw2518c671997-11-05 00:51:08 +0000588 (define-key py-mode-map "\C-c\C-k" 'py-mark-block)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000589 ;; Miscellaneous
590 (define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
591 (define-key py-mode-map "\C-c\t" 'py-indent-region)
592 (define-key py-mode-map "\C-c\C-n" 'py-next-statement)
593 (define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
594 (define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000595 (define-key py-mode-map "\C-c#" 'py-comment-region)
596 (define-key py-mode-map "\C-c?" 'py-describe-mode)
597 (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
598 (define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
599 (define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000600 (define-key py-mode-map "\C-c-" 'py-up-exception)
601 (define-key py-mode-map "\C-c=" 'py-down-exception)
Barry Warsaw6d48c4a1997-11-04 19:21:50 +0000602 ;; information
603 (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
604 (define-key py-mode-map "\C-c\C-v" 'py-version)
605 ;; py-newline-and-indent mappings
Barry Warsaw82aecb91998-01-21 05:14:24 +0000606 (define-key py-mode-map "\n" 'py-newline-and-indent)
607 (define-key py-mode-map "\C-m" 'py-newline-and-indent)
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000608 ;; shadow global bindings for newline-and-indent w/ the py- version.
609 ;; BAW - this is extremely bad form, but I'm not going to change it
610 ;; for now.
Barry Warsawa0ee8cd1997-11-26 01:04:44 +0000611 (mapcar #'(lambda (key)
612 (define-key py-mode-map key 'py-newline-and-indent))
613 (where-is-internal 'newline-and-indent))
614 )
615
616(defvar py-mode-output-map nil
617 "Keymap used in *Python Output* buffers*")
618(if py-mode-output-map
619 nil
620 (setq py-mode-output-map (make-sparse-keymap))
621 (define-key py-mode-output-map [button2] 'py-mouseto-exception)
622 (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
623 ;; TBD: Disable all self-inserting keys. This is bogus, we should
624 ;; really implement this as *Python Output* buffer being read-only
625 (mapcar #' (lambda (key)
626 (define-key py-mode-output-map key
627 #'(lambda () (interactive) (beep))))
628 (where-is-internal 'self-insert-command))
Barry Warsaw850437a1995-03-08 21:50:28 +0000629 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000630
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000631(defvar py-mode-syntax-table nil
632 "Syntax table used in `python-mode' buffers.")
Barry Warsaw7ae77681994-12-12 20:38:05 +0000633(if py-mode-syntax-table
Barry Warsawc72c11c1997-08-09 06:42:08 +0000634 nil
Barry Warsaw7ae77681994-12-12 20:38:05 +0000635 (setq py-mode-syntax-table (make-syntax-table))
Barry Warsawc72c11c1997-08-09 06:42:08 +0000636 (modify-syntax-entry ?\( "()" py-mode-syntax-table)
637 (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
638 (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
639 (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
640 (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
641 (modify-syntax-entry ?\} "){" py-mode-syntax-table)
642 ;; Add operator symbols misassigned in the std table
643 (modify-syntax-entry ?\$ "." py-mode-syntax-table)
644 (modify-syntax-entry ?\% "." py-mode-syntax-table)
645 (modify-syntax-entry ?\& "." py-mode-syntax-table)
646 (modify-syntax-entry ?\* "." py-mode-syntax-table)
647 (modify-syntax-entry ?\+ "." py-mode-syntax-table)
648 (modify-syntax-entry ?\- "." py-mode-syntax-table)
649 (modify-syntax-entry ?\/ "." py-mode-syntax-table)
650 (modify-syntax-entry ?\< "." py-mode-syntax-table)
651 (modify-syntax-entry ?\= "." py-mode-syntax-table)
652 (modify-syntax-entry ?\> "." py-mode-syntax-table)
653 (modify-syntax-entry ?\| "." py-mode-syntax-table)
654 ;; For historical reasons, underscore is word class instead of
655 ;; symbol class. GNU conventions say it should be symbol class, but
656 ;; there's a natural conflict between what major mode authors want
657 ;; and what users expect from `forward-word' and `backward-word'.
658 ;; Guido and I have hashed this out and have decided to keep
659 ;; underscore in word class. If you're tempted to change it, try
660 ;; binding M-f and M-b to py-forward-into-nomenclature and
661 ;; py-backward-into-nomenclature instead.
662 (modify-syntax-entry ?\_ "w" py-mode-syntax-table)
663 ;; Both single quote and double quote are string delimiters
664 (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
665 (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
666 ;; backquote is open and close paren
667 (modify-syntax-entry ?\` "$" py-mode-syntax-table)
668 ;; comment delimiters
669 (modify-syntax-entry ?\# "<" py-mode-syntax-table)
670 (modify-syntax-entry ?\n ">" py-mode-syntax-table)
671 )
Barry Warsaw7ae77681994-12-12 20:38:05 +0000672
Barry Warsawb3e81d51996-09-04 15:12:42 +0000673
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000674
Barry Warsaw42f707f1996-07-29 21:05:05 +0000675;; Menu definitions, only relevent if you have the easymenu.el package
676;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
Barry Warsaw5490a061996-08-06 15:43:33 +0000677(defvar py-menu nil
678 "Menu for Python Mode.
Barry Warsawc72c11c1997-08-09 06:42:08 +0000679This menu will get created automatically if you have the `easymenu'
680package. Note that the latest X/Emacs releases contain this package.")
Barry Warsaw5490a061996-08-06 15:43:33 +0000681
Barry Warsawc72c11c1997-08-09 06:42:08 +0000682(and (py-safe (require 'easymenu) t)
683 (easy-menu-define
684 py-menu py-mode-map "Python Mode menu"
685 '("Python"
686 ["Comment Out Region" py-comment-region (mark)]
687 ["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
688 "-"
689 ["Mark current block" py-mark-block t]
Barry Warsaw2518c671997-11-05 00:51:08 +0000690 ["Mark current def" py-mark-def-or-class t]
691 ["Mark current class" (py-mark-def-or-class t) t]
Barry Warsawc72c11c1997-08-09 06:42:08 +0000692 "-"
693 ["Shift region left" py-shift-region-left (mark)]
694 ["Shift region right" py-shift-region-right (mark)]
695 "-"
696 ["Execute buffer" py-execute-buffer t]
697 ["Execute region" py-execute-region (mark)]
698 ["Start interpreter..." py-shell t]
699 "-"
700 ["Go to start of block" py-goto-block-up t]
701 ["Go to start of class" (beginning-of-python-def-or-class t) t]
702 ["Move to end of class" (end-of-python-def-or-class t) t]
703 ["Move to start of def" beginning-of-python-def-or-class t]
704 ["Move to end of def" end-of-python-def-or-class t]
705 "-"
706 ["Describe mode" py-describe-mode t]
707 )))
Barry Warsaw42f707f1996-07-29 21:05:05 +0000708
Barry Warsaw81437461996-08-01 19:48:02 +0000709
710
711;; imenu definitions, courtesy of Perry A. Stoll <stoll@atr-sw.atr.co.jp>
712(defvar imenu-example--python-class-regexp
713 (concat ; <<classes>>
714 "\\(" ;
715 "^[ \t]*" ; newline and maybe whitespace
716 "\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
717 ; possibly multiple superclasses
718 "\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
719 "[ \t]*:" ; and the final :
720 "\\)" ; >>classes<<
721 )
722 "Regexp for Python classes for use with the imenu package."
723 )
724
725(defvar imenu-example--python-method-regexp
726 (concat ; <<methods and functions>>
727 "\\(" ;
728 "^[ \t]*" ; new line and maybe whitespace
729 "\\(def[ \t]+" ; function definitions start with def
730 "\\([a-zA-Z0-9_]+\\)" ; name is here
731 ; function arguments...
732 "[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
733 "\\)" ; end of def
734 "[ \t]*:" ; and then the :
735 "\\)" ; >>methods and functions<<
736 )
737 "Regexp for Python methods/functions for use with the imenu package."
738 )
739
740(defvar imenu-example--python-method-no-arg-parens '(2 8)
741 "Indicies into groups of the Python regexp for use with imenu.
742
743Using these values will result in smaller imenu lists, as arguments to
744functions are not listed.
745
746See the variable `imenu-example--python-show-method-args-p' for more
747information.")
748
749(defvar imenu-example--python-method-arg-parens '(2 7)
750 "Indicies into groups of the Python regexp for use with imenu.
751Using these values will result in large imenu lists, as arguments to
752functions are listed.
753
754See the variable `imenu-example--python-show-method-args-p' for more
755information.")
756
757;; Note that in this format, this variable can still be used with the
758;; imenu--generic-function. Otherwise, there is no real reason to have
759;; it.
760(defvar imenu-example--generic-python-expression
761 (cons
762 (concat
763 imenu-example--python-class-regexp
764 "\\|" ; or...
765 imenu-example--python-method-regexp
766 )
767 imenu-example--python-method-no-arg-parens)
768 "Generic Python expression which may be used directly with imenu.
769Used by setting the variable `imenu-generic-expression' to this value.
770Also, see the function \\[imenu-example--create-python-index] for a
771better alternative for finding the index.")
772
773;; These next two variables are used when searching for the python
774;; class/definitions. Just saving some time in accessing the
775;; generic-python-expression, really.
Barry Warsaw01af4011996-09-04 14:57:22 +0000776(defvar imenu-example--python-generic-regexp nil)
777(defvar imenu-example--python-generic-parens nil)
Barry Warsaw81437461996-08-01 19:48:02 +0000778
779
Barry Warsaw81437461996-08-01 19:48:02 +0000780(defun imenu-example--create-python-index ()
781 "Python interface function for imenu package.
782Finds all python classes and functions/methods. Calls function
783\\[imenu-example--create-python-index-engine]. See that function for
784the details of how this works."
785 (setq imenu-example--python-generic-regexp
786 (car imenu-example--generic-python-expression))
787 (setq imenu-example--python-generic-parens
788 (if imenu-example--python-show-method-args-p
789 imenu-example--python-method-arg-parens
790 imenu-example--python-method-no-arg-parens))
791 (goto-char (point-min))
792 (imenu-example--create-python-index-engine nil))
793
794(defun imenu-example--create-python-index-engine (&optional start-indent)
795 "Function for finding imenu definitions in Python.
796
797Finds all definitions (classes, methods, or functions) in a Python
798file for the imenu package.
799
800Returns a possibly nested alist of the form
801
802 (INDEX-NAME . INDEX-POSITION)
803
804The second element of the alist may be an alist, producing a nested
805list as in
806
807 (INDEX-NAME . INDEX-ALIST)
808
809This function should not be called directly, as it calls itself
810recursively and requires some setup. Rather this is the engine for
811the function \\[imenu-example--create-python-index].
812
813It works recursively by looking for all definitions at the current
814indention level. When it finds one, it adds it to the alist. If it
815finds a definition at a greater indentation level, it removes the
816previous definition from the alist. In it's place it adds all
817definitions found at the next indentation level. When it finds a
818definition that is less indented then the current level, it retuns the
819alist it has created thus far.
820
821The optional argument START-INDENT indicates the starting indentation
822at which to continue looking for Python classes, methods, or
823functions. If this is not supplied, the function uses the indentation
824of the first definition found."
825 (let ((index-alist '())
826 (sub-method-alist '())
827 looking-p
828 def-name prev-name
829 cur-indent def-pos
830 (class-paren (first imenu-example--python-generic-parens))
831 (def-paren (second imenu-example--python-generic-parens)))
832 (setq looking-p
833 (re-search-forward imenu-example--python-generic-regexp
834 (point-max) t))
835 (while looking-p
836 (save-excursion
837 ;; used to set def-name to this value but generic-extract-name is
838 ;; new to imenu-1.14. this way it still works with imenu-1.11
839 ;;(imenu--generic-extract-name imenu-example--python-generic-parens))
840 (let ((cur-paren (if (match-beginning class-paren)
841 class-paren def-paren)))
842 (setq def-name
Barry Warsawc8520351997-11-26 06:14:40 +0000843 (buffer-substring-no-properties (match-beginning cur-paren)
844 (match-end cur-paren))))
Barry Warsaw81437461996-08-01 19:48:02 +0000845 (beginning-of-line)
846 (setq cur-indent (current-indentation)))
847
848 ;; HACK: want to go to the next correct definition location. we
849 ;; explicitly list them here. would be better to have them in a
850 ;; list.
851 (setq def-pos
852 (or (match-beginning class-paren)
853 (match-beginning def-paren)))
854
855 ;; if we don't have a starting indent level, take this one
856 (or start-indent
857 (setq start-indent cur-indent))
858
859 ;; if we don't have class name yet, take this one
860 (or prev-name
861 (setq prev-name def-name))
862
863 ;; what level is the next definition on? must be same, deeper
864 ;; or shallower indentation
865 (cond
866 ;; at the same indent level, add it to the list...
867 ((= start-indent cur-indent)
868
869 ;; if we don't have push, use the following...
870 ;;(setf index-alist (cons (cons def-name def-pos) index-alist))
871 (push (cons def-name def-pos) index-alist))
872
873 ;; deeper indented expression, recur...
874 ((< start-indent cur-indent)
875
876 ;; the point is currently on the expression we're supposed to
877 ;; start on, so go back to the last expression. The recursive
878 ;; call will find this place again and add it to the correct
879 ;; list
880 (re-search-backward imenu-example--python-generic-regexp
881 (point-min) 'move)
882 (setq sub-method-alist (imenu-example--create-python-index-engine
883 cur-indent))
884
885 (if sub-method-alist
886 ;; we put the last element on the index-alist on the start
887 ;; of the submethod alist so the user can still get to it.
888 (let ((save-elmt (pop index-alist)))
Barry Warsawc8520351997-11-26 06:14:40 +0000889 (push (cons prev-name
Barry Warsaw81437461996-08-01 19:48:02 +0000890 (cons save-elmt sub-method-alist))
891 index-alist))))
892
893 ;; found less indented expression, we're done.
894 (t
895 (setq looking-p nil)
896 (re-search-backward imenu-example--python-generic-regexp
897 (point-min) t)))
898 (setq prev-name def-name)
899 (and looking-p
900 (setq looking-p
901 (re-search-forward imenu-example--python-generic-regexp
902 (point-max) 'move))))
903 (nreverse index-alist)))
904
Barry Warsaw42f707f1996-07-29 21:05:05 +0000905
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000906;;;###autoload
Barry Warsaw7ae77681994-12-12 20:38:05 +0000907(defun python-mode ()
908 "Major mode for editing Python files.
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000909To submit a problem report, enter `\\[py-submit-bug-report]' from a
910`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
911documentation. To see what version of `python-mode' you are running,
912enter `\\[py-version]'.
913
914This mode knows about Python indentation, tokens, comments and
915continuation lines. Paragraphs are separated by blank lines only.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000916
917COMMANDS
918\\{py-mode-map}
919VARIABLES
920
Barry Warsaw42f707f1996-07-29 21:05:05 +0000921py-indent-offset\t\tindentation increment
922py-block-comment-prefix\t\tcomment string used by comment-region
923py-python-command\t\tshell command to invoke Python interpreter
924py-scroll-process-buffer\t\talways scroll Python process buffer
925py-temp-directory\t\tdirectory used for temp files (if needed)
926py-beep-if-tab-change\t\tring the bell if tab-width is changed"
Barry Warsaw7ae77681994-12-12 20:38:05 +0000927 (interactive)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000928 ;; set up local variables
Barry Warsaw7ae77681994-12-12 20:38:05 +0000929 (kill-all-local-variables)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000930 (make-local-variable 'font-lock-defaults)
931 (make-local-variable 'paragraph-separate)
932 (make-local-variable 'paragraph-start)
933 (make-local-variable 'require-final-newline)
934 (make-local-variable 'comment-start)
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000935 (make-local-variable 'comment-end)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000936 (make-local-variable 'comment-start-skip)
937 (make-local-variable 'comment-column)
938 (make-local-variable 'indent-region-function)
939 (make-local-variable 'indent-line-function)
Barry Warsawb3e81d51996-09-04 15:12:42 +0000940 (make-local-variable 'add-log-current-defun-function)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000941 ;;
Barry Warsaw7ae77681994-12-12 20:38:05 +0000942 (set-syntax-table py-mode-syntax-table)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000943 (setq major-mode 'python-mode
944 mode-name "Python"
945 local-abbrev-table python-mode-abbrev-table
Barry Warsaw5c38bf61997-12-02 22:01:04 +0000946 font-lock-defaults '(python-font-lock-keywords)
Barry Warsaw615d4a41996-09-04 14:14:10 +0000947 paragraph-separate "^[ \t]*$"
948 paragraph-start "^[ \t]*$"
949 require-final-newline t
950 comment-start "# "
Barry Warsaw5c8bef11996-12-17 21:56:10 +0000951 comment-end ""
Barry Warsaw615d4a41996-09-04 14:14:10 +0000952 comment-start-skip "# *"
953 comment-column 40
Barry Warsaw550a02e1996-09-04 14:23:00 +0000954 indent-region-function 'py-indent-region
955 indent-line-function 'py-indent-line
Barry Warsawb3e81d51996-09-04 15:12:42 +0000956 ;; tell add-log.el how to find the current function/method/variable
957 add-log-current-defun-function 'py-current-defun
Barry Warsawb1f89511996-09-03 16:38:30 +0000958 )
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000959 (use-local-map py-mode-map)
Barry Warsaw42f707f1996-07-29 21:05:05 +0000960 ;; add the menu
961 (if py-menu
962 (easy-menu-add py-menu))
Barry Warsaw57697af1995-09-14 20:01:14 +0000963 ;; Emacs 19 requires this
Barry Warsawc72c11c1997-08-09 06:42:08 +0000964 (if (boundp 'comment-multi-line)
Barry Warsaw57697af1995-09-14 20:01:14 +0000965 (setq comment-multi-line nil))
Barry Warsaw742a5111998-03-13 17:29:15 +0000966 ;; Install Imenu, only works for Emacs.
967 (when (py-safe (require 'imenu))
968 (make-variable-buffer-local 'imenu-create-index-function)
969 (setq imenu-create-index-function
970 (function imenu-example--create-python-index))
971 (setq imenu-generic-expression
972 imenu-example--generic-python-expression)
973 (if (fboundp 'imenu-add-to-menubar)
974 (imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
975 )
976 ;; Run the mode hook. Note that py-mode-hook is deprecated.
Barry Warsaw7ae77681994-12-12 20:38:05 +0000977 (if python-mode-hook
978 (run-hooks 'python-mode-hook)
Barry Warsaw742a5111998-03-13 17:29:15 +0000979 (run-hooks 'py-mode-hook))
980 ;; Now do the automagical guessing
981 (if py-smart-indentation
982 (let ((offset py-indent-offset))
983 ;; Its okay if this fails to guess a good value
984 (if (and (py-safe (py-guess-indent-offset))
985 (<= py-indent-offset 8)
986 (>= py-indent-offset 2))
987 (setq offset py-indent-offset))
988 (setq py-indent-offset offset)
Barry Warsaw639eea61998-03-16 18:12:13 +0000989 ;; Only turn indent-tabs-mode off if tab-width !=
990 ;; py-indent-offset. Never turn it on, because the user must
991 ;; have explicitly turned it off.
992 (if (/= tab-width py-indent-offset)
993 (setq indent-tabs-mode nil))
Barry Warsaw742a5111998-03-13 17:29:15 +0000994 )))
Barry Warsaw7ae77681994-12-12 20:38:05 +0000995
Barry Warsaw7b0f5681995-03-08 21:33:04 +0000996
Barry Warsawb91b7431995-03-14 15:55:20 +0000997;; electric characters
Barry Warsaw3874a3d1995-03-14 22:05:53 +0000998(defun py-outdent-p ()
999 ;; returns non-nil if the current line should outdent one level
1000 (save-excursion
1001 (and (progn (back-to-indentation)
1002 (looking-at py-outdent-re))
Barry Warsawf06777d1998-01-21 05:36:18 +00001003 (progn (forward-line -1)
1004 (py-goto-initial-line)
1005 (back-to-indentation)
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001006 (while (or (looking-at py-blank-or-comment-re)
1007 (bobp))
1008 (backward-to-indentation 1))
1009 (not (looking-at py-no-outdent-re)))
1010 )))
1011
Barry Warsawb91b7431995-03-14 15:55:20 +00001012(defun py-electric-colon (arg)
1013 "Insert a colon.
1014In certain cases the line is outdented appropriately. If a numeric
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001015argument is provided, that many colons are inserted non-electrically.
1016Electric behavior is inhibited inside a string or comment."
Barry Warsawb91b7431995-03-14 15:55:20 +00001017 (interactive "P")
1018 (self-insert-command (prefix-numeric-value arg))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001019 ;; are we in a string or comment?
1020 (if (save-excursion
1021 (let ((pps (parse-partial-sexp (save-excursion
1022 (beginning-of-python-def-or-class)
1023 (point))
1024 (point))))
1025 (not (or (nth 3 pps) (nth 4 pps)))))
1026 (save-excursion
1027 (let ((here (point))
1028 (outdent 0)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001029 (indent (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001030 (if (and (not arg)
1031 (py-outdent-p)
1032 (= indent (save-excursion
Barry Warsawa7661821996-08-02 16:22:43 +00001033 (py-next-statement -1)
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001034 (py-compute-indentation t)))
Barry Warsaw0c6563f1995-09-14 20:57:02 +00001035 )
1036 (setq outdent py-indent-offset))
1037 ;; Don't indent, only outdent. This assumes that any lines that
1038 ;; are already outdented relative to py-compute-indentation were
1039 ;; put there on purpose. Its highly annoying to have `:' indent
1040 ;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
1041 ;; there a better way to determine this???
1042 (if (< (current-indentation) indent) nil
1043 (goto-char here)
1044 (beginning-of-line)
1045 (delete-horizontal-space)
1046 (indent-to (- indent outdent))
1047 )))))
Barry Warsawb91b7431995-03-14 15:55:20 +00001048
1049
Barry Warsawa97a3f31997-11-04 18:47:06 +00001050;; Python subprocess utilities and filters
1051(defun py-execute-file (proc filename)
1052 ;; Send a properly formatted execfile('FILENAME') to the underlying
1053 ;; Python interpreter process FILENAME. Make that process's buffer
1054 ;; visible and force display. Also make comint believe the user
1055 ;; typed this string so that kill-output-from-shell does The Right
1056 ;; Thing.
1057 (let ((curbuf (current-buffer))
1058 (procbuf (process-buffer proc))
1059 (comint-scroll-to-bottom-on-output t)
1060 (msg (format "## working on region in file %s...\n" filename))
1061 (cmd (format "execfile('%s')\n" filename)))
1062 (unwind-protect
1063 (progn
1064 (set-buffer procbuf)
1065 (goto-char (point-max))
1066 (move-marker (process-mark proc) (point))
1067 (funcall (process-filter proc) proc msg))
1068 (set-buffer curbuf))
1069 (process-send-string proc cmd)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001070
1071(defun py-process-filter (pyproc string)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001072 (let ((curbuf (current-buffer))
1073 (pbuf (process-buffer pyproc))
1074 (pmark (process-mark pyproc))
1075 file-finished)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001076 ;; make sure we switch to a different buffer at least once. if we
1077 ;; *don't* do this, then if the process buffer is in the selected
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001078 ;; window, and point is before the end, and lots of output is
1079 ;; coming at a fast pace, then (a) simple cursor-movement commands
1080 ;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
1081 ;; to have a visible effect (the window just doesn't get updated,
1082 ;; sometimes for minutes(!)), and (b) it takes about 5x longer to
1083 ;; get all the process output (until the next python prompt).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001084 ;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001085 ;; #b makes no sense to me at all. #a almost makes sense: unless
1086 ;; we actually change buffers, set_buffer_internal in buffer.c
1087 ;; doesn't set windows_or_buffers_changed to 1, & that in turn
1088 ;; seems to make the Emacs command loop reluctant to update the
1089 ;; display. Perhaps the default process filter in process.c's
1090 ;; read_process_output has update_mode_lines++ for a similar
1091 ;; reason? beats me ...
1092
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001093 (unwind-protect
1094 ;; make sure current buffer is restored
1095 ;; BAW - we want to check to see if this still applies
1096 (progn
1097 ;; mysterious ugly hack
1098 (if (eq curbuf pbuf)
1099 (set-buffer (get-buffer-create "*scratch*")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001100
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001101 (set-buffer pbuf)
1102 (let* ((start (point))
1103 (goback (< start pmark))
1104 (goend (and (not goback) (= start (point-max))))
1105 (buffer-read-only nil))
1106 (goto-char pmark)
1107 (insert string)
1108 (move-marker pmark (point))
1109 (setq file-finished
1110 (and py-file-queue
1111 (equal ">>> "
1112 (buffer-substring
1113 (prog2 (beginning-of-line) (point)
1114 (goto-char pmark))
1115 (point)))))
1116 (if goback (goto-char start)
1117 ;; else
1118 (if py-scroll-process-buffer
1119 (let* ((pop-up-windows t)
1120 (pwin (display-buffer pbuf)))
1121 (set-window-point pwin (point)))))
1122 (set-buffer curbuf)
1123 (if file-finished
1124 (progn
Barry Warsawf4710561997-11-26 21:00:36 +00001125 (py-safe (delete-file (car py-file-queue)))
Barry Warsaw7a73ef81996-09-30 23:00:40 +00001126 (setq py-file-queue (cdr py-file-queue))
1127 (if py-file-queue
1128 (py-execute-file pyproc (car py-file-queue)))))
1129 (and goend
1130 (progn (set-buffer pbuf)
1131 (goto-char (point-max))))
1132 ))
1133 (set-buffer curbuf))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001134
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001135(defun py-postprocess-output-buffer (buf)
Barry Warsaw512af041998-03-25 23:27:17 +00001136 ;; Highlight exceptions found in BUF
Barry Warsaw9981d221997-12-03 05:25:48 +00001137 (let (line file bol)
1138 (save-excursion
1139 (set-buffer buf)
1140 (beginning-of-buffer)
1141 (while (re-search-forward py-traceback-line-re nil t)
1142 (setq file (match-string 1)
1143 line (string-to-int (match-string 2))
1144 bol (py-point 'bol))
1145 (py-highlight-line bol (py-point 'eol) file line))
1146 (when (and py-jump-on-exception line)
1147 (beep)
1148 (py-jump-to-exception file line))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001149 )))
1150
Barry Warsaw9981d221997-12-03 05:25:48 +00001151
Barry Warsawa97a3f31997-11-04 18:47:06 +00001152
1153;;; Subprocess commands
1154
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001155;; only used when (memq 'broken-temp-names py-emacs-features)
1156(defvar py-serial-number 0)
1157(defvar py-exception-buffer nil)
1158(defconst py-output-buffer "*Python Output*")
1159
Barry Warsawa97a3f31997-11-04 18:47:06 +00001160;;;###autoload
1161(defun py-shell ()
1162 "Start an interactive Python interpreter in another window.
1163This is like Shell mode, except that Python is running in the window
1164instead of a shell. See the `Interactive Shell' and `Shell Mode'
1165sections of the Emacs manual for details, especially for the key
1166bindings active in the `*Python*' buffer.
1167
1168See the docs for variable `py-scroll-buffer' for info on scrolling
1169behavior in the process window.
1170
1171Warning: Don't use an interactive Python if you change sys.ps1 or
1172sys.ps2 from their default values, or if you're running code that
1173prints `>>> ' or `... ' at the start of a line. `python-mode' can't
1174distinguish your output from Python's output, and assumes that `>>> '
1175at the start of a line is a prompt from Python. Similarly, the Emacs
1176Shell mode code assumes that both `>>> ' and `... ' at the start of a
1177line are Python prompts. Bad things can happen if you fool either
1178mode.
1179
1180Warning: If you do any editing *in* the process buffer *while* the
1181buffer is accepting output from Python, do NOT attempt to `undo' the
1182changes. Some of the output (nowhere near the parts you changed!) may
1183be lost if you do. This appears to be an Emacs bug, an unfortunate
1184interaction between undo and process filters; the same problem exists in
1185non-Python process buffers using the default (Emacs-supplied) process
1186filter."
1187 ;; BAW - should undo be disabled in the python process buffer, if
1188 ;; this bug still exists?
1189 (interactive)
1190 (require 'comint)
Barry Warsaw2518c671997-11-05 00:51:08 +00001191 (switch-to-buffer-other-window
Barry Warsaw8f972b71998-02-05 20:45:49 +00001192 (apply 'make-comint "Python" py-python-command nil py-python-command-args))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001193 (make-local-variable 'comint-prompt-regexp)
1194 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
1195 (set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
1196 (set-syntax-table py-mode-syntax-table)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001197 ;; set up keybindings for this subshell
1198 (local-set-key [tab] 'self-insert-command)
1199 (local-set-key "\C-c-" 'py-up-exception)
1200 (local-set-key "\C-c=" 'py-down-exception)
1201 )
Barry Warsawa97a3f31997-11-04 18:47:06 +00001202
Barry Warsawa97a3f31997-11-04 18:47:06 +00001203(defun py-clear-queue ()
1204 "Clear the queue of temporary files waiting to execute."
1205 (interactive)
1206 (let ((n (length py-file-queue)))
1207 (mapcar 'delete-file py-file-queue)
1208 (setq py-file-queue nil)
1209 (message "%d pending files de-queued." n)))
1210
1211(defun py-execute-region (start end &optional async)
1212 "Execute the the region in a Python interpreter.
1213The region is first copied into a temporary file (in the directory
1214`py-temp-directory'). If there is no Python interpreter shell
1215running, this file is executed synchronously using
1216`shell-command-on-region'. If the program is long running, use an
1217optional \\[universal-argument] to run the command asynchronously in
1218its own buffer.
1219
1220If the Python interpreter shell is running, the region is execfile()'d
1221in that shell. If you try to execute regions too quickly,
1222`python-mode' will queue them up and execute them one at a time when
1223it sees a `>>> ' prompt from Python. Each time this happens, the
1224process buffer is popped into a window (if it's not already in some
1225window) so you can see it, and a comment of the form
1226
1227 \t## working on region in file <name>...
1228
1229is inserted at the end. See also the command `py-clear-queue'."
1230 (interactive "r\nP")
1231 (or (< start end)
1232 (error "Region is empty"))
1233 (let* ((proc (get-process "Python"))
Barry Warsaw5e21cb01997-11-05 18:41:11 +00001234 (temp (if (memq 'broken-temp-names py-emacs-features)
1235 (prog1
1236 (format "python-%d" py-serial-number)
1237 (setq py-serial-number (1+ py-serial-number)))
Barry Warsaw2f32fbb1998-02-25 16:45:43 +00001238 (make-temp-name "python-")))
1239 (file (expand-file-name temp py-temp-directory)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001240 (write-region start end file nil 'nomsg)
1241 (cond
1242 ;; always run the code in it's own asynchronous subprocess
1243 (async
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001244 (let* ((buf (generate-new-buffer-name py-output-buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001245 (start-process "Python" buf py-python-command "-u" file)
1246 (pop-to-buffer buf)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001247 (py-postprocess-output-buffer buf)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001248 ))
1249 ;; if the Python interpreter shell is running, queue it up for
1250 ;; execution there.
1251 (proc
1252 ;; use the existing python shell
1253 (if (not py-file-queue)
1254 (py-execute-file proc file)
Barry Warsawa97a3f31997-11-04 18:47:06 +00001255 (message "File %s queued for execution" file))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001256 (push file py-file-queue)
1257 (setq py-exception-buffer (cons file (current-buffer))))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001258 (t
1259 ;; otherwise either run it synchronously in a subprocess
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001260 (shell-command-on-region start end py-python-command py-output-buffer)
Barry Warsaw512af041998-03-25 23:27:17 +00001261 ;; shell-command-on-region kills the output buffer if it never
1262 ;; existed and there's no output from the command
1263 (if (not (get-buffer py-output-buffer))
1264 (message "No output.")
1265 (setq py-exception-buffer (current-buffer))
1266 (py-postprocess-output-buffer py-output-buffer)
1267 (pop-to-buffer py-output-buffer)
1268 ))
1269 )))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001270
1271;; Code execution command
1272(defun py-execute-buffer (&optional async)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001273 "Send the contents of the buffer to a Python interpreter.
Barry Warsawc0ecb531998-01-20 21:43:34 +00001274If the file local variable `py-master-file' is non-nil, execute the
1275named file instead of the buffer's file.
1276
Barry Warsaw7ae77681994-12-12 20:38:05 +00001277If there is a *Python* process buffer it is used. If a clipping
1278restriction is in effect, only the accessible portion of the buffer is
1279sent. A trailing newline will be supplied if needed.
1280
1281See the `\\[py-execute-region]' docs for an account of some subtleties."
Barry Warsawa97a3f31997-11-04 18:47:06 +00001282 (interactive "P")
Barry Warsawc0ecb531998-01-20 21:43:34 +00001283 (if py-master-file
1284 (let* ((filename (expand-file-name py-master-file))
1285 (buffer (or (get-file-buffer filename)
1286 (find-file-noselect filename))))
1287 (set-buffer buffer)))
Barry Warsawa97a3f31997-11-04 18:47:06 +00001288 (py-execute-region (point-min) (point-max) async))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001289
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001290
1291
1292(defun py-jump-to-exception (file line)
1293 (let ((buffer (cond ((string-equal file "<stdin>")
1294 py-exception-buffer)
1295 ((and (consp py-exception-buffer)
1296 (string-equal file (car py-exception-buffer)))
1297 (cdr py-exception-buffer))
1298 ((py-safe (find-file-noselect file)))
1299 ;; could not figure out what file the exception
1300 ;; is pointing to, so prompt for it
1301 (t (find-file (read-file-name "Exception file: "
1302 nil
1303 file t))))))
1304 (pop-to-buffer buffer)
1305 (goto-line line)
1306 (message "Jumping to exception in file %s on line %d" file line)))
1307
1308(defun py-mouseto-exception (event)
1309 (interactive "e")
1310 (cond
1311 ((fboundp 'event-point)
1312 ;; XEmacs
1313 (let* ((point (event-point event))
1314 (buffer (event-buffer event))
1315 (e (and point buffer (extent-at point buffer 'py-exc-info)))
1316 (info (and e (extent-property e 'py-exc-info))))
1317 (message "Event point: %d, info: %s" point info)
1318 (and info
1319 (py-jump-to-exception (car info) (cdr info)))
1320 ))
1321 ;; Emacs -- Please port this!
1322 ))
1323
1324(defun py-goto-exception ()
1325 "Go to the line indicated by the traceback."
1326 (interactive)
1327 (let (file line)
1328 (save-excursion
1329 (beginning-of-line)
1330 (if (looking-at py-traceback-line-re)
1331 (setq file (match-string 1)
1332 line (string-to-int (match-string 2)))))
1333 (if (not file)
1334 (error "Not on a traceback line."))
1335 (py-jump-to-exception file line)))
1336
1337(defun py-find-next-exception (start buffer searchdir errwhere)
1338 ;; Go to start position in buffer, search in the specified
1339 ;; direction, and jump to the exception found. If at the end of the
1340 ;; exception, print error message
1341 (let (file line)
1342 (save-excursion
1343 (set-buffer buffer)
1344 (goto-char (py-point start))
1345 (if (funcall searchdir py-traceback-line-re nil t)
1346 (setq file (match-string 1)
1347 line (string-to-int (match-string 2)))))
1348 (if (and file line)
1349 (py-jump-to-exception file line)
1350 (error "%s of traceback" errwhere))))
1351
1352(defun py-down-exception (&optional bottom)
1353 "Go to the next line down in the traceback.
1354With optional \\[universal-argument], jump to the bottom (innermost)
1355exception in the exception stack."
1356 (interactive "P")
1357 (let* ((proc (get-process "Python"))
1358 (buffer (if proc "*Python*" py-output-buffer)))
1359 (if bottom
1360 (py-find-next-exception 'eob buffer 're-search-backward "Bottom")
1361 (py-find-next-exception 'eol buffer 're-search-forward "Bottom"))))
1362
1363(defun py-up-exception (&optional top)
1364 "Go to the previous line up in the traceback.
1365With optional \\[universal-argument], jump to the top (outermost)
1366exception in the exception stack."
1367 (interactive "P")
1368 (let* ((proc (get-process "Python"))
1369 (buffer (if proc "*Python*" py-output-buffer)))
1370 (if top
1371 (py-find-next-exception 'bob buffer 're-search-forward "Top")
Barry Warsawffbc17d1997-11-27 20:08:14 +00001372 (py-find-next-exception 'bol buffer 're-search-backward "Top"))))
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001373
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001374
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001375;; Electric deletion
1376(defun py-electric-backspace (arg)
1377 "Deletes preceding character or levels of indentation.
1378Deletion is performed by calling the function in `py-backspace-function'
Barry Warsawb0539931996-12-17 22:05:07 +00001379with a single argument (the number of characters to delete).
Barry Warsaw7ae77681994-12-12 20:38:05 +00001380
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001381If point is at the leftmost column, deletes the preceding newline.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001382
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001383Otherwise, if point is at the leftmost non-whitespace character of a
1384line that is neither a continuation line nor a non-indenting comment
1385line, or if point is at the end of a blank line, this command reduces
1386the indentation to match that of the line that opened the current
1387block of code. The line that opened the block is displayed in the
1388echo area to help you keep track of where you are. With numeric arg,
1389outdents that many blocks (but not past column zero).
1390
1391Otherwise the preceding character is deleted, converting a tab to
1392spaces if needed so that only a single column position is deleted.
1393Numeric argument deletes that many preceding characters."
Barry Warsaw03970731996-07-03 23:12:52 +00001394 (interactive "*p")
Barry Warsaw7ae77681994-12-12 20:38:05 +00001395 (if (or (/= (current-indentation) (current-column))
1396 (bolp)
1397 (py-continuation-line-p)
Barry Warsaw6e527d21996-08-01 15:57:48 +00001398 (not py-honor-comment-indentation)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001399 (looking-at "#[^ \t\n]")) ; non-indenting #
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001400 (funcall py-backspace-function arg)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001401 ;; else indent the same as the colon line that opened the block
Barry Warsaw7ae77681994-12-12 20:38:05 +00001402 ;; force non-blank so py-goto-block-up doesn't ignore it
1403 (insert-char ?* 1)
1404 (backward-char)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001405 (let ((base-indent 0) ; indentation of base line
1406 (base-text "") ; and text of base line
1407 (base-found-p nil))
Barry Warsaw03970731996-07-03 23:12:52 +00001408 (save-excursion
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001409 (while (< 0 arg)
Barry Warsaw03970731996-07-03 23:12:52 +00001410 (condition-case nil ; in case no enclosing block
1411 (progn
1412 (py-goto-block-up 'no-mark)
1413 (setq base-indent (current-indentation)
1414 base-text (py-suck-up-leading-text)
1415 base-found-p t))
1416 (error nil))
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001417 (setq arg (1- arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001418 (delete-char 1) ; toss the dummy character
1419 (delete-horizontal-space)
1420 (indent-to base-indent)
1421 (if base-found-p
1422 (message "Closes block: %s" base-text)))))
1423
Barry Warsawfc8a01f1995-03-09 16:07:29 +00001424
Barry Warsaw6d48c4a1997-11-04 19:21:50 +00001425(defun py-electric-delete (arg)
1426 "Deletes preceding or following character or levels of whitespace.
1427
1428The behavior of this function depends on the variable
1429`delete-key-deletes-forward'. If this variable is nil (or does not
1430exist, as in older Emacsen), then this function behaves identical to
1431\\[c-electric-backspace].
1432
1433If `delete-key-deletes-forward' is non-nil and is supported in your
1434Emacs, then deletion occurs in the forward direction, by calling the
1435function in `py-delete-function'."
1436 (interactive "*p")
1437 (if (and (boundp 'delete-key-deletes-forward)
1438 delete-key-deletes-forward)
1439 (funcall py-delete-function arg)
1440 ;; else
1441 (py-electric-backspace arg)))
1442
1443;; required for pending-del and delsel modes
1444(put 'py-electric-backspace 'delete-selection 'supersede) ;delsel
1445(put 'py-electric-backspace 'pending-delete 'supersede) ;pending-del
1446(put 'py-electric-delete 'delete-selection 'supersede) ;delsel
1447(put 'py-electric-delete 'pending-delete 'supersede) ;pending-del
1448
1449
1450
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001451(defun py-indent-line (&optional arg)
1452 "Fix the indentation of the current line according to Python rules.
1453With \\[universal-argument], ignore outdenting rules for block
1454closing statements (e.g. return, raise, break, continue, pass)
1455
1456This function is normally bound to `indent-line-function' so
1457\\[indent-for-tab-command] will call it."
1458 (interactive "P")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001459 (let* ((ci (current-indentation))
1460 (move-to-indentation-p (<= (current-column) ci))
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001461 (need (py-compute-indentation (not arg))))
Barry Warsaw4f009fb1995-03-14 20:53:08 +00001462 ;; see if we need to outdent
Barry Warsaw3874a3d1995-03-14 22:05:53 +00001463 (if (py-outdent-p)
Barry Warsaw0012c1e1995-03-14 16:32:55 +00001464 (setq need (- need py-indent-offset)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001465 (if (/= ci need)
1466 (save-excursion
1467 (beginning-of-line)
1468 (delete-horizontal-space)
1469 (indent-to need)))
1470 (if move-to-indentation-p (back-to-indentation))))
1471
1472(defun py-newline-and-indent ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001473 "Strives to act like the Emacs `newline-and-indent'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001474This is just `strives to' because correct indentation can't be computed
1475from scratch for Python code. In general, deletes the whitespace before
1476point, inserts a newline, and takes an educated guess as to how you want
1477the new line indented."
1478 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001479 (let ((ci (current-indentation)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001480 (if (< ci (current-column)) ; if point beyond indentation
1481 (newline-and-indent)
1482 ;; else try to act like newline-and-indent "normally" acts
1483 (beginning-of-line)
1484 (insert-char ?\n 1)
1485 (move-to-column ci))))
1486
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001487(defun py-compute-indentation (honor-block-close-p)
1488 ;; implements all the rules for indentation computation. when
1489 ;; honor-block-close-p is non-nil, statements such as return, raise,
1490 ;; break, continue, and pass force one level of outdenting.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001491 (save-excursion
Barry Warsawf64b4051998-02-12 16:52:14 +00001492 (beginning-of-line)
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001493 (let* ((bod (py-point 'bod))
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001494 (pps (parse-partial-sexp bod (point)))
1495 (boipps (parse-partial-sexp bod (py-point 'boi))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001496 (cond
Barry Warsawa0ee8cd1997-11-26 01:04:44 +00001497 ;; are we inside a multi-line string or comment?
Barry Warsaw3b3ff4e1997-11-26 20:58:48 +00001498 ((or (and (nth 3 pps) (nth 3 boipps))
1499 (and (nth 4 pps) (nth 4 boipps)))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001500 (save-excursion
1501 (if (not py-align-multiline-strings-p) 0
1502 ;; skip back over blank & non-indenting comment lines
1503 ;; note: will skip a blank or non-indenting comment line
1504 ;; that happens to be a continuation line too
1505 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)" nil 'move)
1506 (back-to-indentation)
1507 (current-column))))
1508 ;; are we on a continuation line?
1509 ((py-continuation-line-p)
1510 (let ((startpos (point))
1511 (open-bracket-pos (py-nesting-level))
Barry Warsawce60bc71996-08-01 18:17:14 +00001512 endpos searching found state)
Barry Warsaw095e9c61995-09-19 20:01:42 +00001513 (if open-bracket-pos
1514 (progn
1515 ;; align with first item in list; else a normal
1516 ;; indent beyond the line with the open bracket
1517 (goto-char (1+ open-bracket-pos)) ; just beyond bracket
1518 ;; is the first list item on the same line?
1519 (skip-chars-forward " \t")
1520 (if (null (memq (following-char) '(?\n ?# ?\\)))
1521 ; yes, so line up with it
1522 (current-column)
1523 ;; first list item on another line, or doesn't exist yet
1524 (forward-line 1)
1525 (while (and (< (point) startpos)
1526 (looking-at "[ \t]*[#\n\\\\]")) ; skip noise
1527 (forward-line 1))
1528 (if (< (point) startpos)
1529 ;; again mimic the first list item
1530 (current-indentation)
1531 ;; else they're about to enter the first item
1532 (goto-char open-bracket-pos)
1533 (+ (current-indentation) py-indent-offset))))
1534
1535 ;; else on backslash continuation line
1536 (forward-line -1)
1537 (if (py-continuation-line-p) ; on at least 3rd line in block
1538 (current-indentation) ; so just continue the pattern
1539 ;; else started on 2nd line in block, so indent more.
1540 ;; if base line is an assignment with a start on a RHS,
1541 ;; indent to 2 beyond the leftmost "="; else skip first
1542 ;; chunk of non-whitespace characters on base line, + 1 more
1543 ;; column
1544 (end-of-line)
1545 (setq endpos (point) searching t)
1546 (back-to-indentation)
1547 (setq startpos (point))
1548 ;; look at all "=" from left to right, stopping at first
1549 ;; one not nested in a list or string
1550 (while searching
1551 (skip-chars-forward "^=" endpos)
1552 (if (= (point) endpos)
1553 (setq searching nil)
1554 (forward-char 1)
1555 (setq state (parse-partial-sexp startpos (point)))
1556 (if (and (zerop (car state)) ; not in a bracket
1557 (null (nth 3 state))) ; & not in a string
1558 (progn
1559 (setq searching nil) ; done searching in any case
1560 (setq found
1561 (not (or
1562 (eq (following-char) ?=)
1563 (memq (char-after (- (point) 2))
1564 '(?< ?> ?!)))))))))
1565 (if (or (not found) ; not an assignment
1566 (looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
1567 (progn
1568 (goto-char startpos)
1569 (skip-chars-forward "^ \t\n")))
1570 (1+ (current-column))))))
1571
1572 ;; not on a continuation line
Barry Warsawa7891711996-08-01 15:53:09 +00001573 ((bobp) (current-indentation))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001574
Barry Warsawa7891711996-08-01 15:53:09 +00001575 ;; Dfn: "Indenting comment line". A line containing only a
1576 ;; comment, but which is treated like a statement for
1577 ;; indentation calculation purposes. Such lines are only
1578 ;; treated specially by the mode; they are not treated
1579 ;; specially by the Python interpreter.
1580
1581 ;; The rules for indenting comment lines are a line where:
1582 ;; - the first non-whitespace character is `#', and
1583 ;; - the character following the `#' is whitespace, and
1584 ;; - the line is outdented with respect to (i.e. to the left
1585 ;; of) the indentation of the preceding non-blank line.
1586
1587 ;; The first non-blank line following an indenting comment
1588 ;; line is given the same amount of indentation as the
1589 ;; indenting comment line.
1590
1591 ;; All other comment-only lines are ignored for indentation
1592 ;; purposes.
1593
1594 ;; Are we looking at a comment-only line which is *not* an
1595 ;; indenting comment line? If so, we assume that its been
1596 ;; placed at the desired indentation, so leave it alone.
1597 ;; Indenting comment lines are aligned as statements down
1598 ;; below.
1599 ((and (looking-at "[ \t]*#[^ \t\n]")
1600 ;; NOTE: this test will not be performed in older Emacsen
1601 (fboundp 'forward-comment)
1602 (<= (current-indentation)
1603 (save-excursion
1604 (forward-comment (- (point-max)))
1605 (current-indentation))))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001606 (current-indentation))
1607
1608 ;; else indentation based on that of the statement that
1609 ;; precedes us; use the first line of that statement to
1610 ;; establish the base, in case the user forced a non-std
1611 ;; indentation for the continuation lines (if any)
1612 (t
Barry Warsawc01c5c81995-09-14 18:49:11 +00001613 ;; skip back over blank & non-indenting comment lines note:
1614 ;; will skip a blank or non-indenting comment line that
Barry Warsawfd0fb381996-03-04 17:15:40 +00001615 ;; happens to be a continuation line too. use fast Emacs 19
1616 ;; function if it's there.
Barry Warsaw6d627751996-03-06 18:41:38 +00001617 (if (and (eq py-honor-comment-indentation nil)
Barry Warsaw33d6ec01996-03-05 16:28:07 +00001618 (fboundp 'forward-comment))
Barry Warsawfd0fb381996-03-04 17:15:40 +00001619 (forward-comment (- (point-max)))
Barry Warsaw6d627751996-03-06 18:41:38 +00001620 (let (done)
1621 (while (not done)
1622 (re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
1623 nil 'move)
1624 (setq done (or (eq py-honor-comment-indentation t)
1625 (bobp)
1626 (/= (following-char) ?#)
1627 (not (zerop (current-column)))))
1628 )))
Barry Warsaw095e9c61995-09-19 20:01:42 +00001629 ;; if we landed inside a string, go to the beginning of that
1630 ;; string. this handles triple quoted, multi-line spanning
1631 ;; strings.
Barry Warsawf64b4051998-02-12 16:52:14 +00001632 (let* ((pps3 (nth 3 (parse-partial-sexp bod (point))))
1633 (delim (and pps3 (int-to-char pps3)))
1634 (skip (and delim (make-string 1 delim))))
1635 (when skip
1636 (save-excursion
1637 (py-safe (search-backward skip))
1638 (if (and (eq (char-before) delim)
1639 (eq (char-before (1- (point))) delim))
1640 (setq skip (make-string 3 delim))))
1641 ;; we're looking at a triple-quoted string
1642 (py-safe (search-backward skip))))
Barry Warsawc210e691998-01-20 22:52:56 +00001643 ;; now skip backward over continued lines
Barry Warsaw095e9c61995-09-19 20:01:42 +00001644 (py-goto-initial-line)
Barry Warsawf831d811996-07-31 20:42:59 +00001645 (+ (current-indentation)
1646 (if (py-statement-opens-block-p)
1647 py-indent-offset
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001648 (if (and honor-block-close-p (py-statement-closes-block-p))
Barry Warsawf831d811996-07-31 20:42:59 +00001649 (- py-indent-offset)
1650 0)))
1651 )))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001652
1653(defun py-guess-indent-offset (&optional global)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001654 "Guess a good value for, and change, `py-indent-offset'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001655By default (without a prefix arg), makes a buffer-local copy of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001656`py-indent-offset' with the new value. This will not affect any other
Barry Warsaw7ae77681994-12-12 20:38:05 +00001657Python buffers. With a prefix arg, changes the global value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001658`py-indent-offset'. This affects all Python buffers (that don't have
Barry Warsaw7ae77681994-12-12 20:38:05 +00001659their own buffer-local copy), both those currently existing and those
1660created later in the Emacs session.
1661
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001662Some people use a different value for `py-indent-offset' than you use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001663There's no excuse for such foolishness, but sometimes you have to deal
1664with their ugly code anyway. This function examines the file and sets
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001665`py-indent-offset' to what it thinks it was when they created the
1666mess.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001667
1668Specifically, it searches forward from the statement containing point,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001669looking for a line that opens a block of code. `py-indent-offset' is
1670set to the difference in indentation between that line and the Python
Barry Warsaw7ae77681994-12-12 20:38:05 +00001671statement following it. If the search doesn't succeed going forward,
1672it's tried again going backward."
1673 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001674 (let (new-value
1675 (start (point))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001676 (restart (point))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001677 (found nil)
1678 colon-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001679 (py-goto-initial-line)
1680 (while (not (or found (eobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001681 (when (and (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1682 (not (py-in-literal restart)))
1683 (setq restart (point))
1684 (py-goto-initial-line)
1685 (if (py-statement-opens-block-p)
1686 (setq found t)
1687 (goto-char restart))))
1688 (unless found
Barry Warsaw7ae77681994-12-12 20:38:05 +00001689 (goto-char start)
1690 (py-goto-initial-line)
1691 (while (not (or found (bobp)))
Barry Warsawe908b6b1998-03-19 22:48:02 +00001692 (setq found (and
1693 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1694 (or (py-goto-initial-line) t) ; always true -- side effect
1695 (py-statement-opens-block-p)))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001696 (setq colon-indent (current-indentation)
1697 found (and found (zerop (py-next-statement 1)))
1698 new-value (- (current-indentation) colon-indent))
1699 (goto-char start)
Barry Warsawe908b6b1998-03-19 22:48:02 +00001700 (if (not found)
1701 (error "Sorry, couldn't guess a value for py-indent-offset")
1702 (funcall (if global 'kill-local-variable 'make-local-variable)
1703 'py-indent-offset)
1704 (setq py-indent-offset new-value)
1705 (message "%s value of py-indent-offset set to %d"
1706 (if global "Global" "Local")
1707 py-indent-offset))
1708 ))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001709
1710(defun py-shift-region (start end count)
1711 (save-excursion
1712 (goto-char end) (beginning-of-line) (setq end (point))
1713 (goto-char start) (beginning-of-line) (setq start (point))
1714 (indent-rigidly start end count)))
1715
1716(defun py-shift-region-left (start end &optional count)
1717 "Shift region of Python code to the left.
1718The lines from the line containing the start of the current region up
1719to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001720shifted to the left, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001721
1722If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001723many columns. With no active region, outdent only the current line.
1724You cannot outdent the region if any line is already at column zero."
1725 (interactive
1726 (let ((p (point))
1727 (m (mark))
1728 (arg current-prefix-arg))
1729 (if m
1730 (list (min p m) (max p m) arg)
1731 (list p (save-excursion (forward-line 1) (point)) arg))))
1732 ;; if any line is at column zero, don't shift the region
1733 (save-excursion
1734 (goto-char start)
1735 (while (< (point) end)
1736 (back-to-indentation)
Barry Warsaw71e315b1996-07-23 15:03:16 +00001737 (if (and (zerop (current-column))
1738 (not (looking-at "\\s *$")))
Barry Warsawdea4a291996-07-03 22:59:12 +00001739 (error "Region is at left edge."))
1740 (forward-line 1)))
1741 (py-shift-region start end (- (prefix-numeric-value
1742 (or count py-indent-offset))))
1743 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001744
1745(defun py-shift-region-right (start end &optional count)
1746 "Shift region of Python code to the right.
1747The lines from the line containing the start of the current region up
1748to (but not including) the line containing the end of the region are
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001749shifted to the right, by `py-indent-offset' columns.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001750
1751If a prefix argument is given, the region is instead shifted by that
Barry Warsawdea4a291996-07-03 22:59:12 +00001752many columns. With no active region, indent only the current line."
1753 (interactive
1754 (let ((p (point))
1755 (m (mark))
1756 (arg current-prefix-arg))
1757 (if m
1758 (list (min p m) (max p m) arg)
1759 (list p (save-excursion (forward-line 1) (point)) arg))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001760 (py-shift-region start end (prefix-numeric-value
Barry Warsawdea4a291996-07-03 22:59:12 +00001761 (or count py-indent-offset)))
1762 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001763
1764(defun py-indent-region (start end &optional indent-offset)
1765 "Reindent a region of Python code.
Barry Warsaw867a32a1996-03-07 18:30:26 +00001766
Barry Warsaw7ae77681994-12-12 20:38:05 +00001767The lines from the line containing the start of the current region up
1768to (but not including) the line containing the end of the region are
1769reindented. If the first line of the region has a non-whitespace
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001770character in the first column, the first line is left alone and the
1771rest of the region is reindented with respect to it. Else the entire
Barry Warsaw867a32a1996-03-07 18:30:26 +00001772region is reindented with respect to the (closest code or indenting
1773comment) statement immediately preceding the region.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001774
1775This is useful when code blocks are moved or yanked, when enclosing
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001776control structures are introduced or removed, or to reformat code
1777using a new value for the indentation offset.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001778
1779If a numeric prefix argument is given, it will be used as the value of
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001780the indentation offset. Else the value of `py-indent-offset' will be
Barry Warsaw7ae77681994-12-12 20:38:05 +00001781used.
1782
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001783Warning: The region must be consistently indented before this function
Barry Warsaw7ae77681994-12-12 20:38:05 +00001784is called! This function does not compute proper indentation from
1785scratch (that's impossible in Python), it merely adjusts the existing
1786indentation to be correct in context.
1787
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001788Warning: This function really has no idea what to do with
1789non-indenting comment lines, and shifts them as if they were indenting
1790comment lines. Fixing this appears to require telepathy.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001791
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001792Special cases: whitespace is deleted from blank lines; continuation
1793lines are shifted by the same amount their initial line was shifted,
1794in order to preserve their relative indentation with respect to their
Barry Warsaw7ae77681994-12-12 20:38:05 +00001795initial line; and comment lines beginning in column 1 are ignored."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001796 (interactive "*r\nP") ; region; raw prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001797 (save-excursion
1798 (goto-char end) (beginning-of-line) (setq end (point-marker))
1799 (goto-char start) (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001800 (let ((py-indent-offset (prefix-numeric-value
1801 (or indent-offset py-indent-offset)))
1802 (indents '(-1)) ; stack of active indent levels
1803 (target-column 0) ; column to which to indent
1804 (base-shifted-by 0) ; amount last base line was shifted
1805 (indent-base (if (looking-at "[ \t\n]")
Barry Warsaw7cb505c1996-10-23 20:44:59 +00001806 (py-compute-indentation t)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001807 0))
1808 ci)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001809 (while (< (point) end)
1810 (setq ci (current-indentation))
1811 ;; figure out appropriate target column
1812 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001813 ((or (eq (following-char) ?#) ; comment in column 1
1814 (looking-at "[ \t]*$")) ; entirely blank
1815 (setq target-column 0))
1816 ((py-continuation-line-p) ; shift relative to base line
1817 (setq target-column (+ ci base-shifted-by)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001818 (t ; new base line
1819 (if (> ci (car indents)) ; going deeper; push it
1820 (setq indents (cons ci indents))
1821 ;; else we should have seen this indent before
1822 (setq indents (memq ci indents)) ; pop deeper indents
1823 (if (null indents)
1824 (error "Bad indentation in region, at line %d"
1825 (save-restriction
1826 (widen)
1827 (1+ (count-lines 1 (point)))))))
1828 (setq target-column (+ indent-base
1829 (* py-indent-offset
1830 (- (length indents) 2))))
1831 (setq base-shifted-by (- target-column ci))))
1832 ;; shift as needed
1833 (if (/= ci target-column)
1834 (progn
1835 (delete-horizontal-space)
1836 (indent-to target-column)))
1837 (forward-line 1))))
1838 (set-marker end nil))
1839
Barry Warsawa7891711996-08-01 15:53:09 +00001840(defun py-comment-region (beg end &optional arg)
1841 "Like `comment-region' but uses double hash (`#') comment starter."
1842 (interactive "r\nP")
Barry Warsaw3fcaf611996-08-01 20:11:51 +00001843 (let ((comment-start py-block-comment-prefix))
Barry Warsawa7891711996-08-01 15:53:09 +00001844 (comment-region beg end arg)))
1845
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001846
1847;; Functions for moving point
Barry Warsaw7ae77681994-12-12 20:38:05 +00001848(defun py-previous-statement (count)
1849 "Go to the start of previous Python statement.
1850If the statement at point is the i'th Python statement, goes to the
1851start of statement i-COUNT. If there is no such statement, goes to the
1852first statement. Returns count of statements left to move.
1853`Statements' do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001854 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001855 (if (< count 0) (py-next-statement (- count))
1856 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001857 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001858 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001859 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001860 (> count 0)
1861 (zerop (forward-line -1))
1862 (py-goto-statement-at-or-above))
1863 (setq count (1- count)))
1864 (if (> count 0) (goto-char start)))
1865 count))
1866
1867(defun py-next-statement (count)
1868 "Go to the start of next Python statement.
1869If the statement at point is the i'th Python statement, goes to the
1870start of statement i+COUNT. If there is no such statement, goes to the
1871last statement. Returns count of statements left to move. `Statements'
1872do not include blank, comment, or continuation lines."
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001873 (interactive "p") ; numeric prefix arg
Barry Warsaw7ae77681994-12-12 20:38:05 +00001874 (if (< count 0) (py-previous-statement (- count))
1875 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001876 (let (start)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001877 (while (and
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001878 (setq start (point)) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00001879 (> count 0)
1880 (py-goto-statement-below))
1881 (setq count (1- count)))
1882 (if (> count 0) (goto-char start)))
1883 count))
1884
1885(defun py-goto-block-up (&optional nomark)
1886 "Move up to start of current block.
1887Go to the statement that starts the smallest enclosing block; roughly
1888speaking, this will be the closest preceding statement that ends with a
1889colon and is indented less than the statement you started on. If
1890successful, also sets the mark to the starting point.
1891
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001892`\\[py-mark-block]' can be used afterward to mark the whole code
1893block, if desired.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001894
1895If called from a program, the mark will not be set if optional argument
1896NOMARK is not nil."
1897 (interactive)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001898 (let ((start (point))
1899 (found nil)
1900 initial-indent)
Barry Warsaw7ae77681994-12-12 20:38:05 +00001901 (py-goto-initial-line)
1902 ;; if on blank or non-indenting comment line, use the preceding stmt
1903 (if (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
1904 (progn
1905 (py-goto-statement-at-or-above)
1906 (setq found (py-statement-opens-block-p))))
1907 ;; search back for colon line indented less
1908 (setq initial-indent (current-indentation))
1909 (if (zerop initial-indent)
1910 ;; force fast exit
1911 (goto-char (point-min)))
1912 (while (not (or found (bobp)))
1913 (setq found
1914 (and
1915 (re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
1916 (or (py-goto-initial-line) t) ; always true -- side effect
1917 (< (current-indentation) initial-indent)
1918 (py-statement-opens-block-p))))
1919 (if found
1920 (progn
1921 (or nomark (push-mark start))
1922 (back-to-indentation))
1923 (goto-char start)
1924 (error "Enclosing block not found"))))
1925
1926(defun beginning-of-python-def-or-class (&optional class)
1927 "Move point to start of def (or class, with prefix arg).
1928
1929Searches back for the closest preceding `def'. If you supply a prefix
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001930arg, looks for a `class' instead. The docs assume the `def' case;
1931just substitute `class' for `def' for the other case.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001932
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001933If point is in a def statement already, and after the `d', simply
1934moves point to the start of the statement.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001935
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001936Else (point is not in a def statement, or at or before the `d' of a
1937def statement), searches for the closest preceding def statement, and
1938leaves point at its start. If no such statement can be found, leaves
1939point at the start of the buffer.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001940
1941Returns t iff a def statement is found by these rules.
1942
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001943Note that doing this command repeatedly will take you closer to the
1944start of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001945
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001946If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001947`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001948 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001949 (let ((at-or-before-p (<= (current-column) (current-indentation)))
1950 (start-of-line (progn (beginning-of-line) (point)))
1951 (start-of-stmt (progn (py-goto-initial-line) (point))))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001952 (if (or (/= start-of-stmt start-of-line)
1953 (not at-or-before-p))
1954 (end-of-line)) ; OK to match on this line
1955 (re-search-backward (if class "^[ \t]*class\\>" "^[ \t]*def\\>")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001956 nil 'move)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001957
1958(defun end-of-python-def-or-class (&optional class)
1959 "Move point beyond end of def (or class, with prefix arg) body.
1960
1961By default, looks for an appropriate `def'. If you supply a prefix arg,
1962looks for a `class' instead. The docs assume the `def' case; just
1963substitute `class' for `def' for the other case.
1964
1965If point is in a def statement already, this is the def we use.
1966
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001967Else if the def found by `\\[beginning-of-python-def-or-class]'
1968contains the statement you started on, that's the def we use.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001969
1970Else we search forward for the closest following def, and use that.
1971
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001972If a def can be found by these rules, point is moved to the start of
1973the line immediately following the def block, and the position of the
1974start of the def is returned.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001975
1976Else point is moved to the end of the buffer, and nil is returned.
1977
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001978Note that doing this command repeatedly will take you closer to the
1979end of the buffer each time.
Barry Warsaw7ae77681994-12-12 20:38:05 +00001980
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001981If you want to mark the current def/class, see
Barry Warsaw2518c671997-11-05 00:51:08 +00001982`\\[py-mark-def-or-class]'."
Barry Warsaw7ae77681994-12-12 20:38:05 +00001983 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00001984 (let ((start (progn (py-goto-initial-line) (point)))
1985 (which (if class "class" "def"))
1986 (state 'not-found))
Barry Warsaw7ae77681994-12-12 20:38:05 +00001987 ;; move point to start of appropriate def/class
1988 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
1989 (setq state 'at-beginning)
1990 ;; else see if beginning-of-python-def-or-class hits container
1991 (if (and (beginning-of-python-def-or-class class)
1992 (progn (py-goto-beyond-block)
1993 (> (point) start)))
1994 (setq state 'at-end)
1995 ;; else search forward
1996 (goto-char start)
1997 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
1998 (progn (setq state 'at-beginning)
1999 (beginning-of-line)))))
2000 (cond
2001 ((eq state 'at-beginning) (py-goto-beyond-block) t)
2002 ((eq state 'at-end) t)
2003 ((eq state 'not-found) nil)
2004 (t (error "internal error in end-of-python-def-or-class")))))
2005
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002006
2007;; Functions for marking regions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002008(defun py-mark-block (&optional extend just-move)
2009 "Mark following block of lines. With prefix arg, mark structure.
2010Easier to use than explain. It sets the region to an `interesting'
2011block of succeeding lines. If point is on a blank line, it goes down to
2012the next non-blank line. That will be the start of the region. The end
2013of the region depends on the kind of line at the start:
2014
2015 - If a comment, the region will include all succeeding comment lines up
2016 to (but not including) the next non-comment line (if any).
2017
2018 - Else if a prefix arg is given, and the line begins one of these
2019 structures:
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002020
2021 if elif else try except finally for while def class
2022
Barry Warsaw7ae77681994-12-12 20:38:05 +00002023 the region will be set to the body of the structure, including
2024 following blocks that `belong' to it, but excluding trailing blank
2025 and comment lines. E.g., if on a `try' statement, the `try' block
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002026 and all (if any) of the following `except' and `finally' blocks
2027 that belong to the `try' structure will be in the region. Ditto
2028 for if/elif/else, for/else and while/else structures, and (a bit
2029 degenerate, since they're always one-block structures) def and
2030 class blocks.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002031
2032 - Else if no prefix argument is given, and the line begins a Python
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002033 block (see list above), and the block is not a `one-liner' (i.e.,
2034 the statement ends with a colon, not with code), the region will
2035 include all succeeding lines up to (but not including) the next
2036 code statement (if any) that's indented no more than the starting
2037 line, except that trailing blank and comment lines are excluded.
2038 E.g., if the starting line begins a multi-statement `def'
2039 structure, the region will be set to the full function definition,
2040 but without any trailing `noise' lines.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002041
2042 - Else the region will include all succeeding lines up to (but not
2043 including) the next blank line, or code or indenting-comment line
2044 indented strictly less than the starting line. Trailing indenting
2045 comment lines are included in this case, but not trailing blank
2046 lines.
2047
2048A msg identifying the location of the mark is displayed in the echo
2049area; or do `\\[exchange-point-and-mark]' to flip down to the end.
2050
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002051If called from a program, optional argument EXTEND plays the role of
2052the prefix arg, and if optional argument JUST-MOVE is not nil, just
2053moves to the end of the block (& does not set mark or display a msg)."
Barry Warsaw7ae77681994-12-12 20:38:05 +00002054 (interactive "P") ; raw prefix arg
2055 (py-goto-initial-line)
2056 ;; skip over blank lines
2057 (while (and
2058 (looking-at "[ \t]*$") ; while blank line
2059 (not (eobp))) ; & somewhere to go
2060 (forward-line 1))
2061 (if (eobp)
2062 (error "Hit end of buffer without finding a non-blank stmt"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002063 (let ((initial-pos (point))
2064 (initial-indent (current-indentation))
2065 last-pos ; position of last stmt in region
2066 (followers
2067 '((if elif else) (elif elif else) (else)
2068 (try except finally) (except except) (finally)
2069 (for else) (while else)
2070 (def) (class) ) )
2071 first-symbol next-symbol)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002072
2073 (cond
2074 ;; if comment line, suck up the following comment lines
2075 ((looking-at "[ \t]*#")
2076 (re-search-forward "^[ \t]*[^ \t#]" nil 'move) ; look for non-comment
2077 (re-search-backward "^[ \t]*#") ; and back to last comment in block
2078 (setq last-pos (point)))
2079
2080 ;; else if line is a block line and EXTEND given, suck up
2081 ;; the whole structure
2082 ((and extend
2083 (setq first-symbol (py-suck-up-first-keyword) )
2084 (assq first-symbol followers))
2085 (while (and
2086 (or (py-goto-beyond-block) t) ; side effect
2087 (forward-line -1) ; side effect
2088 (setq last-pos (point)) ; side effect
2089 (py-goto-statement-below)
2090 (= (current-indentation) initial-indent)
2091 (setq next-symbol (py-suck-up-first-keyword))
2092 (memq next-symbol (cdr (assq first-symbol followers))))
2093 (setq first-symbol next-symbol)))
2094
2095 ;; else if line *opens* a block, search for next stmt indented <=
2096 ((py-statement-opens-block-p)
2097 (while (and
2098 (setq last-pos (point)) ; always true -- side effect
2099 (py-goto-statement-below)
2100 (> (current-indentation) initial-indent))
2101 nil))
2102
2103 ;; else plain code line; stop at next blank line, or stmt or
2104 ;; indenting comment line indented <
2105 (t
2106 (while (and
2107 (setq last-pos (point)) ; always true -- side effect
2108 (or (py-goto-beyond-final-line) t)
2109 (not (looking-at "[ \t]*$")) ; stop at blank line
2110 (or
2111 (>= (current-indentation) initial-indent)
2112 (looking-at "[ \t]*#[^ \t\n]"))) ; ignore non-indenting #
2113 nil)))
2114
2115 ;; skip to end of last stmt
2116 (goto-char last-pos)
2117 (py-goto-beyond-final-line)
2118
2119 ;; set mark & display
2120 (if just-move
2121 () ; just return
2122 (push-mark (point) 'no-msg)
2123 (forward-line -1)
2124 (message "Mark set after: %s" (py-suck-up-leading-text))
2125 (goto-char initial-pos))))
2126
Barry Warsaw2518c671997-11-05 00:51:08 +00002127(defun py-mark-def-or-class (&optional class)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002128 "Set region to body of def (or class, with prefix arg) enclosing point.
2129Pushes the current mark, then point, on the mark ring (all language
2130modes do this, but although it's handy it's never documented ...).
2131
2132In most Emacs language modes, this function bears at least a
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002133hallucinogenic resemblance to `\\[end-of-python-def-or-class]' and
2134`\\[beginning-of-python-def-or-class]'.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002135
2136And in earlier versions of Python mode, all 3 were tightly connected.
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002137Turned out that was more confusing than useful: the `goto start' and
2138`goto end' commands are usually used to search through a file, and
2139people expect them to act a lot like `search backward' and `search
2140forward' string-search commands. But because Python `def' and `class'
2141can nest to arbitrary levels, finding the smallest def containing
2142point cannot be done via a simple backward search: the def containing
2143point may not be the closest preceding def, or even the closest
2144preceding def that's indented less. The fancy algorithm required is
2145appropriate for the usual uses of this `mark' command, but not for the
2146`goto' variations.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002147
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002148So the def marked by this command may not be the one either of the
2149`goto' commands find: If point is on a blank or non-indenting comment
2150line, moves back to start of the closest preceding code statement or
2151indenting comment line. If this is a `def' statement, that's the def
2152we use. Else searches for the smallest enclosing `def' block and uses
2153that. Else signals an error.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002154
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002155When an enclosing def is found: The mark is left immediately beyond
2156the last line of the def block. Point is left at the start of the
2157def, except that: if the def is preceded by a number of comment lines
2158followed by (at most) one optional blank line, point is left at the
2159start of the comments; else if the def is preceded by a blank line,
2160point is left at its start.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002161
2162The intent is to mark the containing def/class and its associated
2163documentation, to make moving and duplicating functions and classes
2164pleasant."
2165 (interactive "P") ; raw prefix arg
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002166 (let ((start (point))
2167 (which (if class "class" "def")))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002168 (push-mark start)
2169 (if (not (py-go-up-tree-to-keyword which))
2170 (progn (goto-char start)
2171 (error "Enclosing %s not found" which))
2172 ;; else enclosing def/class found
2173 (setq start (point))
2174 (py-goto-beyond-block)
2175 (push-mark (point))
2176 (goto-char start)
2177 (if (zerop (forward-line -1)) ; if there is a preceding line
2178 (progn
2179 (if (looking-at "[ \t]*$") ; it's blank
2180 (setq start (point)) ; so reset start point
2181 (goto-char start)) ; else try again
2182 (if (zerop (forward-line -1))
2183 (if (looking-at "[ \t]*#") ; a comment
2184 ;; look back for non-comment line
2185 ;; tricky: note that the regexp matches a blank
2186 ;; line, cuz \n is in the 2nd character class
2187 (and
2188 (re-search-backward "^[ \t]*[^ \t#]" nil 'move)
2189 (forward-line 1))
2190 ;; no comment, so go back
Barry Warsaw4da6bd51997-11-26 06:00:26 +00002191 (goto-char start)))))))
2192 (exchange-point-and-mark)
2193 (py-keep-region-active))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002194
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002195;; ripped from cc-mode
2196(defun py-forward-into-nomenclature (&optional arg)
2197 "Move forward to end of a nomenclature section or word.
2198With arg, to it arg times.
2199
2200A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2201 (interactive "p")
2202 (let ((case-fold-search nil))
2203 (if (> arg 0)
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002204 (re-search-forward
2205 "\\(\\W\\|[_]\\)*\\([A-Z]*[a-z0-9]*\\)"
2206 (point-max) t arg)
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002207 (while (and (< arg 0)
2208 (re-search-backward
Barry Warsawc5a8cbd1996-08-05 21:53:02 +00002209 "\\(\\W\\|[a-z0-9]\\)[A-Z]+\\|\\(\\W\\|[_]\\)\\w+"
Barry Warsaw9e5a9c81996-07-24 18:26:53 +00002210 (point-min) 0))
2211 (forward-char 1)
2212 (setq arg (1+ arg)))))
2213 (py-keep-region-active))
2214
2215(defun py-backward-into-nomenclature (&optional arg)
2216 "Move backward to beginning of a nomenclature section or word.
2217With optional ARG, move that many times. If ARG is negative, move
2218forward.
2219
2220A `nomenclature' is a fancy way of saying AWordWithMixedCaseNotUnderscores."
2221 (interactive "p")
2222 (py-forward-into-nomenclature (- arg))
2223 (py-keep-region-active))
2224
2225
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002226
2227;; Documentation functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002228
2229;; dump the long form of the mode blurb; does the usual doc escapes,
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002230;; plus lines of the form ^[vc]:name$ to suck variable & command docs
2231;; out of the right places, along with the keys they're on & current
2232;; values
Barry Warsaw7ae77681994-12-12 20:38:05 +00002233(defun py-dump-help-string (str)
2234 (with-output-to-temp-buffer "*Help*"
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002235 (let ((locals (buffer-local-variables))
2236 funckind funcname func funcdoc
2237 (start 0) mstart end
2238 keys )
Barry Warsaw7ae77681994-12-12 20:38:05 +00002239 (while (string-match "^%\\([vc]\\):\\(.+\\)\n" str start)
2240 (setq mstart (match-beginning 0) end (match-end 0)
2241 funckind (substring str (match-beginning 1) (match-end 1))
2242 funcname (substring str (match-beginning 2) (match-end 2))
2243 func (intern funcname))
2244 (princ (substitute-command-keys (substring str start mstart)))
2245 (cond
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002246 ((equal funckind "c") ; command
2247 (setq funcdoc (documentation func)
2248 keys (concat
2249 "Key(s): "
2250 (mapconcat 'key-description
2251 (where-is-internal func py-mode-map)
2252 ", "))))
2253 ((equal funckind "v") ; variable
Barry Warsaw604cefa1996-09-03 18:17:04 +00002254 (setq funcdoc (documentation-property func 'variable-documentation)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002255 keys (if (assq func locals)
2256 (concat
2257 "Local/Global values: "
2258 (prin1-to-string (symbol-value func))
2259 " / "
2260 (prin1-to-string (default-value func)))
2261 (concat
2262 "Value: "
2263 (prin1-to-string (symbol-value func))))))
2264 (t ; unexpected
2265 (error "Error in py-dump-help-string, tag `%s'" funckind)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002266 (princ (format "\n-> %s:\t%s\t%s\n\n"
2267 (if (equal funckind "c") "Command" "Variable")
2268 funcname keys))
2269 (princ funcdoc)
2270 (terpri)
2271 (setq start end))
2272 (princ (substitute-command-keys (substring str start))))
2273 (print-help-return-message)))
2274
2275(defun py-describe-mode ()
2276 "Dump long form of Python-mode docs."
2277 (interactive)
2278 (py-dump-help-string "Major mode for editing Python files.
2279Knows about Python indentation, tokens, comments and continuation lines.
2280Paragraphs are separated by blank lines only.
2281
2282Major sections below begin with the string `@'; specific function and
2283variable docs begin with `->'.
2284
2285@EXECUTING PYTHON CODE
2286
2287\\[py-execute-buffer]\tsends the entire buffer to the Python interpreter
2288\\[py-execute-region]\tsends the current region
2289\\[py-shell]\tstarts a Python interpreter window; this will be used by
2290\tsubsequent \\[py-execute-buffer] or \\[py-execute-region] commands
2291%c:py-execute-buffer
2292%c:py-execute-region
2293%c:py-shell
2294
2295@VARIABLES
2296
2297py-indent-offset\tindentation increment
Barry Warsaw42f707f1996-07-29 21:05:05 +00002298py-block-comment-prefix\tcomment string used by comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002299
2300py-python-command\tshell command to invoke Python interpreter
2301py-scroll-process-buffer\talways scroll Python process buffer
2302py-temp-directory\tdirectory used for temp files (if needed)
2303
2304py-beep-if-tab-change\tring the bell if tab-width is changed
2305%v:py-indent-offset
2306%v:py-block-comment-prefix
2307%v:py-python-command
2308%v:py-scroll-process-buffer
2309%v:py-temp-directory
2310%v:py-beep-if-tab-change
2311
2312@KINDS OF LINES
2313
2314Each physical line in the file is either a `continuation line' (the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002315preceding line ends with a backslash that's not part of a comment, or
2316the paren/bracket/brace nesting level at the start of the line is
2317non-zero, or both) or an `initial line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002318
2319An initial line is in turn a `blank line' (contains nothing except
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002320possibly blanks or tabs), a `comment line' (leftmost non-blank
2321character is `#'), or a `code line' (everything else).
Barry Warsaw7ae77681994-12-12 20:38:05 +00002322
2323Comment Lines
2324
2325Although all comment lines are treated alike by Python, Python mode
2326recognizes two kinds that act differently with respect to indentation.
2327
2328An `indenting comment line' is a comment line with a blank, tab or
2329nothing after the initial `#'. The indentation commands (see below)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002330treat these exactly as if they were code lines: a line following an
Barry Warsaw7ae77681994-12-12 20:38:05 +00002331indenting comment line will be indented like the comment line. All
2332other comment lines (those with a non-whitespace character immediately
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002333following the initial `#') are `non-indenting comment lines', and
2334their indentation is ignored by the indentation commands.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002335
2336Indenting comment lines are by far the usual case, and should be used
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002337whenever possible. Non-indenting comment lines are useful in cases
2338like these:
Barry Warsaw7ae77681994-12-12 20:38:05 +00002339
2340\ta = b # a very wordy single-line comment that ends up being
2341\t #... continued onto another line
2342
2343\tif a == b:
2344##\t\tprint 'panic!' # old code we've `commented out'
2345\t\treturn a
2346
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002347Since the `#...' and `##' comment lines have a non-whitespace
2348character following the initial `#', Python mode ignores them when
2349computing the proper indentation for the next line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002350
2351Continuation Lines and Statements
2352
2353The Python-mode commands generally work on statements instead of on
2354individual lines, where a `statement' is a comment or blank line, or a
2355code line and all of its following continuation lines (if any)
2356considered as a single logical unit. The commands in this mode
2357generally (when it makes sense) automatically move to the start of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002358statement containing point, even if point happens to be in the middle
2359of some continuation line.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002360
2361
2362@INDENTATION
2363
2364Primarily for entering new code:
2365\t\\[indent-for-tab-command]\t indent line appropriately
2366\t\\[py-newline-and-indent]\t insert newline, then indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002367\t\\[py-electric-backspace]\t reduce indentation, or delete single character
Barry Warsaw7ae77681994-12-12 20:38:05 +00002368
2369Primarily for reindenting existing code:
2370\t\\[py-guess-indent-offset]\t guess py-indent-offset from file content; change locally
2371\t\\[universal-argument] \\[py-guess-indent-offset]\t ditto, but change globally
2372
2373\t\\[py-indent-region]\t reindent region to match its context
2374\t\\[py-shift-region-left]\t shift region left by py-indent-offset
2375\t\\[py-shift-region-right]\t shift region right by py-indent-offset
2376
2377Unlike most programming languages, Python uses indentation, and only
2378indentation, to specify block structure. Hence the indentation supplied
2379automatically by Python-mode is just an educated guess: only you know
2380the block structure you intend, so only you can supply correct
2381indentation.
2382
2383The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on
2384the indentation of preceding statements. E.g., assuming
2385py-indent-offset is 4, after you enter
2386\tif a > 0: \\[py-newline-and-indent]
2387the cursor will be moved to the position of the `_' (_ is not a
2388character in the file, it's just used here to indicate the location of
2389the cursor):
2390\tif a > 0:
2391\t _
2392If you then enter `c = d' \\[py-newline-and-indent], the cursor will move
2393to
2394\tif a > 0:
2395\t c = d
2396\t _
2397Python-mode cannot know whether that's what you intended, or whether
2398\tif a > 0:
2399\t c = d
2400\t_
2401was your intent. In general, Python-mode either reproduces the
2402indentation of the (closest code or indenting-comment) preceding
2403statement, or adds an extra py-indent-offset blanks if the preceding
2404statement has `:' as its last significant (non-whitespace and non-
2405comment) character. If the suggested indentation is too much, use
Barry Warsaw27ee1151997-12-03 05:03:44 +00002406\\[py-electric-backspace] to reduce it.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002407
2408Continuation lines are given extra indentation. If you don't like the
2409suggested indentation, change it to something you do like, and Python-
2410mode will strive to indent later lines of the statement in the same way.
2411
2412If a line is a continuation line by virtue of being in an unclosed
2413paren/bracket/brace structure (`list', for short), the suggested
2414indentation depends on whether the current line contains the first item
2415in the list. If it does, it's indented py-indent-offset columns beyond
2416the indentation of the line containing the open bracket. If you don't
2417like that, change it by hand. The remaining items in the list will mimic
2418whatever indentation you give to the first item.
2419
2420If a line is a continuation line because the line preceding it ends with
2421a backslash, the third and following lines of the statement inherit their
2422indentation from the line preceding them. The indentation of the second
2423line in the statement depends on the form of the first (base) line: if
2424the base line is an assignment statement with anything more interesting
2425than the backslash following the leftmost assigning `=', the second line
2426is indented two columns beyond that `='. Else it's indented to two
2427columns beyond the leftmost solid chunk of non-whitespace characters on
2428the base line.
2429
2430Warning: indent-region should not normally be used! It calls \\[indent-for-tab-command]
2431repeatedly, and as explained above, \\[indent-for-tab-command] can't guess the block
2432structure you intend.
2433%c:indent-for-tab-command
2434%c:py-newline-and-indent
Barry Warsaw27ee1151997-12-03 05:03:44 +00002435%c:py-electric-backspace
Barry Warsaw7ae77681994-12-12 20:38:05 +00002436
2437
2438The next function may be handy when editing code you didn't write:
2439%c:py-guess-indent-offset
2440
2441
2442The remaining `indent' functions apply to a region of Python code. They
2443assume the block structure (equals indentation, in Python) of the region
2444is correct, and alter the indentation in various ways while preserving
2445the block structure:
2446%c:py-indent-region
2447%c:py-shift-region-left
2448%c:py-shift-region-right
2449
2450@MARKING & MANIPULATING REGIONS OF CODE
2451
2452\\[py-mark-block]\t mark block of lines
Barry Warsaw2518c671997-11-05 00:51:08 +00002453\\[py-mark-def-or-class]\t mark smallest enclosing def
2454\\[universal-argument] \\[py-mark-def-or-class]\t mark smallest enclosing class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002455\\[comment-region]\t comment out region of code
2456\\[universal-argument] \\[comment-region]\t uncomment region of code
Barry Warsaw7ae77681994-12-12 20:38:05 +00002457%c:py-mark-block
Barry Warsaw2518c671997-11-05 00:51:08 +00002458%c:py-mark-def-or-class
Barry Warsaw42f707f1996-07-29 21:05:05 +00002459%c:comment-region
Barry Warsaw7ae77681994-12-12 20:38:05 +00002460
2461@MOVING POINT
2462
2463\\[py-previous-statement]\t move to statement preceding point
2464\\[py-next-statement]\t move to statement following point
2465\\[py-goto-block-up]\t move up to start of current block
2466\\[beginning-of-python-def-or-class]\t move to start of def
2467\\[universal-argument] \\[beginning-of-python-def-or-class]\t move to start of class
2468\\[end-of-python-def-or-class]\t move to end of def
2469\\[universal-argument] \\[end-of-python-def-or-class]\t move to end of class
2470
2471The first two move to one statement beyond the statement that contains
2472point. A numeric prefix argument tells them to move that many
2473statements instead. Blank lines, comment lines, and continuation lines
2474do not count as `statements' for these commands. So, e.g., you can go
2475to the first code statement in a file by entering
2476\t\\[beginning-of-buffer]\t to move to the top of the file
2477\t\\[py-next-statement]\t to skip over initial comments and blank lines
2478Or do `\\[py-previous-statement]' with a huge prefix argument.
2479%c:py-previous-statement
2480%c:py-next-statement
2481%c:py-goto-block-up
2482%c:beginning-of-python-def-or-class
2483%c:end-of-python-def-or-class
2484
2485@LITTLE-KNOWN EMACS COMMANDS PARTICULARLY USEFUL IN PYTHON MODE
2486
2487`\\[indent-new-comment-line]' is handy for entering a multi-line comment.
2488
2489`\\[set-selective-display]' with a `small' prefix arg is ideally suited for viewing the
2490overall class and def structure of a module.
2491
2492`\\[back-to-indentation]' moves point to a line's first non-blank character.
2493
2494`\\[indent-relative]' is handy for creating odd indentation.
2495
2496@OTHER EMACS HINTS
2497
2498If you don't like the default value of a variable, change its value to
2499whatever you do like by putting a `setq' line in your .emacs file.
2500E.g., to set the indentation increment to 4, put this line in your
2501.emacs:
2502\t(setq py-indent-offset 4)
2503To see the value of a variable, do `\\[describe-variable]' and enter the variable
2504name at the prompt.
2505
2506When entering a key sequence like `C-c C-n', it is not necessary to
2507release the CONTROL key after doing the `C-c' part -- it suffices to
2508press the CONTROL key, press and release `c' (while still holding down
2509CONTROL), press and release `n' (while still holding down CONTROL), &
2510then release CONTROL.
2511
2512Entering Python mode calls with no arguments the value of the variable
2513`python-mode-hook', if that value exists and is not nil; for backward
2514compatibility it also tries `py-mode-hook'; see the `Hooks' section of
2515the Elisp manual for details.
2516
2517Obscure: When python-mode is first loaded, it looks for all bindings
2518to newline-and-indent in the global keymap, and shadows them with
2519local bindings to py-newline-and-indent."))
2520
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002521
2522;; Helper functions
Barry Warsaw7ae77681994-12-12 20:38:05 +00002523(defvar py-parse-state-re
2524 (concat
2525 "^[ \t]*\\(if\\|elif\\|else\\|while\\|def\\|class\\)\\>"
2526 "\\|"
2527 "^[^ #\t\n]"))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002528
Barry Warsaw7ae77681994-12-12 20:38:05 +00002529;; returns the parse state at point (see parse-partial-sexp docs)
2530(defun py-parse-state ()
2531 (save-excursion
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002532 (let ((here (point))
Barry Warsaw742a5111998-03-13 17:29:15 +00002533 pps done)
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002534 (while (not done)
2535 ;; back up to the first preceding line (if any; else start of
2536 ;; buffer) that begins with a popular Python keyword, or a
2537 ;; non- whitespace and non-comment character. These are good
2538 ;; places to start parsing to see whether where we started is
2539 ;; at a non-zero nesting level. It may be slow for people who
2540 ;; write huge code blocks or huge lists ... tough beans.
2541 (re-search-backward py-parse-state-re nil 'move)
2542 (beginning-of-line)
Barry Warsawf64b4051998-02-12 16:52:14 +00002543 ;; In XEmacs, we have a much better way to test for whether
2544 ;; we're in a triple-quoted string or not. Emacs does not
2545 ;; have this built-in function, which is it's loss because
2546 ;; without scanning from the beginning of the buffer, there's
2547 ;; no accurate way to determine this otherwise.
2548 (if (not (fboundp 'buffer-syntactic-context))
2549 ;; Emacs
2550 (save-excursion
2551 (setq pps (parse-partial-sexp (point) here))
2552 ;; make sure we don't land inside a triple-quoted string
Barry Warsaw742a5111998-03-13 17:29:15 +00002553 (setq done (or (not (nth 3 pps))
2554 (bobp))))
Barry Warsawf64b4051998-02-12 16:52:14 +00002555 ;; XEmacs
2556 (setq done (or (not (buffer-syntactic-context))
2557 (bobp)))
2558 (when done
2559 (setq pps (parse-partial-sexp (point) here)))
2560 ))
Barry Warsaw43ecf8e1996-04-06 00:00:19 +00002561 pps)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002562
2563;; if point is at a non-zero nesting level, returns the number of the
2564;; character that opens the smallest enclosing unclosed list; else
2565;; returns nil.
2566(defun py-nesting-level ()
Barry Warsawf64b4051998-02-12 16:52:14 +00002567 (let ((status (py-parse-state)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002568 (if (zerop (car status))
2569 nil ; not in a nest
2570 (car (cdr status))))) ; char# of open bracket
2571
2572;; t iff preceding line ends with backslash that's not in a comment
2573(defun py-backslash-continuation-line-p ()
2574 (save-excursion
2575 (beginning-of-line)
2576 (and
2577 ;; use a cheap test first to avoid the regexp if possible
2578 ;; use 'eq' because char-after may return nil
2579 (eq (char-after (- (point) 2)) ?\\ )
2580 ;; make sure; since eq test passed, there is a preceding line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002581 (forward-line -1) ; always true -- side effect
Barry Warsaw7ae77681994-12-12 20:38:05 +00002582 (looking-at py-continued-re))))
2583
2584;; t iff current line is a continuation line
2585(defun py-continuation-line-p ()
2586 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002587 (beginning-of-line)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002588 (or (py-backslash-continuation-line-p)
2589 (py-nesting-level))))
2590
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002591;; go to initial line of current statement; usually this is the line
2592;; we're on, but if we're on the 2nd or following lines of a
2593;; continuation block, we need to go up to the first line of the
2594;; block.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002595;;
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002596;; Tricky: We want to avoid quadratic-time behavior for long continued
2597;; blocks, whether of the backslash or open-bracket varieties, or a
2598;; mix of the two. The following manages to do that in the usual
2599;; cases.
Barry Warsawc210e691998-01-20 22:52:56 +00002600;;
2601;; Also, if we're sitting inside a triple quoted string, this will
2602;; drop us at the line that begins the string.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002603(defun py-goto-initial-line ()
Barry Warsaw9ec9fbc1998-01-21 05:15:57 +00002604 (let (open-bracket-pos)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002605 (while (py-continuation-line-p)
2606 (beginning-of-line)
2607 (if (py-backslash-continuation-line-p)
2608 (while (py-backslash-continuation-line-p)
2609 (forward-line -1))
2610 ;; else zip out of nested brackets/braces/parens
2611 (while (setq open-bracket-pos (py-nesting-level))
2612 (goto-char open-bracket-pos)))))
2613 (beginning-of-line))
2614
2615;; go to point right beyond final line of current statement; usually
2616;; this is the start of the next line, but if this is a multi-line
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002617;; statement we need to skip over the continuation lines. Tricky:
2618;; Again we need to be clever to avoid quadratic time behavior.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002619(defun py-goto-beyond-final-line ()
2620 (forward-line 1)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002621 (let (state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002622 (while (and (py-continuation-line-p)
2623 (not (eobp)))
2624 ;; skip over the backslash flavor
2625 (while (and (py-backslash-continuation-line-p)
2626 (not (eobp)))
2627 (forward-line 1))
2628 ;; if in nest, zip to the end of the nest
2629 (setq state (py-parse-state))
2630 (if (and (not (zerop (car state)))
2631 (not (eobp)))
2632 (progn
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002633 (parse-partial-sexp (point) (point-max) 0 nil state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002634 (forward-line 1))))))
2635
2636;; t iff statement opens a block == iff it ends with a colon that's
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002637;; not in a comment. point should be at the start of a statement
Barry Warsaw7ae77681994-12-12 20:38:05 +00002638(defun py-statement-opens-block-p ()
2639 (save-excursion
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002640 (let ((start (point))
2641 (finish (progn (py-goto-beyond-final-line) (1- (point))))
2642 (searching t)
2643 (answer nil)
2644 state)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002645 (goto-char start)
2646 (while searching
2647 ;; look for a colon with nothing after it except whitespace, and
2648 ;; maybe a comment
2649 (if (re-search-forward ":\\([ \t]\\|\\\\\n\\)*\\(#.*\\)?$"
2650 finish t)
2651 (if (eq (point) finish) ; note: no `else' clause; just
2652 ; keep searching if we're not at
2653 ; the end yet
2654 ;; sure looks like it opens a block -- but it might
2655 ;; be in a comment
2656 (progn
2657 (setq searching nil) ; search is done either way
2658 (setq state (parse-partial-sexp start
2659 (match-beginning 0)))
2660 (setq answer (not (nth 4 state)))))
2661 ;; search failed: couldn't find another interesting colon
2662 (setq searching nil)))
2663 answer)))
2664
Barry Warsawf831d811996-07-31 20:42:59 +00002665(defun py-statement-closes-block-p ()
2666 ;; true iff the current statement `closes' a block == the line
Barry Warsaw7cb505c1996-10-23 20:44:59 +00002667 ;; starts with `return', `raise', `break', `continue', and `pass'.
2668 ;; doesn't catch embedded statements
Barry Warsawf831d811996-07-31 20:42:59 +00002669 (let ((here (point)))
2670 (back-to-indentation)
2671 (prog1
Barry Warsawaffc0ca1997-11-03 16:59:38 +00002672 (looking-at (concat py-block-closing-keywords-re "\\>"))
Barry Warsawf831d811996-07-31 20:42:59 +00002673 (goto-char here))))
2674
Barry Warsaw7ae77681994-12-12 20:38:05 +00002675;; go to point right beyond final line of block begun by the current
2676;; line. This is the same as where py-goto-beyond-final-line goes
2677;; unless we're on colon line, in which case we go to the end of the
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002678;; block. assumes point is at bolp
Barry Warsaw7ae77681994-12-12 20:38:05 +00002679(defun py-goto-beyond-block ()
2680 (if (py-statement-opens-block-p)
2681 (py-mark-block nil 'just-move)
2682 (py-goto-beyond-final-line)))
2683
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002684;; go to start of first statement (not blank or comment or
2685;; continuation line) at or preceding point. returns t if there is
2686;; one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002687(defun py-goto-statement-at-or-above ()
2688 (py-goto-initial-line)
2689 (if (looking-at py-blank-or-comment-re)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002690 ;; skip back over blank & comment lines
2691 ;; note: will skip a blank or comment line that happens to be
2692 ;; a continuation line too
2693 (if (re-search-backward "^[ \t]*[^ \t#\n]" nil t)
2694 (progn (py-goto-initial-line) t)
2695 nil)
Barry Warsaw7ae77681994-12-12 20:38:05 +00002696 t))
2697
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002698;; go to start of first statement (not blank or comment or
2699;; continuation line) following the statement containing point returns
2700;; t if there is one, else nil
Barry Warsaw7ae77681994-12-12 20:38:05 +00002701(defun py-goto-statement-below ()
2702 (beginning-of-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002703 (let ((start (point)))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002704 (py-goto-beyond-final-line)
2705 (while (and
2706 (looking-at py-blank-or-comment-re)
2707 (not (eobp)))
2708 (forward-line 1))
2709 (if (eobp)
2710 (progn (goto-char start) nil)
2711 t)))
2712
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002713;; go to start of statement, at or preceding point, starting with
2714;; keyword KEY. Skips blank lines and non-indenting comments upward
2715;; first. If that statement starts with KEY, done, else go back to
2716;; first enclosing block starting with KEY. If successful, leaves
2717;; point at the start of the KEY line & returns t. Else leaves point
2718;; at an undefined place & returns nil.
Barry Warsaw7ae77681994-12-12 20:38:05 +00002719(defun py-go-up-tree-to-keyword (key)
2720 ;; skip blanks and non-indenting #
2721 (py-goto-initial-line)
2722 (while (and
2723 (looking-at "[ \t]*\\($\\|#[^ \t\n]\\)")
2724 (zerop (forward-line -1))) ; go back
2725 nil)
2726 (py-goto-initial-line)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002727 (let* ((re (concat "[ \t]*" key "\\b"))
2728 (case-fold-search nil) ; let* so looking-at sees this
2729 (found (looking-at re))
2730 (dead nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002731 (while (not (or found dead))
2732 (condition-case nil ; in case no enclosing block
2733 (py-goto-block-up 'no-mark)
2734 (error (setq dead t)))
2735 (or dead (setq found (looking-at re))))
2736 (beginning-of-line)
2737 found))
2738
2739;; return string in buffer from start of indentation to end of line;
2740;; prefix "..." if leading whitespace was skipped
2741(defun py-suck-up-leading-text ()
2742 (save-excursion
2743 (back-to-indentation)
2744 (concat
2745 (if (bolp) "" "...")
2746 (buffer-substring (point) (progn (end-of-line) (point))))))
2747
2748;; assuming point at bolp, return first keyword ([a-z]+) on the line,
2749;; as a Lisp symbol; return nil if none
2750(defun py-suck-up-first-keyword ()
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002751 (let ((case-fold-search nil))
Barry Warsaw7ae77681994-12-12 20:38:05 +00002752 (if (looking-at "[ \t]*\\([a-z]+\\)\\b")
2753 (intern (buffer-substring (match-beginning 1) (match-end 1)))
2754 nil)))
2755
Barry Warsawb3e81d51996-09-04 15:12:42 +00002756(defun py-current-defun ()
2757 ;; tell add-log.el how to find the current function/method/variable
2758 (save-excursion
2759 (if (re-search-backward py-defun-start-re nil t)
2760 (or (match-string 3)
2761 (let ((method (match-string 2)))
2762 (if (and (not (zerop (length (match-string 1))))
2763 (re-search-backward py-class-start-re nil t))
2764 (concat (match-string 1) "." method)
2765 method)))
2766 nil)))
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002767
2768
Barry Warsawfec75d61995-07-05 23:26:15 +00002769(defconst py-help-address "python-mode@python.org"
Barry Warsaw850437a1995-03-08 21:50:28 +00002770 "Address accepting submission of bug reports.")
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002771
Barry Warsaw850437a1995-03-08 21:50:28 +00002772(defun py-version ()
2773 "Echo the current version of `python-mode' in the minibuffer."
2774 (interactive)
2775 (message "Using `python-mode' version %s" py-version)
2776 (py-keep-region-active))
2777
2778;; only works under Emacs 19
2779;(eval-when-compile
2780; (require 'reporter))
2781
2782(defun py-submit-bug-report (enhancement-p)
2783 "Submit via mail a bug report on `python-mode'.
2784With \\[universal-argument] just submit an enhancement request."
2785 (interactive
2786 (list (not (y-or-n-p
2787 "Is this a bug report? (hit `n' to send other comments) "))))
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002788 (let ((reporter-prompt-for-summary-p (if enhancement-p
2789 "(Very) brief summary: "
2790 t)))
Barry Warsaw850437a1995-03-08 21:50:28 +00002791 (require 'reporter)
2792 (reporter-submit-bug-report
2793 py-help-address ;address
Barry Warsawb5e0ecb1995-03-14 18:32:54 +00002794 (concat "python-mode " py-version) ;pkgname
Barry Warsaw850437a1995-03-08 21:50:28 +00002795 ;; varlist
2796 (if enhancement-p nil
2797 '(py-python-command
2798 py-indent-offset
2799 py-block-comment-prefix
2800 py-scroll-process-buffer
2801 py-temp-directory
2802 py-beep-if-tab-change))
2803 nil ;pre-hooks
2804 nil ;post-hooks
2805 "Dear Barry,") ;salutation
2806 (if enhancement-p nil
2807 (set-mark (point))
2808 (insert
2809"Please replace this text with a sufficiently large code sample\n\
2810and an exact recipe so that I can reproduce your problem. Failure\n\
2811to do so may mean a greater delay in fixing your bug.\n\n")
2812 (exchange-point-and-mark)
2813 (py-keep-region-active))))
2814
2815
Barry Warsaw47384781997-11-26 05:27:45 +00002816(defun py-kill-emacs-hook ()
2817 (mapcar #'(lambda (filename)
2818 (py-safe (delete-file filename)))
2819 py-file-queue))
2820
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002821;; arrange to kill temp files when Emacs exists
Barry Warsawc72c11c1997-08-09 06:42:08 +00002822(add-hook 'kill-emacs-hook 'py-kill-emacs-hook)
Barry Warsaw7b0f5681995-03-08 21:33:04 +00002823
2824
2825
2826(provide 'python-mode)
2827;;; python-mode.el ends here